/*
 * Create:      柿子
 * CreateDate:  2023/09/12
 * Describe：   查看在途数
 * */
import React, { Component } from 'react';
import { Modal, Button, message, Select } from 'antd';
import { Util } from 'tools';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';

class ViewTheNumberOfInTransit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      selectData: {},
      paramsData: {},
      queryParams: {
        ordLocID: undefined, // 开单科室
      },
      page: 1,
      pageSize: 20,
      total: 0,
      rowID: '',
      loading: false,
      tableData: [],
      columns: [],
      totalWidth: 1250,
      selectedRowKeys: [],
      selectedRows: []
    };
  }

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

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

  // 修改弹窗状态
  modifyVisible = (visible, record, componentName) => {
    const { columns } = this.state;
    if (!(columns && columns.length > 0) && visible) {
      this.getTableColumns(componentName);
    }
    this.setState({ visible, paramsData: record, rowID: '', selectedRowKeys: [], selectedRows: [] }, () => {
      if (visible) {
        this.getTableData();
      }
    });
  }

  // 获取列表表头数据
  getTableColumns = async (componentName) => {
    try {
      let data = {
        params: [{
          type: 'C',
          compontName: componentName || 'ViewTheNumberOfInTransit',
        }]
      }
      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();
    })
  }

  // 提供修改page和pageSize的回调函数
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 请求列表数据
  getTableData = async () => {
    try {
      let { queryCode } = this.props;
      queryCode = queryCode || '02060195'
      let { queryParams, paramsData, pageSize, page } = this.state;
      this.setState({ loading: true })
      let data = {
        params: [{
          ...queryParams,
          ...paramsData
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, queryCode, data);
      let result = queryCode === '02060195' && Array.isArray(res.result) && res.result.length === 1 ? res.result[0] : res.result;
      this.setState({ tableData: Util.addKeyValueToDataSource(result?.rows || []), total: result?.total || tableData.length, loading: false, rowID: '' });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false, rowID: '' });
    }
  }

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

  // 确定
  handleOk = async () => {
    try {
      const { idIndex, okCode } = this.props;
      let { selectedRows } = this.state;
      if (!(selectedRows && selectedRows.length > 0)) {
        message.warning('请选择数据');
        return;
      }
      let data = {
        params: selectedRows && selectedRows.map((item) => {
          return {
            [idIndex || 'reswayID']: item[idIndex || 'reswayID'] || ''
          }
        }),
      }
      let res = await React.$asyncPost(this, okCode || '02060196', data);
      message.success(res?.errorMessage || '清除在途数成功');
      this.modifyVisible(false);
      this.setState({ selectedRowKeys: [], selectedRows: [] }, () => {
        this.props && this.props.handleQuery && this.props.handleQuery();
      })
    } catch (error) {
      console.log(error);
    }
  }

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

  render() {
    const { okText } = this.props;
    let { visible, page, total, loading, tableData, columns, totalWidth, queryParams, selectedRowKeys, selectData } = this.state;

    let rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ selectedRowKeys, selectedRows })
      },
    };

    return (
      <Modal
        width="1200px"
        title="在途数明细"
        okText={okText || '清除'}
        visible={visible}
        destroyOnClose={true}
        onOk={this.handleOk}
        onCancel={() => this.modifyVisible(false)}
      >
        <div className="table-body-height">
          <div className="flex-align-items" style={{ marginBottom: '12px' }}>
            开单科室：
            <Select
              allowClear
              showSearch
              value={queryParams?.ordLocID}
              placeholder="请选择"
              optionFilterProp="search"
              className="common-query-input"
              style={{ marginRight: 15 }}
              onChange={(e) => this.handleModifyInputValue(e, 'ordLocID')}
            >
              {React.$SelectOptions(selectData?.stkLoc || [])}
            </Select>
            <Button type="primary" onClick={this.handleQuery}>查询</Button>
          </div>
          <PubilcTablePagination
            param={{
              page,
              pageSize: '20',
              total,
              loading,
              columns, // 表头配置
              data: tableData, // 表格数据
              x: totalWidth, // 表格的宽度
              y: 400,
              height: '450px',
              componentName: 'ViewTheNumberOfInTransit',
            }}
            rowSelectionPublic={rowSelection}
            compilePage={this.compilePage}
            getColumns={this.getTableColumns}
            onClickRowPublic={this.onClickRowPublic}
            setRowClassNamePublic={this.setRowClassNamePublic}
          />
        </div>
      </Modal>
    );
  }
};

export default ViewTheNumberOfInTransit;
