/*
 * Create:      柿子
 * CreateDate:  2022/10/10
 * Describe：   下载任务
 * */
import React, { Component } from 'react';
import { Modal, Badge, Button, Row, Col, Icon, message } from 'antd';
import { Util, dayFormat } from 'tools';
import store from 'store';
import moment from 'moment';
import RangeDatePicker from 'components/rangePicker/index';
import PublicTablePagination from 'pages/common/PubilcTablePagination.jsx';
import SVGLoading from 'assets/images/svg/loading.svg';
import SVGDownloadComplete from 'assets/images/svg/download-complete.svg';
import './style/index.less';

class DownloadTask extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      queryParams: {
        startDate: moment().format(dayFormat), // 开始日期
        endDate: moment().format(dayFormat), // 结束日期
      },
      total: 0,
      page: 1,
      pageSize: 20,
      loading: false,
      totalWidth: 500,
      tableData: [],
      columns: [],
      rowID: '',
      timeStamp: '',
      loadingNum: 0, //正在加载的数量
    };
    this.staticColumns = [
      {
        key: 1,
        title: '医院名称',
        dataIndex: 'hospName',
        align: 'center',
        width: 150
      }, {
        key: 2,
        title: '起始日期',
        dataIndex: 'startDate',
        align: 'center',
        width: 100
      }, {
        key: 3,
        title: '截止日期',
        dataIndex: 'endDate',
        align: 'center',
        width: 100
      }, {
        key: 4,
        title: '操作',
        dataIndex: 'operName',
        align: 'center',
        width: 80
      }, {
        key: 5,
        title: '记录日期',
        dataIndex: 'createDate',
        align: 'center',
        width: 100
      }, {
        key: 6,
        title: '状态',
        dataIndex: 'status',
        align: 'center',
        width: 80
      }];
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    store.subscribe(() => {
      const state = store.getState();
      let downloadParams = state.userRedux.downloadParams;
      if (downloadParams && downloadParams.timeStamp && (downloadParams.timeStamp !== this.state.timeStamp)) {
        this.setState({
          timeStamp: downloadParams.timeStamp,
          queryParams: {
            startDate: downloadParams?.startDate || this.state.queryParams.startDate,
            endDate: downloadParams.endDate || this.state.queryParams.endDate
          }
        }, () => {
          if (downloadParams?.visible === 'Y') {
            this.modifyVisible(true);
          } else {
            this.handleQuery();
          }
        })
      }
    })
  }

  // 修改弹窗状态
  modifyVisible = (visible) => {
    const { columns } = this.state;
    if (visible && columns && columns.length === 0) {
      this.getColumnsData();
    }
    this.setState({ visible }, function () {
      this.handleQuery();
    });
  }

  // 获取表头数据
  getColumnsData = async () => {
    try {
      const { renderFlag } = this.props;
      if (renderFlag === 'icon') return;
      let data = {
        params: [{
          compontName: 'DownloadTask',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
      this.renderList(columns);//对指定的列进行渲染操作
      if (columns && columns.length > 0) {
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 修改操作框数据
  handleModifyInputValue = (e, dataIndex) => {
    this.state.queryParams[dataIndex] = e;
    this.setState({}, () => {
      if (dataIndex === 'startDate' || dataIndex === 'endDate') {
        this.handleQuery();
      }
    })
  };

  // 查询
  handleQuery = () => {
    this.setState({ page: 1, rowID: '' }, () => {
      this.getTableData();
    })
  };

  //对表头列进行渲染操作
  renderList = (columnsValue) => {
    for (let i = 0; i < columnsValue.length; i++) {
      //状态渲染
      if (columnsValue[i].dataIndex === 'createDate') {
        columnsValue[i].render = (text, record) => {
          return (<span>{text} {record.createTime}</span>)
        }
      }
      //状态渲染
      if (columnsValue[i].dataIndex === 'status') {
        columnsValue[i].render = (text, record) => {
          if (+text === 2) {
            return (<span style={{ color: '#45B38E' }}>导出成功</span>)
          } else if (+text === 99) {
            return (<span style={{ color: '#EE3F3F' }}>导出失败</span>)
          } else if (+text === 0) {
            return (<span style={{ color: '#eeaa03' }}>队列中</span>)
          } else if (+text === 1) {
            return (<span style={{ color: '#0c74ee' }}>导出中</span>)
          }
        }
      }
    }
  };

  // 请求列表数据
  getTableData = async () => {
    try {
      const { renderFlag } = this.props;
      if (renderFlag === 'icon') return;
      this.setState({ loading: true })
      let { queryParams, pageSize, page } = this.state;
      let data = {
        params: [{
          ...queryParams
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      };

      let res = await React.$asyncPost(this, '11020001', data);
      let tableData = res.result && 'rows' in res.result ? Util.addKeyValueToDataSource(res.result.rows) : [];

      let loadingNum = 0; //正在导出中个数
      for (let i = 0; i < tableData.length; i++) {
        let retObj = tableData[i];
        if (retObj.status === 0) {
          loadingNum++;
        }
      }
      this.setState({ tableData, total: res.result.total, loadingNum, loading: false });
    } catch (error) {
      message.error(error)
    }
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.key))) {
          this.setState({ rowID: record.key });
        } else {
          this.setState({ rowID: '' });
        }
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    return record.key === this.state.rowID ? 'clickRowStyle' : '';
  }

  // 获取相对应的图标
  getSvgImage = () => {
    let { tableData } = this.state;
    let isLoading = false;
    for (var i = 0; i < tableData.length; i++) {
      if (+tableData[i].status === 0) {
        isLoading = true;
        break;
      }
    }
    // 都下载完成显示SVGDownloadComplete,下载中显示SVGLoading，自行判断
    return isLoading ? SVGLoading : SVGDownloadComplete;
  }


  render() {
    const { renderFlag } = this.props;
    const { queryParams, visible, total, page, loading, totalWidth, tableData, columns, loadingNum } = this.state;

    // 列表操作
    const operationObj = {
      width: 100,
      title: '操作',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <span>
          {+record.status === 2 ?
            <a className='span' download="" href={record.downloadURL}><Icon type="download" /> 下载</a> :
            <span style={{ color: '#ccc' }}><Icon type="download" /> 下载</span>
          }
        </span>
      )
    };
    return (
      <>
        {renderFlag === 'icon' ? (
          <Badge count={loadingNum} className="download-task-badge">
            <span style={{ padding: '0 6px', cursor: 'pointer', display: 'inline-block' }} onClick={this.props.iconClick ? this.props.iconClick : () => this.modifyVisible(true)}>
              <embed style={{ pointerEvents: 'none' }} src={this.getSvgImage()} type="image/svg+xml" />
            </span>
          </Badge>
        ) : ''}
        {renderFlag === 'icon' ? '' : (
          <Modal
            width="60vw"
            title="导出任务列表"
            footer={null}
            visible={visible}
            destroyOnClose={true}
            onCancel={() => this.modifyVisible(false)}
          >
            <div style={{ marginBottom: 12 }}>
              <Row>
                <Col span={18} className="flex">
                  <RangeDatePicker
                    width="280px"
                    label="日期选择："
                    isChange={true}
                    format={dayFormat}
                    startDate={queryParams?.startDate}
                    endDate={queryParams?.endDate}
                    startChange={(e) => this.handleModifyInputValue(e, 'startDate')}
                    endChange={(e) => this.handleModifyInputValue(e, 'endDate')}
                  />
                  <Button style={{ marginLeft: 12 }} onClick={this.handleQuery}>查询</Button>
                </Col>
              </Row>
            </div>
            <PublicTablePagination
              param={{
                page,
                total,
                loading,
                y: 400,
                height: 450,
                x: totalWidth,
                data: tableData,
                componentName: 'DownloadTask',
                columns: columns && columns.length > 0 ? [...columns, operationObj] : [...this.staticColumns, operationObj],
              }}
              compilePage={this.compilePage}
              getColumns={this.getColumnsData}
              onClickRowPublic={this.onClickRowPublic}
              setRowClassNamePublic={this.setRowClassNamePublic}
            />
          </Modal>
        )}
      </>
    )
  }
}

export default DownloadTask;