import React, { Component } from 'react';
import {
  Alert,
  Steps,
  Upload,
  message,
  Button,
  Modal,
  Table,
  Spin
} from 'antd';
import { connect } from 'dva';
import { withRouter } from 'dva/router';
import store from 'store';
import moment from 'moment';
import './less/batch.less';
import {
  host,
  systemComDepartImportDepart,
  enterpriseInsComInsGetOnlineInsBlbPreservationLink, //生成保全,
  systemComVaseInfoGet, //获取部门信息
  findUninsuredPerList
} from '../../../services/api';
import axios from 'axios';
import $nModal from '../../../utils/modal/nModal';
import ExcelButtonOline from "../../../components/ExcelButtonOline";
const { Step } = Steps;
let newwin;
@connect(
  state => ({
    profile: state.profile,
    global: state.global
  })
)
// 批量导入-新建组织机构
@withRouter
export default class BatchImport extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      addpeoplevisible: false,
      addpeoplevisible1: false,
      dataSource: [],
      perIds: [],
      //导入人员
      visible: false,
      visibleFormat: false,
      uploadResponse: [], //格式正确后返回的json字符串
      dataFormat: '', //格式错误提示内容
      comId: '', //企业Id
      faileDisabled: 'none', //上传文件失败显示下载失败文件
      failData: '', //上传文件失败返回的数据
      loading: false,
      blackNameList:[],//上传文件成功有黑名单人员列表
    };
  }
  componentWillMount() {
    this.systemComVaseInfoGet();
  }
  systemComVaseInfoGet = () => {
    systemComVaseInfoGet({}).then(
      response => {
        this.setState({
          comId: response.data.comId
        });
      },
      err => {
        console.log(err, 'systemComVaseInfoGet-err-获取企业详情');
      }
    );
  };
  //批量导入组织架构
  systemComDepartImportDepart = () => {
    systemComDepartImportDepart({
      data: JSON.stringify(this.state.uploadResponse)
    }).then(
      data => {
        if (data.msg !== '') {
          data.msg = data.msg.replace(/<br>/, '').trim();
        }
        message.success(data.msg);
        const perIds = data.data.map(val => val.perId);
        this.setState({ perIds });
        if (this.state.dataSource.length > 0) {
          this.setState({
            addpeoplevisible: true
          });
        }
      },
      err => {
        console.log(err, 'systemComDepartImportDepart-err-批量导入组织架构');
      }
    );
  };

  showModal = () => {
    this.setState({
      visible: true
    });
  };

  handleOk = ifError => {
    this.setState({
      visible: false
    });
    if (!ifError) {
      this.systemComDepartImportDepart();
    }
  };

  handleCancel = e => {
    this.setState({
      visible: false
    });
  };

  //保险选择
  renderTable = () => {
    const rowSelection = {
      type: 'radio',
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: selectedRowKeys => {
        this.setState({ selectedRowKeys });
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User' // Column configuration not to be checked
      })
    };
    const columns = [
      {
        title: '订单号',
        dataIndex: 'blbOrderId',
        key: 'blbOrderId'
      },
      {
        title: '保险产品',
        dataIndex: 'insComName',
        key: 'insComName'
      },
      {
        title: '人数',
        dataIndex: 'perNum',
        key: 'perNum'
      },
      {
        title: '购买时间',
        dataIndex: 'effectStartDate',
        key: 'effectStartDate'
      }
    ];

    return (
      <Table
        size="middle"
        width={800}
        rowSelection={rowSelection}
        columns={columns}
        pagination={false}
        dataSource={this.state.dataSource}
      />
    );
  };

  //保全链接生成
  enterpriseInsComInsGetOnlineInsBlbPreservationLink = () => {
    enterpriseInsComInsGetOnlineInsBlbPreservationLink({
      orderId: this.state.selectedRowKeys,
      perIds: this.state.perIds.join(','),
      reviseType: '1'
    })
      .then(res => {
        this.setState({ addpeoplevisible1: false });
        newwin.location.href = res.data;
      })
      .catch(err => {
        newwin.close();
        this.setState({ addpeoplevisible1: false });
      });
  };

  //格式错误提示框
  handleFormatOk = () => {
    this.setState({ visibleFormat: false });
  };

  //下载
  handleClickLink = () => {
    return (
      <Button
        type="primary"
        onClick={() => {
          // window.open(
          //   `${host}/system/com-depart/export-depart-temp?comId=${
          //     this.state.comId
          //   }`,
          //   '_self'
          // );
          axios({
            method: 'get',
            url:
              `${host}/system/com-depart/export-depart-temp?comId=${
              this.state.comId
              }`, //后台请求地址
            responseType: 'blob',
            headers: {
              access_token: store.get('saas')['access_token'],
        Accesstoken: store.get('saas')['access_token']|| sessionStorage.userV5Token,

            }
          }).then(data => {
            if (!data) {
              return;
            }
            let url = window.URL.createObjectURL(data.data);
            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute(
              'download',
              `组织架构模板.xls`
            );
            document.body.appendChild(link);
            link.click();
          });
        }}
      >
        下载模板
      </Button>
      // <Button type="primary" onClick={() => window.open(`${lib.host}/static/template/OrderPerson_Template.xls`, "_self")}>下载模板</Button>
    );
  };
  //上传
  handleClickUpload = () => {
    const uploadExcel = {
      name: 'xfile',
      // action: `${host}/system/com-depart/get-import-depart-json`,
      action: `${host}/system/com-depart/import-excel-per`,
      headers: {
        authorization: 'Basic c2Fhc3dlYjp3ZWI=',
        access_token: store.get('saas')['access_token'],
        Accesstoken: store.get('saas')['access_token']|| sessionStorage.userV5Token,

      },
      showUploadList: false,
      // responseType:'blob',
      data: {}
    };
    const beforeUpload = file => {
      this.setState({
        loading: true
      });
      let ifError = true;
      if (file.name.indexOf('xls') === -1 && file.name.indexOf('xlsx') === -1) {
        this.setState({
          loading: false
        });
        message.error('请上传xls或xlsx文件!');
        return false
      }
      console.log(file.size)
      if(file.size/1024/1024 > 1.5){
        this.setState({
          loading: false
        });
        message.error('请上传小于1.5M文件!');
        ifError = false;
      }
      return ifError;
    };

    //上传文件
    const UploadChange = async info => {
      this.setState({
        faileDisabled: 'none',
        // loading: true
      });
      if (info.file.status === 'uploading') {
        return;
      }
      if (info.file.status === 'done') {
        const { data, msg, retType } = info.file.response;
        this.setState({
          blackNameList:data?data.blackList:[]
        })
        //"retType":"-1"为错误，data会有相应的路径值
        //"retType":"0"为正确，data为空
        if (retType === '-1') {
          message.error(msg);
          this.setState({
            faileDisabled: 'block',
            failData: data
          });
        } else if (retType === '0') {
          const unInsureNumRes = await findUninsuredPerList({
            perType: '',  //人员类型
            keyword: '',  //关键字
            departId: '',  //部门id
            pageNumber: '1',  // 页	
            pageSize: '10'  //条目
          });
          const nowTimeStamp = moment().valueOf();
          const preTimeStamp = store.get('addPersonModalTime');
          let canShow = false;
          if (!preTimeStamp) {
            canShow = true;
          } else {
            if (nowTimeStamp - preTimeStamp > 2 * 60 * 1000) {
              canShow = true;
            }
          }

          let successCount = 0;
          const matchInfo = msg.match(/【\d+】/g);
          if (matchInfo && matchInfo[1]) {
            successCount = matchInfo[1].replace(/^【/, '').replace(/】$/, '');
          }

          // 未投保人数
          const unInsureNum = unInsureNumRes.data.other;
          // 存在未投保人数并且距离上一次弹窗时间大于2分钟并且是服务公司的时候弹窗
          if (unInsureNum > 0 &&
            canShow &&
            (this.props.global.companyInfo.institutionType == '0102' || this.props.global.companyInfo.institutionType == '0104')
          ) {
            store.set('addPersonModalTime', nowTimeStamp);
            $nModal({
              title: '保险增员提示',
              destroyOnClose: true,
              okText: "马上办理",
              cancelText: '取消',
              content: <div>
                <p style={{ color: '#ff4d4f', fontSize: 14 }}>*保险产品的新增、减员等操作可通过【人员投保管理】-【未投保】【已投保】选择相应人员进行保全增减操作！</p>
                <p style={{ fontSize: 16 }}>
                  本次新增人员 {successCount} 位，还存在 {unInsureNum} 位人员未投保，执行任务存在风险，请及时为其投保，以减轻企业负担！
                </p>
              </div>,
              onOk: close => {
                close();
                this.props.history.push('/insurancemanagement/insurance-management?tab=1');
              }
            });
            // this.props.dispatch({
            //   type: 'insurance/showQuitModal',
            //   payload: {
            //     title: '保险增员提示',
            //     type: 'add',
            //     warningText: '*保险产品的新增、减员等操作可通过【人员投保管理】-【未投保】【已投保】选择相应人员进行保全增减操作！',
            //     contentText: `本次新增人员 ${successCount} 位，还存在 ${unInsureNum} 位人员未投保，执行任务存在风险，请及时为其投保，以减轻企业负担！`,
            //     okCallBack: () => {
            //       this.props.history.push('/insurancemanagement/insurance-management?tab=1');
            //     }
            //   }
            // });
          } else {
            message.success(msg);
          }
        } else {
          message.error(msg);
        }
        this.setState({
          loading: false
        });
      }
    };
    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        render:(text,record,index)=>{
          return <span>{index+1}</span>
        }
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '身份证号',
        dataIndex: 'idCardNo',
        key: 'idCardNo',
        render:(text)=> {
          return<span>{text}&nbsp;</span>
        }
      },
      {
        title: '手机号',
        dataIndex: 'mobilePhone',
        key: 'mobilePhone',
        render:(text)=> {
          return<span>{text}&nbsp;</span>
        }
      },
      {
        title: '入单原因',
        dataIndex: 'reason',
        key: 'reason',
      }
    ];
    return (
      <div>
        <div
          style={{
            position: 'fixed',
            width: '100%',
            height: '100%',
            top: 0,
            left: 0,
            zIndex: 99999,
            display: this.state.loading ? 'block' : 'none'
          }}
        >
          <div
            style={{
              width: '100%',
              height: '100%',
              background: 'rgba(0, 0, 0, .2)'
            }}
          />
          <Spin
            style={{
              position: 'absolute',
              top: '50%',
              left: '50%'
            }}
            // tip="正在导入数据，请稍后..."
            tip={(() => {
              return (
                <div>
                  <span>系统正在为您识别并导入数据内容...</span><br />
                  <span>若数据量较大，导入时间相对偏长，请耐心等待</span>
                </div>
              );
            })()}
          />
        </div>
        <Upload
          onChange={UploadChange}
          beforeUpload={beforeUpload}
          {...uploadExcel}
        >
          <Button type="primary">选择上传文件</Button>
        </Upload>
        <div style={{ display: this.state.faileDisabled }}>
          导入失败信息表：
          {this.state.failData&&
          <a
            type="primary"
            href={this.state.failData.fileUrl}
            style={{ color: 'red', textDecoration: 'underline' }}
            onClick={() => {
              this.setState({
                faileDisabled: 'none'
              });
            }}
          >
            点击下载
          </a>}
        </div>
        {
          this.state.blackNameList.length>0&& 
          <div style={{ marginTop: '20px',maxWidth:'1000px' }}> 
            <div style={{color:'red',fontSize:'16px'}}>本次成功导入入职的人员中以下人员为行业黑名单人员，若有疑问请咨询监管机构进行了解。</div>
            <Button type="primary" onClick={()=>{
              var excelContent = document.getElementById('black_name').innerHTML;
              var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";
              excelFile += "<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>";
              excelFile += "<body><table width='10%'  border='1'>";
              excelFile += excelContent;
              excelFile += "</table></body>";
              excelFile += "</html>";
              var link = "data:application/vnd.ms-excel;base64," + window.btoa(unescape(encodeURIComponent(excelFile)))
              var a = document.createElement("a");
              a.download = "黑名单.xls";
              a.href = link;
              a.click();
            }}>导出</Button>
            <Table
              id='black_name'
              dataSource={this.state.blackNameList}
              columns={columns}
              pagination={pageInitStudent}
            />
          </div>
        }
      </div>
    );
  };

  //导入通讯录
  // renderUploadResult = () => {
  //   const columns = [
  //     {
  //       title: '姓名',
  //       dataIndex: 'name',
  //       key: 'name',
  //       // fixed: 'left',
  //       width: '120'
  //     },
  //     {
  //       title: '证件类型',
  //       dataIndex: 'idCardType',
  //       key: 'idCardType'
  //     },
  //     {
  //       title: '证件号码',
  //       dataIndex: 'idCardNo',
  //       key: 'idCardNo'
  //     },
  //     {
  //       title: '手机号',
  //       dataIndex: 'mobilePhone',
  //       key: 'mobilePhone'
  //     },
  //     {
  //       title: '部门名称',
  //       dataIndex: 'departName',
  //       key: 'departName',
  //       width: '140px'
  //     },
  //     {
  //       title: '角色',
  //       dataIndex: 'roleName',
  //       key: 'roleName',
  //       width: '130px'
  //     },
  //     {
  //       title: '入职时间',
  //       dataIndex: 'entryDate',
  //       key: 'entryDate'
  //     },
  //     {
  //       title: '校验提示',
  //       dataIndex: 'errorMsg',
  //       key: 'errorMsg'
  //     }
  //   ];

  //   //格式错误列展示
  //   let uploadResponse = JSON.parse(JSON.stringify(this.state.uploadResponse));
  //   //后台的为null 统一转""
  //   uploadResponse = uploadResponse.map(val => {
  //     Object.keys(val).forEach(v => {
  //       if (v === 'entryDate') {
  //         val[v] = val[v].slice(0, 10);
  //       }
  //       if (!val[v]) {
  //         val[v] = '';
  //       }
  //     });
  //     return val;
  //   });
  //   //过滤，包含错误信息的数组
  //   const errorLength = uploadResponse.filter(
  //     val => val.errorMsg.trim() !== ''
  //   );
  //   const ifError = errorLength.length !== 0; //判断是否包含错误信息
  //   let alert = '';
  //   if (ifError) {
  //     //上传失败
  //     uploadResponse = uploadResponse.map(val => {
  //       if (val.errorMsg !== '') {
  //         val.errorMsg = val.errorMsg.replace(/<br>/, '').trim();
  //       }
  //       return val;
  //     });
  //     alert = (
  //       <Alert
  //         message={`本次上传失败，共 ${
  //           uploadResponse.length
  //           } 条员工数据，其中有 ${
  //           errorLength.length
  //           } 条员工的信息格式校验有误。请核对，若有误，则调整 excel`}
  //         type="error"
  //         showIcon
  //       />
  //     );
  //   } else {
  //     //上传成功
  //     alert = (
  //       <Alert
  //         message={`本次上传全部成功，共上传${
  //           uploadResponse.length
  //           }条员工数据。请再次核对，无误则确认导入~`}
  //         type="success"
  //         showIcon
  //       />
  //     );
  //     columns.pop();
  //   }

  //   return (
  //     <Modal
  //       title="导入通讯录"
  //       visible={this.state.visible}
  //       onOk={this.handleOk.bind(this, ifError)}
  //       okText={`${ifError ? '有误，稍后上传' : '确认无误'}`}
  //       onCancel={this.handleCancel}
  //       cancelText="取消"
  //       width="1200px"
  //     >
  //       {alert}
  //       <Table
  //         columns={columns}
  //         dataSource={uploadResponse}
  //         pagination={pageInitStudent}
  //         style={{ marginTop: '16px' }}
  //       />
  //     </Modal>
  //   );
  // };

  //加载格式错误提示框
  // renderUploadFormat = () => {
  //   const columnsFormat = [
  //     {
  //       title: '序号',
  //       dataIndex: 'index',
  //       key: 'index'
  //     },
  //     {
  //       title: '错误提示',
  //       dataIndex: 'info',
  //       key: 'info'
  //     }
  //   ];
  //   const { dataFormat } = this.state;
  //   const [total, ...errorInfo] = dataFormat.split('<br>');
  //   if (errorInfo.length !== 1) {
  //     errorInfo.pop();
  //   }
  //   const errorInfos = errorInfo.map((val, key) => {
  //     return {
  //       index: key + 1,
  //       info: val,
  //       key
  //     };
  //   });
  //   return (
  //     <Modal
  //       title="导入通讯录"
  //       visible={this.state.visibleFormat}
  //       onOk={this.handleFormatOk}
  //       okText="有误，稍后上传"
  //       onCancel={this.handleFormatOk}
  //       cancelText=""
  //     >
  //       <Alert
  //         message={`本次上传失败，共 ${total} 条员工数据，其中有 ${
  //           errorInfos.length
  //           } 条员工的信息格式校验有误。请核对，若有误，则调整 excel`}
  //         type="error"
  //         showIcon
  //       />
  //       <Table
  //         columns={columnsFormat}
  //         dataSource={errorInfos}
  //         pagination={pageInitStudent}
  //         style={{ marginTop: '16px' }}
  //       />
  //     </Modal>
  //   );
  // };

  render() {
    return (
      <div className="BatchImport">
        <div className="batch-content">
          <div className="batch-body">
            <div className="tabs-content">
              <Steps direction="vertical" size="small" current={1}>
                <Step
                  title="下载员工信息模板，批量填写员工信息"
                  description={this.handleClickLink()}
                />
                <Step
                  title="上传填写好的员工信息表"
                  description={this.handleClickUpload()}
                />
              </Steps>
            </div>
            <div className="upload">
              {/* <Button size="large" type="primary" onClick={this.showModal}>
                确认上传
              </Button> */}
              {/* 导入通讯录弹窗 */}
              {/* {this.renderUploadResult()} */}

              {/*格式错误提示框*/}
              {/* {this.renderUploadFormat()} */}
            </div>
          </div>
        </div>
        <Modal
          className="reducepeople"
          title="保险员增员提示"
          visible={this.state.addpeoplevisible}
          onOk={this.handlereducepeopleOk}
          onCancel={() => this.setState({ addpeoplevisible: false })}
          footer={[
            <Button
              key="cancel"
              onClick={() => this.setState({ addpeoplevisible: false })}
            >
              取消
            </Button>,
            <Button
              key="submit"
              type="primary"
              onClick={() => {
                this.setState({
                  addpeoplevisible: false,
                  addpeoplevisible1: true
                });
              }}
            >
              马上办理
            </Button>
          ]}
        >
          <div>
            <div>
              <Alert
                message="保险产品的增员、减员、替换等操作可通过【金融保险】-【保险订单】-选择有效订单的【保全】对保单中的人员增减操作！"
                type="warning"
                showIcon
              />
            </div>
            <p>
              本次新增人员共
              {this.state.perIds.length}
              位，企业目前已购买团意险产品[产品名称]（订单号：[订单编号]），企业可对新增人员办理保险保全的增员操作。
            </p>
          </div>
        </Modal>

        <Modal
          width={1000}
          title="选择订单"
          visible={this.state.addpeoplevisible1}
          onCancel={() => this.setState({ addpeoplevisible1: false })}
          footer={[
            <Button
              key="submit1"
              onClick={() => {
                this.setState({ addpeoplevisible1: false });
              }}
            >
              取消
            </Button>,
            <Button
              key="submit"
              type="primary"
              onClick={() => {
                if (!this.state.selectedRowKeys) {
                  message.error('请选择订单');
                  return null;
                }
                newwin = window.open('about:blank');
                this.enterpriseInsComInsGetOnlineInsBlbPreservationLink();
              }}
            >
              确认
            </Button>
          ]}
        >
          {this.renderTable()}
        </Modal>
      </div>
    );
  }
}

const pageInitStudent = {
  defaultPageSize: 10,
  showQuickJumper: true,
  pageSizeOptions: ['10', '20', '50'],
  showSizeChanger: true
};
