/*
 * Create:      柿子
 * CreateDate:  2023/04/30
 * Describe：   取镜订单查询/取镜记录查询(MirrorOrderQuery) / 退镜订单查询(ReturnMirrorOrderQuery)
 * */
import React, { Component } from 'react';
import { Row, Col, message, Button, Card } from 'antd';
import { Util, dayFormat } from 'tools';
import { handleExcel } from 'tools/handleExcel';
import store from 'store';
import moment from 'moment';
import RangeDatePicker from 'components/rangePicker/index';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import GetPatientInformation from 'pages/optometry/component/GetPatientInformation';
import iconListvisits from 'assets/images/icon_listvisits.png';

class OrderQuery extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    this.state = {
      userData,
      queryParams: {},
      categoryData: {},
      selectData: {},
      queryFormData: [],
      page: 1,
      pageSize: 50,
      total: 0,
      loading: false,
      tableData: [],
      totalWidth: 0,
      columns: [],
      rowID: '',
      rowData: {},
      exportLoading: false,
      ERPExportLoading: false,
      GSPExportLoading: false
    };
  }

  componentDidMount() {
    let newCategory;
    if ('paras' in this.props && this.props.paras && this.props.paras.params) { // 侧菜单获取类别参数
      newCategory = this.props.paras.params;
    } else {
      if ('location' in this.props && this.props.location.state && this.props.location.state.params) { // 头菜单获取类别参数
        newCategory = this.props.location.state.params;
        React.$setSessionData('OrderQuery', newCategory, false);
      } else { // 头菜单刷新界面时获取类别
        newCategory = React.$getSessionData('OrderQuery', false);
      }
    }
    let categoryData = Util.getObjByUrlStr(newCategory);
    console.log('OrderQuery', categoryData);
    let defaultPageSize = categoryData?.paginationSize === 'small' ? (categoryData?.defaultPageSize || 10) : (categoryData?.defaultPageSize || 50); // 默认条数
    this.setState({ categoryData, pageSize: defaultPageSize }, () => {
      this.getSelectData();
      this.getTableColumns();
    });
  }

  // 组件销毁前将静止让setState修改state的状态
  componentWillUnmount() {
    this.setState = (state, callback) => { return; }
  }

  // 获取下拉框数据
  getSelectData = async () => {
    try {
      let { categoryData, queryParams, userData } = this.state;
      if (!(categoryData && categoryData.selectCode)) {
        return
      };
      let data = {
        params: [{
          hospID: userData?.hospID || '',
          status: categoryData?.groupType || undefined, // 界面标识
          groupType: categoryData?.groupType || undefined,
        }]
      }
      let res = await React.$asyncPost(this, categoryData.selectCode, data);
      let selectData = res.result;
      // 默认日期
      queryParams.startDate = selectData?.defaultValue?.startDate || moment().format(dayFormat);
      queryParams.endDate = selectData?.defaultValue?.endDate || moment().format(dayFormat);
      this.setState({ selectData, queryParams }, () => {
        this.getTableData();
      });
    } catch (error) {
      this.getTableData();
    }
  }

  // 获取表头数据
  getTableColumns = async () => {
    try {
      const { categoryData } = this.state;
      if (!(categoryData && categoryData.componentName)) {
        message.error('列表数据还未配置呢，快去配置先！');
        return;
      }
      let data = {
        params: [{
          compontName: categoryData.componentName,
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

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

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

  // 获取列表数据
  getTableData = async (isClear) => {
    try {
      let { pageSize, page, categoryData, queryParams } = this.state;
      if (!(categoryData && categoryData.queryCode)) {
        message.error('查询接口未配置，快去配置先！');
        return
      };
      this.setState({ loading: true });
      let patientInfo = this.patientRef && this.patientRef.getPatientInfo();
      let data = {
        params: [{
          ...queryParams,
          ...patientInfo,
          status: categoryData?.groupType || undefined, // 界面标识
          groupType: categoryData?.groupType || undefined,
          compontName: categoryData?.componentName || undefined,
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, categoryData.queryCode, data);
      let idIndex = categoryData?.idIndex || 'id';
      let tableData = Util.addKeyValueToDataSource(res.result && 'rows' in res.result ? res.result.rows : (Array.isArray(res.result) ? res.result : []), idIndex);
      this.setState({ tableData, total: res.result?.total || tableData.length, loading: false }, () => {
        isClear !== 'N' ? this.handleClearSelectData() : ''; // 清除操作数据
      });
    } catch (error) {
      console.log('错误', error)
      this.setState({ tableData: [], total: 0, loading: false }, () => {
        this.handleClearSelectData();
      });
    }
  }

  // 清除操作数据
  handleClearSelectData = () => {
    this.setState({ rowID: '', rowData: {} });
  }

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

  // 操作行
  onClickRowPublic = (record) => {
    const { categoryData } = this.state;
    let idIndex = categoryData?.idIndex || 'id';
    return {
      // 单击行选中
      onClick: () => {
        let rowID = record && idIndex in record ? record[idIndex] : record.key;
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== rowID))) {
          this.setState({ rowID, rowData: record });
        } else {
          this.handleClearSelectData();
        }
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    const { categoryData } = this.state;
    let idIndex = categoryData?.idIndex || 'id';
    let rowID = record && idIndex in record ? record[idIndex] : record.key;
    return rowID === this.state.rowID ? 'clickRowStyle' : '';
  }

  // 导出 
  handleExport = async () => {
    try {
      let { categoryData, queryParams } = this.state;
      if (!(categoryData && categoryData.exportCode)) {
        message.error('导出接口未配置，快去配置先！');
        return
      };
      this.setState({ exportLoading: true });
      let patientInfo = this.patientRef && this.patientRef.getPatientInfo();
      let data = {
        params: [{
          ...queryParams,
          ...patientInfo,
          status: categoryData?.groupType || undefined, // 界面标识
          groupType: categoryData?.groupType || undefined,
          compontName: categoryData?.componentName || undefined,
        }]
      }
      let res = await React.$asyncPost(this, categoryData.exportCode, data);
      handleExcel.downloadExcel(res.result);
      this.setState({ exportLoading: false });
    } catch (error) {
      this.setState({ exportLoading: false });
    }
  }

  // 其他导出 - ERP导出
  handleERPExport = async (type, exportCode, exportFlag) => {
    try {
      let { categoryData, queryParams } = this.state;
      if (!(categoryData && categoryData.mainListERPExportCode)) {
        message.error('ERP导出接口未配置，快去配置先！');
        return
      };
      this.state[type] = true;
      this.setState({});
      let patientInfo = this.patientRef && this.patientRef.getPatientInfo();
      let data = {
        params: [{
          ...queryParams,
          ...patientInfo,
          status: categoryData?.groupType || undefined, // 界面标识
          groupType: categoryData?.groupType || undefined,
          compontName: categoryData?.componentName || undefined,
        }]
      }
      let res = await React.$asyncPost(this, exportCode, data);
      if (categoryData && exportFlag in categoryData && categoryData[exportFlag] === 'Y') { // 前端导出标志
        handleExcel.downloadExcel(res.result);
      } else {
        let columns = res.result?.columns || [];
        let tableData = res.result?.rows || [];
        if (columns && columns.length > 0 && tableData && tableData.length > 0) {
          handleExcel.exportExcel(columns, tableData, res.result?.fileName || '订单查询', '', res.result?.type || 'xlsx', res.result?.sheetName || 'mySheet');
        } else {
          message.error('前端导出异常，请检查返回数据！');
        }
      }
      this.state[type] = false;
      this.setState({});
    } catch (error) {
      this.state[type] = false;
      this.setState({});
    }
  }

  render() {
    const { categoryData, selectData, page, total, loading, tableData, totalWidth, columns, exportLoading, queryParams, ERPExportLoading, GSPExportLoading } = this.state;

    return (
      <div className="dynamic-component">
        <Row style={{ minHeight: '64px', padding: '14px 12px 0' }}>
          <Col span={20} className="flex-align-items">
            <div style={{ marginRight: '12px' }}>
              <RangeDatePicker
                width="280px"
                isChange={true}
                format={dayFormat}
                label={categoryData?.componentName === 'MirrorOrderQuery' ? '取镜日期：' : '退镜日期：'}
                endDate={queryParams?.endDate || undefined}
                startDate={queryParams?.startDate || undefined}
                endChange={(e) => this.handleModifyInputValue(e, 'endDate')}
                startChange={(e) => this.handleModifyInputValue(e, 'startDate')}
              />
            </div>
            <GetPatientInformation
              // queryType="fuzzySearch"
              cardType={selectData?.cardType || []}
              cardSelectData={selectData?.cardSelectData || []}
              onRef={ref => this.patientRef = ref}
              handleQuery={this.handleQuery}
            />
            <Button type="primary" onClick={this.handleQuery}>查询</Button>
          </Col>
          <Col span={4} style={{ textAlign: 'right' }}>
            {categoryData?.mainListERPExportCode ? (
              <Button
                ghost type="primary"
                loading={ERPExportLoading}
                style={{ marginRight: '12px' }}
                onClick={() => this.handleERPExport('ERPExportLoading', categoryData?.mainListERPExportCode || '', 'interfaceExportERPFlag')}
              >
                {categoryData?.mainListEMRExportBtnTitle || '导出ERP明细'}
              </Button>
            ) : ''}
            {categoryData?.mainListGSPExportCode ? (
              <Button
                ghost type="primary"
                loading={GSPExportLoading}
                style={{ marginRight: '12px' }}
                onClick={() => this.handleERPExport('GSPExportLoading', categoryData?.mainListGSPExportCode || '', 'interfaceExportGSPFlag')}
              >
                {categoryData?.mainListGSPExportBtnTitle || '导出GSP明细'}
              </Button>
            ) : ''}
            {categoryData?.exportCode ? (
              <Button ghost type="primary" loading={exportLoading} onClick={this.handleExport}>{categoryData?.exportBtnTitle || '导出'}</Button>
            ) : ''}
          </Col>
        </Row>
        <div className="common-query-split-line"></div>
        <Card
          size="small"
          bordered={false}
          className="table-body-height"
          title={(
            <div className="card-title-left-img">
              <img src={iconListvisits} alt="" />
              {categoryData?.cardTitle || '订单列表'}
            </div>
          )}
          extra={(
            <div className="flex-align-items">
              <span className="common-record-color-notes" style={{ background: '#ffca93' }}></span>
              处方交换
            </div>
          )}
        >
          <PublicTablePagination
            param={{
              page,
              total,
              loading,
              columns, // 表头配置
              pageSize: categoryData?.defaultPageSize || '',
              size: categoryData?.paginationSize || 'large',
              componentName: categoryData?.componentName || '',
              data: tableData, // 表格数据
              x: totalWidth, // 表格的宽度
              y: store.getState().tableHeight.y + 15,
              height: store.getState().tableHeight.y + 65 + 'px',
            }}
            compilePage={this.compilePage}
            getColumns={this.getTableColumns}
            onClickRowPublic={this.onClickRowPublic}
            setRowClassNamePublic={this.setRowClassNamePublic}
          />
        </Card>
      </div>
    )
  }
};

export default OrderQuery;