import React, { Component } from 'react';
import { DownOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
// import '@ant-design/compatible/assets/index.css';
import { Layout, Spin, Button, Row, Col, message } from 'antd-v4';
import CommonListEvent from '@/components/Common/CommonListEvent';/* 继承销售模块业务功能 */
// import * as commonUtils from '../../utils/utils'; /* 通用方法 */
import * as commonFunc from '@/components/Common//commonFunc';/* 通用单据方法 */ /* 通用单据方法 */
// eslint-disable-next-line import/no-named-as-default
import StaticEditTable from '@/components/Common//CommonTable';/* 可编辑表格 */
import StaticEditTree from '@/components/Common/Tree/StaticTree';
import CommonBase from '@/components/Common/CommonBase';/* 获取配置及数据 */
import * as commonBusiness from '@/components/Common//commonBusiness';/* 单据业务功能 */
import SearchComponent from '@/components/Common/SearchComponent';
import AntdDraggableModal from '@/components/Common/AntdDraggableModal';
import * as commonUtils from '@/utils/utils';
import ShowType from '@/components/Common/CommonComponent';
import commonConfig from '@/utils/config';
// import DelIcon from '../../assets/delete.svg';
// import DisableDelIcon from '../../assets/disabledelete.svg';

const { Content } = Layout;
/**
 此组件是选择工序、放大镜弹窗等的通用窗体
 */
class CommonList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      btnList: [],
      openFlag: false,
    };
  }
  componentWillReceiveProps(nextProps) {
    const {
      slaveData, selectedRowKeys, sModelsType, slaveFilterData, slaveSelectedData, masterConfig,
      gdsjurisdiction,
    } = nextProps;
    if (slaveFilterData === undefined && sModelsType === 'search/sisColor') {
      if (commonUtils.isNotEmptyArr(slaveData) && commonUtils.isNotEmptyArr(selectedRowKeys)) {
        const slaveFilterData = slaveData.filter(item => selectedRowKeys.includes(item.sSlaveId));
        if (commonUtils.isNotEmptyArr(slaveFilterData)) {
          this.props.onSaveState({
            slaveFilterData, slaveSelectedRowKeys: selectedRowKeys,
          });
        }
      }
    } else if (commonUtils.isEmptyArr(slaveFilterData) && sModelsType === 'search/commonPopup') {
      if (commonUtils.isNotEmptyArr(slaveData) && commonUtils.isNotEmptyArr(slaveSelectedData)) {
        this.props.onSaveState({
          slaveFilterData: slaveSelectedData,
        });
      }
    }
    if (masterConfig) {
      // 过滤存储需要展示的按钮
      let btnList = masterConfig.gdsconfigformslave.filter(item => item.bVisible && !item.sName && item.showName && item.sControlName);
      btnList = btnList.filter(item => gdsjurisdiction.findIndex(child => item.sControlName === child.sAction) < 0 && (item.sControlName.includes('BtnAdd') || item.sControlName.includes('BtnCopyTo')));
      // 过滤权限
      this.setState({ btnList });
    }
    if (this.state.openFlag) {
      this.setState({ openFlag: false }, () => {
        this.props.onButtonClick('BtnRefresh');
      });
    }
  }

  onOpenNewTab = () => {
    this.setState({ openFlag: true });
    this.props.onOpenNewTab();
  }

  /**   确认下单   */
  handleSelect = () => {
    const { slaveFilterData, app } = this.props;
    // 这一段个性化，标版不要yhl
    if (commonUtils.isNotEmptyArr(slaveFilterData)) {
      const { sVersionNum, iNumberOfTime } = slaveFilterData[0];
      if (sVersionNum && iNumberOfTime) {
        const index = slaveFilterData.findIndex(item => !(item.sVersionNum === sVersionNum && item.iNumberOfTime === iNumberOfTime));
        if (index > -1) {
          message.error('请选择相同版本的烫金工次！');
          return;
        }
        // if (iNumberOfTime) {
        //   for (const slaveFilter of slaveFilterData) {
        //     console.log(slaveFilter.iNumberOfTime, iNumberOfTime);
        //     if (slaveFilter.iNumberOfTime !== iNumberOfTime) {
        //       message.error('请选择相同烫金工次！');
        //       return;
        //     }
        //   }
        // }
      }
    }
    this.props.app.currentPane.select(app.currentPane.name, app.currentPane.config, slaveFilterData);
    this.props.app.currentPane.selectCancel(app.currentPane.name);
    this.props.onSaveState({
      slaveFilterData: [],
    });
  };
  handleDoubleClickSelect = () => {
    const { slaveConfig } = this.props;
    if (commonUtils.isNotEmptyObject(slaveConfig) && !slaveConfig.bMutiSelect) { // 单选时双击选中数据
      this.handleSelect();
    }
  }
  /**   关闭   */
  handleCancelModal = () => {
    const { app } = this.props;
    this.props.app.currentPane.selectCancel(app.currentPane.name);
  };
  /**   树节点多选框选中   */
  handleTreeCheck = (checkedKeys, e) => {
    this.props.onCheck(checkedKeys, e); /* 调用CommonListEvent通用处理 */
  };
  /**   树节点选中   */
  handleTreeSelect = (name, checkedKeys, e) => {
    this.props.onSelect(name, checkedKeys, e); /* 调用CommonListEvent通用处理 */
  };

  handleTableSelectRowChangeContinue = (name, selectedRowKeys, changeValue, chooseProcessParams) => { /* 表格行选择 */
    this.props.onTableSelectRowChange(name, selectedRowKeys);
    if (name === 'slave') { /* 选择工序 从表表 */
      const {
        [`${name}Data`]: tableData, slaveConfig, fatherModelsType, sModelsType, sModelsId,
      } = this.props;
      const { selectedRowKeysLength } = this.props;
      const { slaveFilterData } = this.props;
      const oldSlaveFilterData = slaveFilterData === undefined ? [] : JSON.parse(JSON.stringify(slaveFilterData));
      const newSlaveFilterData = JSON.parse(JSON.stringify(oldSlaveFilterData));
      selectedRowKeys.forEach((key) => {
        const filterDataIndex = oldSlaveFilterData.findIndex(item => item.sSlaveId === key);
        if (filterDataIndex < 0) {
          const tableDataIndex = tableData.findIndex(item => item.sSlaveId === key);
          if (tableDataIndex > -1) {
            const newRow = JSON.parse(JSON.stringify(tableData[tableDataIndex]));
            const tableRow = tableData[tableDataIndex];
            newRow.sId = commonUtils.createSid();
            newRow.sSlaveId = newRow.sId;
            newRow.handleType = 'add';
            newRow.key = newRow.sId;
            if (sModelsId === '12710101117043535363530') { /* 电化铝相同批次，版本 一起选入 */
              const filterData = tableData.filter(item => item.sVersionNum === tableRow.sVersionNum && item.iNumberOfTime === tableRow.iNumberOfTime);
              if (commonUtils.isNotEmptyArr(filterData)) {
                filterData.filter(item => item.sSlaveId === key).forEach((item) => {
                  newSlaveFilterData.push(item);
                });
                filterData.filter(item => item.sSlaveId !== key).forEach((item) => {
                  newSlaveFilterData.push(item);
                });
              }
            } else if (sModelsId === '12710101117192007380600') { /* 托盘版本相同的工单，版本 一起选入 */
              const filterData = tableData.filter(item => item.sId === tableRow.sId && item.sWorkOrderNo === tableRow.sWorkOrderNo);
              if (commonUtils.isNotEmptyArr(filterData)) {
                filterData.forEach((item) => {
                  newSlaveFilterData.push(item);
                });
              }
            } else {
              newSlaveFilterData.push(newRow);
            }
          }
        } else if (sModelsId !== '12710101117043535363530' && sModelsId !== '12710101117192007380600') {
          /* 连续点击 复制数据 */
          const newRow = JSON.parse(JSON.stringify(oldSlaveFilterData[filterDataIndex]));
          newRow.sId = commonUtils.createSid();
          newRow.sSlaveId = newRow.sId;
          newRow.handleType = 'add';
          newRow.key = newRow.sId;
          newSlaveFilterData.push(newRow);
        }
      });
      let sDeliverRemark = '';
      if (sModelsType === 'search/commonPopup') { /* 选择成品库存 改变时候 增加数量信息提示 */
        let dChooseProductQty = 0;
        let dSrcQty = 0;
        let dMinsQty = 0; /* 欠数 */
        newSlaveFilterData.forEach((item, index) => {
          if (index === 0) {
            dSrcQty += commonUtils.isNull(item.dSReserve1, 0); /* 源单数量取其中一条 */
          }
          dChooseProductQty += commonUtils.isNull(item.dProductQty, 0); /* 库存数量叠加 */
        });
        dMinsQty = commonUtils.convertFixNum(dSrcQty, 2) - commonUtils.convertFixNum(dChooseProductQty, 2);
        sDeliverRemark = `源单数量：${dSrcQty}  已选数量：${dChooseProductQty}  欠数：${dMinsQty}`;
      }

      this.props.onSaveState({
        slaveFilterData: newSlaveFilterData, sDeliverRemark,
      });
      if (chooseProcessParams) {
        let modalVisible = false;
        let slaveSelectOneData = {};
        let slaveSelectOneDataIndex = -1;
        if (commonUtils.isNotEmptyArr(tableData)) {
          if (selectedRowKeys instanceof Array) { // 多选情况下
            if (commonUtils.isEmpty(selectedRowKeysLength) || (selectedRowKeys.length - selectedRowKeysLength) > 0) {
              modalVisible = true;
            }
            slaveSelectOneDataIndex = tableData.findIndex(item => item.sId === selectedRowKeys[selectedRowKeys.length - 1]); // 多选选择最后一个
          } else { // 单选情况下
            slaveSelectOneDataIndex = tableData.findIndex(item => item.sId === selectedRowKeys);
          }
          if (slaveSelectOneDataIndex > -1) {
            slaveSelectOneData = tableData[slaveSelectOneDataIndex];
          }
        }
        // let masterData = {};
        const sProcessParamsSelects = [];
        let paramType = '';
        if (commonUtils.isNotEmptyObject(slaveSelectOneData) && commonUtils.isNotEmptyObject(fatherModelsType)) {
          if (fatherModelsType.includes('manufacture/')) {
            paramType = slaveSelectOneData.sWorkOrderParam;
            if (commonUtils.isNotEmptyObject(slaveSelectOneData.sWorkOrderParam)) {
              slaveSelectOneData = { ...slaveSelectOneData, ...commonUtils.convertStrToObj(slaveSelectOneData.sWorkOrderParam) };
              tableData[slaveSelectOneDataIndex] = { ...tableData[slaveSelectOneDataIndex], ...slaveSelectOneData };
            }
          } else if (fatherModelsType.includes('quotation/')) {
            paramType = slaveSelectOneData.sProcessParam;
            if (commonUtils.isNotEmptyObject(slaveSelectOneData.sProcessParam)) {
              slaveSelectOneData = { ...slaveSelectOneData, ...commonUtils.convertStrToObj(slaveSelectOneData.sProcessParam) };
              tableData[slaveSelectOneDataIndex] = { ...tableData[slaveSelectOneDataIndex], ...slaveSelectOneData };
            }
          }
        }
        if (commonUtils.isNotEmptyObject(paramType)) {
          // eslint-disable-next-line no-plusplus
          for (let i = 1; i < 31; i++) {
            const iIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.sName === `sParamValue${i.toString()}`);
            if (iIndex > -1 && !commonUtils.isEmpty(slaveSelectOneData[`sParam${i.toString()}`])) {
              slaveConfig.gdsconfigformslave[iIndex].showName = slaveSelectOneData[`sParam${i.toString()}`];
              slaveConfig.gdsconfigformslave[iIndex].bVisible = !slaveSelectOneData[`sParam${i.toString()}`].includes('参数值');
              /* 判断是否是sql下拉 */
              if (!commonUtils.isEmpty(slaveSelectOneData[`sParamDropDown${i.toString()}`])) {
                slaveConfig.gdsconfigformslave[iIndex].sDropDownType = 'sql';
              }
              // masterData = { ...masterNewData, ...commonUtils.convertStrToObj(slaveFilterData[0].sProcessParam) };
              sProcessParamsSelects.push(slaveConfig.gdsconfigformslave[iIndex]);
            } else if (iIndex > -1) {
              slaveConfig.gdsconfigformslave[iIndex].bVisible = false;
            }
          }
        } else {
          modalVisible = false;
          // eslint-disable-next-line no-plusplus
          for (let i = 1; i < 31; i++) {
            const iIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.sName === `sParamValue${i.toString()}`);
            if (iIndex > -1) {
              slaveConfig.gdsconfigformslave[iIndex].bVisible = false;
            }
          }
        }
        this.props.onSaveState({
          sProcessParamsModalVisible: modalVisible,
          sProcessParamsSelects,
          slaveSelectOneDataIndex,
          selectedRowKeysLength: selectedRowKeys.length,
        });
      }
    }
  }

  handleTableSelectRowChange = (name, selectedRowKeys, changeValue, chooseProcessParams) => { /* 表格行选择 */
    const { app } = this.props;
    // eslint-disable-next-line prefer-destructuring
    let bContinueClick = commonUtils.isNotEmptyObject(app.currentPane.config.sControlName) ?
      app.currentPane.config.sControlName.includes('BtnPopupMaterials') || app.currentPane.config.sControlName.includes('BtnHeadPopup')
      || app.currentPane.config.sControlName.includes('BtnChooseProcess')
      || app.currentPane.config.sControlName.includes('BtnPopupTray')
      || app.currentPane.config.sControlName.includes('BtnPopupsAlumiteBomBillNo') : false;
    if (!bContinueClick) {
      bContinueClick = app.currentPane.config?.sName === 'sAlumiteBomBillNo';
    }
    if (bContinueClick) { /* 连续点击 */
      this.handleTableSelectRowChangeContinue(name, selectedRowKeys, changeValue, chooseProcessParams);
    } else {
      this.props.onTableSelectRowChange(name, selectedRowKeys);
      if (name === 'slave') { /* 选择工序 从表表 */
        const {
          [`${name}Data`]: tableData, slaveConfig, fatherModelsType, sModelsType, sModelsId,
        } = this.props;
        const { selectedRowKeysLength } = this.props;
        const { slaveFilterData } = this.props;
        const oldSlaveFilterData = slaveFilterData === undefined ? [] : JSON.parse(JSON.stringify(slaveFilterData));
        const newSlaveFilterData = [];
        selectedRowKeys.forEach((key) => {
          const filterDataIndex = oldSlaveFilterData.findIndex(item => item.sSlaveId === key);
          if (filterDataIndex < 0) {
            const tableDataIndex = tableData.findIndex(item => item.sSlaveId === key);
            /* 电化铝找到相同批次版本的添加进去 */
            const tableRow = tableData[tableDataIndex];
            newSlaveFilterData.push({ ...tableData[tableDataIndex] });
            if (sModelsId === '12710101117043535363530') { /* 电化铝相同批次，版本 一起选入 */
              const filterData = tableData.filter(item => item.sVersionNum === tableRow.sVersionNum && item.iNumberOfTime === tableRow.iNumberOfTime &&
                item.sSlaveId !== tableRow.sSlaveId);
              if (commonUtils.isNotEmptyArr(filterData)) {
                filterData.forEach((item) => {
                  newSlaveFilterData.push(item);
                });
              }
            }
          } else {
            newSlaveFilterData.push({ ...oldSlaveFilterData[filterDataIndex] });
          }
        });
        let sDeliverRemark = '';
        if (sModelsType === 'search/commonPopup') { /* 选择成品库存 改变时候 增加数量信息提示 */
          let dChooseProductQty = 0;
          let dSrcQty = 0;
          let dMinsQty = 0; /* 欠数 */
          newSlaveFilterData.forEach((item, index) => {
            if (index === 0) {
              dSrcQty += commonUtils.isNull(item.dSReserve1, 0); /* 源单数量取其中一条 */
            }
            dChooseProductQty += commonUtils.isNull(item.dProductQty, 0); /* 库存数量叠加 */
          });
          dMinsQty = commonUtils.convertFixNum(dSrcQty, 2) - commonUtils.convertFixNum(dChooseProductQty, 2);
          sDeliverRemark = `源单数量：${dSrcQty}  已选数量：${dChooseProductQty}  欠数：${dMinsQty}`;
        }

        this.props.onSaveState({
          slaveFilterData: newSlaveFilterData, sDeliverRemark,
        });
        if (chooseProcessParams) {
          let modalVisible = false;
          let slaveSelectOneData = {};
          let slaveSelectOneDataIndex = -1;
          if (commonUtils.isNotEmptyArr(tableData)) {
            if (selectedRowKeys instanceof Array) { // 多选情况下
              if (commonUtils.isEmpty(selectedRowKeysLength) || (selectedRowKeys.length - selectedRowKeysLength) > 0) {
                modalVisible = true;
              }
              slaveSelectOneDataIndex = tableData.findIndex(item => item.sId === selectedRowKeys[selectedRowKeys.length - 1]); // 多选选择最后一个
            } else { // 单选情况下
              slaveSelectOneDataIndex = tableData.findIndex(item => item.sId === selectedRowKeys);
            }
            if (slaveSelectOneDataIndex > -1) {
              slaveSelectOneData = tableData[slaveSelectOneDataIndex];
            }
          }
          // let masterData = {};
          const sProcessParamsSelects = [];
          let paramType = '';
          if (commonUtils.isNotEmptyObject(slaveSelectOneData) && commonUtils.isNotEmptyObject(fatherModelsType)) {
            if (fatherModelsType.includes('manufacture/')) {
              paramType = slaveSelectOneData.sWorkOrderParam;
              if (commonUtils.isNotEmptyObject(slaveSelectOneData.sWorkOrderParam)) {
                slaveSelectOneData = { ...slaveSelectOneData, ...commonUtils.convertStrToObj(slaveSelectOneData.sWorkOrderParam) };
                tableData[slaveSelectOneDataIndex] = { ...tableData[slaveSelectOneDataIndex], ...slaveSelectOneData };
              }
            } else if (fatherModelsType.includes('quotation/')) {
              paramType = slaveSelectOneData.sProcessParam;
              if (commonUtils.isNotEmptyObject(slaveSelectOneData.sProcessParam)) {
                slaveSelectOneData = { ...slaveSelectOneData, ...commonUtils.convertStrToObj(slaveSelectOneData.sProcessParam) };
                tableData[slaveSelectOneDataIndex] = { ...tableData[slaveSelectOneDataIndex], ...slaveSelectOneData };
              }
            }
          }
          if (commonUtils.isNotEmptyObject(paramType)) {
            // eslint-disable-next-line no-plusplus
            for (let i = 1; i < 31; i++) {
              const iIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.sName === `sParamValue${i.toString()}`);
              if (iIndex > -1 && !commonUtils.isEmpty(slaveSelectOneData[`sParam${i.toString()}`])) {
                slaveConfig.gdsconfigformslave[iIndex].showName = slaveSelectOneData[`sParam${i.toString()}`];
                slaveConfig.gdsconfigformslave[iIndex].bVisible = !slaveSelectOneData[`sParam${i.toString()}`].includes('参数值');
                /* 判断是否是sql下拉 */
                if (!commonUtils.isEmpty(slaveSelectOneData[`sParamDropDown${i.toString()}`])) {
                  slaveConfig.gdsconfigformslave[iIndex].sDropDownType = 'sql';
                }
                // masterData = { ...masterNewData, ...commonUtils.convertStrToObj(slaveFilterData[0].sProcessParam) };
                sProcessParamsSelects.push(slaveConfig.gdsconfigformslave[iIndex]);
              } else if (iIndex > -1) {
                slaveConfig.gdsconfigformslave[iIndex].bVisible = false;
              }
            }
          } else {
            modalVisible = false;
            // eslint-disable-next-line no-plusplus
            for (let i = 1; i < 31; i++) {
              const iIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.sName === `sParamValue${i.toString()}`);
              if (iIndex > -1) {
                slaveConfig.gdsconfigformslave[iIndex].bVisible = false;
              }
            }
          }
          this.props.onSaveState({
            sProcessParamsModalVisible: modalVisible,
            sProcessParamsSelects,
            slaveSelectOneDataIndex,
            selectedRowKeysLength: selectedRowKeys.length,
          });
        }
      }
    }
  }
  handleCancelProcessParamsModalVisible = () => {
    this.props.onSaveState({
      sProcessParamsModalVisible: false,
    });
  }
  handleProcessParamsOk = () => {
    const {
      slaveData, slaveSelectOneDataIndex, slaveFilterData, sProcessParamsSelects,
    } = this.props;
    let sProcessParamStr = '';
    if (commonUtils.isNotEmptyArr(slaveData) && !commonUtils.isEmpty(slaveSelectOneDataIndex) && commonUtils.isNotEmptyArr(slaveFilterData) && commonUtils.isNotEmptyArr(sProcessParamsSelects)) {
      // eslint-disable-next-line array-callback-return
      sProcessParamsSelects.map((item) => {
        let sParamValue = '';
        if (commonUtils.isNotEmptyObject(slaveData[slaveSelectOneDataIndex][item.sName])) {
          sParamValue = slaveData[slaveSelectOneDataIndex][item.sName];
        }
        sProcessParamStr += `${item.showName}:${sParamValue},`;
      });
      slaveFilterData[slaveFilterData.length - 1].sProcessParamStr = sProcessParamStr;
      slaveFilterData[slaveFilterData.length - 1] = { ...slaveFilterData[slaveFilterData.length - 1], ...slaveData[slaveSelectOneDataIndex] };
    }
    this.props.onSaveState({
      slaveFilterData,
      sProcessParamsModalVisible: false,
    });
  }
  // ----------------------------数据修改回带end  ---------------------------- //
  copyTo = (sActiveId) => {
    const {
      dispatch, masterConfig, masterData, contactData, addressData, slavePagination,
      sisproductclassifyProcessClassifyData, machineData, assortData, outsideData, processstyleData, processApsRuleData,
      eleemployeeData, elemachineData, eleknifemouldproductData, eleknifemouldfileData, eleteststandarditemData,
      slaveSelectedData,
    } = this.props;
    const copyTo = {};
    const copyToConfig = masterConfig.gdsconfigformslave.filter(item => item.sControlName.includes(name));
    copyTo.name = 'BtnCopyTo';
    copyTo.config = copyToConfig;
    copyTo.masterData = slaveSelectedData[0] || masterData;
    copyTo.supplyData = [];
    copyTo.stockData = [];
    copyTo.contactData = contactData;
    copyTo.addressData = addressData;
    copyTo.picFileData = [];
    copyTo.customerInfoData = [];
    copyTo.sisproductclassifyProcessClassifyData = sisproductclassifyProcessClassifyData;
    copyTo.machineData = machineData;
    copyTo.assortData = assortData;
    copyTo.outsideData = outsideData;
    copyTo.processstyleData = processstyleData;
    copyTo.processApsRuleData = processApsRuleData;
    copyTo.eleemployeeData = eleemployeeData;
    copyTo.elemachineData = elemachineData;
    copyTo.eleknifemouldproductData = eleknifemouldproductData;
    copyTo.eleknifemouldfileData = eleknifemouldfileData;
    copyTo.eleteststandarditemData = eleteststandarditemData;
    dispatch({
      type: 'content/onRouter',
      payload: {
        url: `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`, /*   接口地址   */
        copyTo,
        pages: slavePagination,
        newRecordFlag: `NewRecord_${sActiveId}`,
      },
    });
  }

  handleDrag = (data) => {
    this.props.onSaveState({
      slaveFilterData: data,
    });
  }

  handleTableDel = (name, isWait, tableSelectedRowKeys) => {
    const {
      slaveSelectedRowKeys, sModelsId, slaveFilterData, slaveFilterDelData = [],
    } = this.props;
    if (commonUtils.isNotEmptyArr(tableSelectedRowKeys) && commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
      if (sModelsId === '12710101117043535363530') { /* 电化铝相同批次，版本 一起选入 */
        const iIndex = slaveFilterData.findIndex(item => tableSelectedRowKeys.includes(item.sSlaveId));
        if (iIndex > -1) {
          const tableRow = slaveFilterData[iIndex];
          const filterData = slaveFilterData.filter(item => item.sVersionNum === tableRow.sVersionNum && item.iNumberOfTime === tableRow.iNumberOfTime);
          if (commonUtils.isNotEmptyArr(filterData)) {
            filterData.forEach((item) => {
              tableSelectedRowKeys.push(item.sSlaveId);
              const iDelIndex = slaveFilterData.findIndex(row => row.sSlaveId === item.sSlaveId);
              if (iDelIndex > -1) {
                slaveFilterDelData.push(slaveFilterData[iDelIndex]);
                slaveFilterData.splice(iDelIndex, 1);
              }
            });
            this.props.onSaveState({ [`${name}Data`]: slaveFilterData, slaveSelectedData: slaveFilterData });
            return;
          }
        }
      } else if (sModelsId === '12710101117192007380600') { /* 托盘放大镜选择相同工单 */
        const iIndex = slaveFilterData.findIndex(item => tableSelectedRowKeys.includes(item.sSlaveId));
        if (iIndex > -1) {
          const tableRow = slaveFilterData[iIndex];
          const filterData = slaveFilterData.filter(item => item.sVersionNum === tableRow.sVersionNum && item.iNumberOfTime === tableRow.iNumberOfTime);
          if (commonUtils.isNotEmptyArr(filterData)) {
            filterData.forEach((item) => {
              tableSelectedRowKeys.push(item.sSlaveId);
              const iDelIndex = slaveFilterData.findIndex(row => row.sSlaveId === item.sSlaveId);
              if (iDelIndex > -1) {
                slaveFilterDelData.push(slaveFilterData[iDelIndex]);
                slaveFilterData.splice(iDelIndex, 1);
              }
            });
            this.props.onSaveState({ [`${name}Data`]: slaveFilterData, slaveSelectedData: slaveFilterData });
            return;
          }
        }
      }
      slaveSelectedRowKeys.forEach((item, index) => {
        if (tableSelectedRowKeys.includes(item)) {
          slaveSelectedRowKeys.splice(index, 1);
        }
      });
      const value = this.props.onDataRowDel(name, true, tableSelectedRowKeys);
      this.props.onSaveState({
        ...value,
        slaveSelectedData: value?.[`${name}Data`],
      });
    }
  }
  render() {
    const { pageLoading } = this.props;
    return (
      <div style={{ height: '100%' }}>
        <Spin spinning={pageLoading}>
          <div style={{ height: '100%' }}>
            <CommonListComponent
              {...this.props}
              {...this.state}
              onOpenNewTab={this.onOpenNewTab}
              onSelect={this.handleSelect}
              onCancel={this.handleCancelModal}
              onDoubleClick={this.handleDoubleClickSelect}
              onCheck={this.handleTreeCheck}
              onSelectTree={this.handleTreeSelect}
              onTableSelectRowChange={this.handleTableSelectRowChange}
              onProcessParamsOk={this.handleProcessParamsOk}
              onCancelProcessParamsModalVisible={this.handleCancelProcessParamsModalVisible}
              onCopyTo={this.copyTo}
              onDrag={this.handleDrag}
              onDataRowDel={this.handleTableDel}
            />
          </div>
        </Spin>
      </div>
    );
  }
}

const CommonListComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form);
    return obj;
  },
})((props) => {
  const {
    form,
    onReturnForm,
    slavePagination,
    app,
    // masterData: masterDataNew,
    slaveData,
    sProcessParamsSelects,
    slaveSelectedRowKeys: selectedRowKeys,
    sModelsType,
    onCopyTo,
    slaveSelectedData,
    slaveConfig,
  } = props;
  /*   回带表单   */
  onReturnForm(form);
  const pagination = {
    ...slavePagination,
    size: 'large',
    showQuickJumper: true,
    hideOnSinglePage: false,
    showTotal: false,
    simple: true,
  };

  const btnConfig = commonUtils.isNotEmptyObject(app) && commonUtils.isNotEmptyObject(app.currentPane) ? app.currentPane.config : '';
  /* 工序里选择用连续点击 */
  let bContinueClick = commonUtils.isNotEmptyObject(btnConfig) ? (commonUtils.isNotEmptyObject(btnConfig.sControlName) ?
    btnConfig.sControlName.includes('BtnPopupMaterials') || btnConfig.sControlName.includes('BtnPopupsAlumiteBomBillNo')
    || btnConfig.sControlName.includes('BtnPopupTray')
    || btnConfig.sControlName.includes('BtnHeadPopup') || btnConfig.sControlName.includes('BtnChooseProcess') : false) : false;
  if (!bContinueClick) {
    bContinueClick = btnConfig?.sName === 'sAlumiteBomBillNo';
  }
  const tableProps = {
    ...commonBusiness.getTableTypes('slave', props),
    tableProps: {
      rowKey: 'sSlaveId', pagination, onChange: props.onTitleChange, chooseProcessParams: true, sModelsType, AutoTableHeight: 350, // chooseProcessParams为选择工序中点击工序名称表格行出现弹窗
    },
    bContinueClick,
  };
  // const width = '18px';
  // const height = '18px';
  // const setDelete = {
  //   title: '删除',
  //   width: { width },
  //   height: { height },
  //   img: <img src={DelIcon} alt="删除" width={width} height={height} />,
  //   disableimg: <img src={DisableDelIcon} alt="删除" width={width} height={height} />,
  // };
  const deleteSet = {
    autoHeight: '100%',
    setOpterationColumn: 'Y',
  };
  let tableFilterProps = {
    ...commonBusiness.getTableTypes('slaveFilter', props),
    tableProps: {
      rowSelection: null, rowKey: 'sSlaveId', onChange: props.onTitleChange, AutoTableHeight: 350,
    },
    onDrag: props.onDrag,
  };
  if (props.sModelsType === 'modal/searchProcess') {
    tableFilterProps = {
      ...tableFilterProps,
      ...deleteSet,
      enabled: true,
    };
  }
  const BtnSure =commonFunc.showMessage(app.commonConst, 'BtnSure') || '确认';
  const BtnCancel  =commonFunc.showMessage(app.commonConst, 'BtnCancel') || '取消';
  if (commonUtils.isNotEmptyObject(app.currentPane) && commonUtils.isNotEmptyObject(app.currentPane.name) && app.currentPane.bEdit) {
    tableFilterProps = {
      ...tableFilterProps,
      enabled: true,
    };
  }
  const tableBelone = commonUtils.isNotEmptyObject(app.currentPane) && commonUtils.isNotEmptyObject(app.currentPane.name) && app.currentPane.bEdit ? 'none' : 'list';

  const name = 'filterTree';
  const treeProps = {
    ...commonBusiness.getTreeTypes('tree', props),
    isSearch: false,
    checkable: false,
    [`${name}Column`]: props[`${name}Column`],
    [`${name}Config`]: props[`${name}Config`],
    [`${name}Data`]: props[`${name}Data`],
    getFloatNum: props.getFloatNum,
    getSqlDropDownData: props.getSqlDropDownData,
    getSqlCondition: props.getSqlCondition,
    handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
    getDateFormat: props.getDateFormat,
    onDoubleClick: props.onDoubleClick,
    onCheck: props.onCheck,
    onSelect: props.onSelectTree,
    disabled: false,
    checkedAll: false,
    unChecked: false,
    defaultExpandAll: true,
    multiple: false,
    expandedKeys: props.expandedKeys,
    showLine: true,
    switcherIcon: <DownOutlined />,
  };
  const sProcessParams = commonFunc.showMessage(app.commonConst, 'sProcessParams');/* 选择工艺参数标题 */
  const displayLeft = (sModelsType !== 'search/sisColor' && sModelsType !== 'search/commonPopup');
  const realizeHeight = commonUtils.isNotEmptyNumber(props.realizeHeight) ? props.realizeHeight : 0;
  const btnClick = (btn) => {
    const { sControlName } = btn;
    const picArr = slaveConfig.gdsconfigformslave.filter(item => (item.sName === 'picArr'));
    if (picArr.length) {
      const sActiveId = picArr[0] ? picArr[0].sActiveId : '';
      if (sControlName === 'BtnAdd') {
        const params = {
          newRecordFlag: `NewRecord_${sActiveId}`,
        };
        if (props.outerMasterData && props.outerMasterData.sCustomerId) {
          params.newRecordRelation = {
            sCustomerId: props.outerMasterData.sCustomerId,
            sCustomerNo: props.outerMasterData.sCustomerNo,
            sCustomerName: props.outerMasterData.sCustomerName,
          };
        }
        props.onAdd(params);
        props.onOpenNewTab();
      } else if (sControlName === 'BtnCopyTo') {
        if (!Array.isArray(slaveSelectedData) || slaveSelectedData.length !== 1) {
          message.warn('请选择一例单据'); // 请选择数据
        } else {
          onCopyTo(sActiveId);
          props.onOpenNewTab();
        }
      }
    }
  };
  return (
    <div className="modalChooseProcessContent">
      <Form >
        <Layout>
          <Layout>
            <div id="modalChooseProcess">
              <div style={{ maxHeight: '100%', zIndex: 20 }}>
                <SearchComponent {...props} />
              </div>
              <Content
                className={realizeHeight <= 0 ? 'xly-normal-list' : 'xly-normal-list resize-container'}
                style={{ height: realizeHeight > 0 ? `${500 + realizeHeight}px` : 'auto', paddingLeft: '10px' }}
              >
                <Row gutter={[8, 0]}>
                  {displayLeft ?
                    <Col span={4} style={{ height: realizeHeight > 0 ? `${500 + realizeHeight}px` : 'auto' }}>
                      <div className="xly-tree-box">
                        <div className="xly-tree-title">过滤项</div>
                        <StaticEditTree {...treeProps} noVlist />
                      </div>
                    </Col> : ''
                  }
                  <Col style={{ height: realizeHeight > 0 ? `${500 + realizeHeight}px` : 'auto' }} span={sModelsType === 'search/commonPopup' ? 15 : 5}>
                    <StaticEditTable {...tableProps} footer="hidden" tableBelone="list" showConfig={props.showConfig} />
                  </Col>
                  <Col style={{ height: realizeHeight > 0 ? `${500 + realizeHeight}px` : 'auto' }} span={displayLeft ? 15 : sModelsType === 'search/commonPopup' ? 9 : 19} >
                    <StaticEditTable dragHandle={props.dragHandle} {...tableFilterProps} bDirectDel={bContinueClick} setOpterationColumn={bContinueClick ? 'Y' : 'N'} footer="hidden" tableBelone={tableBelone} showConfig={props.showConfig} noVlist />
                  </Col>
                </Row>
              </Content>
            </div>
          </Layout>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div>
              {
                props.btnList.map(btn => (
                  <Button
                    onClick={() => btnClick(btn)}
                    style={{ marginRight: 8 }}
                    type="primary"
                    key={btn.sControlName}
                  >
                    { btn.showName }
                  </Button>
                ))
              }
            </div>
            {
              commonUtils.isNotEmptyObject(app.currentPane) && commonUtils.isNotEmptyObject(app.currentPane.name) && app.currentPane.bEdit ?
                <div style={{ width: '46%', color: 'red' }}> {props.sDeliverRemark}</div> : ''
            }
            <div style={{
              width: '50%', textAlign: 'right', marginRight: '9px', marginBottom: '9px',
            }}
            >
              <Button key="back" style={{ marginRight: '8px' }} onClick={props.onCancel}> {BtnCancel}</Button>
              <Button type="primary" onClick={props.onSelect}> {BtnSure}</Button>
            </div>
          </div>
        </Layout>
        {
          props.sProcessParamsModalVisible ?
            <AntdDraggableModal
              width="33%"
              title={sProcessParams}
              visible={props.sProcessParamsModalVisible}
              onOk={props.onProcessParamsOk}
              onCancel={props.onCancelProcessParamsModalVisible}
              // footer={null}
            >
              <div className="sProcessParamsModal" style={{ height: '80%', overflowY: 'auto' }}>
                { commonUtils.isNotEmptyArr(sProcessParamsSelects) && commonUtils.isNotEmptyArr(selectedRowKeys) ?
                  sProcessParamsSelects.map((child) => {
                    const sMemo = child.sName.toLowerCase().endsWith('memo');
                    let enabledNew = !child.bReadonly;
                    if (child.iTag === 1) {
                      enabledNew = false;
                    } else if (child.iTag === 3) {
                      enabledNew = true;
                    }
                    const slaveSelectOneDataIndex = slaveData.findIndex(item => item.sId === selectedRowKeys[selectedRowKeys.length - 1]); // 多选选择最后一个
                    /* 如果没值 则取默认值 */
                    let sDataValue = '';
                    if (commonUtils.isNotEmptyArr(slaveData) && commonUtils.isNotEmptyObject(slaveData[slaveSelectOneDataIndex])) {
                      sDataValue = slaveData[slaveSelectOneDataIndex][child.sName];
                      const sDefaultName = child.sName.replace('Value', 'Default');
                      let sDefaultValue = '';
                      if (sDefaultName) {
                        sDefaultValue = slaveData[slaveSelectOneDataIndex][sDefaultName];
                      }
                      if (commonUtils.isEmptyObject(sDataValue) && commonUtils.isNotEmptyObject(sDefaultValue)) {
                        slaveData[slaveSelectOneDataIndex][child.sName] = sDefaultValue;
                      }
                    }
                    const showTypeProps = {
                      name: 'slave',
                      form: props.form,
                      record: slaveData[slaveSelectOneDataIndex],
                      sId: slaveData[slaveSelectOneDataIndex].sId,
                      getSqlDropDownData: props.getSqlDropDownData,
                      getSqlCondition: props.getSqlCondition,
                      handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
                      getFloatNum: props.getFloatNum,
                      onChange: props.onDataChange,
                      showConfig: child,
                      formItemLayout: {},
                      textArea: sMemo,
                      enabled: enabledNew,
                      dataValue: slaveData[slaveSelectOneDataIndex][child.sName],
                      bTable: true,
                      formRoute: props.formRoute,
                    };
                    return (
                      <div className="sProcessParamsModalType">
                        <span>{`${child.showName}:`}</span>
                        <ShowType {...showTypeProps} />
                      </div>
                      );
                  }) : ''
                }
              </div>
            </AntdDraggableModal>
            : ''
        }
      </Form>
    </div>
  );
});

export default CommonBase(CommonListEvent(CommonList));
