/*
 * Create:      柿子
 * CreateDate:  2022/09/06
 * Describe：   库房 - 辅助转移制单 - 已审核入库制单
 * */
import React, { Component } from 'react';
import { Modal, Button, message, Tooltip } from 'antd';
import { Util, dayFormat } from 'tools';
import moment from 'moment';
import RangeDatePicker from 'components/rangePicker/index';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';

class ReviewedReceiptVPModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      selectData: {},
      queryParams: { // 查询条件
        endDate: moment().format(dayFormat), // 结束日期
        startDate: moment().format(dayFormat), // 开始日期
      },
      page: 1,
      pageSize: 10,
      total: 0,
      rowID: '',
      rowData: {},
      loading: false,
      tableData: [],
      columns: [],
      totalWidth: 1250,
      defaultStatus: '30', // 默认已审核
      frLocID: '',
      defaultDate: 0,
    };
    this.staticColumns = [{
      key: 1,
      title: '入库单号',
      dataIndex: 'inOpeNo',
      align: 'center',
      width: 250
    }, {
      key: 2,
      title: '入库类型',
      dataIndex: 'operTypeDesc',
      align: 'center',
      width: 100
    }, {
      key: 3,
      title: '入库科室',
      dataIndex: 'locDesc',
      align: 'center',
      width: 100
    }, {
      key: 4,
      title: '入库日期',
      dataIndex: 'creatDateTime',
      align: 'center',
      width: 150
    }, {
      key: 5,
      title: '供应商',
      dataIndex: 'vendorDesc',
      align: 'center',
      width: 200
    }, {
      key: 6,
      title: '审核日期',
      dataIndex: 'auditDateTime',
      align: 'center',
      width: 150
    }, {
      key: 7,
      title: '审核人',
      dataIndex: 'auditUserDesc',
      align: 'center',
      width: 100
    }, {
      key: 8,
      title: '建单人',
      dataIndex: 'createUserDesc',
      align: 'center',
      width: 100
    }, {
      key: 9,
      title: '状态',
      dataIndex: 'stateDesc',
      align: 'center',
      width: 100
    }];
  }

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

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.frLocID !== prevState.frLocID) {
      return {
        frLocID: nextProps.frLocID
      }
    }
    if ('defaultDate' in nextProps && (nextProps.defaultDate !== prevState.defaultDate)) { // 默认日期
      return {
        defaultDate: nextProps.defaultDate,
        queryParams: {
          ...prevState.queryParams,
          startDate: moment().subtract(parseInt(nextProps?.defaultDate || 0), 'days').format(dayFormat),
        }
      }
    }
    return null
  }

  // 修改弹窗状态
  modifyVisible = (visible) => {
    const { columns, tableData } = this.state;
    if (!(columns && columns.length > 0) && visible) {
      this.getTableColumns();
    }
    this.setState({ visible }, () => {
      if (this.state.visible && tableData && tableData.length === 0) {
        this.getTableData();
      }
    });
  }

  // 获取列表表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          type: 'C',
          compontName: 'ReviewedReceiptVPModal',
        }]
      }
      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) => {
              return (
                <Tooltip title={text}>
                  <span className='ellipsis' style={{ width: '100%', display: 'block' }}>{text}</span>
                </Tooltip>
              );
            },
          }
        })
        this.setState({
          columns,
          totalWidth: res.totalWidth
        }, () => {
          this.patientRef && this.patientRef.getCardSelectData();
        })
      }
    } 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 { queryParams, pageSize, page, defaultStatus, frLocID } = this.state;
      this.setState({ loading: true })
      let data = {
        params: [{
          ...queryParams,
          frLocID,
          status: defaultStatus,
          statusID: defaultStatus,
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, '17030030', data);
      let tableData = Util.addKeyValueToDataSource(res.result && 'rows' in res.result ? res.result.rows : (Array.isArray(res.result) ? res.result : []));
      this.setState({ tableData, total: res.result?.total || tableData.length, loading: false, rowID: '', rowData: {} });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false, rowID: '', rowData: {} });
    }
  }

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

  // 确定
  handleOk = async () => {
    try {
      let { rowID, rowData, frLocID } = this.state;
      if (!rowID) {
        message.warning('请选择一条操作数据！');
        return;
      }
      let data = {
        params: [{
          frLocID,
          stkRecID: rowID
        }],
      }
      let res = await React.$asyncPost(this, '17060014', data);
      let result = res?.result || [];
      if (result && result.length > 0) {
        this.props.addDetailData && this.props.addDetailData(result, 'ReviewedReceiptVPModal');
        this.modifyVisible(false);
      } else {
        message.error('单号（' + rowData.inOpeNo + '）没有明细数据，请核对入是否转移质检！'); // 最好走后台提示
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.metStkRecID))) {
          this.setState({ rowID: record.metStkRecID, rowData: record });
        } else {
          this.setState({ rowID: '', rowData: {} });
        }
      },
      onDoubleClick: () => {
        this.setState({ rowID: record.metStkRecID, rowData: record }, () => {
          this.handleOk();
        })
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    return record.metStkRecID === this.state.rowID ? 'clickRowStyle' : '';
  }

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

    return (
      <Modal
        width="1200px"
        title="辅助入库制单 - 已审核入库单"
        visible={visible}
        destroyOnClose={true}
        onOk={this.handleOk}
        onCancel={() => this.modifyVisible(false)}
      >
        <div className="table-body-height">
          <div style={{ marginBottom: '12px' }}>
            <div className="flex-align-items">
              <div style={{ marginRight: 12 }}>
                <RangeDatePicker
                  width="300px"
                  label="订单日期："
                  isChange={true}
                  format={dayFormat}
                  endDate={queryParams?.endDate}
                  startDate={queryParams?.startDate}
                  endChange={(e) => this.handleModifyInputValue(e, 'endDate')}
                  startChange={(e) => this.handleModifyInputValue(e, 'startDate')}
                />
              </div>
              <Button type="primary" onClick={this.handleQuery}>查询</Button>
            </div>
          </div>
          <PubilcTablePagination
            param={{
              page,
              total,
              loading,
              componentName: 'ReviewedReceiptVPModal',
              data: tableData, // 表格数据
              x: totalWidth, // 表格的宽度
              y: 400,
              height: '450px',
              columns: columns && columns.length > 0 ? columns : this.staticColumns, // 表头配置
            }}
            compilePage={this.compilePage}
            getColumns={this.getTableColumns}
            onClickRowPublic={this.onClickRowPublic}
            setRowClassNamePublic={this.setRowClassNamePublic}
          />
        </div>
      </Modal>
    );
  }
};

export default ReviewedReceiptVPModal;
