/*
 * Create:      柿子
 * CreateDate:  2022/09/19
 * Describe：   库房 - 制单公共组件 - 入库制单(NVPReceiptVP) / 转移制单(NVPTransferVP) / 退货制单(NVPReturnVP) / 调价单录入(NVPProductPrice)
 * */
import React, { Component } from 'react';
import { Card, Button, Radio, Popconfirm, Icon, message, Modal, Tooltip, Input, Spin, Tag, Upload } from 'antd';
import { Util } from 'tools';
import { handleExcel } from 'tools/handleExcel';
import { $loopPrint } from 'pages/lodop/Common/Print.js';
import store from 'store';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import MatchingDetails from 'pages/optometry/glassesManagement/component/MatchingDetails';
import OrderOfGlassesModal from 'pages/optometry/storageRoom/component/OrderOfGlassesModal';
import ReviewedReceiptVPModal from 'pages/optometry/storageRoom/component/ReviewedReceiptVPModal';
import iconListvisits from 'assets/images/icon_listvisits.png';
import iconMessages from 'assets/images/icon_messages.png';
import './style/index.less';

class VoucherPreparation extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    this.state = {
      categoryData: {},
      userData,
      selectData: {},
      queryFormData: [],
      queryHeight: 125, // 查询栏高度
      queryWidth: 762,
      statusRadioVal: '',
      statusRadioData: [],
      columns: [],
      totalWidth: 550,
      tableData: [],
      page: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      rowID: '',
      rowData: {},
      baseFormData: [],
      detailRowData: {},
      inputFormData: [],
      detailColumns: [],
      detailTotalWidth: 1100,
      detailLoading: false,
      detailTableData: [],
      detailRowID: '',
      modalTableColumns: [],
      modalTotalWidth: 800,
      scanningCode: undefined,
      spinLoading: true,
      selectedRowKeys: [],
      orderModalType: '',
      statusFormItem: {}, // 单据状态铺开展示对应的formItem
      frLocID: '', // 供给科室，提供给辅助制单用
      defaultDate: 0,
      saveBtnLoading: false,
      auditBtnLoading: false,
      printBtnLoading: false,
      sumRp: 0, // 进价总金额
      sumSp: 0, // 售价总金额
      leftCardFlag: false,
    };
    this.scanningRef = React.createRef();
    this.queryRef = React.createRef();
  }

  componentDidMount() {
    let newCategory;
    if ('paras' in this.props && this.props.paras && this.props.paras.params) { // 侧菜单获取类别参数
      newCategory = this.props.paras.params;
    } else {
      if ('location' in this.props && this.props.location.state && this.props.location.state.params) { // 头菜单获取类别参数
        newCategory = this.props.location.state.params;
        React.$setSessionData('NewVoucherPreparation', newCategory, false);
      } else { // 头菜单刷新界面时获取类别
        newCategory = React.$getSessionData('NewVoucherPreparation', false);
      }
    }
    let categoryData = Util.getObjByUrlStr(newCategory);
    console.log("NewVoucherPreparation", categoryData)
    this.setState({ categoryData, orderModalType: categoryData?.orderModalType || '' }, () => {
      this.getSelectData();
    });
  }

  componentWillUnmount() {
    // 组件销毁前将静止让setState修改state的状态
    this.setState = (state, callback) => { return; }
  }

  // 获取下拉框数据
  getSelectData = async () => {
    try {
      let { userData, categoryData } = this.state;
      if (!(categoryData && categoryData.selectCode)) {
        this.getTableColumns('Y');
        this.getBaseFormData();
        this.getDetailColumns();
      } else {
        let data = {
          params: [{
            hospID: userData?.hospID || '',
            groupType: categoryData?.groupType || undefined, //  H 医院   G集团
            componentName: categoryData?.componentName || undefined, // 组件名
          }]
        }
        let res = await React.$asyncPost(this, categoryData.selectCode, data);
        let statusRadioData = res.result?.status || [];
        let defaultVal = statusRadioData && statusRadioData.filter(item => (item.defaultFlag === 'Y' || item.default === 'Y')); // 默认状态值
        this.setState({ selectData: res.result, statusRadioData, statusRadioVal: defaultVal && defaultVal.length > 0 ? defaultVal[0].id : '' }, () => {
          this.getTableColumns('Y');
          this.getBaseFormData();
          this.getDetailColumns();
        });
      }
    } catch (error) {
      this.setState({ selectData: {}, statusRadioData: [], currentStep: '' }, () => {
        this.getTableColumns('Y');
        this.getBaseFormData();
        this.getDetailColumns();
      });
    }
  }

  // 获取列表表头数据
  getTableColumns = async (isQuery) => {
    try {
      const { categoryData } = this.state;
      if (!(categoryData && categoryData.componentName)) {
        this.setState({ spinLoading: false });
        message.error('主列表数据还未配置呢，快去配置先！');
        return;
      }
      let data = {
        params: [{
          compontName: categoryData.componentName,
          type: 'C',
        }]
      }
      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
        })
      }
      // 表单操作数据
      let queryFormData = res.result?.formData || [];
      let defaultDate = 0;
      let statusFormItem = {};
      if (categoryData?.stateSpreadingFlag === 'Y') { // 配置单据状态是否铺开显示，铺开显示则需要维护对应单据状态的dataIndex，因为铺开展示得显示对应状态的数量，得联合后台一起
        let stateSpreadingIndex = categoryData?.stateSpreadingIndex || 'status';
        let statusFormData = queryFormData && queryFormData.filter(item => item.dataIndex === stateSpreadingIndex);
        statusFormItem = statusFormData && statusFormData.length > 0 ? statusFormData[0] : {};
        queryFormData = queryFormData && queryFormData.filter(item => item.dataIndex !== stateSpreadingIndex);
      }
      if (queryFormData && queryFormData.length > 0) {
        for (var i = 0; i < queryFormData.length; i++) {
          if (queryFormData[i].typeCode === 'RangePicker') {
            defaultDate = (queryFormData[i]?.default || 0);
            break;
          }
        }
      }
      this.setState({ queryFormData, statusFormItem, defaultDate }, () => {
        this.setState({ queryHeight: this.queryRef?.current?.clientHeight || 125, queryWidth: this.queryRef?.current?.clientWidth || 762 });
      });
    } catch (error) {
      console.log(error);
    }
    if (isQuery === 'Y') { // 自动查询标志
      this.setState({ spinLoading: false }, () => {
        setTimeout(() => {
          this.getTableData();
        }, 300)
      });
    };
  }

  // 获取基本信息表单数据
  getBaseFormData = async () => {
    try {
      const { categoryData } = this.state;
      let compontName = categoryData?.baseComponentName || (categoryData.componentName ? (categoryData.componentName + 'Base') : '');
      if (!compontName) {
        message.error('基本信息数据还未配置呢，快去配置先！');
        return;
      }
      let data = {
        params: [{
          compontName,
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      // 表单操作数据
      let baseFormData = res.result?.formData || [];
      if (baseFormData && baseFormData.length > 0) {
        for (var i = 0; i < baseFormData.length; i++) {
          baseFormData[i].defaultDisabled = baseFormData[i]?.disabled || 'N';
        }
      }
      this.setState({ baseFormData });
    } catch (error) {
      this.setState({ baseFormData: [] });
    }
  }

  // 获取明细表头数据
  getDetailColumns = async () => {
    try {
      const { categoryData } = this.state;
      let compontName = categoryData?.detailComponentName || (categoryData.componentName ? (categoryData.componentName + 'Detail') : '');
      if (!compontName) {
        message.error('明细列表数据还未配置呢，快去配置先！');
        return;
      }
      let data = {
        params: [{
          compontName,
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let detailColumns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
      if (detailColumns && detailColumns.length > 0) {
        detailColumns = detailColumns.map(item => {
          return {
            ...item,
            render: (text, record) => {
              if (item.dataIndex === 'receiptStatusDesc') {
                return (
                  <Tooltip title={text}>
                    <span className={record.receiptStatus === 'T' ? 'common-record-delete-span' : '' + ' ellipsis'} style={{ width: '100%', display: 'block' }}>{text}</span>
                  </Tooltip>
                )
              } else if (item.dataIndex === 'reqNo') { // 订单号 / 保存接口返回1000，订单号显示异常
                return (
                  <Tooltip title={text}>
                    <span
                      className={record.errorReqNo === 'Y' ? 'common-record-delete-span' : 'span' + ' ellipsis'}
                      onClick={(e) => this.handleViewDetails(record, e)}
                      style={{ width: '100%', display: 'block' }}
                    >
                      {text}
                    </span>
                  </Tooltip>
                );
              } else if (item.dataIndex === 'urgentSign' && (text === '一级加急' || text === '二级加急')) { // 加急标志
                return (
                  <Tag style={{ fontWeight: 'normal' }} color={text === '一级加急' ? '#FF3D00' : (text === '二级加急' ? '#FA8C17' : '')}>{text}</Tag>
                );
              } else {
                return (
                  <Tooltip title={text}>
                    <span className="ellipsis" style={{ width: '100%', display: 'block' }}>{text}</span>
                  </Tooltip>
                )
              }
            },
          }
        })
        this.setState({
          detailColumns,
          detailTotalWidth: res.totalWidth
        });
      }
      // 表单操作数据
      let inputFormData = res.result && res.result.formData && res.result.formData.length > 0 ? Util.addKeyValueToDataSource(res.result.formData, '', 0) : [];
      let inputFormButton = [{
        col: 4,
        title: '清空',
        typeCode: 'Button',
        onClick: this.handleDetailEmpty,
        style: { textAlign: 'right', lineHeight: '40px', paddingRight: '30px' }
      }, {
        col: 2,
        title: '保存',
        ghost: true,
        type: 'primary',
        typeCode: 'Button',
        onClick: this.handleDetailSave,
        style: { lineHeight: '40px' }
      }];
      if (inputFormData && inputFormData.length > 0) {
        inputFormData = [...inputFormData, ...inputFormButton]
        for (var i = 0; i < inputFormData.length; i++) {
          inputFormData[i].defaultDisabled = inputFormData[i]?.disabled || 'N';
          if (inputFormData[i].dataIndex === 'qty' || inputFormData[i].dataIndex === 'rp' || inputFormData[i].dataIndex === 'sp') {
            inputFormData[i].callBackResult = 'Fn';
            inputFormData[i].changeCallBack = this.handleQtyChange;
          }
        }
      }
      this.setState({ inputFormData });
    } catch (error) {
      this.setState({ inputFormData: [] });
    }
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1, rowID: '' }, () => {
      this.getTableData();
    })
  }

  // 请求列表数据
  getTableData = async (isClear) => {
    try {
      let { pageSize, page, categoryData, statusRadioData, statusFormItem, statusRadioVal, modalTableColumns } = this.state;
      if (!(categoryData && categoryData.queryCode)) return;
      let values = await this.queryFormRef.handleSave();
      if (values.error) {
        message.error('请完善必填信息');
        return;
      }
      this.setState({ loading: true });
      let data = {
        params: [{
          ...values,
          [categoryData?.stateSpreadingFlag === 'Y' ? (statusFormItem?.dataIndex || 'status') : '']: statusRadioVal,
          groupType: categoryData?.groupType || undefined, //  H 医院   G集团
          componentName: categoryData?.componentName || undefined, // 组件名
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, categoryData.queryCode, data);
      let tableData = Util.addKeyValueToDataSource(res.result && 'rows' in res.result ? res.result.rows : (Array.isArray(res.result) ? res.result : []));
      let count = res.result?.count || [];
      for (let i = 0; i < statusRadioData.length; i++) {
        let currentObj = count.filter(item => item.id === statusRadioData[i].id);
        statusRadioData[i].count = currentObj && currentObj.length > 0 ? currentObj[0].count : 0;
      }
      this.setState({ tableData, total: res.result?.total || tableData.length, loading: false, statusRadioData }, () => {
        if (!(modalTableColumns && modalTableColumns.length > 0)) {
          this.getModalTableColumns();
        }
        isClear !== 'N' ? this.handleClearSelectData() : ''; // 清除操作数据
      });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false }, () => {
        this.handleClearSelectData();
      });
    }
  }

  // 数量change后自动计算进价售价金额
  handleQtyChange = (e, dataIndex, fieldsValue) => {
    let rpAmt = 0, spAmt = 0; // 进价/售价金额
    if (fieldsValue && 'rp' in fieldsValue && fieldsValue.rp !== undefined) { // 进价
      rpAmt = this.handleCalculatePrice(fieldsValue?.rp || 0, fieldsValue?.qty || 0);
    }
    if (fieldsValue && 'sp' in fieldsValue && fieldsValue.sp !== undefined) { // 售价
      spAmt = this.handleCalculatePrice(fieldsValue?.sp || 0, fieldsValue?.qty || 0);
    }
    this.inputFormRef && this.inputFormRef.setFieldsValue({
      rpAmt,
      spAmt
    });
  }

  // 单据状态change事件
  handleStatusRadioChange = e => {
    this.setState({ statusRadioVal: e.target.value }, () => {
      this.handleQuery();
    });
  }

  // 清除操作数据
  handleClearSelectData = () => {
    this.setState({ rowID: '', rowData: {}, detailTableData: [], scanningCode: undefined, sumRp: 0, sumSp: 0 }, () => {
      this.handleDetailEmpty();
      this.handleIsDisabled('baseFormData');
      this.handleIsDisabled('inputFormData');
      this.baseFormRef && this.baseFormRef.resetFields();
    })
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 操作行
  onClickRowPublic = (record) => {
    const { categoryData } = this.state;
    let idIndex = categoryData?.idIndex || 'id';
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record[idIndex]))) {
          this.setState({ rowID: record[idIndex] }, () => {
            this.queryRowDataByID(record);
          });
        } else {
          this.handleClearSelectData();
        }
      }
    }
  }

  // 根据行ID获取明细数据
  queryRowDataByID = async (record) => {
    try {
      const { categoryData, rowID } = this.state;
      let idIndex = categoryData?.idIndex || 'id';
      let queryDetailCode = categoryData?.queryDetailCode || '';
      if (!queryDetailCode) {
        this.setState({ rowData: record, detailTableData: [record] }, () => {
          this.totalAmountCalculation();
          this.handleDetailEmpty();
        })
        return;
      };
      this.setState({ detailLoading: true });
      let data = {
        params: [{
          [idIndex]: rowID,
          groupType: categoryData?.groupType || undefined, //  H 医院   G集团
          componentName: categoryData?.componentName || undefined, // 组件名
        }]
      }
      let res = await React.$asyncPost(this, queryDetailCode, data);
      let rowData = res.result?.baseInfo || {};
      this.setState({
        rowData,
        sumRp: rowData?.sumRp || 0, // 进价总金额
        sumSp: rowData?.sumSp || 0, // 售价总金额
        detailTableData: Util.addKeyValueToDataSource(res.result?.detailInfo || []),
        detailLoading: false
      }, () => {
        this.inputFormRef && this.inputFormRef.resetFields();
        this.handleIsDisabled('baseFormData');
        this.handleIsDisabled('inputFormData');
        this.handleDetailEmpty();
      })
    } catch (error) {
      console.log(error);
      this.setState({ detailLoading: false });
    }
  }

  // 输入域是否可以操作
  handleIsDisabled = (dataIndex) => {
    let { rowID, rowData, categoryData } = this.state;
    let detailDeleteFlag = rowID ? (rowData.statusCode === '10' ? true : false) : true;
    let formData = this.state[dataIndex];
    if (formData && formData.length > 0) {
      for (let i = 0; i < formData.length; i++) {
        let dataIndexArr = ['produceDate', 'expDate', 'manfDesc', 'rp']; // 已审核入库单生产日期、效期、进价、厂家可修改
        let dataIndexDisabled = rowData?.statusCode === '30' && categoryData?.componentName === 'NVPReceiptVP' && dataIndexArr.indexOf(formData[i].dataIndex) > -1 ? 'N' : 'Y';
        this.state[dataIndex][i].disabled = detailDeleteFlag ? this.state[dataIndex][i].defaultDisabled : dataIndexDisabled;
      }
      this.setState({});
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    const { categoryData } = this.state;
    let idIndex = categoryData?.idIndex || 'id';
    return record[idIndex] === this.state.rowID ? 'clickRowStyle' : '';
  }

  // 删除
  handleDelete = async (record, e) => {
    try {
      React.$stopPropagation(e)
      const { categoryData, rowID } = this.state;
      let idIndex = categoryData?.idIndex || 'id';
      let deleteCode = categoryData?.deleteCode || '';
      if (!deleteCode || !idIndex) {
        message.error('删除接口还未配置呢，快去配置先！');
        return
      };
      let data = {
        params: [{
          [idIndex]: record[idIndex] || '',
          groupType: categoryData?.groupType || undefined, //  H 医院   G集团
          componentName: categoryData?.componentName || undefined, // 组件名
        }]
      }
      let res = await React.$asyncPost(this, deleteCode, data);
      message.success(res.errorMessage || '删除成功');
      this.getTableData(rowID === record[idIndex] ? 'Y' : 'N');
    } catch (error) {
      console.log(error)
    }
  }

  // 打开依据订单
  handleOrderOfGlassesClick = () => {
    const { categoryData } = this.state;
    // 供给科室
    let auxiliaryLocIDIndex = categoryData?.auxiliaryLocIDIndex || 'frLocID';
    let frLocID = this.baseFormRef && this.baseFormRef.getFieldValue(auxiliaryLocIDIndex);
    this.setState({ frLocID }, () => {
      if (categoryData?.auxiliaryFlag === 'reviewed') { // 转移制单  -> auxiliaryFlag辅助制单类型
        this.reviewedRVPRef && this.reviewedRVPRef.modifyVisible(true);
      } else {
        this.orderOfGlassesRef && this.orderOfGlassesRef.modifyVisible(true);
      }
    })
  }

  // 清空明细表单数据
  handleDetailEmpty = () => {
    const { detailRowID } = this.state;
    if (detailRowID) {
      this.setState({ detailRowID: '' }, () => {
        this.handleModifyBtnTitle();
      });
    } else {
      this.handleModifyBtnTitle();
    }
    this.handleDetailResetFields();
  }

  // 重置明细表单
  handleDetailResetFields = () => {
    this.setState({ detailRowData: {} });
    this.inputFormRef && this.inputFormRef.resetFields();
  }

  getModalTableColumns = async () => {
    try {
      const { categoryData } = this.state;
      let compontName = categoryData?.modalTableName || (categoryData.componentName ? (categoryData.componentName + 'ModalTable') : '');
      if (!compontName) {
        message.error('明细列表数据还未配置呢，快去配置先！');
        return;
      }
      let data = {
        params: [{
          compontName,
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let modalTableColumns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
      if (modalTableColumns && modalTableColumns.length > 0) {
        this.setState({
          modalTableColumns,
          modalTotalWidth: res.totalWidth
        });
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 明细行操作
  handleDetailRowClick = (record) => {
    const { rowID, rowData, categoryData } = this.state;
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.detailRowID === '' || (this.state.detailRowID && (this.state.detailRowID !== record.key))) {
          let detailDeleteFlag = rowID ? (rowData.statusCode === '10' || rowData.statusCode === 'No' || (rowData?.statusCode === '30' && categoryData?.componentName === 'NVPReceiptVP') ? true : false) : true;
          record.usableQty = this.getUsableQty(record);
          record.rpAmt = this.handleCalculatePrice(record?.rp || 0, record?.qty || 0); // 进价金额
          record.spAmt = this.handleCalculatePrice(record?.sp || 0, record?.qty || 0); // 售价金额
          if (detailDeleteFlag) {
            this.getUnitSelectData(record?.unitArr || []);
            this.setState({ detailRowID: record.key, detailRowData: record }, () => {
              this.handleModifyBtnTitle();
            });
          }
        } else {
          this.handleDetailEmpty();
        }
      }
    }
  }

  // 计算价格
  handleCalculatePrice = (price, qty) => {
    return (((Number(price).toFixed(4)) * 10000) * Number(qty)) / 10000
  }

  // 计算可用数量
  getUsableQty = (record) => {
    let stkLocBatQty = Number(record?.stkLocBatQty || 0); // 总数量
    let dirtyQty = Number(record?.dirtyQty || 0); // 暂用数量
    return stkLocBatQty - dirtyQty
  }

  // 修改明细form操作描述
  handleModifyBtnTitle = () => {
    let { inputFormData, detailRowID } = this.state;
    if (inputFormData && inputFormData.length > 0) {
      let len = inputFormData.length;
      this.state.inputFormData[len - 2].title = detailRowID ? '取消修改' : '清空';
      this.state.inputFormData[len - 1].title = detailRowID ? '确认修改' : '保存';
      this.setState({});
    }
  }

  handleDetailRowClassName = (record) => {
    return record.key === this.state.detailRowID ? 'clickRowStyle' : (record?.presChange === '是' ? 'common-row-color-FDECF2' : '');
  }

  // 保存明细
  handleDetailSave = async () => {
    try {
      const { detailTableData, detailRowID, detailRowData } = this.state;
      let values = await this.inputFormRef.handleSave();
      if (values && values.error) {
        message.info('请先完善必填项。');
        return;
      }
      values = { // 选择产品名称附带的其他数据
        ...detailRowData,
        ...values,
      };
      if (values && 'unitID' in values && values.unitID) {
        values.unitDesc = Util.returnDataCccordingToAttributes(detailRowData?.unitArr || [], values.unitID)?.descripts;
      }
      values.rpAmt = this.handleCalculatePrice(values?.rp || 0, values?.qty || 0); // 进价金额
      values.spAmt = this.handleCalculatePrice(values?.sp || 0, values?.qty || 0); // 售价金额
      if (detailRowID) { // 编辑
        for (var i = 0; i < detailTableData.length; i++) {
          if (detailTableData[i].key === detailRowID) {
            detailTableData[i] = {
              ...detailTableData[i],
              ...values
            };
            break;
          }
        }
      } else { // 新增
        values.key = detailTableData && detailTableData.length > 0 ? (detailTableData.length + 1) : 1;
        detailTableData.push(values);
      }
      this.setState({ detailTableData }, () => {
        this.handleDetailEmpty();
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 录入顺序
  handleEntrySequence = (componentName) => {
    componentName && this.baseFormRef && this.baseFormRef.showFromMaintenanceModal(componentName);
  }

  // 保存/暂存 10-保存；20-完成；30-审核；40-验收
  handleSave = async (statusCode) => {
    const { detailTableData, detailRowID, detailRowData } = this.state;
    let baseValues = await this.baseFormRef.handleSave();
    if (baseValues && baseValues.error) {
      message.info('请完善基本信息中的必填项。');
      return;
    }
    if (!(detailTableData && detailTableData.length > 0) || detailRowID) {
      let inputValues = await this.inputFormRef.handleSave();
      if (inputValues && inputValues.error) {
        message.error(detailRowID ? '明细列表中存在数据处于编辑状态，请完善必填信息后保存。' : '请完善制单表单中的必填项。');
        return;
      }
      if (detailRowID) {
        let detailValue = this.inputFormRef && this.inputFormRef.getFieldsValue();
        let flag = false;
        for (var keys in detailValue) {
          for (var rowKeys in detailRowData) {
            if (keys === rowKeys && detailValue[keys] !== undefined && String(detailValue[keys]) !== String(detailRowData[rowKeys])) {
              flag = true;
              break;
            }
          }
        }
        if (flag) {
          Modal.confirm({
            title: '数据修改提醒',
            content: '您当前正在修改明细数据，且数据已发生变动，是否需要先保存明细数据？',
            okText: '确认',
            cancelText: '取消',
            onOk: () => this.handleDetailSave(),
            onCancel: () => this.handleHttpSave(statusCode, baseValues),
          });
        } else {
          this.handleHttpSave(statusCode, baseValues)
        }
      } else if (!(detailTableData && detailTableData.length > 0)) {
        message.error('请录入明细数据');
        return;
      } else {
        this.handleHttpSave(statusCode, baseValues)
      }
    } else {
      this.handleHttpSave(statusCode, baseValues)
    }
  }

  // 调用接口保存
  handleHttpSave = async (statusCode, baseValues) => {
    let { detailTableData, categoryData, rowData } = this.state;
    try {
      if (!(categoryData && categoryData.saveCode)) {
        message.error('保存接口还未配置呢，快去配置先！');
        return;
      };
      if (statusCode === '10' || (rowData?.statusCode === '30' && categoryData?.componentName === 'NVPReceiptVP')) {
        this.setState({ saveBtnLoading: true });
      } else if (statusCode === '20') {
        this.setState({ auditBtnLoading: true });
      }
      let data = {
        params: [{
          statusCode,
          baseInfo: { ...rowData, ...baseValues },
          detailInfo: detailTableData,
          groupType: categoryData?.groupType || undefined, //  H 医院   G集团
          componentName: categoryData?.componentName || undefined, // 组件名
        }]
      }
      // 已审核入库入库单可以修改部分信息【修改接口：17060107】
      let res = await React.$asyncPost(this, rowData?.statusCode === '30' && categoryData?.componentName === 'NVPReceiptVP' ? '17060107' : categoryData.saveCode, data);
      message.success(res?.errorMessage || '保存成功');
      this.setState({ saveBtnLoading: false, auditBtnLoading: false });
      this.getTableData();
    } catch (error) {
      if (error && error?.errorCode === '1000') {
        let errorReqNoArr = error && error.result && typeof (error.result) === 'string' && error.result.indexOf('^') > -1 ? error.result.split('^') : [error.result];
        for (let i = 0; i < detailTableData.length; i++) {
          detailTableData[i].errorReqNo = errorReqNoArr.indexOf(detailTableData[i].reqNo) > -1 ? 'Y' : 'N';
        }
        this.setState({});
      }
      this.setState({ saveBtnLoading: false, auditBtnLoading: false });
    }
  }

  // 删除明细
  handleDetailDelete = async (record, e) => {
    try {
      React.$stopPropagation(e)
      const { categoryData, detailRowID } = this.state;
      let detailIDIndex = categoryData?.detailIDIndex || 'id';
      let detailDeleteCode = categoryData?.detailDeleteCode || categoryData?.deleteCode || ''; // 默认和主删除接口一样
      if (!detailDeleteCode || !detailIDIndex) {
        message.error('明细接口还未配置呢，快去配置先！');
        return
      };
      let detailDeleteIndex = detailIDIndex && typeof (detailIDIndex) === 'string' && detailIDIndex.indexOf('ID') > -1 && detailIDIndex.replace('ID', 'Arr');
      if (record && record[detailIDIndex]) { // 调用接口删除
        let data = {
          params: [{
            [detailDeleteIndex]: [record[detailIDIndex]],
            groupType: categoryData?.groupType || undefined, //  H 医院   G集团
            componentName: categoryData?.componentName || undefined, // 组件名
          }]
        }
        let res = await React.$asyncPost(this, detailDeleteCode, data);
        message.success(res.errorMessage || '删除成功');
      }
      this.handleRowDelete(record.key);
      if (record.key === detailRowID) {
        this.handleDetailEmpty();
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 本地删除数据
  handleRowDelete = (key) => {
    let { detailTableData } = this.state;
    detailTableData = detailTableData.filter(item => item.key !== key);
    this.setState({ detailTableData: Util.addKeyValueToDataSource(detailTableData) }, () => {
      this.totalAmountCalculation();
    });
  }

  // 确认选择产品
  handleConfirmSelect = record => {
    this.getUnitSelectData(record?.unitArr || []);
    let detailRowData = { ...this.state.detailRowData, ...record };
    detailRowData.rpAmt = this.handleCalculatePrice(detailRowData?.rp || 0, detailRowData?.qty || 0); // 进价金额
    detailRowData.spAmt = this.handleCalculatePrice(detailRowData?.sp || 0, detailRowData?.qty || 0); // 售价金额
    this.setState({ detailRowData });
  }

  // 获取单位下拉数据
  getUnitSelectData = (unitArr = []) => {
    let { inputFormData } = this.state;
    for (var i = 0; i < inputFormData.length; i++) {
      let dataIndex = inputFormData[i]?.dataIndex || '';
      if (dataIndex && dataIndex.indexOf('nitID') > -1) {
        let unitKey = Util.returnDataCccordingToAttributes(inputFormData, dataIndex, 'dataIndex')?.key;
        if (unitKey !== undefined && unitArr && unitArr.length > 0) {
          this.state.inputFormData[unitKey].detailItem = unitArr;
        }
      }
    }
    this.setState({});
  }

  // 清空产品选择数据
  handleModalSelectClear = () => {
    this.setState({ detailRowData: {} });
  }

  // 更改单据状态
  handleModifyOrderStatus = async (statusCode) => {
    try {
      const { categoryData, rowID } = this.state;
      if (!(categoryData && categoryData.idIndex && categoryData.revokeCode)) {
        message.error('撤销接口还未配置呢，快去配置先！');
        return
      };
      this.setState({ auditBtnLoading: true });
      let data = {
        params: [{
          [categoryData.idIndex]: rowID,
          statusCode,
          groupType: categoryData?.groupType || undefined, //  H 医院   G集团
          componentName: categoryData?.componentName || undefined, // 组件名
        }]
      }
      let res = await React.$asyncPost(this, categoryData.revokeCode, data);
      message.success(res?.errorMessage || '订单撤回成功');
      this.setState({ auditBtnLoading: false });
      this.getTableData();
    } catch (error) {
      console.log(error);
      this.setState({ auditBtnLoading: false });
    }
  }

  // 扫码入库
  handleScanningCodePressEnter = async () => {
    try {
      const { categoryData, detailTableData, scanningCode, baseFormData } = this.state;
      let auxiliaryLocIDIndex = categoryData?.auxiliaryLocIDIndex || 'frLocID';
      let locID = this.baseFormRef && this.baseFormRef.getFieldValue(auxiliaryLocIDIndex);
      if (!locID) {
        let auxiliaryLocData = baseFormData && baseFormData.filter(item => item.dataIndex === auxiliaryLocIDIndex);
        let auxiliaryLocDesc = auxiliaryLocData && auxiliaryLocData.length > 0 ? auxiliaryLocData[0].descripts : '供给科室';
        message.error('请先选择' + auxiliaryLocDesc);
        return;
      }
      if (!scanningCode) return;
      let data = {
        params: [{
          productNo: scanningCode,
          frLocID: locID,
          groupType: categoryData?.groupType || undefined, //  H 医院   G集团
          componentName: categoryData?.componentName || undefined, // 组件名
        }]
      }
      let res = await React.$asyncPost(this, categoryData?.scanningCode || '17030034', data);
      let detailObj = res && 'result' in res && Object.prototype.toString.call(res.result) === '[object Object]' ? res.result : {};
      // 判断当前明细列表是否已添加该产品
      let addFlag = true;
      for (var i = 0; i < detailTableData.length; i++) {
        if (detailObj && 'productNo' in detailObj && detailTableData[i].productNo === detailObj.productNo) {
          addFlag = false;
          break;
        }
      }
      if (!addFlag) {
        message.error('当前订单已添加，无需重复添加');
        setTimeout(() => {
          this.scanningRef.current?.focus();
        }, 300)
        return;
      }
      detailObj.key = detailTableData && detailTableData.length > 0 ? detailTableData.length + 1 : 1;
      detailObj.usableQty = this.getUsableQty(detailObj);
      if (categoryData?.componentName === 'PurchaseReceipt') { // 采购收货辅助制单默认为收货 - 后台有返回则取后台返回的
        detailObj.receiptStatus = detailObj?.receiptStatus || 'R';
        detailObj.receiptStatusDesc = detailObj?.requestStatusDesc || '收货';
      }
      this.setState({ detailTableData: [...detailTableData, detailObj], scanningCode: undefined }, () => {
        this.totalAmountCalculation();
        setTimeout(() => {
          this.scanningRef.current?.focus();
        }, 300)
      });
    } catch (error) {
      console.log(error)
    }
  }

  // 获取查询产品名称所需参数
  getModalTableParams = () => {
    const { categoryData, userData } = this.state;
    // 供给科室
    let auxiliaryLocIDIndex = categoryData?.auxiliaryLocIDIndex || 'frLocID';
    let frLocID = this.baseFormRef && this.baseFormRef.getFieldValue(auxiliaryLocIDIndex);
    return {
      [auxiliaryLocIDIndex]: frLocID || userData?.locID
    };
  }

  // 添加明细数据
  handleAddDetailData = (data, flag) => {
    const { categoryData, detailTableData } = this.state;
    if (data && Array.isArray(data) && data.length > 0) {
      if (categoryData?.componentName === 'PurchaseReceipt') { // 采购收货辅助制单默认为收货 - 后台有返回则取后台返回的
        for (var i = 0; i < data.length; i++) {
          data[i].receiptStatus = data[i]?.receiptStatus || 'R';
          data[i].receiptStatusDesc = data[i]?.requestStatusDesc || '收货';
        }
      }
      let repeatArr = []; // 产品编号相同的无需重复添加
      let currentTableProductNo = [];
      for (var i = 0; i < detailTableData.length; i++) {
        currentTableProductNo.push(detailTableData[i].productNo);
      }
      for (var i = 0; i < data.length; i++) {
        if (currentTableProductNo.indexOf(data[i].productNo) > -1) {
          repeatArr.push(data[i].productNo);
          continue;
        }
      }
      if (flag === 'ReviewedReceiptVPModal' && repeatArr && repeatArr.length > 0) { // 辅助入库制单 - 已审核入库单
        message.error('编号为' + repeatArr.join('、') + '的产品已添加，无需重复添加');
        return;
      }
      this.setState({ detailTableData: Util.addKeyValueToDataSource([...detailTableData, ...data]) }, () => {
        this.totalAmountCalculation();
      });
    }
  }

  // 向外输出明细列表数据
  getDetailTableData = () => {
    const { detailTableData } = this.state;
    return detailTableData;
  }

  // 打印
  handlePrint = async () => {
    try {
      const { categoryData, rowID } = this.state;
      if (!(categoryData && categoryData.idIndex && categoryData.printCode)) {
        message.error('打印接口还未配置呢，快去配置先！');
        return
      };
      this.setState({ printBtnLoading: true });
      let data = {
        params: [{
          [categoryData.idIndex]: rowID,
          groupType: categoryData?.groupType || undefined, //  H 医院   G集团
          componentName: categoryData?.componentName || undefined, // 组件名
        }]
      }
      let res = await React.$asyncPost(this, categoryData.printCode, data);
      this.setState({ printBtnLoading: false });
      let dataArr = res?.result || [];
      dataArr && dataArr.map((item, i) => {
        $loopPrint(item.template, item.printStr);
      })
    } catch (error) {
      console.log(error);
      this.setState({ printBtnLoading: false });
    }
  }

  // 计算进价总金额/售价总金额
  totalAmountCalculation = () => {
    const { detailTableData, categoryData } = this.state;
    let spCountDataIndex = categoryData?.spCountDataIndex || 'sp';
    let rpCountDataIndex = categoryData?.rpCountDataIndex || 'rp';
    let sumRp = 0; // 进价
    let sumSp = 0; // 售价
    for (var i = 0; i < detailTableData.length; i++) {
      sumRp += (Number((detailTableData[i][rpCountDataIndex] || 0)) * 10000);
      sumSp += (Number((detailTableData[i][spCountDataIndex] | 0)) * 10000);
    }
    this.setState({ sumRp: sumRp / 10000, sumSp: sumSp / 10000 });
  }

  // 控制左侧card显隐
  handleChangeLeftCardFlag = () => {
    this.setState({
      leftCardFlag: !this.state.leftCardFlag
    })
  }

  // 查看详情
  handleViewDetails = (record, e) => {
    React.$stopPropagation(e);
    const { categoryData, rowData } = this.state;
    this.matchingDetailsRef && this.matchingDetailsRef.modifyVisible(true, { ...record, suppFlag: categoryData?.componentName || '', statusCode: rowData?.statusCode });
  }

  // 导入明细数据
  handleImportDetailDate = (file, fileList) => {
    let { categoryData, detailTableData } = this.state;
    handleExcel.importExcel(file, categoryData?.detailImportExcelHandlingMethod !== 'none' ? 'keyVal' : '')
      .then(async (jsonData) => {
        let excelData = [];
        if (!!(categoryData?.detailImportExcelCode)) { // 需要调用接口的情况
          let data = {
            params: [{
              [categoryData.detailImportExcelDataIndex || 'importArr']: jsonData,
              groupType: categoryData?.groupType || undefined, //  H 医院   G集团
              componentName: categoryData?.componentName || undefined, // 组件名
            }]
          }
          let res = await React.$asyncPost(this, categoryData?.detailImportExcelCode || '', data);
          let result = res?.result || {};
          excelData = Array.isArray(result) ? result : (result?.rows || result?.data || []);
        } else if (categoryData?.detailImportExcelHandlingMethod === 'keyValColumns') { // 如果表头是描述的情况 - 将导入数据和明细表头对比得到最终数据
          excelData = Array.isArray(jsonData) ? Util.processingImportedDataBasedOnColumns(jsonData, detailColumns) : [];
        } else { // 正常显示
          excelData = Array.isArray(jsonData) ? jsonData : [];
        }
        this.setState({ detailTableData: Util.addKeyValueToDataSource([...detailTableData, ...excelData]) }, () => {
          this.totalAmountCalculation();
        });
      })
      .catch((error) => {
        console.error(error); // 处理错误
      });
    return false;
  }

  render() {
    const { categoryData, selectData, queryFormData, queryWidth, queryHeight, statusRadioVal, statusRadioData, columns, totalWidth, tableData, page, total, loading, rowData, baseFormData, detailRowData, inputFormData,
      detailColumns, detailLoading, detailTableData, detailTotalWidth, rowID, modalTotalWidth, modalTableColumns, scanningCode, spinLoading, orderModalType, statusFormItem, frLocID, defaultDate, saveBtnLoading,
      auditBtnLoading, printBtnLoading, sumRp, sumSp, leftCardFlag
    } = this.state;
    let firstCol = queryFormData && queryFormData.length > 0 ? queryFormData[0].col : 12;
    let firstLabelCol = queryFormData && queryFormData.length > 0 ? queryFormData[0].labelCol : 8;
    let statusWidth = parseInt((queryWidth / 24 * firstCol) / 24 * firstLabelCol);
    let componentName = categoryData?.componentName || '';
    let detailComponentName = categoryData?.detailComponentName || (componentName ? (componentName + 'Detail') : '');
    let baseCompontName = categoryData?.baseComponentName || (categoryData.componentName ? (categoryData.componentName + 'Base') : '');
    let modalTableName = categoryData?.modalTableName || (componentName ? (componentName + 'ModalTable') : '');

    // 列表操作
    const operationObj = {
      width: 80,
      title: '操作',
      align: 'center',
      key: 'operation',
      fixed: categoryData?.operationFixedFlag === 'Y' ? 'right' : null,
      render: (text, record) => (
        <span>
          <Icon type="delete" className="common-record-delete-span" style={{ color: record.deleteFlag === 'Y' ? 'red' : '#999' }}></Icon>
          {record && record.deleteFlag === 'Y' ? (
            <Popconfirm
              title="删除后不可恢复，确定要删除吗?"
              onClick={React.$stopPropagation}
              onCancel={React.$stopPropagation}
              onConfirm={(e) => this.handleDelete(record, e)}
            >
              <span className="span common-record-delete-span">删除</span>
            </Popconfirm>
          ) : (
            <span
              style={{ color: '#999', cursor: 'no-drop', fontWeight: 'normal' }}
              onClick={React.$stopPropagation}
            >
              删除
            </span>
          )}
        </span>
      ),
    };

    let detailDeleteFlag = rowID ? (rowData.statusCode === '10' ? true : false) : true;
    // 明细列表操作
    const operationDetailObj = {
      width: 80,
      title: '操作',
      align: 'center',
      key: 'operation',
      fixed: 'right',
      render: (text, record) => (
        <span>
          <Icon type="delete" className="common-record-delete-span" style={{ color: detailDeleteFlag ? 'red' : '#999' }}></Icon>
          {record && detailDeleteFlag ? (
            <Popconfirm
              title="删除后不可恢复，确定要删除吗?"
              onClick={React.$stopPropagation}
              onCancel={React.$stopPropagation}
              onConfirm={(e) => this.handleDetailDelete(record, e)}
            >
              <span className="span" style={{ color: 'rgba(240, 65, 52, 1)' }}>删除</span>
            </Popconfirm>
          ) : (
            <span
              style={{ color: '#999', cursor: 'no-drop', fontWeight: 'normal' }}
              onClick={React.$stopPropagation}
            >
              删除
            </span>
          )}
        </span>
      ),
    };

    let mainCardTitle = (categoryData?.cardTitle || '主') + '列表';

    // 明细导入按钮入参
    const detailUploadExcelParams = {
      accept: '.xls,.xlsx',
      name: 'file',
      headers: {
        authorization: 'authorization-text',
      },
      showUploadList: false,
      beforeUpload: this.handleImportDetailDate
    }
    return (
      <Spin tip="正在初始化表单数据……" spinning={spinLoading}>
        <div style={{ height: store.getState().tableHeight.y + 243 + 'px' }} className="dynamic-component common-voucher-preparation new-voucher-preparation flex">
          {!leftCardFlag ? (
            <Card
              size="small"
              bordered={false}
              className="table-body-height"
              style={{ width: '620px' }}
              title={(
                <div className="card-title-left-img">
                  <img src={iconListvisits} alt="" />
                  {categoryData?.cardTitle || '主'}列表
                </div>
              )}
              extra={(
                <div onClick={this.handleChangeLeftCardFlag}>
                  <Tooltip title={'隐藏' + mainCardTitle}>
                    <Icon type="double-left" className="cvp-card-hide-icon" />
                  </Tooltip>
                </div>
              )}
            >
              <div ref={this.queryRef} className="cvp-left-card-query">
                <DynamicRenderingForm
                  className="dynamic-component-form"
                  onRef={ref => this.queryFormRef = ref}
                  rowData={{}}
                  selectData={selectData}
                  formData={queryFormData && queryFormData.length > 0 && [...queryFormData, {
                    col: 2,
                    typeCode: 'Button',
                    type: 'primary',
                    title: '查询',
                    marginBottom: 12,
                    onClick: this.handleQuery
                  }].map((item => {
                    return {
                      ...item,
                      onPressEnter: item.typeCode === 'Input' || item.typeCode === 'InputNumber' || item.typeCode === 'TextArea' ? this.handleQuery : ''
                    }
                  }))}
                />
                {categoryData?.stateSpreadingFlag === 'Y' ? ( // 单据状态是否铺开显示
                  <div className="flex">
                    <div style={{ width: statusWidth + 'px', textAlign: 'right', color: '#333', fontWeight: 'normal' }}>
                      {statusFormItem?.descripts || '单据状态'}：
                    </div>
                    <div className="flex-wrap" style={{ width: `calc(100% - ${statusWidth + 'px'})` }}>
                      <Radio.Group value={statusRadioVal} onChange={this.handleStatusRadioChange}>
                        {statusRadioData && statusRadioData.map((item, index) => {
                          return (
                            <Radio key={index} value={item.id}>{item.descripts + (item && 'count' in item ? '(' + item.count + ')' : '')}</Radio>
                          )
                        })}
                      </Radio.Group>
                    </div>
                  </div>
                ) : ''}
              </div>
              <PubilcTablePagination
                param={{
                  page,
                  total,
                  loading,
                  componentName,
                  pageSize: '20',
                  data: tableData, // 表格数据
                  x: totalWidth, // 表格的宽度
                  y: store.getState().tableHeight.y + 94 - queryHeight,
                  height: store.getState().tableHeight.y + 144 - queryHeight + 'px',
                  columns: columns && columns.length > 0 ? [...columns, operationObj] : [], // 表头配置
                }}
                compilePage={this.compilePage}
                getColumns={this.getTableColumns}
                onClickRowPublic={this.onClickRowPublic}
                setRowClassNamePublic={this.setRowClassNamePublic}
              />
            </Card>
          ) : (
            <Card
              bordered={false}
              style={{ width: '48px', cursor: 'pointer', height: '100%' }}
              className="cvp-hide-modal"
              onClick={this.handleChangeLeftCardFlag}
              title={(
                <Tooltip title={'展开' + mainCardTitle}>
                  <Icon
                    type="double-right"
                    className="cvp-card-hide-icon cvp-card-show-icon"
                    onClick={this.handleChangeLeftCardFlag}
                  />
                </Tooltip>
              )}>
              <span>展开{mainCardTitle}</span>
            </Card>
          )}
          <div className="common-query-split-line" style={{ width: 8, height: '100%' }}></div>
          <div style={{ width: !leftCardFlag ? 'calc(100% - 628px)' : 'calc(100% - 56px)' }} className="common-voucher-preparation-right-card">
            <Card
              size="small"
              bordered={false}
              title={(
                <div className="card-title-left-img">
                  <img src={iconMessages} alt="" />
                  正在{rowID ? '编辑' : '添加'}{categoryData?.cardTitle || '明细'}
                </div>
              )}
              extra={(
                <>
                  {categoryData?.printBtnFlag === 'Y' ? (
                    <Button
                      ghost
                      size="small"
                      type="primary"
                    >
                      打印
                    </Button>
                  ) : ''}
                  {categoryData?.addBtnFlag === 'Y' ? (
                    <Button
                      icon="plus"
                      size="small"
                      style={{ marginLeft: '12px' }}
                      className="add-btn add-btn-nohover"
                      onClick={this.handleClearSelectData}
                    >
                      新增{categoryData?.cardTitle || '单据'}
                    </Button>
                  ) : ''}
                </>
              )}
            >
              <div className="common-voucher-preparation-right-card-content scroll-bar-style" style={{ height: store.getState().tableHeight.y + 181 + 'px' }}>
                <Card
                  type="inner"
                  size="small"
                  title="基本信息"
                  extra={(
                    categoryData?.entrySequenceBtnFlag === 'Y' ? (
                      <Button
                        size="small"
                        onClick={() => this.handleEntrySequence(baseCompontName)}
                      >
                        录入顺序
                      </Button>
                    ) : ''
                  )}
                >
                  <DynamicRenderingForm
                    isEnterJump='Y'
                    formItemCol={{ labelCol: 8, wrapperCol: 16, col: 6 }}
                    rowData={rowData}
                    selectData={selectData}
                    formData={baseFormData}
                    onRef={ref => this.baseFormRef = ref}
                    handleQueryFormData={this.getTableColumns}
                  />
                </Card>
                <Card
                  type="inner"
                  size="small"
                  title={categoryData?.detailCardTitle || '明细'}
                  style={{ margin: '12px 0', minHeight: store.getState().tableHeight.y - 80 + 'px' }}
                  extra={(
                    categoryData?.entrySequenceBtnFlag === 'Y' ? (
                      <Button
                        size="small"
                        onClick={() => this.handleEntrySequence(detailComponentName)}
                      >
                        录入顺序
                      </Button>
                    ) : ''
                  )}
                >
                  <DynamicRenderingForm
                    isEnterJump='Y'
                    selectData={selectData}
                    rowData={detailRowData}
                    formData={inputFormData}
                    modalTotalWidth={modalTotalWidth}
                    modalTableComponentName={modalTableName}
                    modalColumns={modalTableColumns && modalTableColumns.length > 0 ? modalTableColumns : []}
                    onRef={ref => this.inputFormRef = ref}
                    handleQueryFormData={this.getDetailColumns}
                    modalConfirmSelect={this.handleConfirmSelect}
                    modalSelectClear={this.handleModalSelectClear}
                    getModalTableParams={this.getModalTableParams}
                    getModalTableColumns={this.getModalTableColumns}
                  />

                  <PubilcTablePagination
                    title={componentName === 'ProductPriceAdjustment' ? '' : () => {
                      return (
                        <div className="flex-between-center">
                          <div className="flex-align-items">
                            {/* <Button
                            ghost
                            type="primary"
                            disabled={!(selectedRowKeys && selectedRowKeys.length > 0)}
                          >
                            打印标签
                          </Button> */}
                            <Input
                              ref={this.scanningRef}
                              placeholder={categoryData?.scanningPlaceholder || '扫码添加'}
                              value={scanningCode}
                              style={{ width: '350px', marginRight: '12px' }}
                              disabled={!detailDeleteFlag}
                              onChange={Util.commonInputChange.bind(this, 'scanningCode')}
                              onPressEnter={this.handleScanningCodePressEnter}
                            />
                            {categoryData?.auxiliaryBtnFlag === 'Y' ? (
                              <Button
                                ghost
                                type="primary"
                                onClick={this.handleOrderOfGlassesClick}
                                disabled={!(!rowID || (rowData && rowData.statusCode === '10'))}
                              >
                                {categoryData?.auxiliaryBtnTitle || '辅助录单'}
                              </Button>
                            ) : ''}
                            {categoryData?.detailImportExcelBtnFlag === 'Y' ? (
                              <Upload  {...detailUploadExcelParams}>
                                <Button
                                  ghost
                                  type="primary"
                                  style={{ marginLeft: '12px' }}
                                  disabled={!(!rowID || (rowData && rowData.statusCode === '10'))}
                                >
                                  {categoryData?.detailImportExcelBtnTitle || '导入'}
                                </Button>
                              </Upload>
                            ) : ''}
                          </div>
                          <div className="common-voucher-preparation-statistics">
                            共计：<span className="common-voucher-preparation-statistics-span">{detailTableData?.length || 0}</span>条记录
                            {categoryData.totalAmountFlag === 'Y' ? <>
                              <span style={{ marginLeft: 12 }}>{categoryData?.rpSumDesc || '进价总金额'}：</span>
                              <span className="common-voucher-preparation-statistics-span">{sumRp || 0}</span>
                              <span style={{ marginLeft: 12 }}>{categoryData?.spSumDesc || '售价总金额'}：</span>
                              <span className="common-voucher-preparation-statistics-span">{sumSp || 0}</span>
                            </> : ''}
                          </div>
                        </div>
                      )
                    }}
                    param={{
                      y: 'N',
                      height: 'auto',
                      loading: detailLoading,
                      data: detailTableData, // 表格数据
                      x: detailTotalWidth, // 表格的宽度
                      componentName: detailComponentName,
                      columns: detailColumns && detailColumns.length > 0 ? [...detailColumns, operationDetailObj] : [], // 表头配置
                    }}
                    // rowSelectionPublic={rowSelection}
                    getColumns={this.getDetailColumns}
                    onClickRowPublic={this.handleDetailRowClick}
                    setRowClassNamePublic={this.handleDetailRowClassName}
                  />
                </Card>
                <div className="common-voucher-preparation-right-footer flex-center-align-end">
                  <Button
                    ghost
                    type="primary"
                    loading={saveBtnLoading}
                    // 注：入库制单已审核的数据可以修改部分信息
                    disabled={rowID ? (rowData.statusCode === '10' || rowData.statusCode === 'No' || (rowData?.statusCode === '30' && componentName === 'NVPReceiptVP') ? false : true) : false}
                    onClick={() => this.handleSave('10')}
                  >
                    {rowID ? '确认修改' : (categoryData.revokeCode ? '暂存' : '保存')}
                  </Button>
                  {categoryData.revokeCode ? ( // 取消审核接口
                    <>
                      <Button
                        type="primary"
                        loading={auditBtnLoading}
                        style={{ display: !rowID || (rowData.statusCode === '10') ? 'inline-block' : 'none', marginLeft: '12px' }}
                        onClick={() => this.handleSave('20')}
                      >
                        {categoryData?.auditBtnTitle || '提交审核'}
                      </Button>
                      <Popconfirm
                        title="撤销后不可恢复，确定要撤销吗?"
                        onConfirm={() => this.handleModifyOrderStatus('40')}
                      >
                        <Button
                          ghost
                          type="danger"
                          loading={auditBtnLoading}
                          style={{ display: rowData.statusCode === '20' ? 'inline-block' : 'none', marginLeft: '12px' }}
                        >
                          {categoryData?.revokeBtnTitle || '撤回单据'}
                        </Button>
                      </Popconfirm>
                    </>
                  ) : ''}
                  {categoryData.printCode ? ( // 打印单据
                    <>
                      <Button
                        type="primary"
                        loading={printBtnLoading}
                        style={{ display: rowID ? 'inline-block' : 'none', marginLeft: '12px' }}
                        onClick={this.handlePrint}
                      >
                        {categoryData?.printBtnTitle || '打印单据'}
                      </Button>
                    </>
                  ) : ''}
                </div>
              </div>
            </Card>
          </div>
          <OrderOfGlassesModal
            frLocID={frLocID}
            defaultDate={defaultDate}
            orderModalType={orderModalType}
            modalTitle={categoryData?.auxiliaryModalTitle || ''}
            interfaceFlag={categoryData?.componentName || ''}
            selectData={selectData}
            getTableData={this.getDetailTableData}
            addDetailData={this.handleAddDetailData}
            onRef={ref => this.orderOfGlassesRef = ref}
          />
          <ReviewedReceiptVPModal
            frLocID={frLocID}
            defaultDate={defaultDate}
            addDetailData={this.handleAddDetailData}
            onRef={ref => this.reviewedRVPRef = ref}
          />

          {/* 查看详情 */}
          <MatchingDetails interfaceFlag="VoucherPreparation" onRef={ref => this.matchingDetailsRef = ref} />
        </div>
      </Spin>
    )
  }
};

export default VoucherPreparation;

/*
 * 菜单参数配置
 * interfaceType - 动态组件类型（采购计划样式，入库制单样式）
 * componentName - 组件名
 * selectCode - 初始化接口对应的code
 * queryCode - 查询接口
 * idIndex - 主列表行ID字段名
 * deleteCode - 删除接口对应code
 * queryDetailCode - 明细列表对应code
 * detailIDIndex - 明细列表行ID字段名
 * saveCode - 保存接口对应code
 * modalTableName - 产品名称对应的table表头名
 * cardTitle - 左侧card描述
 * detailCardTitle - 明细card描述
 * revokeCode - 撤销代码
 * scanningPlaceholder - 扫码输入域提示文字
 * auxiliaryModalTitle - 辅助制单弹窗描述
 * auditBtnTitle - 审核按钮文字描述
 * revokeBtnTitle - 撤销按钮文字描述
 * orderModalType - 辅助制单弹窗查询列表类型，用于区分界面
 * 入库制单: params=interfaceType:voucherPreparation&selectCode:17030029&cardTitle:入库制单&detailCardTitle:入库明细&componentName:NVPReceiptVP&queryCode:17030030&queryDetailCode:17030031&idIndex:metStkRecID&detailIDIndex:metStkRecDetailID&deleteCode:17030035&saveCode:17030032&revokeCode:17030050&auxiliaryBtnTitle:依据订单&scanningPlaceholder:扫码入库&orderModalType:InOperate&auxiliaryLocIDIndex:locID&printCode:17030081&stateSpreadingFlag:N&auxiliaryBtnFlag:Y&totalAmountFlag:Y&entrySequenceBtnFlag:Y&addBtnFlag:Y&printBtnFlag:N&operationFixedFlag:N&interfaceTypeDesc:入库制单样式
 * 转移制单: params=interfaceType:voucherPreparation&selectCode:17030059&cardTitle:出库单&detailCardTitle:出库单明细&componentName:NVPTransferVP&queryCode:17030060&queryDetailCode:17030061&idIndex:metStkTransferID&detailIDIndex:metStkTransDetailID&deleteCode:17030064&saveCode:17030063&revokeCode:17030065&modalTableName:NVPReceiptVPModalTable&auxiliaryBtnTitle:已审核入库单&scanningPlaceholder:扫码出库&printCode:17030082&stateSpreadingFlag:N&auxiliaryBtnFlag:Y&totalAmountFlag:Y&entrySequenceBtnFlag:Y&addBtnFlag:Y&printBtnFlag:N&operationFixedFlag:N&interfaceTypeDesc:入库制单样式
 * 退货制单: params=interfaceType:voucherPreparation&selectCode:17030036&cardTitle:退货制单&detailCardTitle:退货单明细&componentName:NVPReturnVP&queryCode:17030040&queryDetailCode:17030041&idIndex:stkReturnID&detailIDIndex:stkReturnDetailID&deleteCode:17030038&saveCode:17030037&revokeCode:17030044&modalTableName:NVPReceiptVPModalTable&scanningPlaceholder:扫码退货&stateSpreadingFlag:N&auxiliaryBtnFlag:N&totalAmountFlag:N&entrySequenceBtnFlag:N&addBtnFlag:Y&interfaceTypeDesc:入库制单样式
 * 
 * */
