/*
 * Create:      柿子
 * CreateDate:  2022/09/02
 * Describe：   配镜管理 - 病人退镜
 * */
import React, { Component } from 'react';
import { Card, Button, Radio, Tooltip, message, Popconfirm, Select } from 'antd';
import { Util, dayFormat } from 'tools';
import { $loadTemplate } from 'pages/lodop/Common/Print.js';
import store from 'store';
import moment from 'moment';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import GetPatientInformation from '../component/GetPatientInformation';
import RangeDatePicker from 'components/rangePicker/index';
import ReturnOrder from './component/ReturnOrder';
import iconListvisits from 'assets/images/icon_listvisits.png';
import iconMessages from 'assets/images/icon_messages.png';
import './style/index.less';

class PatientWithdrawal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectData: {},
      startDate: moment().format(dayFormat),
      endDate: moment().format(dayFormat),
      cardType: [],
      cardSelectData: [],
      orderPage: 1,
      orderPageSize: 20,
      orderTotal: 0,
      orderLoading: false,
      orderColumns: [],
      orderTotalWidth: 1360,
      orderTableData: [],
      orderRowID: '',
      orderRowData: {},
      withdrawStatus: '1',
      selectedRowKeys: [],
      selectedRows: [],
      detailsLoading: false,
      detailsColumns: [],
      detailsTotalWidth: 1080,
      detailsTableData: [],
      waitingForMirrorRetraction: 0, // 待退镜
      mirrorBacked: 0, // 已退镜
      cancelBtnLoading: false,
      skipFlag: 'N', // 取镜标志
    };

    // 订单列表
    this.staticOrderColumns = [{
      key: 1,
      title: '姓名',
      dataIndex: 'patName',
      align: 'center',
      width: 100
    }, {
      key: 2,
      title: '性别',
      dataIndex: 'sexDesc',
      align: 'center',
      width: 80
    }, {
      key: 3,
      title: '年龄',
      dataIndex: 'patAge',
      align: 'center',
      width: 80
    }, {
      key: 4,
      title: '病人ID',
      dataIndex: 'patNo',
      align: 'center',
      width: 100
    }, {
      key: 5,
      title: '订单编号',
      dataIndex: 'reqNo',
      align: 'center',
      width: 150
    }, {
      key: 6,
      title: '订单金额',
      dataIndex: 'ordAmt',
      align: 'center',
      width: 100
    }, {
      key: 7,
      title: '收费日期',
      dataIndex: 'payDateTime',
      align: 'center',
      width: 150
    }, {
      key: 8,
      title: '收费员',
      dataIndex: 'payUserDesc',
      align: 'center',
      width: 100
    }, {
      key: 9,
      title: '开单日期',
      dataIndex: 'createDateTime',
      align: 'center',
      width: 150
    }, {
      key: 10,
      title: '取镜日期',
      dataIndex: 'takeDateTIme',
      align: 'center',
      width: 150
    }, {
      key: 11,
      title: '开单人员',
      dataIndex: 'createUserDesc',
      align: 'center',
      width: 100
    }, {
      key: 12,
      title: '订单状态',
      dataIndex: 'statusDesc',
      align: 'center',
      width: 100
    }];

    // 订单详情
    this.staticDetailsColumns = [{
      key: 1,
      title: '订购产品',
      dataIndex: 'medDesc',
      align: 'center',
      width: 200
    }, {
      key: 2,
      title: '眼别',
      dataIndex: 'partDesc',
      align: 'center',
      width: 80
    }, {
      key: 3,
      title: '申请数量',
      dataIndex: 'qty',
      align: 'center',
      width: 100,
      // render: (text, record, index) => {
      //   return (
      //     <Input
      //       placeholder="请输入"
      //       type="number"
      //       className="input-number"
      //       style={{ width: '90%' }}
      //       value={record['qty']}
      //       onChange={e => this.handleApplicationsNumChange('qty', index, e.target.value)}
      //     />
      //   )
      // }
    }, {
      key: 4,
      title: '可退数量',
      dataIndex: 'qty',
      align: 'center',
      width: 100
    }, {
      key: 5,
      title: '总数量',
      dataIndex: 'qty',
      align: 'center',
      width: 100
    }, {
      key: 6,
      title: '已退数量',
      dataIndex: 'qty',
      align: 'center',
      width: 100
    }, {
      key: 7,
      title: '单位',
      dataIndex: 'unitDesc',
      align: 'center',
      width: 100
    }, {
      key: 8,
      title: '总金额',
      dataIndex: 'patAmt',
      align: 'center',
      width: 100
    }, {
      key: 9,
      title: '收费状态',
      dataIndex: 'billStatusDesc',
      align: 'center',
      width: 100
    }, {
      key: 10,
      title: '申请人',
      dataIndex: 'rtnUserDesc',
      align: 'center',
      width: 100
    }, {
      key: 11,
      title: '退镜时间',
      dataIndex: 'rtnDate',
      align: 'center',
      width: 150
    }]
  }

  componentDidMount() {
    this.getSelectData();
    this.getOrderColumns();
    this.getDetailsColumns();
    this.patientRef && this.patientRef?.getCardSelectData();
  }

  componentWillUnmount() {
    this.setState = (state, callback) => { return; }
  }

  // 获取下拉数据
  getSelectData = async () => {
    try {
      const { startDate, endDate } = this.state;
      let res = await React.$asyncPost(this, '17030058');
      let selectData = res?.result || {};
      let skipList = selectData?.skipFlag || [];
      let skipFlag = 'N';
      for (let i = 0; i < skipList.length; i++) {
        if (skipList[i]?.default === 'Y' || skipList[i]?.defaultValue === 'Y') {
          skipFlag = skipList[i]?.id;
          break;
        }
      }
      this.setState({
        skipFlag,
        selectData,
        endDate: selectData?.endDate || endDate,
        startDate: selectData?.startDate || startDate,
      }, () => {
        this.getOrderTableData();
      });
    } catch (error) {
      this.setState({ selectData: {} });
    }
  }

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

  // 查询患者列表
  handleQuery = () => {
    this.setState({ orderPage: 1 }, () => {
      this.getOrderTableData();
    })
  }

  // 获取订单列表表头数据
  getOrderColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'PatientWithdrawalOrderC',
          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 : [];
      if (columns && columns.length > 0) {
        columns = columns.map(item => {
          return {
            ...item,
            render: (text, record) => {
              if (item.dataIndex === 'statusDesc') {
                return (
                  <Tooltip title={text}>
                    <span className={record.statusCode === '07' ? 'common-record-delete-span' : '' + ' ellipsis'} style={{ width: '100%', display: 'block' }}>{text}</span>
                  </Tooltip>
                );
              } else {
                return (
                  <Tooltip title={text}>
                    <span className="ellipsis" style={{ width: '100%', display: 'block' }}>{text}</span>
                  </Tooltip>
                );
              }
            },
          }
        })
        this.setState({
          orderColumns: columns,
          orderTotalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ orderPage: page, orderPageSize: pageSize }, () => {
      this.getOrderTableData();
    })
  }

  // 获取病人订单列表数据
  getOrderTableData = async () => {
    try {
      this.setState({ orderLoading: true });
      const { startDate, endDate, orderPageSize, orderPage, skipFlag } = this.state;
      const patID = this.patientRef && this.patientRef.getPatientID();
      let data = {
        params: [{
          startDate,
          endDate,
          patInfo: patID,
          skipFlag
        }],
        pagination: [{
          pageSize: orderPageSize,
          currentPage: orderPage
        }]
      }
      let res = await React.$asyncPost(this, '17030053', data);
      let orderTableData = res.result && 'rows' in res.result ? Util.addKeyValueToDataSource(res.result.rows) : [];
      this.setState({ orderTableData, orderTotal: res.result?.total, orderLoading: false, orderRowID: '', orderRowData: {} }, () => {
        this.clearRowData();
      });
    } catch (error) {
      this.setState({ orderTableData: [], orderLoading: false, orderRowID: '', orderRowData: {} }, () => {
        this.clearRowData();
      });
    }
  }

  // 操作行
  handleOrderRowClick = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.orderRowID === '' || (this.state.orderRowID && (this.state.orderRowID !== record.glassesRequestID))) {
          let statusID = record?.statusID || ''; // 根据选中数据默认退镜状态
          this.setState({ orderRowID: record.glassesRequestID, withdrawStatus: statusID === '4' ? '2' : '1', orderRowData: record }, () => {
            this.getDetailsTableData();
          })
        } else {
          this.setState({ orderRowID: '', orderRowData: {} }, () => {
            this.clearRowData();
          });
        }
      }
    }
  }

  // 选中行操作
  handleOrderRowClassName = (record) => {
    return record.glassesRequestID === this.state.orderRowID ? 'clickRowStyle' : '';
  }

  // 切换退镜状态
  handleWithdrawStatusChange = e => {
    this.setState({ withdrawStatus: e.target.value, selectedRowKeys: [], selectedRows: [] });
  }

  // 获取订单列表表头数据
  getDetailsColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'PatientWithdrawalDetailsC',
          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 : [];
      if (columns && columns.length > 0) {
        columns = columns.map(item => {
          return {
            ...item,
            render: (text, record) => {
              if (item.dataIndex === 'exchange' && text === '是') {
                return (
                  <span style={{ color: 'red' }}>{text}</span>
                );
              } else {
                return text;
              }
            },
          }
        })
        this.setState({
          detailsColumns: columns,
          detailsTotalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 获取订单详情
  getDetailsTableData = async () => {
    try {
      this.setState({ detailsLoading: true });
      const { orderRowID } = this.state;
      let data = {
        params: [{
          glassesRequestID: orderRowID,
        }]
      }
      let res = await React.$asyncPost(this, '17030055', data);
      let detailsTableData = Util.addKeyValueToDataSource((res.result && 'rows' in res.result ? res.result.rows : (res?.result || [])), 'exeID');
      let waitingForMirrorRetraction = 0, mirrorBacked = 0;
      for (var i = 0; i < detailsTableData.length; i++) {
        if (detailsTableData[i].statusCode === 'R') {
          mirrorBacked += 1;
        } else {
          waitingForMirrorRetraction += 1;
        }
      }
      this.setState({
        detailsTableData,
        waitingForMirrorRetraction,
        mirrorBacked,
        detailsLoading: false,
        selectedRowKeys: [],
        selectedRows: [],
      });
    } catch (error) {
      this.setState({ detailsLoading: false });
      this.clearRowData();
    }
  }

  // 清除操作数据
  clearRowData = () => {
    this.setState({
      detailsTableData: [],
      waitingForMirrorRetraction: 0,
      mirrorBacked: 0,
      selectedRowKeys: [],
      selectedRows: [],
    });
  }

  // 申请数量change事件
  handleApplicationsNumChange = (dataIndex, index, e) => {
    let { detailsTableData } = this.state;
    detailsTableData[index][dataIndex] = e;
    this.setState({});
  }

  // 切换状态过滤订单详情列表
  filterDetailsTableData = () => {
    let { detailsTableData, withdrawStatus } = this.state;
    let filterData = detailsTableData && detailsTableData.filter(item => {
      if (withdrawStatus === '2') {
        return item.statusCode === 'R';
      } else {
        return item.statusCode !== 'R';
      }
    });
    return filterData;
  }

  // 退镜
  handleMirrorRetraction = async () => {
    const { orderRowID } = this.state;
    let filterDetailsData = this.filterDetailsTableData();
    let selectInfo = {};
    let partDesc = ''; // 眼别
    let patAmt = 0; // 退镜金额
    for (let i = 0; i < filterDetailsData.length; i++) {
      let currentIndex = i;
      partDesc += (currentIndex > 0 ? '、' : '') + filterDetailsData[i].partDesc;
      patAmt += Number(filterDetailsData[i].patAmt);
    }
    selectInfo.partDesc = partDesc;
    selectInfo.patAmt = patAmt;
    selectInfo.glassesRequestID = orderRowID;
    this.returnOrderRef && this.returnOrderRef.modifyVisible(true, selectInfo);
  }

  // 确认退镜 - otherParams(reasonID: 退镜原因, exchange: 需换货)
  handleConfirmMirrorRetraction = async (otherParams = {}, httpCode = '17030056', isPrint) => {
    try {
      let filterDetailsData = this.filterDetailsTableData();
      let selectedRowKeys = [];
      for (var i = 0; i < filterDetailsData.length; i++) {
        selectedRowKeys.push(filterDetailsData[i].exeID);
      }
      let { orderRowID, selectData, orderRowData } = this.state;
      let data = {
        params: [{
          ...otherParams,
          glassesRequestID: orderRowID,
          exeIDArr: selectedRowKeys,
          skipFlag: orderRowData?.skipFlag || ''
        }]
      }
      let res = await React.$asyncPost(this, httpCode, data);
      message.success(res?.errorMessage || '退镜成功');
      this.getOrderTableData();
      this.setState({ cancelBtnLoading: false });
      otherParams && otherParams.reasonID && this.returnOrderRef && this.returnOrderRef.modifyVisible(false, '', '', 'Y');
      if (isPrint !== 'none' && selectData && 'autoPrintRtnFlag' in selectData && selectData.autoPrintRtnFlag === 'Y') {
        this.handlePrint(orderRowID);
      }
    } catch (error) {
      console.log(error);
      this.setState({ cancelBtnLoading: false });
      otherParams && otherParams.reasonID && this.returnOrderRef && this.returnOrderRef.clearLoading();
    }
  }

  // 取消退镜 - 取消退镜不需要打印
  handleCancelMirrorRetraction = () => {
    this.setState({ cancelBtnLoading: true }, () => {
      this.handleConfirmMirrorRetraction({}, '17030069', 'none');
    });
  }

  // 打印单据
  handlePrint = async (glassesRequestID) => {
    try {
      let { orderRowID } = this.state;
      let data = {
        params: [{
          glassesRequestID: glassesRequestID ? glassesRequestID : orderRowID
        }]
      }
      let res = await React.$asyncPost(this, '17030075', data);
      let dataArr = res?.result || [];
      dataArr && dataArr.map((item, i) => {
        $loadTemplate(item.template, item.printStr);
      })
    } catch (error) {
      console.log(error);
    }
  }

  render() {
    const { endDate, startDate, orderColumns, orderLoading, orderPage, orderTotal, orderTableData, withdrawStatus, detailsLoading, orderTotalWidth, detailsColumns, cancelBtnLoading,
      detailsTotalWidth, waitingForMirrorRetraction, mirrorBacked, selectData, skipFlag } = this.state;
    // let rowSelection = {
    //   selectedRowKeys,
    //   selectedRows,
    //   onChange: (selectedRowKeys, selectedRows) => {
    //     this.setState({
    //       selectedRowKeys,
    //       selectedRows,
    //     })
    //   }
    // };
    let filterDetailsData = this.filterDetailsTableData();
    return (
      <div className="patient-withdrawal table-body-height">
        <div style={{ height: '64px', padding: '16px 24px' }}>
          <div style={{ display: 'inline-block', marginRight: 15 }}>
            <RangeDatePicker
              width="300px"
              label="取镜日期："
              isChange={true}
              endDate={endDate}
              startDate={startDate}
              format={dayFormat}
              endChange={(e) => this.handleModifyInputValue(e, 'endDate')}
              startChange={(e) => this.handleModifyInputValue(e, 'startDate')}
            />
          </div>
          <GetPatientInformation parLabelClass="common-input-label" queryType="fuzzySearch" onRef={ref => this.patientRef = ref} handleQuery={this.getOrderTableData} />
          {/* 取镜状态：<Select
            allowClear
            showSearch
            optionFilterProp="seachprop"
            placeholder="请选择"
            className="common-query-input"
            value={skipFlag}
            onChange={(e) => this.handleModifyInputValue(e, 'skipFlag')}
          >
            {React.$SelectOptions(selectData?.skipFlag || [])}
          </Select> */}
          <Button type="primary" onClick={this.getOrderTableData}>查询</Button>
        </div>
        <div className="common-query-split-line" style={{ height: 8 }}></div>
        <div>
          <Card
            size="small"
            title={(
              <div className="card-title-left-img">
                <img src={iconListvisits} alt="" />
                取镜订单
              </div>
            )}
          >
            <PubilcTablePagination
              param={{
                loading: orderLoading,
                data: orderTableData, // 表格数据
                x: orderTotalWidth, // 表格的宽度
                y: store.getState().tableHeight.y / 2 - 50,
                height: store.getState().tableHeight.y / 2 + 'px',
                page: orderPage,
                pageSize: '20',
                total: orderTotal,
                columns: orderColumns && orderColumns.length > 0 ? orderColumns : this.staticOrderColumns, // 表头配置
                componentName: 'PatientWithdrawalOrderC',
              }}
              compilePage={this.compilePage}
              getColumns={this.getOrderColumns}
              onClickRowPublic={this.handleOrderRowClick}
              setRowClassNamePublic={this.handleOrderRowClassName}
            />
          </Card>
          <div className="common-query-split-line" style={{ height: 8 }}></div>
          <Card
            size="small"
            title={(
              <div className="card-title-left-img">
                <img src={iconMessages} alt="" />
                订单详情
              </div>
            )}
          >
            <div style={{ paddingBottom: 8 }} className="flex-between-center">
              <Radio.Group
                size="small"
                buttonStyle="solid"
                value={withdrawStatus}
                onChange={this.handleWithdrawStatusChange}
              >
                <Radio.Button value="1">待退镜({waitingForMirrorRetraction || 0})</Radio.Button>
                <Radio.Button value="2">已退镜({mirrorBacked || 0})</Radio.Button>
              </Radio.Group>
              {withdrawStatus === '1' ? (
                <Button ghost type="danger" onClick={this.handleMirrorRetraction} disabled={!(filterDetailsData && filterDetailsData.length > 0)}>退镜</Button>
              ) : (
                <div>
                  <Button
                    style={{ marginRight: 12 }}
                    ghost
                    type="primary"
                    // disabled={!(filterDetailsData && filterDetailsData.length > 0)}
                    disabled={!(filterDetailsData && filterDetailsData.length > 0)}
                    onClick={() => this.handlePrint()}
                  >
                    打印单据
                  </Button>
                  {filterDetailsData && filterDetailsData.length > 0 ? (
                    <Popconfirm placement="topRight" title="撤销后不可恢复，确定撤销退镜吗?" onConfirm={this.handleCancelMirrorRetraction}>
                      <Button
                        ghost
                        type="danger"
                        loading={cancelBtnLoading}
                      >
                        撤销退镜
                      </Button>
                    </Popconfirm>
                  ) : (
                    <Button ghost type="danger" disabled>撤销退镜</Button>
                  )}
                </div>
              )}
            </div>
            <PubilcTablePagination
              param={{
                loading: detailsLoading,
                data: filterDetailsData, // 表格数据
                x: detailsTotalWidth, // 表格的宽度
                y: store.getState().tableHeight.y / 2 - 90,
                height: store.getState().tableHeight.y / 2 - 40 + 'px',
                componentName: 'PatientWithdrawalDetailsC',
                columns: detailsColumns && detailsColumns.length > 0 ? detailsColumns : this.staticDetailsColumns, // 表头配置
              }}
              // rowSelectionPublic={rowSelection}
              getColumns={this.getDetailsColumns}
            />
          </Card>
        </div>
        {/* 退镜原因 */}
        <ReturnOrder selectData={selectData} componentSource="mirrorRetraction" confirmMirrorRetraction={this.handleConfirmMirrorRetraction} onRef={ref => this.returnOrderRef = ref} />
      </div>
    )
  }
};

export default PatientWithdrawal;