/*
 * Create:      柿子
 * CreateDate:  2023/11/16
 * Describe：   复制病区信息配置【复制配置】
 * */
import React, { Component } from 'react';
import { Modal, Select, Button, message } from 'antd';
import { Util } from 'tools';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination.jsx';

class CopyWardInfoConfig extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    this.state = {
      userData,
      visible: false,
      rowData: {},
      loading: false,
      tableData: [],
      columns: [],
      totalWidth: 0,
      selectData: {},
      queryParams: {
        copyHospID: userData?.hospID || undefined, // 医院ID
      },
      locList: [],
      selectedRowKeys: [],
      selectedRows: [],
      copyQueryLocListHospID: '', // 查询科室数据的医院ID
    }
  };

  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) => {
    let { columns } = this.state;
    this.setState({ visible }, () => {
      this.state.visible && this.getTableData();
      this.state.visible && this.getLocList();
      if (!(columns && columns.length > 0) && this.state.visible) {
        this.getTableColumns();
      }
    })
  };

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

  // 获取列表数据
  getTableData = async () => {
    try {
      let queryCode = this.props?.queryCode || '';
      if (!queryCode) return;
      this.setState({ loading: true });
      const { queryParams } = this.state;
      let data = {
        params: [{
          ...queryParams
        }]
      }
      let res = await React.$asyncPost(this, queryCode, data);
      let tableData = Util.addKeyValueToDataSource(res?.result || [], 'id');
      this.setState({ tableData, loading: false, selectedRowKeys: [], selectedRows: [] });
    } catch (error) {
      console.log(error);
      this.setState({ loading: false });
    }
  };

  // 操作框change事件
  handleInputChange = (e, dataIndex) => {
    let { queryParams } = this.state;
    queryParams[dataIndex] = e;
    this.setState({}, () => {
      if (dataIndex === 'copyHospID') {
        this.getLocList();
      } else {
        this.getTableData();
      }
    });
  };

  // 根据选择医院获取科室数据
  getLocList = async () => {
    try {
      let { queryParams, userData, copyQueryLocListHospID } = this.state;
      let queryHospID = queryParams?.copyHospID || userData?.hospID || '';
      if (copyQueryLocListHospID === queryHospID) return; // 相同医院不做重复查询
      let data = {
        params: [{
          hospID: queryHospID,
          locTypeCode: 'W', // 科室类型 - 病区
        }]
      }
      let res = await React.$asyncPost(this, '03050216', data);
      queryParams.copyLocID = undefined; // 清除科室选择
      this.setState({ locList: res?.result?.Data || [], copyQueryLocListHospID: queryHospID });
    } catch (error) {
      console.log(error);
    }
  };

  handleOk = () => {
    const { selectedRows } = this.state;
    let repeatArr = this.props?.duplicateCheck(selectedRows);
    if (repeatArr && Array.isArray(repeatArr) && repeatArr.length > 0) {
      Modal.confirm({
        title: '复制提醒',
        content: repeatArr.join(',') + '已存在，复制将会覆盖原数据，确认复制吗？',
        okText: '是 -> 复制',
        cancelText: '否 -> 不复制',
        onOk: () => this.handleHttpCopy(),
        onCancel: () => { },
      });
    } else {
      this.handleHttpCopy();
    }
  };

  handleHttpCopy = async () => {
    try {
      let copyCode = this.props?.copyCode || '';
      if (!copyCode) return;
      const { selectedRowKeys } = this.state;
      if (!(selectedRowKeys && selectedRowKeys.length > 0)) {
        message.info('请勾选需要复制的数据。');
        return
      }
      let data = {
        params: [{
          copyArr: selectedRowKeys,
          locID: this.props?.locID || '',
        }]
      }
      let res = await React.$asyncPost(this, copyCode, data);
      message.success(res?.errorMessage || '复制成功');
      this.modifyVisible(false);
      this.props.handleQuery && this.props.handleQuery();
    } catch (error) {
      console.log(error);
    }
  };

  render() {
    const { visible, loading, tableData, totalWidth, columns, queryParams, selectData, locList, selectedRowKeys, selectedRows } = this.state;

    const rowSelection = {
      selectedRowKeys,
      selectedRows,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ selectedRowKeys, selectedRows });
      },
    };
    return (
      <Modal
        title="复制配置"
        width="50vw"
        visible={visible}
        onCancel={() => this.modifyVisible(false)}
        onOk={this.handleOk}
      >
        <div className="table-body-height">
          <div style={{ marginBottom: 12 }}>
            医院：
            <Select
              allowClear
              showSearch
              placeholder="请选择"
              optionFilterProp="search"
              className="common-query-input"
              value={queryParams?.copyHospID}
              onChange={(e) => this.handleInputChange(e, 'copyHospID')}
            >
              {React.$SelectOptions(selectData?.hospArr || [])}
            </Select>
            科室：
            <Select
              allowClear
              showSearch
              placeholder="请选择"
              optionFilterProp="search"
              className="common-query-input"
              value={queryParams?.copyLocID}
              onChange={(e) => this.handleInputChange(e, 'copyLocID')}
            >
              {React.$SelectOptions(locList)}
            </Select>
            <Button type="primary" onClick={this.getTableData}>查询</Button>
          </div>
          <PublicTablePagination
            param={{
              loading,
              columns, // 表头配置
              data: tableData, // 表格数据
              x: totalWidth, // 表格的宽度
              y: store.getState().tableHeight.y - 150,
              height: store.getState().tableHeight.y - 100,
              componentName: 'CopyWardInfoConfig',
            }}
            rowSelectionPublic={rowSelection}
            getColumns={this.getTableColumns}
          />
        </div>
      </Modal>
    )
  }
};

export default CopyWardInfoConfig;