import React, { Component } from 'react';
import {
  Alert,
  Steps,
  Upload,
  message,
  Button,
  Modal,
  Table,
  Spin
} from 'antd';
import store from 'store';
import './batch.less';
import {
  host,
  systemComDepartImportDepart,
  systemComVaseInfoGet //获取部门信息
} from '../../../../services/api';
import axios from 'axios';

const { Step } = Steps;
let newwin;
// 批量导入-新建组织机构
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
    };
  }
  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}
      />
    );
  };


  //格式错误提示框
  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/per-cer-baseinfo/export-per-cer-temp`, //后台请求地址
            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/per-cer-baseinfo/import-excel-per-cer`,
      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;
      }
      if(file.size/1024/1024 > 1.5){
        this.setState({
          loading:false
        });
        message.error('请上传小于1.5M文件!');
        ifError = false;
      }
      return ifError;
    };

    //上传文件
    const UploadChange = 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;
        //"retType":"-1"为错误，data会有相应的路径值
        //"retType":"0"为正确，data为空
        if (retType === '-1') {
          message.error(msg);
          this.setState({
            faileDisabled: 'block',
            failData: data
          });
        } else if (retType === '0') {
          message.success(msg);
        } else {
          message.error(msg);
        }
        this.setState({
          loading: false
        });
      }
    };
    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 }}>
          导入失败信息表：
          <a
            type="primary"
            href={this.state.failData}
            style={{ color: 'red', textDecoration: 'underline' }}
            onClick={() => {
              this.setState({
                faileDisabled: 'none'
              });
            }}
          >
            点击下载
          </a>
        </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
};
