import React, { Component } from 'react';
import store from 'store';
import {
  Modal,
  Button,
  Upload,
  message
} from 'antd';
import { withRouter } from 'dva/router';
import $loading from '../../../../../utils/loading';
import {
  enterpriseInsComInsExportErrInsPer
} from '../../../../../services/api';
import { getHostByPath } from '../../../../../utils/config';
import st from 'styled-components';
@withRouter
export default class BulkInsuranceModal extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      errCount: 0,  //错误条数
      preImportBatchId: ''
    };
  }
  componentWillMount() {

  }
  componentWillReceiveProps(nextprops) {
    const { importBatchId } = nextprops;
    const { preImportBatchId } = this.state;
    if(importBatchId != preImportBatchId) {
      this.setState({
        preImportBatchId: importBatchId,
        errCount: 0
      });
    }
  }
  render() {
    return (
      <Modal
        title="导入投保人员"
        visible={this.props.visible}
        okText="下一步"
        okButtonProps={{disabled: (!this.props.importBatchId || this.props.importCount == 0)}}
        onOk={() => {
          if(this.props.importBatchId) {
            this.props.setParentState({
              bulkVisible: false,
              modalVisible: true
            });
          }
        }}
        cancelText="取消"
        onCancel={() => this.props.setParentState({
          bulkVisible: false
        })}
      >
        {/* 下载 */}
        <a
          href="/files/雇主人员范本.xls" target="_blank"
        >点击下载导入投保人员模板</a>


        <UploadContainer>
          <span style={{ marginRight: 15 }}>
            投保人员数据:
          </span>

          <Upload
            name="xfile"
            action= {getHostByPath()+'/enterprise/ins/com-ins/batch-upload-ins-per'}
            headers={{
              authorization: 'Basic c2Fhc3dlYjp3ZWI=',
              access_token: store.get('saas')['access_token']
            }}
            showUploadList={false}
            onChange={info => {
              if (info.file.status === 'uploading') {
                return;
              }
              if (info.file.status === 'done') {
                $loading.close();
                const { data, msg, retType } = info.file.response;
                //"retType":"-1"为错误，data会有相应的路径值
                //"retType":"0"为正确，data为空
                
                if (retType === '-1') {
                  message.error(msg);
                } else if (retType === '0') {
                  this.props.setParentState && this.props.setParentState({
                    importBatchId: data.importBatchId
                  });
                  message.info(`导入成功：${data.successCount}条, 导入失败：${data.errCount}条`);
                  if (data.errCount > 0) {  //错误条数（大于0可以做下载错误文件）
                    this.setState({
                      errCount: data.errCount
                    });
                  }
                  if (data.successCount > 0) { //正确条数（大于0可以提交增员保全）
                    
                    this.props.setParentState && this.props.setParentState({
                      // isImport: true,  //导入投保
                      importCount: +data.successCount
                    });
                  }
                } else {
                  message.error(msg);
                }
              }
            }}
            beforeUpload={file => {
              $loading.open(<div>
                <span>系统正在为您识别并导入数据内容...</span><br />
                <span>若数据量较大，导入时间相对偏长，请耐心等待</span>
              </div>);
              this.setState({
                errCount: 0
              });
              if (file.name.indexOf('xls') === -1 && file.name.indexOf('xlsx') === -1) {
                $loading.close();
                message.error('请上传xls或xlsx文件!');
                return false;
              }
              return true;
            }}
          >
            <Button type="primary">选择上传文件</Button>
          </Upload>
        </UploadContainer>

        {
          this.state.errCount > 0 &&
          <div style={{marginTop: 10}}>
            <span style={{ color: '#D9001B' }}>有人员数据无法识别，请下载失败文件查看，调整人员后重新导入。</span>
            <a onClick={() => {
              const { importBatchId } = this.props;
              enterpriseInsComInsExportErrInsPer({ importBatchId }).then(res => {
                if (!res) {
                  return;
                }
                let url = window.URL.createObjectURL(res.data);
                let link = document.createElement('a');
                link.style.display = 'none';
                link.href = url;
                link.setAttribute(
                  'download',
                  `导入投保失败文件.xls`
                );
                document.body.appendChild(link);
                link.click();
                // const content = response;
                // const blob = new Blob([content]);
                // const fileName = `导入投保失败文件.xls`;
                // if ("download" in document.createElement("a")) {
                //     // 非IE下载
                //     const elink = document.createElement("a");
                //     elink.download = fileName;
                //     elink.style.display = "none";
                //     elink.href = URL.createObjectURL(blob);
                //     document.body.appendChild(elink);
                //     elink.click();
                //     URL.revokeObjectURL(elink.href); // 释放URL 对象
                //     document.body.removeChild(elink);
                // } else {
                //     // IE10+下载
                //     navigator.msSaveBlob(blob, fileName);
                // }                
              });
            }}>下载失败文件</a>
          </div>
        }
      </Modal>

    );
  }
}

const UploadContainer = st.div`
  margin-top: 10px;
  display: flex;
  align-items: center;
`;
