/*
 * Creator:     柿子
 * CreatDate:   2022-09-05
 * descripts：  供应商 - 发货
 * */
import React, { Component } from 'react';
import { Modal, DatePicker, Input, Tooltip, message, Select } from 'antd';
import { Util } 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 '../style/index.less';

class DeliverGoods extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      rowData: {},
      requestIDArr: [],
      loading: false,
      tableData: [],
      columns: [],
      totalWidth: 0,
      selectData: {},
      expressServiceID: undefined,
      logisticsNo: undefined,
      deliverType: '', // 发货类型
    }
  }

  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, requestIDArr, deliverType, logistics) => {
    let { columns } = this.state;
    if (deliverType === 'import') { // 导入
      this.state.expressServiceID = logistics?.expressServiceID || undefined; // 物流公司
      this.state.logisticsNo = logistics?.logisticsNo || undefined; // 物流单号
      let tableData = JSON.parse(JSON.stringify(requestIDArr));
      this.state.tableData = tableData;
      requestIDArr = requestIDArr.map((item) => item?.glassesRequestID || item?.requestID || '');
    }
    this.setState({ visible, requestIDArr, deliverType }, () => {
      this.state.visible && deliverType !== 'import' && this.getTableData();
      if (!(columns && columns.length > 0) && this.state.visible) {
        this.getTableColumns();
      }
    })
  }

  // 获取列表表头数据
  getTableColumns = async () => {
    let columns = [];
    let totalWidth = 1200;
    try {
      let data = {
        params: [{
          compontName: 'DeliverGoods',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      columns = res.result && Array.isArray(res.result.C) && res.result.C.length > 0 ? res.result.C : [];
      totalWidth = res.totalWidth;
    } catch (error) {
      columns = [{
        key: 1,
        title: '产品名称',
        dataIndex: 'medDesc',
        align: 'center',
        width: 300
      }, {
        key: 2,
        title: '部位',
        dataIndex: 'partDesc',
        align: 'center',
        width: 80
      }, {
        key: 3,
        title: '数量',
        dataIndex: 'qty',
        align: 'center',
        width: 80
      }, {
        key: 4,
        title: '生产日期',
        dataIndex: 'produceDate',
        align: 'center',
        width: 150
      }, {
        key: 5,
        title: '有效期',
        dataIndex: 'expDate',
        align: 'center',
        width: 150
      }, {
        key: 6,
        title: '产品编号',
        dataIndex: 'productNo',
        align: 'center',
        width: 150
      }]
    }
    this.setState({ columns, totalWidth }, () => {
      this.handleFilterColumns();
    })
  }

  // 处理表头数据
  handleFilterColumns = () => {
    let { columns } = this.state;
    columns = columns && columns.map((item) => {
      return {
        ...item,
        render: (text, record, index) => {
          let dataIndex = item?.dataIndex || '';
          if (dataIndex === 'produceDate' || dataIndex === 'expDate' || item?.linkMethod === 'Date') { // 生产日期
            return (
              <DatePicker
                allowClear
                style={{ width: '90%' }}
                value={record[dataIndex] ? moment(record[dataIndex]) : (undefined)}
                onChange={(e, dateString) => this.handleInputChange(dataIndex, index, dateString)}
              />
            )
          } else if (dataIndex === 'productNo' || dataIndex === 'batchNo' || item?.linkMethod === 'Input') {
            return (
              <Input
                allowClear
                placeholder="请输入"
                style={{ width: '90%' }}
                value={record[dataIndex]}
                ref={ref => this[dataIndex + 'Ref' + index] = ref}
                onChange={e => this.handleInputChange(dataIndex, index, e.target.value)}
                onPressEnter={() => this.handleProductNoPressEnter(dataIndex, index)}
              />
            )
          } else {
            return (
              <Tooltip title={text}>
                <span className='ellipsis' style={{ width: '100%', display: 'block' }}>{text}</span>
              </Tooltip>
            );
          }
        }
      }
    })
    this.setState({
      columns
    })
  }

  // 产品编号回车到下一个产品编号
  handleProductNoPressEnter = (dataIndex, index) => {
    const { tableData } = this.state;
    let currentRef = '';
    if (dataIndex === 'productNo') {
      currentRef = 'batchNoRef' + index;
    } else if (dataIndex === 'batchNo') {
      if (tableData && tableData.length && (tableData.length === (index + 1))) {
        return;
      }
      currentRef = 'productNoRef' + (index + 1);
    }
    this[currentRef] && this[currentRef].focus(); // 自动获取焦点
  }

  // 获取列表数据
  getTableData = async () => {
    try {
      const { requestIDArr } = this.state;
      let data = {
        params: [{
          requestIDArr: requestIDArr
        }]
      }
      let res = await React.$asyncPost(this, '17030098', data);
      let tableData = Util.addKeyValueToDataSource(res?.result || []);
      for (var i = 0; i < tableData.length; i++) {
        tableData[i].productNo = undefined;
        tableData[i].batchNo = undefined;
        // tableData[i].expDate = moment().format(dayFormat); // 有效期不默认当前
        // tableData[i].produceDate = moment().format(dayFormat);
      }
      this.setState({ tableData }, () => {
        if (this.state.tableData && this.state.tableData.length > 0) {
          this['productNoRef0'] && this['productNoRef0'].focus(); // 自动获取焦点
        }
      })
    } catch (error) {
      this.setState({ tableData: [] })
    }
  }

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

  // 确认发货
  handleOk = async () => {
    try {
      const { requestIDArr, tableData, expressServiceID, logisticsNo } = this.state;
      let isFlag = false;
      let isRepeat = [];
      for (var i = 0; i < tableData.length; i++) {
        if (!(tableData[i].batchNo) || !(tableData[i].productNo) || !(tableData[i].produceDate) || !(tableData[i].expDate)) {
          isFlag = true;
          continue;
        } else if (isRepeat.indexOf(tableData[i].productNo) < 0) {
          isRepeat.push(tableData[i].productNo);
        }
      }
      if (isFlag) {
        message.error('生产日期/有效期/产品编号/批号不能为空！');
        return;
      }
      if (tableData?.length !== isRepeat?.length) {
        message.error('产品编号不能一致，请确认后再保存。');
        return;
      }
      let data = {
        params: [{
          requestIDArr: requestIDArr,
          medArr: tableData,
          expressServiceID,
          logisticsNo
        }]
      }
      let res = await React.$asyncPost(this, '17030099', data);
      message.success(res.errorMessage || '确认发货成功');
      this.setState({ expressServiceID: undefined, logisticsNo: undefined });
      this.modifyVisible(false);
      this.props.handleQuery && this.props.handleQuery('N');
    } catch (error) {
      console.log(error);
    }
  }

  // 打印订单
  handlePrintOrder = async () => {
    try {
      const { requestIDArr } = this.state;
      let data = {
        params: [{
          glassesRequestIDArr: requestIDArr,
          invoiceFlag: 'Y', // Y:发货订单 N:配镜申请订单
          suppFlag: 'Y', // 供应商标志 - 供应商界面打印脱敏
        }]
      }
      let res = await React.$asyncPost(this, '17030077', data);
      let dataArr = res?.result || [];
      dataArr && dataArr.map((item, i) => {
        $loadTemplate(item.template, item.printStr);
      });
      if (!(dataArr && dataArr.length > 0)) {
        message.warning('暂无打印数据');
      }
    } catch (error) {
      console.log(error);
    }
  }

  render() {
    const { visible, loading, tableData, columns, totalWidth, expressServiceID, logisticsNo, selectData, deliverType } = this.state;
    return (
      <Modal
        title={deliverType === 'import' ? '订单导入' : '订单发货'}
        width="76vw"
        okText={deliverType === 'import' ? '确认导入' : '确认发货'}
        className="deliver-goods"
        visible={visible}
        onCancel={() => this.modifyVisible(false)}
        onOk={this.handleOk}
      // footer={[
      //   <Button key="1" ghost type="primary" onClick={this.handlePrintOrder}>
      //     打印订单
      //   </Button>,
      //   <Button key="2" type="primary" onClick={this.handleOk}>
      //     确认发货
      //   </Button>
      // ]}
      >
        <div className="table-body-height">
          {/* <div className="deliver-goods-header">
            姓名：<span>{patInfo?.patName || '--'}</span>
            性别：<span>{patInfo?.patSexDesc || '--'}</span>
            年龄：<span>{patInfo?.patAge || '--'}</span>
            病人ID：<span>{patInfo?.patNo || '--'}</span>
          </div>
          <div style={{ marginBottom: 12 }}>
            {patInfo?.receiveInfo || '--'}
          </div> */}
          <div style={{ marginBottom: 12 }}>
            物流公司：<Select
              allowClear
              showSearch
              placeholder="请选择"
              optionFilterProp="search"
              className="common-query-input"
              value={expressServiceID}
              onChange={e => this.setState({ expressServiceID: e })}
            >
              {React.$SelectOptions(selectData?.logistics || [])}
            </Select>
            物流单号：<Input
              placeholder="请输入"
              className="common-query-input"
              style={{ width: '300px' }}
              value={logisticsNo}
              onChange={e => this.setState({ logisticsNo: e.target.value })}
            />
          </div>
          <PubilcTablePagination
            param={{
              loading,
              data: tableData, // 表格数据
              x: totalWidth, // 表格的宽度
              y: store.getState().tableHeight.y - 150,
              height: store.getState().tableHeight.y - 100,
              componentName: 'DeliverGoods',
              columns: columns && columns.length > 0 ? columns : this.staticColumns, // 表头配置
            }}
            getColumns={this.getTableColumns}
          />
        </div>
      </Modal>
    )
  }
};

export default DeliverGoods;