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";
// eslint-disable-next-line no-unused-vars
import stylesIndex from "@/components/Common/CommonListSelectMulti/index.less";
// 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, processData, controlSelectedRowKeys } = this.props;
    let startIndex = 0; /* 最开始下标 */
    const iOrderArr = [];
    /* 当前控制表选中行下的工序 接着编号 */
    const filterData =
      commonUtils.isNotEmptyArr(processData) && commonUtils.isNotEmptyArr(controlSelectedRowKeys)
        ? processData.filter(item => controlSelectedRowKeys.includes(item.sControlId))
        : [];
    if (commonUtils.isNotEmptyArr(filterData)) {
      /* 找到最大序号值 接着拍 */
      filterData.forEach(item => {
        const iOrder = commonUtils.isNotEmptyNumber(item.iOrder) ? item.iOrder : 0; /* 获取tableData中iOrder最大值 */
        iOrderArr.push(iOrder);
      });
    }
    /* 对所有移动的数据 进行一次重新排序 */
    if (commonUtils.isNotEmptyArr(iOrderArr)) {
      startIndex = Math.max(...iOrderArr);
    }
    if (commonUtils.isNotEmptyArr(slaveFilterData)) {
      slaveFilterData.forEach((item, index) => {
        const iOrderNew = startIndex + index + 1;
        slaveFilterData[index] = { ...item, iOrder: iOrderNew };
      });
    }
    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通用处理 */
  };
  handleTableSelectRowChange = (name, selectedRowKeys, changeValue, chooseProcessParams) => {
    /* 表格行选择 */
    this.props.onTableSelectRowChange(name, selectedRowKeys);
    if (name === "slave") {
      /* 选择工序 从表表 */
      const { [`${name}Data`]: tableData, slaveConfig, fatherModelsType, sModelsType } = 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);
          newSlaveFilterData.push({ ...tableData[tableDataIndex] });
        } 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) };
            }
          } else if (fatherModelsType.includes("quotation/")) {
            paramType = slaveSelectOneData.sProcessParam;
            if (commonUtils.isNotEmptyObject(slaveSelectOneData.sProcessParam)) {
              slaveSelectOneData = { ...slaveSelectOneData, ...commonUtils.convertStrToObj(slaveSelectOneData.sProcessParam) };
            }
          }
        }
        /* 工序参数以表格形式展示 列 */
        const sParamConfig = {
          bisMutiSelect: false,
          bMutiSelect: false,
        };
        const gdsconfigformslave = [
          {
            sId: commonUtils.createSid(),
            sName: "sId",
            showName: "主键",
            bVisible: false,
            iFitWidth: 45,
          },
          {
            sId: commonUtils.createSid(),
            sName: "bSelfCbx",
            showName: "选择",
            bVisible: true,
            iFitWidth: 37,
          },
          {
            sId: commonUtils.createSid(),
            sName: "sParamKey",
            showName: "参数主键",
            bVisible: false,
            iFitWidth: 200,
          },
          {
            sId: commonUtils.createSid(),
            sName: "sParamName",
            showName: "参数名",
            bVisible: true,
            iFitWidth: 230,
          },
          {
            sId: commonUtils.createSid(),
            sName: "sParamValue",
            showName: "参数值",
            bVisible: true,
          },
        ];
        sParamConfig.gdsconfigformslave = gdsconfigformslave;
        const sParamColumn = commonFunc.getHeaderConfig(sParamConfig);
        /* 要把数据以表格的形式显示出来 */
        const sParamJsonObj = commonUtils.isJSON(paramType) ? JSON.parse(paramType) : [];
        const sParamData = [];
        if (commonUtils.isNotEmptyArr(sParamJsonObj)) {
          for (const key of Object.keys(sParamJsonObj)) {
            if (key.includes("sParam") && !key.includes("DropDown") && !key.includes("Default")) {
              const obj = {};
              obj.sId = commonUtils.createSid();
              obj.sParamKey = key;
              obj.sParamName = sParamJsonObj[key];
              /* 找到数字 找到下拉数据源 */
              const num = key.replace(/[^\d]/g, "").trim();
              if (Number(num)) {
                const number = Number(num);
                const sParamDropDownKey = `sParamDropDown${number}`;
                obj.sDropDownData = sParamJsonObj[sParamDropDownKey]; /* 下拉 */
                const sParamDefaultKey = `sParamDefault${number}`;
                obj.sParamValue = sParamJsonObj[sParamDefaultKey]; /* 默认值 */
              }

              sParamData.push(obj);
            }
          }
        }
        if (commonUtils.isNotEmptyObject(paramType)) {
          // eslint-disable-next-line no-plusplus
          for (let i = 1; i < 11; 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 < 11; i++) {
            const iIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.sName === `sParamValue${i.toString()}`);
            if (iIndex > -1) {
              slaveConfig.gdsconfigformslave[iIndex].bVisible = false;
            }
          }
        }
        /* 选择工序弹框，选择工序默认不需要弹出参数,放在控件里面去选(包括工单参数，和工艺指导书参数) */
        modalVisible = false;
        this.props.onSaveState({
          sProcessParamsModalVisible: modalVisible,
          sProcessParamsSelects,
          slaveSelectOneDataIndex,
          selectedRowKeysLength: selectedRowKeys.length,
          sParamConfig,
          sParamColumn,
          sParamData,
        });
      }
    } else if (name === "sParam" && commonUtils.isNotEmptyArr(selectedRowKeys)) {
      /* 点击工艺参数列表 根据点击行动态加载配置 */
      const { sParamData, sParamConfig } = this.props;
      /* 找到最后一个选中 */
      const lastSelectedKeys = selectedRowKeys[selectedRowKeys.length - 1];
      const iIndex = sParamData.findIndex(item => lastSelectedKeys === item.sId);
      /* 选中数据时 塞入选中行的配置 */
      if (iIndex > -1) {
        const sParamObj = sParamData[iIndex];
        const index = sParamConfig.gdsconfigformslave.findIndex(item => item.sName === "sParamValue");
        if (index > -1) {
          if (commonUtils.isNotEmptyObject(sParamObj.sDropDownData)) {
            sParamConfig.gdsconfigformslave[index].sDropDownType = "const";
            sParamConfig.gdsconfigformslave[index].showDropDown = JSON.stringify(sParamObj.sDropDownData);
          } else {
            sParamConfig.gdsconfigformslave[index].sDropDownType = "";
            sParamConfig.gdsconfigformslave[index].showDropDown = undefined;
          }
        }
        /* 点击时 若没打钩 则选择框打钩 若已经打钩则取消打钩 */
        if (sParamData[iIndex].bSelfCbx) {
          // sParamData[iIndex] = { ...sParamData[iIndex], bSelfCbx: false };
        } else {
          sParamData[iIndex] = { ...sParamData[iIndex], bSelfCbx: true };
        }
        this.props.onSaveState({
          sParamData,
        });
      }
    }
  };

  /* 连续点击 复制选择 */
  handleContinueTableSelectRowChange = (name, selectedRowKeys, changeValue, chooseProcessParams) => {
    /* 表格行选择 */
    this.props.onTableSelectRowChange(name, selectedRowKeys);
    if (name === "slave") {
      /* 选择工序 从表表 */
      const { [`${name}Data`]: tableData, slaveConfig, fatherModelsType, sModelsType } = this.props;
      const { selectedRowKeysLength } = this.props;
      const { slaveFilterData } = this.props;
      const oldSlaveFilterData = slaveFilterData === undefined ? [] : JSON.parse(JSON.stringify(slaveFilterData));
      let newSlaveFilterData = [];
      selectedRowKeys.forEach(key => {
        const filterDataIndex = oldSlaveFilterData.findIndex(item => item.sSlaveId === key);
        if (filterDataIndex < 0) {
          newSlaveFilterData = JSON.parse(JSON.stringify(oldSlaveFilterData));
          const tableDataIndex = tableData.findIndex(item => item.sSlaveId === key);
          if (tableDataIndex > -1) {
            const newRow = JSON.parse(JSON.stringify(tableData[tableDataIndex]));
            newRow.sId = commonUtils.createSid();
            newRow.sSlaveId = newRow.sId;
            newRow.handleType = "add";
            newRow.key = newRow.sId;
            newSlaveFilterData.push(newRow);
          }
        } else {
          /* 连续点击 复制数据 */
          newSlaveFilterData = JSON.parse(JSON.stringify(oldSlaveFilterData));
          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) };
            }
          } else if (fatherModelsType.includes("quotation/")) {
            paramType = slaveSelectOneData.sProcessParam;
            if (commonUtils.isNotEmptyObject(slaveSelectOneData.sProcessParam)) {
              slaveSelectOneData = { ...slaveSelectOneData, ...commonUtils.convertStrToObj(slaveSelectOneData.sProcessParam) };
            }
          }
        }
        /* 工序参数以表格形式展示 列 */
        const sParamConfig = {
          bisMutiSelect: false,
          bMutiSelect: false,
        };
        const gdsconfigformslave = [
          {
            sId: commonUtils.createSid(),
            sName: "sId",
            showName: "主键",
            bVisible: false,
            iFitWidth: 45,
          },
          {
            sId: commonUtils.createSid(),
            sName: "bSelfCbx",
            showName: "选择",
            bVisible: true,
            iFitWidth: 37,
          },
          {
            sId: commonUtils.createSid(),
            sName: "sParamKey",
            showName: "参数主键",
            bVisible: false,
            iFitWidth: 200,
          },
          {
            sId: commonUtils.createSid(),
            sName: "sParamName",
            showName: "参数名",
            bVisible: true,
            iFitWidth: 230,
          },
          {
            sId: commonUtils.createSid(),
            sName: "sParamValue",
            showName: "参数值",
            bVisible: true,
          },
        ];
        sParamConfig.gdsconfigformslave = gdsconfigformslave;
        const sParamColumn = commonFunc.getHeaderConfig(sParamConfig);
        /* 要把数据以表格的形式显示出来 */
        const sParamJsonObj = commonUtils.isJSON(paramType) ? JSON.parse(paramType) : [];
        const sParamData = [];
        if (commonUtils.isNotEmptyArr(sParamJsonObj)) {
          for (const key of Object.keys(sParamJsonObj)) {
            if (key.includes("sParam") && !key.includes("DropDown") && !key.includes("Default")) {
              const obj = {};
              obj.sId = commonUtils.createSid();
              obj.sParamKey = key;
              obj.sParamName = sParamJsonObj[key];
              /* 找到数字 找到下拉数据源 */
              const num = key.replace(/[^\d]/g, "").trim();
              if (Number(num)) {
                const number = Number(num);
                const sParamDropDownKey = `sParamDropDown${number}`;
                obj.sDropDownData = sParamJsonObj[sParamDropDownKey]; /* 下拉 */
                const sParamDefaultKey = `sParamDefault${number}`;
                obj.sParamValue = sParamJsonObj[sParamDefaultKey]; /* 默认值 */
              }

              sParamData.push(obj);
            }
          }
        }
        if (commonUtils.isNotEmptyObject(paramType)) {
          // eslint-disable-next-line no-plusplus
          for (let i = 1; i < 11; 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 < 11; i++) {
            const iIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.sName === `sParamValue${i.toString()}`);
            if (iIndex > -1) {
              slaveConfig.gdsconfigformslave[iIndex].bVisible = false;
            }
          }
        }
        /* 选择工序弹框，选择工序默认不需要弹出参数,放在控件里面去选(包括工单参数，和工艺指导书参数) */
        modalVisible = false;
        this.props.onSaveState({
          sProcessParamsModalVisible: modalVisible,
          sProcessParamsSelects,
          slaveSelectOneDataIndex,
          selectedRowKeysLength: selectedRowKeys.length,
          sParamConfig,
          sParamColumn,
          sParamData,
        });
      }
    } else if (name === "sParam" && commonUtils.isNotEmptyArr(selectedRowKeys)) {
      /* 点击工艺参数列表 根据点击行动态加载配置 */
      const { sParamData, sParamConfig } = this.props;
      /* 找到最后一个选中 */
      const lastSelectedKeys = selectedRowKeys[selectedRowKeys.length - 1];
      const iIndex = sParamData.findIndex(item => lastSelectedKeys === item.sId);
      /* 选中数据时 塞入选中行的配置 */
      if (iIndex > -1) {
        const sParamObj = sParamData[iIndex];
        const index = sParamConfig.gdsconfigformslave.findIndex(item => item.sName === "sParamValue");
        if (index > -1) {
          if (commonUtils.isNotEmptyObject(sParamObj.sDropDownData)) {
            sParamConfig.gdsconfigformslave[index].sDropDownType = "const";
            sParamConfig.gdsconfigformslave[index].showDropDown = JSON.stringify(sParamObj.sDropDownData);
          } else {
            sParamConfig.gdsconfigformslave[index].sDropDownType = "";
            sParamConfig.gdsconfigformslave[index].showDropDown = undefined;
          }
        }
        /* 点击时 若没打钩 则选择框打钩 若已经打钩则取消打钩 */
        if (sParamData[iIndex].bSelfCbx) {
          // sParamData[iIndex] = { ...sParamData[iIndex], bSelfCbx: false };
        } else {
          sParamData[iIndex] = { ...sParamData[iIndex], bSelfCbx: true };
        }
        this.props.onSaveState({
          sParamData,
        });
      }
    }
  };

  handleCancelProcessParamsModalVisible = () => {
    this.props.onSaveState({
      sProcessParamsModalVisible: false,
    });
  };
  handleProcessParamsOk1 = () => {
    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,
    });
  };
  handleProcessParamsOk = () => {
    const { slaveData, slaveSelectOneDataIndex, slaveFilterData, sProcessParamsSelects, sParamData } = this.props;
    /* 保存时候把sParamData赛道sParam1中 */
    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},`;
      });
      if (commonUtils.isNotEmptyArr(sParamData)) {
        const sParamSeletedData = sParamData.filter(item => item.bSelfCbx);
        if (commonUtils.isNotEmptyArr(sParamSeletedData)) {
          const sParamJsonData = JSON.stringify(sParamSeletedData);
          slaveData[slaveSelectOneDataIndex].sParams = sParamJsonData;
        }
      }
      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 } = this.props;
    if (commonUtils.isNotEmptyArr(tableSelectedRowKeys) && commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
      slaveSelectedRowKeys.forEach((item, index) => {
        if (tableSelectedRowKeys.includes(item)) {
          slaveSelectedRowKeys.splice(index, 1);
        }
      });
      this.props.onDataRowDel(name, isWait, tableSelectedRowKeys);
    }
  };
  /* 动态参数标题选择框 全选/取消全选 */
  handleCheckParamChange = () => {
    const { sParamData, sParamColumn } = this.props;
    /* 全选 取消全选功能 */
    if (commonUtils.isNotEmptyArr(sParamData)) {
      /* 标题bSelfCbx加标识 */
      const iIndex = sParamColumn.findIndex(item => item.dataIndex === "bSelfCbx");
      if (iIndex > -1) {
        let bSelfCbx = false;
        if (sParamColumn[iIndex].bCheckAll) {
          bSelfCbx = false;
        } else {
          bSelfCbx = true;
        }
        sParamColumn[iIndex] = { ...sParamColumn[iIndex], bCheckAll: bSelfCbx };
        sParamData.forEach((item, index) => {
          sParamData[index] = { ...sParamData[index], bSelfCbx };
        });
      }
      this.props.onSaveState({
        sParamData,
        sParamColumn,
      });
    }
  };
  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.handleContinueTableSelectRowChange}
              onProcessParamsOk={this.handleProcessParamsOk}
              onCancelProcessParamsModalVisible={this.handleCancelProcessParamsModalVisible}
              onCopyTo={this.copyTo}
              onDrag={this.handleDrag}
              onDataRowDel={this.handleTableDel}
              onCheckParamChange={this.handleCheckParamChange}
            />
          </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 tableProps = {
    ...commonBusiness.getTableTypes("slave", props),
    tableProps: {
      rowKey: "sSlaveId",
      pagination,
      onChange: props.onTitleChange,
      chooseProcessParams: true,
      sModelsType,
      AutoTableHeight: 350, // chooseProcessParams为选择工序中点击工序名称表格行出现弹窗
    },
    bContinueClick: true,
  };
  const sParamProps = {
    ...commonBusiness.getTableTypes("sParam", props),
    tableProps: {
      rowKey: "sId",
      pagination,
      onChange: props.onTitleChange,
      sModelsType,
      AutoTableHeight: 350,
    },
    bRowClick: true,
    onCheckParamChange: props.handleCheckParamChange,
    enabled: true,
  };
  // 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 && props.sModelsType.includes("modal/searchProcess")) {
    tableFilterProps = {
      ...tableFilterProps,
      ...deleteSet,
      enabled: true,
    };
  }

  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,
    onExpandTree: () => {},
    onSaveState: props.onSaveState,
    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 BtnSure = commonFunc.showLocalMessage(props, "BtnSure", "确定");
  const BtnCancel = commonFunc.showLocalMessage(props, "BtnCancel", "取消");
  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();
        }
      }
    }
  };
  const filteItem = commonFunc.showLocalMessage(props, "filteItem", "过滤项");
  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">{filteItem}</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}
                      footer="hidden"
                      tableBelone={tableBelone}
                      showConfig={props.showConfig}
                      noVlistTable
                    />
                  </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>
        {false ? (
          <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>
        ) : (
          ""
        )}
        {props.sProcessParamsModalVisible ? (
          <AntdDraggableModal
            width="920px"
            // bodyStyle={{ width: '930px' }}
            className="paramModal"
            title={sProcessParams}
            visible={props.sProcessParamsModalVisible}
            onOk={props.onProcessParamsOk}
            onCancel={props.onCancelProcessParamsModalVisible}
            // footer={null}
          >
            <div className="xly-bill-list">
              <StaticEditTable {...sParamProps} footer="hidden" />
            </div>
          </AntdDraggableModal>
        ) : (
          ""
        )}
      </Form>
    </div>
  );
});

export default CommonBase(CommonListEvent(CommonList));
