/*
 * Create:      柿子
 * CreateDate:  2023/06/28
 * Describe：   配镜管理 - 批量取镜
 * */
import React, { Component } from 'react';
import { Modal, Input, message, Select, Popconfirm } from 'antd';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import '../style/index.less';

class BatchMirrorRetrievalModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      loading: false,
      rowID: '',
      tableData: [],
      columns: [],
      totalWidth: 0,
      selectData: {},
      takeUserID: undefined, // 取镜人
      takeUserDesc: undefined, // 取镜备注，非当前取镜人取镜备注
      patCount: 0, // 患者人次
      okLoading: false
    }
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (JSON.stringify(nextProps.selectData) !== JSON.stringify(prevState.selectData)) {
      return {
        selectData: nextProps.selectData
      }
    }
    return null
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
  }

  // 修改弹窗状态
  modifyVisible = (visible, tableData = []) => {
    let { columns } = this.state;
    if (!(columns && columns.length > 0) && visible) {
      this.getTableColumns();
    }
    if (visible) {
      this.state.okLoading = false;
      this.getPatCount(tableData);
    }
    this.setState({ visible, tableData })
  }

  // 获取批量取镜人次
  getPatCount = (tableData) => {
    let patCount = 0;
    let patIDArr = [];
    for (let i = 0; i < tableData.length; i++) {
      if (patIDArr.indexOf(tableData[i].patNo) < 0) {
        patIDArr.push(tableData[i].patNo);
        patCount += 1;
      }
    }
    this.setState({ patCount });
  }

  // 获取列表表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'BatchMirrorRetrievalModal',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      this.setState({ columns: res.result?.C || [], totalWidth: res.totalWidth });
    } catch (error) {
      console.log(error);
    }
  }

  // 操作框change事件
  handleInputChange = (dataIndex, index, e) => {
    let { tableData } = this.state;
    tableData[index][dataIndex] = e;
    this.setState({});
  }

  // 操作行
  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' : '';
  }

  // 获取明细列表申请单ID
  getRequestIDArr = () => {
    let { tableData } = this.state;
    let requestIDArr = [];
    for (let i = 0; i < tableData.length; i++) {
      requestIDArr.push(tableData[i]?.requestID || tableData[i]?.glassesRequestID || tableData[i]?.key || '');
    }
    return requestIDArr;
  }

  // 确认取镜
  handleOk = async () => {
    try {
      const { categoryData } = this.props;
      const { takeUserID, takeUserDesc, tableData } = this.state;
      console.log('categoryData', categoryData)
      if (!takeUserID) {
        message.warning('请选择取镜人员！')
        return;
      }
      if (!(tableData && tableData.length > 0)) {
        message.warning('批量取镜列表为空，请重新选择订单批量取镜！');
        return;
      }
      this.setState({ okLoading: true });
      let data = {
        params: [{
          takeUserID, // 取镜人
          takeUserDesc,
          requestIDArr: this.getRequestIDArr(),
        }]
      }
      let res = await React.$asyncPost(this, categoryData?.batchTakeCode || '17030088', data);
      message.success(res?.errorMessage || '批量取镜成功');
      this.modifyVisible(false);
      this.props.handleQuery && this.props.handleQuery();
    } catch (error) {
      console.log(error);
      this.setState({ okLoading: false });
    }
  }

  // 移除
  handleRemove = (record, e) => {
    React.$stopPropagation(e);
    let { tableData } = this.state;
    tableData = tableData.filter(item => (item?.requestID || item?.glassesRequestID || item?.key || '') !== (record?.requestID || record?.glassesRequestID || record?.key || ''));
    this.getPatCount(tableData);
    this.setState({ tableData });
  }

  render() {
    const { visible, loading, tableData, columns, totalWidth, takeUserID, takeUserDesc, selectData, patCount, okLoading } = this.state;
    const operationObj = {
      width: 80,
      title: '操作',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <Popconfirm title="确定移除订单吗?" onClick={(e) => React.$stopPropagation(e)} onConfirm={(e) => this.handleRemove(record, e)} >
          <span className="span common-record-delete-span">移除</span>
        </Popconfirm>
      ),
    }
    return (
      <Modal
        title="批量取镜"
        width="72vw"
        className="batch-mirror-retrieval"
        visible={visible}
        okButtonProps={{
          loading: okLoading
        }}
        onCancel={() => this.modifyVisible(false)}
        onOk={this.handleOk}
      >
        <div className="table-body-height">
          <div className="flex-between-center">
            <div className="flex-align-items" style={{ marginBottom: 12 }}>
              <span style={{ position: 'relative', padding: '4px 0 0 20px' }} className="formRequired">取镜人员：</span>
              <Select
                allowClear
                showSearch
                placeholder="请选择"
                optionFilterProp="search"
                className="common-query-input"
                value={takeUserID}
                onChange={e => this.setState({ takeUserID: e })}
              >
                {React.$SelectOptions(selectData?.takeUserList || [])}
              </Select>
              <Input
                placeholder="取镜备注"
                className="common-query-input"
                style={{ width: '300px' }}
                value={takeUserDesc}
                onChange={e => this.setState({ takeUserDesc: e.target.value })}
              />
            </div>
            <div style={{ color: '#666', fontWeight: 'normal' }}>
              共计{patCount}人次，{tableData?.length || 0}片
            </div>
          </div>
          <PubilcTablePagination
            param={{
              loading,
              data: tableData, // 表格数据
              x: totalWidth, // 表格的宽度
              y: 450,
              height: 500,
              componentName: 'BatchMirrorRetrievalModal',
              TableClassName: 'common-table-fixed-operation',
              columns: columns && columns.length > 0 ? [...columns, operationObj] : [], // 表头配置
            }}
            getColumns={this.getTableColumns}
            onClickRowPublic={this.onClickRowPublic}
            setRowClassNamePublic={this.setRowClassNamePublic}
          />
        </div>
      </Modal>
    )
  }
};

export default BatchMirrorRetrievalModal;