/* eslint-disable */
import React, { Component } from 'react';
import { Form } from '@ant-design/compatible';
// import '@ant-design/compatible/assets/index.css';
import {  UploadOutlined } from '@ant-design/icons';
import { Layout, Spin, Button, message, Upload, Modal } from 'antd-v4';
import CommonListEvent from '@/components/Common/CommonListEvent';/* 继承销售模块业务功能 */
import * as commonFunc from '@/components/Common/commonFunc';/* 通用单据方法 */ /* 通用单据方法 */
import StaticEditTable from '@/components/Common/CommonTable';/* 可编辑表格 */
import CommonBase from '@/components/Common/CommonBase';/* 获取配置及数据 */
import * as commonBusiness from '@/components/Common/commonBusiness';/* 单据业务功能 */
import SearchComponent from '@/components/Common/SearchComponent';/* 搜索组件 */
import config from '@/utils/config';
import * as commonUtils from '@/utils/utils';
import Eject from '@/assets/eject.svg';
import StaticEditTree from '@/components/Common/Tree/StaticTree';
import Close from '@/assets/close.svg';
import commonConfig from "../../../utils/config";

const { Content } = Layout;
/**
 此组件是选择材料通用窗体
 */

class CommonList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      btnList: [],
      openFlag: false,
      bPageEdit:false,
    };
    this.pathname = location.pathname;
    this.tableKey = commonUtils.createSid();
  }

  componentDidMount() {
    const isDialog = ['BtnSendDialog'].includes(this.props.app?.currentPane?.config?.sControlName);
    if (this.spanDialog.current && isDialog) {
      this.spanDialog.current.innerHTML = this.props.app?.currentPane?.config?.sFieldToContent;
    }
    window.onSetTableKey = () => {
      this.tableKey = commonUtils.createSid();
      this.forceUpdate();
    }
  }

  componentWillReceiveProps(nextProps) {
    const {
      masterConfig, gdsjurisdiction, data, sModelsType, app,
    } = nextProps;
    let { slaveData } = nextProps;
    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('BtnCopyTo')));
      // 过滤权限
      this.setState({ btnList });
    }
    if (sModelsType === 'search/commonPopupPassRate' && commonUtils.isNotEmptyArr(data) && commonUtils.isEmptyArr(slaveData)) {
      this.props.onSaveState({ slaveData: data });
    }
    // else if (app?.currentPane?.config && app.currentPane.config.sName === 'dSumCompleteAvailableStockQty' && commonUtils.isNotEmptyArr(data) && commonUtils.isEmptyArr(slaveData)) {
    //   this.props.onSaveState({ slaveData: data });
    // }
    const sourceData = commonUtils.isNotEmptyObject(app) && commonUtils.isNotEmptyObject(app.currentPane) ? app.currentPane.slaveDataSource : []; /* 是否可编辑 */
    /* 接收备货消耗数据JSON 回传到弹窗，并完成勾选 */
    if (commonUtils.isNotEmptyArr(sourceData) && commonUtils.isNotEmptyArr(slaveData) && (app.currentPane.config && app.currentPane.config.sControlName !== 'BtnPopup.dSplitworkQty')) {
      // json回传过就不再执行了
      if (this.props.bJsonFinished) return;
      /* 如果消耗数字段没数据  则填充 */
      const iIndex = slaveData.findIndex(item => item.dModifyProductQty);
      if (iIndex === -1) {
        let jsonStr = sourceData[0].sStockUpConsume;
        if(app.currentPane.config && app.currentPane.config.sControlName === 'BtnPopup.dMergeProductionQty') {
          jsonStr = sourceData[0].sMergeProduction;
        } else if(app.currentPane.config && app.currentPane.config.sControlName === 'BtnPopup.dWorkPeriodQty') { /* 在制品占用数弹窗 */
          jsonStr = sourceData[0].sWorkProduct;
        } else if(app.currentPane.config && app.currentPane.config.sName === 'dStockAuxiliaryQty') {
          jsonStr = sourceData[0].sAvailableExclude;
        } else if(app.currentPane.config && app.currentPane.config.sControlName === 'BtnPopup.dPreMatProductQty') {
          jsonStr = sourceData[0].sPreMatProduct;
        } else if(app.currentPane.config && app.currentPane.config.sControlName === 'BtnPopup.dCombinedQty') {
          jsonStr = sourceData[0].sCombinedMemo;
          slaveData.forEach(item => {
            item.dModifyProductQty = item.dUnCombinedQty;
          });
        }
        let jsonArr = [];
        if (commonUtils.isNotEmptyObject(jsonStr) && commonUtils.isJSON(jsonStr)) {
          jsonArr = JSON.parse(jsonStr);
        }
        const slaveSelectedRowNewKeys = [];
        if (commonUtils.isNotEmptyArr(jsonArr)) {
          jsonArr.forEach((item) => {
            const iFIndex = slaveData.findIndex(each => each.sSlaveId === item.sSlaveId);
            if (iFIndex > -1) {
              let addState = {};
              // if(app.currentPane.config && app.currentPane.config.sControlName === 'BtnPopup.dCombinedQty') {
              //   addState = {...item};
              // }
              addState.dModifyProductQty = item.dModifyProductQty;
              addState.bExclude = item.bExclude;
              slaveData[iFIndex] = { ...slaveData[iFIndex], ...addState };
              slaveSelectedRowNewKeys.push(item.sSlaveId);
            }
          });
          this.props.onSaveState({ slaveData, slaveSelectedRowKeys: slaveSelectedRowNewKeys, bJsonFinished: true });
        }
      }
    }else if(commonUtils.isNotEmptyArr(sourceData) && (app.currentPane.config && app.currentPane.config.sControlName === 'BtnPopup.dSplitworkQty')) { /* 将拆分工单json 转化为slaveData */
      // json回传过就不再执行了
      if (this.props.bJsonFinished) return;
      let jsonStr = sourceData[0].sSplitQty;
      let jsonArr = [];
      slaveData = [];
      if (commonUtils.isNotEmptyObject(jsonStr) && commonUtils.isJSON(jsonStr)) {
        jsonArr = JSON.parse(jsonStr);
      }
      const slaveSelectedRowNewKeys = [];
      if (commonUtils.isNotEmptyArr(jsonArr)) {
        jsonArr.forEach((item) => {
          const tableRow = {...item};
          slaveData.push(tableRow);
          slaveSelectedRowNewKeys.push(item.sId);
        });
        this.props.onSaveState({ slaveData, slaveSelectedRowKeys: slaveSelectedRowNewKeys, bJsonFinished: true });
      }
    }
    if (this.state.openFlag && this.pathname === location.pathname) {
      let dom = {};
      if (commonUtils.isNotEmptyArr(document.getElementsByClassName('modalMaterials')) && document.getElementsByClassName('modalMaterials').length > 0) {
        // eslint-disable-next-line prefer-destructuring
        dom = document.getElementsByClassName('modalMaterials')[0];
        dom.parentElement.parentElement.style.display = 'block';
        this.setState({ openFlag: false });
      } else {
        this.setState({ openFlag: false }, () => {
          this.props.onButtonClick('BtnRefresh');
        });
      }
    }
  }

  componentDidUpdate() {
    if (Array.isArray(this.props.slaveData) && this.props.slaveData.length) {
      if (!this.hasUpdate) {
        this.hasUpdate = true;
        this.replaceData();
      }
    }
  }

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

  onOpenNewTab = () => {
    let dom = {};
    if (commonUtils.isNotEmptyArr(document.getElementsByClassName('modalMaterials')) && document.getElementsByClassName('modalMaterials').length > 0) {
      // eslint-disable-next-line prefer-destructuring
      dom = document.getElementsByClassName('modalMaterials')[0];
      dom.parentElement.parentElement.style.display = 'none';
      this.setState({ openFlag: true });
    } else { /* BtnPopup自定义按钮弹窗 */
      this.setState({ openFlag: true });
      this.props.onOpenNewTab();
    }
  }

  // 更新数据
  replaceData = () => {
    const { props } = this;
    const { slaveSelectedRowKeys = [] } = props;
    if (props.app?.currentPane?.config?.sControlName?.startsWith('BtnPopupEdit')) {
      const selectData = props.app?.sMemoData;
      const showHasEditData = [];
      if (Array.isArray(selectData)) {
        selectData.forEach((i) => {
          const index = props.slaveData?.findIndex(j => j && j.sId === i.sId);
          if (index >= 0) {
            props.slaveData[index] = i;
          } else {
            showHasEditData.push(i);
          }
        });
        const slaveData = [...props.slaveData || [], ...showHasEditData];
        const slaveSelectedRowKeysNew = Array.isArray(selectData) ? selectData.map(i => i && i.sSlaveId).filter(Boolean) : [];
        props.onSaveState({ slaveSelectedRowKeys: [...slaveSelectedRowKeysNew, ...slaveSelectedRowKeys], slaveData, slaveSelectedData: selectData || [] });
      }
    }
  };

  // ----------------------------数据修改回带end  ---------------------------- //
  handleEject = (e) => {
    const filterTree = e.currentTarget.parentNode;/* 获取当前页签下的树组件 */
    if (filterTree.attributes.class.value.indexOf('xly-eject') > -1) {
      // eslint-disable-next-line no-unused-expressions
      filterTree.nextSibling.style.display = 'block';
    } else if (filterTree.attributes.class.value.indexOf('xly-tree-close') > -1) {
      // eslint-disable-next-line no-unused-expressions
      filterTree.parentNode.style.display = 'none';
    }
  };

  /**   树节点选中   */
  handleTreeSelect = (name, checkedKeys, e) => {
    this.props.onSelect(name, checkedKeys, e); /* 调用CommonListEvent通用处理 */
  };

  /**   确认下单   */
  handleSelect = () => {
    const {
      slaveSelectedData, app, slaveSelectedRowKeys, slaveData, sModelsId, slaveConfig, slaveDelData,
    } = this.props;
    let newSlaveSelectedData = [];
    let bJson = false;
    if(commonUtils.isNotEmptyObject(app.currentPane.config) && (app.currentPane.config.sName === 'dStockAuxiliaryQty' || app.currentPane.config.sControlName?.includes('dSplitworkQty')
      ||  app.currentPane.config.sControlName?.includes('dCombinedQty')
      ||  app.currentPane.config.sControlName?.includes('dPreMatProductQty'))) {
      bJson = true;
    }
    if (commonUtils.isNotEmptyArr(slaveSelectedData) && commonUtils.isNotEmptyObject(app.currentPane.config) && app.currentPane.config.sControlName
      && (!app.currentPane.config.sControlName.includes('dStockUpConsumeQty')
        && !app.currentPane.config.sControlName.includes('dWorkPeriodQty')
      && !app.currentPane.config.sControlName.includes('dMergeProductionQty') )
      && !app.currentPane.config?.sControlName?.startsWith('BtnPopupEdit') && !bJson) {
      newSlaveSelectedData = slaveSelectedData;
    } else if (commonUtils.isNotEmptyArr(slaveData) && commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
      newSlaveSelectedData = slaveData.filter(item => slaveSelectedRowKeys.includes(item.sSlaveId));
      if(commonUtils.isNotEmptyObject(app.currentPane.config) && app.currentPane.config.sControlName?.includes('dSplitworkQty')) {
        newSlaveSelectedData = slaveData;
      }
    }
    let bTip = false;
    if (sModelsId === '12710101117089504014270') { /* 备货订单消耗界面单独处理 */
      if (commonUtils.isNotEmptyArr(newSlaveSelectedData)) {
        for (const item of newSlaveSelectedData) {
          const minus = commonUtils.convertFixNum(commonUtils.isNull(item.dModifyProductQty, 0), 2) - commonUtils.convertFixNum(commonUtils.isNull(item.dUnStockUpConsumeQty, 0), 2);
          if (minus > 0) {
            message.error('备货消耗数不能大于源数量!');
            bTip = true;
            return;
          }
        }
      }
    } else if (sModelsId === '12710101117167758900360') { /* 合版订单 */
      if (commonUtils.isNotEmptyArr(newSlaveSelectedData)) {
        for (const item of newSlaveSelectedData) {
          const minus = commonUtils.convertFixNum(commonUtils.isNull(item.dModifyProductQty, 0), 2) - commonUtils.convertFixNum(commonUtils.isNull(item.dUnCombinedQty, 0), 2);
          if (minus > 0) {
            message.error('合版数不能大于源数量!');
            bTip = true;
            return;
          }
        }
      }
    } else if (sModelsId === '12710101117153909986410') { /* 合并生产界面单独处理 */
      if (commonUtils.isNotEmptyArr(newSlaveSelectedData)) {
        for (const item of newSlaveSelectedData) {
          const minus = commonUtils.convertFixNum(commonUtils.isNull(item.dModifyProductQty, 0), 2) - commonUtils.convertFixNum(commonUtils.isNull(item.dUnMergeProductionQty, 0), 2);
          if (minus > 0) {
            message.error('合并订单数量不能大于未合并订单数量!');
            bTip = true;
            return;
          }
        }
      }
    } else if (sModelsId === '12710101117163499193470') { /* 备料订单消耗单独处理 */
      if (commonUtils.isNotEmptyArr(newSlaveSelectedData)) {
        for (const item of newSlaveSelectedData) {
          const minus = commonUtils.convertFixNum(commonUtils.isNull(item.dModifyProductQty, 0), 2) - commonUtils.convertFixNum(commonUtils.isNull(item.dUnPreMatProductQty, 0), 2);
          if (minus > 0) {
            message.error('备料订单数量不能大于未消耗备料订单数量!');
            bTip = true;
            return;
          }
        }
      }
    } else if (sModelsId === '12710101117296031584030') { /* 在制品数 */
      if (commonUtils.isNotEmptyArr(newSlaveSelectedData)) {
        for (const item of newSlaveSelectedData) {
          const tempFieldName = commonUtils.isNotEmptyStr(item.dProcessInFeedQty) ? "dProcessInFeedQty" : "dUnWorkReturnSumQty";
          const minus = commonUtils.convertFixNum(commonUtils.isNull(item.dModifyProductQty, 0), 2) - commonUtils.convertFixNum(commonUtils.isNull(item[tempFieldName], 0), 2);
          if (minus > 0) {
            message.error('在制品占用数不能大于出库数!');
            bTip = true;
            return;
          }
        }
      }
    } else if (sModelsId === '12710101117162642065370') { /* 合并生产界面单独处理 */
      const sourceData = commonUtils.isNotEmptyObject(app) && commonUtils.isNotEmptyObject(app.currentPane) ? app.currentPane.slaveDataSource : []; /* 来源数据 */
      if (commonUtils.isNotEmptyArr(newSlaveSelectedData) && commonUtils.isNotEmptyArr(sourceData)) {
        let sum = 0;
        for (const item of newSlaveSelectedData) {
          sum +=  commonUtils.isNull(item.dModifyProductQty, 0)
        }
        const dReferSum = commonUtils.isNull(sourceData[0].dMergeProductionQty, 0) + commonUtils.isNull(sourceData[0].dQdismantledQty, 0) ;
        console.log('1', sum, dReferSum);
        if (sum !== dReferSum) {
          message.error('数量不一致,不能拆分!');
          bTip = true;
          return;
        }
      }
    } else if (
      this.props.app?.currentPane?.config?.sControlName?.includes('popupSingle')
      && this.props.app?.currentPane?.config?.sControlName?.includes('edit')
    ) {
      if (!this.props.editable) {
        this.props.app.currentPane.selectCancel(app.currentPane.name);
        return;
      }
      const data = [];
      data.push(commonBusiness.mergeData('slave', slaveConfig.sTbName, slaveData, slaveDelData));
      if (!data[0]?.column?.length) {
        this.props.app.currentPane.selectCancel(app.currentPane.name);
        return;
      }
      this.handleSaveData({ data, sClientType: '1' }, () => {
        this.props.app.currentPane.select(app.currentPane.name, app.currentPane.config, slaveData);
        this.props.app.currentPane.selectCancel(app.currentPane.name);
        if(location.pathname ==='/indexPage/productionMainPlan' && this.props.onRefresh) {
          console.log('回刷生产主计划', this.props.onRefresh);
          this.props.onRefresh();
        }
      });
      return;
    }
    if (bTip) {
      return;
    }
    // if(sModelsId === '12710101117153126306000') { /* 材料库存可用数 */
    //   const data = [];
    //   data.push(commonBusiness.mergeData('slave', slaveConfig.sTbName, slaveData, slaveDelData));
    //   this.handleSaveData({ data, sClientType: '1' });
    // }
    this.props.app.currentPane.select(app.currentPane.name, app.currentPane.config, newSlaveSelectedData);
    this.props.app.currentPane.selectCancel(app.currentPane.name);
  };
  /**   toolbar保存   */
  handleSaveData = async (params, cb) => {
    this.props.onSaveState({
      pageLoading: true
    });
    const {
      token, sModelsId, slaveFilterCondition, slaveConfig, slavePagination, slaveOrderBy, app,
    } = this.props;
    const { userinfo } = app;
    const BtnSure = commonFunc.showLocalMessage(this.props, 'BtnSure', '确定');
    const FriendlyReminder = commonFunc.showLocalMessage(this.props, 'FriendlyReminder', '温馨提示');

    const onSendSocketMessage = this.props.handleSendSocketMessage;
    const returnData = await commonBusiness.saveData({ token, value: params, sModelsId });
    this.props.onSaveState({
      pageLoading: false
    });
    if (commonUtils.isNotEmptyObject(returnData)) {
      /* 防呆校验 */
      if (returnData.code === -7) {
        // eslint-disable-next-line no-underscore-dangle
        const _this = this;
        confirm({
          title: FriendlyReminder, /* 防呆校验 */
          content: returnData.msg,
          onOk() {
            params.iFlag = 1;
            _this.handleSaveData(params);
          },
          onCancel() {
          },
        });
        this.props.onSaveState({
          loading: false,
        });
        return true;
      } else if (returnData.code === 2 || returnData.code === -8) {
        Modal.info({
          title: FriendlyReminder,
          content: (
            <div>
              {commonFunc.getReturnMsg(returnData.msg)}
            </div>
          ),
          onOk() {},
        });
      } else {
        cb && cb();
      }
    } else {
      return false;
    }
  };

  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);
  };

   handleBtnLockClick = async (btn) => {
     const {
       slaveSelectedRowKeys, slaveData, sModelsId, app, slaveConfig,
     } = this.props;
     if(btn?.sControlName === 'BtnInvoiceUpd') {
       this.setState({  bPageEdit: true });
       return ;
     }
     let interfaceArr = [];
     if (commonUtils.isNotEmptyArr(btn)) {
       interfaceArr = btn.interface;
     }
     if (commonUtils.isNotEmptyArr(interfaceArr)) {

       let newSlaveSelectedData = [];
       if (commonUtils.isNotEmptyArr(slaveData)) {
         if(commonUtils.isEmptyArr(slaveSelectedRowKeys)) {
           if (this.props.sModelsId === '12710101117200946822170') {
             message.error(commonFunc.showMessage(app.commonConst, 'pleaseChooseData'));/* 请选择一条数据 */
             return;
           } else {
             newSlaveSelectedData = [slaveData[0]];
           }
         }else {
           newSlaveSelectedData = slaveData.filter(item => slaveSelectedRowKeys.includes(item.sSlaveId));
         }
       }
       const conditionValues = commonUtils.isNotEmptyObject(app) && commonUtils.isNotEmptyObject(app.currentPane) ? app.currentPane.conditonValues : {}; /* 是否可编辑 */

       let sId = '';
       if(commonUtils.isNotEmptyObject(conditionValues)) {
         sId =  conditionValues.sSrcId;
       }
       console.log('interfaceAr1r', interfaceArr, newSlaveSelectedData, sId);
       const bodyMap = {
         sRowData: commonUtils.isNotEmptyArr(newSlaveSelectedData) ? JSON.stringify(newSlaveSelectedData) : '',
       };
       if(commonUtils.isNotEmptyObject(conditionValues)) {
         bodyMap.sSqlCondition = conditionValues;
       }
      const result = await this.props.onThirdInterfaceCall(interfaceArr[0], false, '', sId, bodyMap);
      if(result) {
        // this.handleCancelModal();
        if(this.props.onGetData){
          this.props.onGetData(slaveConfig);
        }
        if(location.pathname ==='/indexPage/commonList') {
          this.props.app.currentPane.selectCancel(app.currentPane.name);
        } else {
          this.props.app.currentPane.select(app.currentPane.name, app.currentPane.config, newSlaveSelectedData);
        }

      }else {
        console.log('操作失败!');
      }

     }
   };


  handleBtnOutClick = async () => {
    const {
      slaveConfig, slaveFilterCondition, slaveOrderBy, formRoute, slaveSelectedRowKeys, sGroupByList, formData, app,
    } = this.props;
    const { currentPane } = app;
    const slaveFilterConditionNew = slaveFilterCondition === undefined ? [] : [...slaveFilterCondition];
    let sids = '';
    let bMutiSelect = false; /* 默认单选或不选  true ：多选 */
    if (commonUtils.isNotEmptyArr(formData)) {
      bMutiSelect = formData[0].bMutiSelect;
    }
    if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys) && bMutiSelect) { /* 导出Excel 只有多选情况下 导出时是根据勾选行 否则导出全部 */
      slaveSelectedRowKeys.forEach((item, i) => {
        if (i === slaveSelectedRowKeys.length - 1) {
          sids = `${sids}${item}`;
        } else {
          sids = `${sids}${item},`;
        }
      });
      const addFilter = {};
      addFilter.bFilterName = 'sSlaveId';
      addFilter.bFilterCondition = 'in';
      addFilter.bFilterValue = sids;
      slaveFilterConditionNew.push(addFilter);
    }
    /* 如果列表是别的界面弹窗进来，则需要加当前界面的条件 */
    let conditionValues ={};
    if(commonUtils.isNotEmptyObject(currentPane) && !commonUtils.isEmpty(currentPane.conditonValues)) {
      conditionValues = currentPane.conditonValues;
    }
    // let url = `${commonConfig.server_host}excel/export/${slaveConfig.sId}?sModelsId=${slaveConfig.sParentId}&token=${this.props.app.token}&sName=${formRoute}`;
    // if (commonUtils.isNotEmptyArr(slaveFilterConditionNew)) {
    //   url = `${url}&bFilter=${encodeURIComponent(JSON.stringify(slaveFilterConditionNew))}`;
    // }
    // if (slaveOrderBy !== undefined && slaveOrderBy !== '' && Object.keys(slaveOrderBy).length > 0) {
    //   url = `${url}&sFilterOrderBy=${encodeURIComponent(JSON.stringify(slaveOrderBy))}`;
    // }
    // if (commonUtils.isNotEmptyArr(sGroupByList)) {
    //   url = `${url}&sGroupList=${encodeURIComponent(JSON.stringify(sGroupByList))}`;
    // }
    // window.open(url);

    /* 导出使用Post提交 */
    const url = `${commonConfig.server_host}excel/export/${slaveConfig.sId}?sModelsId=${slaveConfig.sParentId}&sName=${formRoute}&token=${encodeURIComponent(this.props.app.token)}`;
    const bFilter = JSON.stringify(slaveFilterConditionNew);
    const sFilterOrderBy = JSON.stringify(slaveOrderBy);
    const sGroupList = JSON.stringify(sGroupByList);
    const conditionValuesStr = JSON.stringify(conditionValues);
    console.log('12', slaveConfig);
    console.log('conditionValues', url, bFilter);
    this.handleOpenOut(url, bFilter, sFilterOrderBy, sGroupList, conditionValuesStr);
  };


  /* Get提交地址栏参数过多,更改Get提交为Post提交 */
  handleOpenOut= (url, bFilter, slaveOrderBy, sGroupByList, conditionValues) => {
    const newWin = window.open();
    let formStr = '';
    // 设置样式为隐藏，打开新标签再跳转页面前，如果有可现实的表单选项，用户会看到表单内容数据
    formStr = `<form style="visibility:hidden;" method="POST" action="${url}">` +
      `<input type="hidden" name="bFilter" value='${bFilter}' />`;
    if (commonUtils.isNotEmptyObject(slaveOrderBy)) {
      formStr += `<input type="hidden" name="sFilterOrderBy" value='${slaveOrderBy}' />`;
    }
    if (commonUtils.isNotEmptyObject(sGroupByList)) {
      formStr += `<input type="hidden" name="sGroupList" value='${sGroupByList}' />`;
    }
    if (commonUtils.isNotEmptyObject(conditionValues)) {
      formStr += `<input type="hidden" name="sSqlCondition" value='${conditionValues}' />`;
    }
    formStr += '</form>';
    newWin.document.body.innerHTML = formStr;
    newWin.document.forms[0].submit();
    return newWin;
  }
  /** 上传发票文件改变时的状态 */
  handleUploadInvoiceChange = async (info) => {
    const {
      slaveConfig,
    } = this.props;
    const { file } = info;
    if (file.response) {
      console.log('sss', file.response);
      if (file.response && file.response.status === 200 && file.response.obj.total > 0) {
        /*   成功   */
        message.success(file.response.msg);
        if(this.props.onGetData){
          this.props.onGetData(slaveConfig);
        }
      } else { /*   失败   */
        this.props.getServiceError({ msg:'发票上传失败！' }); /* 报表设计 */
      }
    }
  };

  customRequest = (option)  =>{
    const { onSuccess, onError, file, action, data = {} } = option;
    // 添加额外的参数
    const formData = new FormData();
    formData.append('uploadFiles', file);
    Object.keys(data).forEach((key) => {
      formData.append(key, data[key]);
    });

    console.log('data:', data);
    fetch(action, {
      method: 'POST',
      body: formData,
    })
      .then(response => response.json())
      .then(data => {
        onSuccess(data, file);
      })
      .catch(error => {
        onError(error);
      });
  }

  // ----------------------------数据修改回带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 = {};
    copyTo.name = 'BtnCopyTo';
    const copyToConfig = masterConfig.gdsconfigformslave.filter(item => item.sControlName.includes(copyTo.name));
    copyTo.config = copyToConfig;
    copyTo.masterData = slaveSelectedData[0] || masterData;
    copyTo.slaveData = slaveSelectedData;
    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: `${config.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`, /*   接口地址   */
        copyTo,
        pages: slavePagination,
        newRecordFlag: `NewRecord_${sActiveId}`,
      },
    });
  }

  // 限制编辑
  otherlimitDisabled = (params) => {
    const{ sModelsId } = this.props;
    let { enabledNew, record, sName } = params;
    if ( sModelsId ==='12710101117089504014270' &&  enabledNew && ['dModifyProductQty'].includes(sName)) {
      if (record?.dUnStockUpConsumeQty === 0) { /* 订单备货消耗里的要加控制，已消耗完的，消耗数不让填 */
        enabledNew = false
      }
    }else if (sModelsId ==='12710101117153909986410' &&  enabledNew && ['dModifyProductQty'].includes(sName)) {
      if (record?.dUnMergeProductionQty === 0 || record?.dUnMergeProductionQty < 0) { /* 校验生产数 */
        enabledNew = false
      }
    }
    return enabledNew;
  };

  spanDialog = React.createRef();

  render() {
    const { pageLoading } = this.props;
    return (
      <div style={{ height: '100%' }}>
        <Spin spinning={pageLoading}>
          <div style={{ height: '100%' }}>
            <CommonListComponent
              {...this.props}
              {...this.state}
              spanDialog={this.spanDialog}
              onOpenNewTab={this.onOpenNewTab}
              onSelect={this.handleSelect}
              onCancel={this.handleCancelModal}
              onDoubleClick={this.handleDoubleClickSelect}
              onEject={this.handleEject.bind(this)}
              onSelectTree={this.handleTreeSelect}
              onCopyTo={this.copyTo}
              onBtnLockClick={this.handleBtnLockClick}
              onBtnOutClick={this.handleBtnOutClick}
              onUploadInvoiceChange = {this.handleUploadInvoiceChange}
              customRequest ={this.customRequest}
              otherlimitDisabled={this.otherlimitDisabled}
              tableKey={this.tableKey}
            />
          </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, sModelsType, onCopyTo, slaveConfig, app, masterConfig, bPageEdit, sourceData, slaveData, editable,
  } = props;
  /*   回带表单   */
  onReturnForm(form);
  const{userinfo} = app;
  const pagination = {
    size: 'large',
    pageSize: sModelsType === 'modal/logView' ? 9999 : commonUtils.isNotEmptyNumber(props.iPageSize) && props.iPageSize !== 0 ? props.iPageSize : config.pageSize,
    ...slavePagination,
    showQuickJumper: true,
    hideOnSinglePage: true,
  };
  const realizeHeight = commonUtils.isNotEmptyNumber(props.realizeHeight) ? props.realizeHeight : 0;

  let bEdit = commonUtils.isNotEmptyObject(app.currentPane) && commonUtils.isNotEmptyObject(app.currentPane.name) && app.currentPane.bEdit; /* 是否可编辑 */
  if(!bEdit) {
    bEdit = bPageEdit;
  }
  const bSingleTree = commonUtils.isNotEmptyObject(slaveConfig) && slaveConfig.sTableType === 'single'; /* 单表数据 */
  const addState = {};
  if (editable !== undefined) {
    bEdit = editable;
    addState.bMutiSelect1 = true;
  }
  if(bSingleTree && slaveData) {
    let keyField = 'sId';
    let keyParentField = 'sParentId';
    let sSqlCondition = '';
    if (commonUtils.isNotEmptyObject(slaveConfig)) {
      sSqlCondition = slaveConfig.sSqlCondition;
      if (commonUtils.isNotEmptyObject(sSqlCondition) && commonUtils.isNotEmptyArr(sSqlCondition.split('.')) && sSqlCondition.split('.').length > 2) {
        keyField = sSqlCondition.split('.')[1];
        keyParentField = sSqlCondition.split('.')[2];
      }
    }
    addState.data = commonUtils.genTreeByArr(slaveData, keyField, keyParentField);
  }
  let customerHeight = 350;
  if (commonUtils.isNotEmptyNumber(realizeHeight)) {
    customerHeight += realizeHeight + 60;
  }
  // addState.noVlistTable = true;
  const tableProps = {
    ...commonBusiness.getTableTypes('slave', props),
    tableProps: {
      rowKey: 'sSlaveId', pagination, onChange: props.onTitleChange, AutoTableHeight: customerHeight,
    },
    bRowClick: bEdit,
    enabled: bEdit,
    onDelRow: (name, isWait, tableSelectedRowKeys, callback, index) => props.onDataRowDel(name, isWait, tableSelectedRowKeys, callback, index, props?.app?.currentPane?.config?.sControlName),
    onAddRow: (name, isWait) => props.onDataRowAdd(name, isWait, props?.app?.currentPane?.config?.sControlName),
    otherlimitDisabled: props.otherlimitDisabled,
    rootType: 'list',
    ...addState
  };

  const name = 'filterTree';
  const treeProps = {
    ...commonBusiness.getTreeTypes('tree', props),
    isSearch: false,
    checkable: false,
    disabled: false,
    checkedAll: false,
    unChecked: 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,
    onSelect: props.onSelectTree,
    expandedKeys: props.expandedKeys,
  };
  let rowSelectionProps = {};
  if (props.rowSelection !== undefined) {
    rowSelectionProps = {
      rowSelection: props.rowSelection,
    };
  }


  /* 解锁 加锁 按钮 */
  const btnLockList = commonUtils.isNotEmptyObject(masterConfig) && commonUtils.isNotEmptyArr(masterConfig.gdsconfigformslave) ? masterConfig.gdsconfigformslave.filter(item => item.sControlName && (item.sControlName.includes('BtnSendSD') || item.sControlName.includes('BtnSendJS'))) : [];

  const btnOperList = commonUtils.isNotEmptyObject(masterConfig) && commonUtils.isNotEmptyArr(masterConfig.gdsconfigformslave) ? masterConfig.gdsconfigformslave.filter(item => item.sControlName && ( item.sControlName.includes('BtnInvoiceUpd') ||
    (bPageEdit && item.sControlName.includes('BtnSendTJ')))) : [];

  const btnUploadApi = commonUtils.isNotEmptyObject(slaveConfig) && commonUtils.isNotEmptyArr(slaveConfig.gdsconfigformslave) ? slaveConfig.gdsconfigformslave.filter(item => item.sControlName && (item.sControlName.includes('BtnUploadApi') )) : [];

  const btnOutList =  commonUtils.isNotEmptyObject(slaveConfig) && commonUtils.isNotEmptyArr(slaveConfig.gdsconfigformslave) ? slaveConfig.gdsconfigformslave.filter(item => item.sControlName && ( item.sControlName.includes('BtnOut') )) : [];

  const bSplitArea = commonUtils.isNotEmptyObject(app.currentPane) && app.currentPane.config && app.currentPane.config.sControlName === 'BtnPopup.dSplitworkQty';
  let dSumQty = 0;
  let dModifyQty= 0;
  let dRoundQty = 0;
  if(bSplitArea) {
    const sourceData = commonUtils.isNotEmptyObject(app) && commonUtils.isNotEmptyObject(app.currentPane) ? app.currentPane.slaveDataSource : []; /* 是否可编辑 */
    if(commonUtils.isNotEmptyArr(sourceData) && commonUtils.isNotEmptyArr(slaveData)) {
      slaveData.forEach((item) => {
        dModifyQty += commonUtils.isNull(item.dModifyProductQty, 0);
        });
      dSumQty = commonUtils.convertToNum(commonUtils.isNull(sourceData[0].dMergeProductionQty, 0) + commonUtils.isNull(sourceData[0].dQdismantledQty, 0), 2);
      dRoundQty =  commonUtils.convertToNum(dSumQty - dModifyQty, 2);
    }
  }

  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 tableBelone = bEdit ? 'none' : 'list';

  const setOpterationColumn = (props.app.currentPane.config?.sControlName?.startsWith('BtnPopupEdit')
    || props.app.currentPane.config?.sControlName?.startsWith('BtnPopup.dSplitworkQty') )? 'Y' : 'N';

  if(setOpterationColumn === 'Y') {
    tableProps.tableProps.rowKey = 'sId';
  }
  const uploadUrl = commonUtils.isNotEmptyArr(btnUploadApi)? btnUploadApi[0].showDropDown : '';
  /* 发票上传  */
  let invoiceBody ={};
  const relaBizMegs ={
    costItems:"",costDearDepart:"",businessType:""
  }
  invoiceBody ={
    operatorId: userinfo?.sEmployeeNo, /* 操作人账号 */
    operatorName: userinfo?.sEmployeeName, /* 操作人名字 */
    InfoSysSource: "EBC", /* 信息系统来源 */
    relaBizMegs:JSON.stringify(relaBizMegs),
    companyCode: '1100',  /* 公司代码 */
  }
  const  upInvoiceProps = {
    action: uploadUrl,
    onChange: props.onUploadInvoiceChange,
    accept: '*/*',
    customRequest: props.customRequest,
    // 添加额外的参数
    data: invoiceBody,
    showUploadList: false,
    beforeUpload: () => {
    },
  };
  const upInvoiceName = commonUtils.isNotEmptyArr(btnUploadApi) ? btnUploadApi[0].showName :  '发票上传（金税）';

  const BtnSure = commonFunc.showLocalMessage(props, 'BtnSure', '确定');
  const BtnCancel = commonFunc.showLocalMessage(props, 'BtnCancel', '取消');
  const BtnClose = commonFunc.showLocalMessage(props, 'BtnClose', '关闭');

  return (
    <Form >
      <Layout>
        <Layout>
          <div id="modalChooseProcess">
            <div style={{ maxHeight: '100%', zIndex: 20, position:'relative' }}>
              <SearchComponent {...props} />
              {
                commonUtils.isNotEmptyArr(btnUploadApi) ?
                  <div style ={{right: '132px', top: '9px', position: 'absolute', zIndex: 100}}>
                    <Upload {...upInvoiceProps}><Button  style={{ color :'#1890FF', fontWeight:'bold'}} ><UploadOutlined fill='#f0ffff' /> {upInvoiceName}</Button>
                    </Upload>
                  </div> : ''
              }

            </div>
            <Content
              className={`xly-bill-list ${realizeHeight <= 0 ? 'xly-normal-list' : 'xly-normal-list resize-container-select'}`}
              style={{  paddingLeft: '10px' }}
              key={props.tableKey}
            >
              <StaticEditTable {...tableProps} tableBelone={tableBelone} showConfig={props.showConfig} {...rowSelectionProps} setOpterationColumn={setOpterationColumn} />
            </Content>
          </div>
        </Layout>
        {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
        {commonUtils.isEmptyArr(treeProps.treeData) || !commonUtils.isEmpty(props.routing) ? '' : <div className="xly-eject" style={{ position: 'absolute', right: '0px' }}> <a onClick={props.onEject}> <img src={Eject} alt="eject" /></a> </div>}
        {commonUtils.isEmptyArr(treeProps.treeData) || !commonUtils.isEmpty(props.routing) ? '' :
        <div className="xly-filter-tree">
          <StaticEditTree {...treeProps} />
          <div className="xly-tree-close" >
            {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
            <a onClick={props.onEject}> <img src={Close} alt="close" /></a>
          </div>
        </div>
        }
        {sModelsType !== 'search/workSchedule' && sModelsType !== 'search/sHistoryQty' ?
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div style={{ textAlign: 'right', marginLeft: '9px', marginBottom: '9px' }}>
              {
                commonUtils.isNotEmptyArr(props.btnList) && props.btnList.map(btn => (
                  <Button
                    style={{ marginRight: '8px' }}
                    onClick={() => btnClick(btn)}
                    type="primary"
                    key={btn.sControlName}
                  >
                    { btn.showName }
                  </Button>
                ))
              }
              {
                commonUtils.isNotEmptyArr(btnOperList) && btnOperList.map(btn => (
                  <Button
                    style={{ marginRight: '8px' }}
                    onClick={() => props.onBtnLockClick(btn)}
                    type="primary"
                    key={btn.sControlName}
                  >
                    { btn.showName }
                  </Button>
                ))
              }
              {
                commonUtils.isNotEmptyArr(btnOutList) && btnOutList.map(btn => (
                  <Button
                    style={{ marginRight: '8px' }}
                    onClick={() => props.onBtnOutClick(btn)}
                    type="primary"
                    key={btn.sControlName}
                  >
                    { btn.showName }
                  </Button>
                ))
              }
              {
                bSplitArea ?
                  <div> 总数：{dSumQty}，已拆分：{dModifyQty}, 剩余{dRoundQty}</div> : ''
              }
            </div>
            {
              props.readOnly ?
                <div style={{ textAlign: 'right', marginRight: '9px', marginBottom: '9px' }}>
                  <Button type="primary" onClick={props.onCancel}>{BtnClose}</Button>
                </div> :
                <div style={{ textAlign: 'right', marginRight: '9px', marginBottom: '9px' }}>
                  {
                    commonUtils.isNotEmptyArr(btnLockList) ? btnLockList.map(btn => (
                      <Button
                        style={{ marginRight: '8px' }}
                        onClick={() => props.onBtnLockClick(btn)}
                        type="primary"
                        key={btn.sControlName}
                      >
                        { btn.showName }
                      </Button>
                    )) :
                      <div>
                      <Button key="back" style={{ marginRight: '8px' }} onClick={props.onCancel}>{BtnCancel}</Button>
                      <Button type="primary" onClick={props.onSelect}>{BtnSure}</Button>
                    </div>
                  }

                </div>
            }
          </div> : ''
        }
        <span ref={props.spanDialog} />
      </Layout>
    </Form>
  );
});

export default CommonBase(CommonListEvent(CommonList));
