import React from 'react';
import { Badge, Button, Divider, message, Modal, Table, Upload } from 'antd';
import pathToRegexp from 'path-to-regexp';
import { curry } from 'ramda';

import { config, networkUtils } from '@utils';

const { api } = config;
const { excel } = api;
const { exportExcelURL } = excel;

/**
 * 设置url上面参数 RESTful
 * @returns {string} 成功设置后的路径
 */
const toUrl = curry((url: string, obj: {}, queryStr: string): string => {
  if (!url) {
    throw 'Ineligible url to put RESTFul parameters.';
  }
  if (queryStr) {
    return pathToRegexp.compile(url)(obj) + queryStr;
  } else {
    return pathToRegexp.compile(url)(obj);
  }
});

class ExcelImport extends React.Component {
  constructor(props: object) {
    super(props);

    this.state = {
      batNo: {},
      sts: {},
      dataSource: [],
      columns: [{
        title: '导入目标',
        dataIndex: 'name',
        key: 'name',
        width: '20%',
      }, {
        title: '下载导入模板',
        dataIndex: 'temp',
        key: 'temp',
        width: '25%',
        render: (value, row, index) => {
          const temp = `/static/templates/${row.temp}.xlsx`;
          return (
            <a
              href={temp}
              download={row.tempName}
              target='_blank'
              style={{ textDecoration: 'underline' }}
            >
              {row.tempName}
            </a>
          );
        }
      }, {
        title: '上传文件',
        dataIndex: 'btn',
        key: 'btn',
        width: '20%',
        render: (value, row, index) => {
          return (
            <Upload
              accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              listType="text"
              multiple={false}
              // action="/api/import/excel/newItem",
              customRequest={(req) => this.handleUpload(req, row.aim, index, row.params)}
              showUploadList={false}
              // onRemove=this.handleRemove,
              // onPreview=this.handlePreview,
              // fileList
              // disabled
              // showUploadList={ showRemoveIcon: !disabled },
            >
              <Button icon="upload" size="small">选择文件</Button>
            </Upload>
          );
        }
      }, {
        title: '状态',
        dataIndex: 'sts',
        key: 'sts',
        width: '20%',
        render: (value, row, index) => {
          if (this.state.sts[row.aim] === '1') {
            return (<Badge status="success" text="已上传"/>);
          } else if (this.state.sts[row.aim] === '2') {
            return (
              <span>
                <Badge status="error" text="导入失败"/>
                <Divider type="vertical"/>
                <a href={`${exportExcelURL}/import-err?batNo=${this.state.batNo[row.aim]}`}>
                  <Button type="primary">下载错误日志</Button>
                </a>
              </span>
            );
          } else if (this.state.sts[row.aim] === '3') {
            return (<Badge status="error" text="服务端报错，请联系管理员"/>);
          } else {
            return (<Badge status="default" text="未上传"/>);
          }
        }
      }]
    };
  };

  componentDidMount = () => {
    this.fetchDataSource();
  };

  fetchDataSource = () => {
    this.setState({
      dataSource: this.props.dataSource
    });
  };

  public showModal = () => {
    this.props.dispatch({
      type: `${this.props.domain}/showUploadModal`,
      payload: true,
    });
  };

  public handleOk = () => {
    this.handleCancel();
  };

  public handleCancel = () => {
    this.setState({
      batNo: {},
      sts: {}
    });
    this.props.dispatch({
      type: `${this.props.domain}/showUploadModal`,
      payload: false,
    });
    if(!this.props.autoQuery === false){
      this.props.dispatch({
        type: `${this.props.domain}/query`,
        payload: this.searchStrToObj(location.search.split('?')[1])
      });
    }
  };

  // 将url中过滤条件（string）转成对象（obj）
  private searchStrToObj(str) {
    if (!str) return;
    // console.warn('str', str, str.substr(1))
    str = str.substr(1);
    let arr = str.split('&'),
      obj = {},
      newArr = [];
    arr.map(a => {
      newArr = a.split('=');
      obj[newArr[0]] = newArr[0] && decodeURIComponent(newArr[1]);
    });
    // console.warn('obj', obj)
    return obj;
  }

  public handleUpload = (req, apiName, index, params) => {
    const { batNo, sts } = this.state;
    // const { dispatch, domain } = this.props;

    const formData = new FormData();

    formData.append('file', req.file);

    let urlStr = '/api/import/excel/:apiName';
    let queryStr = "";

    // 将拓展的查询参数拼接到URL中
    if (params) {
      Object.keys(params).forEach(function (index) {
        if (params[index]) {
          queryStr = `&${queryStr}${index}=${params[index]}`
        } else {
          queryStr = `&${queryStr}${index}=`
        }
      });
      queryStr = `?${queryStr.substring(1)}`;
    }

    networkUtils.request({
      url: toUrl(urlStr, { apiName }, queryStr),
      method: 'upload',
      data: formData,
    }).then((data) => {
      if (data.success) {
        message.success('导入成功');
        sts[apiName] = '1';
        this.setState({
          sts
        });
        this.props.callback && this.props.callback(data.data);
      } else {
        message.error('导入失败');
        if (data.status === 500) {
          sts[apiName] = '3';
          this.setState({
            sts
          });
        } else {
          batNo[apiName] = data.data;
          sts[apiName] = '2';
          this.setState({
            batNo,
            sts
          });
        }
        // message.error('导入失败，请确认是否需要下载错误信息');
      }
    });
  };

  public render() {
    const { batNo, dataSource, columns } = this.state;
    const { showModal } = this.props;

    return (
      <Modal
        title="导入Excel"
        visible={showModal}
        width="60%"
        footer={<Button onClick={this.handleCancel}>关闭</Button>}
        // onOk={handleOk}
        onCancel={this.handleCancel}
      >
        <Table
          rowKey="aim"
          columns={columns}
          dataSource={dataSource}
          pagination={false}
          showHeader={true}
          bordered
        />
      </Modal>
    );
  };
};

export default ExcelImport;
