/* eslint-disable */
import React, { Component } from 'react';
// import '@ant-design/compatible/assets/index.css';
import { Form } from '@ant-design/compatible';
import { Spin, Tabs, message, Modal, Tooltip } from 'antd-v4';
import * as commonUtils from '@/utils/utils';/* 通用方法 */
// import * as commonUtils from '../../utils/utils'; /* 通用方法 */
import * as commonBusiness from '@/components/Common/commonBusiness';/* 单据业务功能 */
import StaticEditTable from '@/components/Common/CommonTable';/* 可编辑表格 */
import * as commonFunc from '@/components/Common/commonFunc';
import ShowType from '@/components/Common/CommonComponent';
import RGL, { WidthProvider } from 'react-grid-layout';
import layoutStyle from './index.less'

const { TabPane } = Tabs;
const ReactGridLayout = WidthProvider(RGL);
/**
 此组件是选择工序、放大镜弹窗等的通用窗体
 */
class CommonListSelectParam extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalLoaded: null, // 弹窗是否加载完成
    };

    this.selectedData = []; // 选中数据
    this.refIds = {}; // 记录所有组件的id
    this.copyData = {};
    this.formData = {};
    this.currentTab = null; // 多tab时当前选中tab
    this.initEventLoaded = false; // 已加载初始化event事件
    this.sidJson = {};
  }

  componentDidMount() {
    if (this.props.bInModal && !this.state.modalLoaded) {
      this.setState({ modalLoaded: true });
    } else {
      this.setState({ modalLoaded: false });
    }
  }

  componentWillReceiveProps() {
    this.refIds = [];
  }

  componentDidUpdate() {
    if (!this.initEventLoaded && this.layoutRef) {
      this.layoutRef.addEventListener(
        "mousedown",
        this.handleSelectMouseDownEvent
      );
      document.addEventListener("mouseup", this.handleSelectMouseUpEvent);
      document.addEventListener("mousemove", this.handleSelectMouseMoveEvent);
      document.addEventListener("copy", this.handleCopyEvent);
      document.addEventListener('paste', this.handlePasteEvent);
      this.initEventLoaded = true;
    }
    if (this.layoutRef) {
      const { x: baseX, y: baseY } = this.layoutRef.getBoundingClientRect();
      this.baseX = baseX;
      this.baseY = baseY;
    }
  }

  componentWillUnmount() {
    if (this.layoutRef) {
      this.layoutRef.removeEventListener(
        "mousedown",
        this.handleSelectMouseDownEvent
      );
      document.removeEventListener("mouseup", this.handleSelectMouseUpEvent);
      document.removeEventListener(
        "mousemove",
        this.handleSelectMouseMoveEvent
      );
      document.removeEventListener("copy", this.handleCopyEvent);
      document.removeEventListener('paste', this.handlePasteEvent);
    }
  }

   // 鼠标按下事件
   handleSelectMouseDownEvent = e => {
    if (e.button === 2) {
      return;
    }
    if (e?.target?.classList?.contains('ant-tabs-tab-btn')) {
      return;
    }
    const { showAllParam, sParamType } = this.props;
    this.selectedData = [];
    let activeKey = '';
    let oTabpane = null;
    if (!showAllParam) {
      activeKey = sParamType;
      oTabpane = this.layoutRef;
    } else {
      activeKey = this.currentTab;
      oTabpane = this.layoutRef.querySelector(
        ".ant-tabs-tabpane:not(.ant-tabs-tabpane-hidden)"
      )
    }

    this.refIds[activeKey]?.forEach(id => {
      const dom = oTabpane.querySelector(`#${id}`);
      if (dom) {
        const oChecked = dom.querySelector(".divChecked");
        oChecked ? (oChecked.style.display = "none") : "";
      }
    });

    this.bMousedwon = true;
    const { clientX, clientY } = e;

    this.clientX = clientX;
    this.clientY = clientY;

    this.selectAreaRef.style.left = clientX - this.baseX + "px";
    this.selectAreaRef.style.top = clientY - this.baseY + "px";
    this.selectAreaRef.style.width = "1px";
    this.selectAreaRef.style.height = "1px";

    this.setState({ maskVisible: true });
  };

  // 鼠标抬起事件
  handleSelectMouseUpEvent = e => {
    const bMousedwonBak = this.bMousedwon;
    this.bMousedwon = false;
    if (bMousedwonBak) {
      this.setState({ maskVisible: false });
    }
  };

  // 鼠标移动事件
  handleSelectMouseMoveEvent = e => {
    if (this.bMousedwon && this.selectAreaRef) {

      const { showAllParam, sParamType } = this.props;
      this.selectedData = [];
      let activeKey = '';
      let oTabpane = null;
      if (!showAllParam) {
        activeKey = sParamType;
        oTabpane = this.layoutRef;
      } else {
        activeKey = this.currentTab;
        oTabpane = this.layoutRef.querySelector(
          ".ant-tabs-tabpane:not(.ant-tabs-tabpane-hidden)"
        )
      }

      const { clientX, clientY } = e;
      const x1 = Math.min(clientX, this.clientX);
      const x2 = Math.max(clientX, this.clientX);
      const y1 = Math.min(clientY, this.clientY);
      const y2 = Math.max(clientY, this.clientY);

      this.selectAreaRef.style.left = x1 - this.baseX + "px";
      this.selectAreaRef.style.top = y1 - this.baseY + "px";
      this.selectAreaRef.style.width = x2 - x1 + "px";
      this.selectAreaRef.style.height = y2 - y1 + "px";

      const {
        right: right1,
        left: left1,
        bottom: bottom1,
        top: top1
      } = this.selectAreaRef.getBoundingClientRect();
      const selectedData = [];
      this.refIds[activeKey]?.forEach(id => {
        const dom = oTabpane.querySelector(`#${id}`);
        if (dom) {
          const {
            right: right2,
            left: left2,
            bottom: bottom2,
            top: top2
          } = dom.getBoundingClientRect();
          if (
            !(
              right1 < left2 ||
              left1 > right2 ||
              bottom1 < top2 ||
              top1 > bottom2
            )
          ) {
            selectedData.push(id);
            dom.querySelector(".divChecked").style.display = "";
          } else {
            dom.querySelector(".divChecked").style.display = "none";
          }
        }
      });
      this.selectedData = selectedData;
    }
  };

  // 复制操作
  handleCopyEvent = e => {
    if (!this.props.bInModal && this.props.commonParamVisible) {
      return;
    }
    if (commonUtils.isNotEmptyArr(this.selectedData)) {
      const clipboardData = e.clipboardData;
      if (!clipboardData) {
        return;
      }
      e.preventDefault();

      const { showAllParam, sParamType } = this.props;
      let activeKey = '';
      if (!showAllParam) {
        activeKey = sParamType;
      } else {
        activeKey = this.currentTab;
      }

      // 获取当前tab页布局
      const { tempLayout: layout, viewRow } = this.copyData[activeKey];
      const formData  = this.formData[activeKey];
      const { processSelectedData } = this.props;

      const selectedLayout = layout.filter(item =>
        this.selectedData.includes(item.i)
      );

      const [minX, maxX, minY, maxY] = selectedLayout.reduce(
        (result, item) => {
          const { x, y, w, h } = item;
          result = [
            Math.min(result[0], x),
            Math.max(result[1], x + w),
            Math.min(result[2], y),
            Math.max(result[3], y + h)
          ];
          return result;
        },
        [999, 0, 999, 0]
      );

      const tableW = maxX - minX;
      const tableH = maxY - minY;

      const filledArr = [];
      const tableContent = `<table><tbody>${new Array(tableH)
        .fill("")
        .map((_, trIndex) => {
          return `<tr>${new Array(tableW)
            .fill("")
            .map((_, tdIndex) => {
              const startX = minX + tdIndex;
              const startY = minY + trIndex;
              const iIndex = selectedLayout.findIndex(
                item => item.x === startX && item.y === startY
              );
              if (iIndex !== -1) {
                const { i, w, h } = selectedLayout[iIndex];
                // 记录占据的单元格位置
                for (let j = startX; j < startX + w; j++) {
                  for (let k = startY; k < startY + h; k++) {
                    filledArr.push(`${j}_${k}`);
                  }
                }

                // const title = viewRow[i];
                let { value } = formData[`${i}_${activeKey}Param_${processSelectedData[0].sId}`] || {};
                value = value === undefined ? "" : value;
                // return `<td rowspan=${h}>${title}</td><td colspan=${w -
                //   1} rowspan=${h}>${value}</td>`;
                return `<td colspan=1 rowspan=${h}>${value}</td>`;
              } else if (filledArr.includes(`${startX}_${startY}`)) {
                return "";
              } else {
                return "<td></td>";
              }
            })
            .join("")}</tr>`;
        })
        .join("")}</tbody></table>`;

      clipboardData.setData("text/plain", tableContent);
    }
  };

  // 粘贴操作
  handlePasteEvent = e => {
    if (!this.props.bInModal && this.props.commonParamVisible) {
      return;
    }

    const { showAllParam, sParamType } = this.props;
    let activeKey = '';
    if (!showAllParam) {
      activeKey = sParamType;
    } else {
      activeKey = this.currentTab;
    }

    // 获取当前tab页布局
    const { tempLayout: layout, tableConfig } = this.copyData[activeKey];

    const selectedLayout = layout.filter(item =>
      this.selectedData.includes(item.i)
    );

    selectedLayout.sort(({ x: x1, y: y1 }, { x: x2, y: y2 }) => y1 === y2 ? x1 - x2 : y1 - y2);
    const iArr = selectedLayout.map(item => item.i);

    const html = e.clipboardData.getData('text/html');
    const $doc = new DOMParser().parseFromString(html,'text/html');
    // 加载所有的行
    const $trs = $doc.querySelectorAll('table tr');
    const tableArr = [];
    $trs.forEach(tr => {
      tr.querySelectorAll('td').forEach(td => {
        tableArr.push({
          value: td.innerHTML.replace(/<[^>]+>/g, "").trim(),
          colspan: td.getAttribute('colspan') || 1,
          rowspan: td.getAttribute('rowspan') || 1,
        })
      })
    })

    const { processData, processSelectedData, sParamData } = this.props;
    const copyExcel2ShowType = async (iArr) => {
      const newState = {};
      const addState = {};
      const sParams = [];
      for (let index = 0; index < iArr.length; index++) {
        const sName = iArr[index];
        if (tableArr[index]) {
          const { value } = tableArr[index];
          newState[`${sName}_${activeKey}Param_${processSelectedData[0].sId}`] = value;
          addState[sName.replace('sParam', 'sParamValue')] = value;

          const config = {};
          const iIndex = tableConfig.findIndex(item => item.sName === sName);
          if (iIndex !== -1) {
            config.showDropDown = tableConfig[iIndex].showDropDown;
            config.sParamName = tableConfig[iIndex].showName;
          }
          sParams.push({
            ...config,
            sId: commonUtils.createSid(),
            sParamKey: sName,
            sParamValue: value,
            bSelfCbx: true,
            handleType: 'update'
          });
        }
      }
      addState.sParams = JSON.stringify(sParams);

      const iIndex = processData.findIndex(item => item.sId === processSelectedData[0].sId);
      const processDataNew = [...processData];
      if (iIndex !== -1) {
        processDataNew[iIndex] = {...processDataNew[iIndex], ...addState }
      }

      this.props.onSaveState({
        masterData: { ...this.props.masterData, ...newState },
        commonListSelectParamId: commonUtils.createSid(),
        processData: processDataNew,
      });
      
    }

    if (commonUtils.isNotEmptyArr(iArr) && commonUtils.isNotEmptyArr(tableArr)) {
      if (iArr.length !== tableArr.length) {
        Modal.confirm({
          title: '温馨提示:',
          content: 'excel数据数量与组件数量不一致, 强制匹配？',
          okText: '确认',
          onOk() {
            copyExcel2ShowType(iArr);
          },
        });
      } else {
        copyExcel2ShowType(iArr);
      }
    } else if (commonUtils.isNotEmptyArr(iArr) && commonUtils.isEmptyArr(tableArr)) {
      message.info('粘贴板无excel数据');
    }
  };


  // 初始化布局数据
  handleGetInitLayout = (configs, panel = "[]") => {
    if ( panel === "[]") { // 如果没有保存过布局数据
      let flag = 0;
      return configs.map((item, index) => {
        if (index % 4 === 0 && index !== 0) {
          flag++;
        }
        const minH = item.sName && item.sName.includes('sParamColumnConfig') ? 2 : 1;
        return {
          i: item.sName,
          x: (index - flag * 4) * 3,
          y: flag,
          w: 3,
          h: minH,
          minH,
        }
      });
    } else { // 如果保存过布局数据
      // 判断配置数据和布局数据的sName是否一致
      const arrAdd = configs.map(item => item.sName); // 新增的字段
      const arrDel = []; // 删除的字段
      const panelArr = JSON.parse(panel);
      panelArr.forEach(({ i: sName }, index) => {
        const minH = sName && sName.includes('sParamColumnConfig')? 2 : 1;
        panelArr[index].minH = minH;
        panelArr[index].h = Math.max(panelArr[index].h, minH);
        const iIndex = arrAdd.findIndex(item => item === sName);
        if (iIndex !== -1) {
          arrAdd.splice(iIndex, 1);
        } else {
          arrDel.push(sName);
        }
      });
      
      if (commonUtils.isEmptyArr(arrAdd) && commonUtils.isEmptyArr(arrDel)) { // 数据没有变化
        return panelArr;
      }

      if (commonUtils.isNotEmptyArr(arrDel)) { // 有删除的数据
        arrDel.forEach(sName => {
          const iIndex = panelArr.findIndex(item => item.i === sName);
          if (iIndex !== -1) {
            panelArr.splice(iIndex, 1);
          }
        });
      }

      if (commonUtils.isNotEmptyArr(arrAdd)) { // 有新增的数据
        let newY = 0; // 新增数据的开始行位置
        panelArr.forEach(({y, h}) => {
          newY = Math.max(y + h, newY);
        });

        let flag = 0;
        arrAdd.forEach((sName, index) => {
          if (index % 4 === 0 && index !== 0) {
            flag++;
          }
          const minH = sName && sName.includes('sParamColumnConfig') ? 2 : 1;
          panelArr.push({
            i: sName,
            x: (index - flag * 4) * 3,
            y: flag + newY,
            w: 3,
            h: minH,
            minH,
          });
        })
      }
      return panelArr;
    }
  }

  handleGetParam = (name, slaveSelectOneData) => {
    const addState ={};
    const paramsConfig = {};
    let paramData = {};
    paramsConfig.gdsconfigformslave = [];
    let paramListConfig ={};
    let paramListData = [];
    let paramListColumn = [];
    const sType = `${name}Param`;
    const bTable = slaveSelectOneData['b'+ name.replace('s','').trim() + 'ParamTable'] ;
    const paramType = commonUtils.isNotEmptyObject(slaveSelectOneData) ? slaveSelectOneData[sType] : '';
    if (commonUtils.isNotEmptyObject(paramType)) {
      /* 表格显示 */
      if(bTable) {
        /* 工序参数以表格形式展示 列 */
        // let paramListData = [];
        paramListConfig = {
          bisMutiSelect: false,
          bMutiSelect: false,
        };
        const gdsconfigformslave = [{
          sId: commonUtils.createSid(),
          sName: 'sId',
          showName: '主键',
          bVisible: false,
          iFitWidth: 200,
        }, {
          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,
        }];
        paramListConfig.gdsconfigformslave = gdsconfigformslave;
        paramListColumn = commonFunc.getHeaderConfig(paramListConfig);
        if (commonUtils.isNotEmptyObject(paramType)) {
          /* 要把数据以表格的形式显示出来 */
          const sParamJsonObj = JSON.parse(paramType);
          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]; /* 默认值 */
              }
              paramListData.push(obj);
            }
          }
        }
        addState[`${name}ParamListConfig`] = paramListConfig;
        addState[`${name}ParamListColumn`] = paramListColumn;
        addState[`${name}ParamListData`] = paramListData;
        addState[`b${name}ParamTable`] = true; /* 是否已表格显示 */
        console.log('addState', addState);
      }else{ /* 控件显示 */
        paramData = { ...paramData, ...commonUtils.convertStrToObj(paramType) };
        if (this.sidJson[`${slaveSelectOneData.sId}_${name}`]) {
          paramData.sId = this.sidJson[`${slaveSelectOneData.sId}_${name}`];
        } else {
          paramData.sId = commonUtils.createSid();
          this.sidJson[`${slaveSelectOneData.sId}_${name}`] = paramData.sId;
        }
        const gdsconfigformslaveSid = {};
        gdsconfigformslaveSid.sName = 'sId';
        gdsconfigformslaveSid.showName = 'sId';
        gdsconfigformslaveSid.bVisible = false;
        paramsConfig.gdsconfigformslave.push(gdsconfigformslaveSid);
        for (const key of Object.keys(paramData)) {
          const num = key.replace('sParam', '').trim();
          const sParamColumnConfig = 'sParamColumnConfig' + num;
          if(key.includes('sParam') && (commonUtils.isEmptyObject(paramData[sParamColumnConfig]) || key.includes('sParamColumnConfig'))
            && !key.includes('sParamDropDown') && !key.includes('sParamDefault')  ) {
            const gdsconfigformslave = {};
            gdsconfigformslave.sName = key;
            gdsconfigformslave.showName = paramData[key];
            gdsconfigformslave.bVisible = true;
            /* 判断是否是sql下拉 */
            const num = Number(key.replace('sParam', ''));
            const sqlDrownName = `sParamDropDown${num}`;
            if (!commonUtils.isEmpty(paramData[sqlDrownName])) {
              gdsconfigformslave.sDropDownType = 'const';
              const conStr = JSON.stringify(paramData[sqlDrownName]);
              gdsconfigformslave.showDropDown = conStr;
            }
            paramsConfig.gdsconfigformslave.push(gdsconfigformslave);
          }
        }
      }
    } else {
      paramsConfig.gdsconfigformslave = [];
      paramData = {};
    }
    return {
      [`${name}ParamConfig`]: paramsConfig,
      [`${name}ParamData`]: [paramData],
      // ...addState,
      [`${name}ParamListConfig`] : paramListConfig,
      [`${name}ParamListColumn`] : paramListColumn,
      [`${name}ParamListData`] : paramListData,
      [`b${name}ParamTable`] : bTable, /* 是否已表格显示 */
    };
  };

  handleChange = (_tableName, _sName, record) => {
    const { masterData, processData, processSelectedData } = this.props;
    if(commonUtils.isNotEmptyArr(processSelectedData) && commonUtils.isNotEmptyObject(_sName)) {
      const iProcessIndex = processData.findIndex(item => item.sId === processSelectedData[0].sId);
      if (iProcessIndex > -1) {
        let sParams = processSelectedData[0].sParams;
        const sParamsData = JSON.parse(sParams);
        const sParamKey = commonUtils.isNotEmptyArr(_sName.split('_')) && _sName.split('_').length > 2 ? _sName.split('_')[0] : '';
        const sProcessId = commonUtils.isNotEmptyArr(_sName.split('_')) && _sName.split('_').length > 2 ? _sName.split('_')[2] : '';
        if (commonUtils.isNotEmptyArr(sParamsData)) {
          const iPIndex = sParamsData.findIndex(item => item.sParamKey === sParamKey);
          if (iPIndex > -1) {
            const addState = {
              sParamValue: record[_sName],
              bSelfCbx: true
          };
            sParamsData[iPIndex] = {...sParamsData[iPIndex], ...addState};
          }
        }
        const sParamsNew =  JSON.stringify(sParamsData);
        processSelectedData.sParams = sParamsNew;
        const addProcessState = {};
        addProcessState.sParams = sParamsNew;
        addProcessState.handleType= commonUtils.isEmpty(processData[iProcessIndex].handleType) ? 'update' : processData[iProcessIndex].handleType;
        processData[iProcessIndex] ={...processData[iProcessIndex], ...addProcessState};
      }
    }

    this.props.onSaveState({
      masterData: { ...masterData, ...record, processData }
    });
  }

  handleGetTabParams = () => {
    const {
      // masterConfig,
      slaveData,
    } = this.props;
    const sParamList = ['sProcess', 'sReport', 'sWorkOrder', 'sNorm', 'sTest'];
    const sParamNameList = ['工序参数', '上报参数', '工单参数', '标准书参数', '测试参数'];

    const oTabPane = sParamList.map((sName, index) => {
      // if (masterConfig?.gdsconfigformslave) {
      //   const iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === `${sName}Param`);
      //   if (iIndex !== -1) {
      //     sParamNameList[index] = masterConfig.gdsconfigformslave[iIndex].showName;
      //   }
      // }

      const {
        [`${sName}ParamConfig`]: sParamConfig,
        [`b${sName}ParamTable`]: bParamTable,
      } = this.handleGetParam(sName, slaveData[0]);
      const tableConfig = commonUtils.isNotEmptyObject(sParamConfig) && commonUtils.isNotEmptyArr(sParamConfig.gdsconfigformslave)
      ? sParamConfig.gdsconfigformslave.filter(item => item.bVisible) : [];

      if (commonUtils.isEmptyArr(tableConfig) && !bParamTable) {
        return '';
      }

      if (!this.currentTab) {
        this.currentTab = sName;
      }

      return (
        <TabPane
          key={sName}
          tab={sParamNameList[index]}
        >
          <CommonParamsComponent
            {...this.props}
            onGetRefIds={this.handleGetRefIds}
            onSetRefIds={this.handleSetRefIds}
            onGetInitLayout={this.handleGetInitLayout}
            onGetParam={this.handleGetParam}
            onSaveCopyData={this.handleSaveCopyData}
            onSaveFormData={this.handleSaveFormData}
            onChange={this.handleChange}
            sParamType={sName}
          />
        </TabPane>
      );
    })


    return (
      <Tabs
        tabBarStyle={{ margin: "0 8px" }}
        onTabClick={key => {
          this.currentTab = key;
        }}
      >
        { oTabPane }
      </Tabs>
    );
  }

  handleGetRefIds = () => {
    return this.refIds;
  }

  handleSetRefIds = (refIds) => {
    this.refIds = refIds;
  }

  handleSaveCopyData = (sParamType, data) => {
    this.copyData[sParamType] = data;
  }

  handleSaveFormData = (sParamType, data) => {
    this.formData[sParamType] = data;
  }

  render() {
    const { pageLoading, showAllParam, bInModal } = this.props;
    const { maskVisible, modalLoaded } = this.state;

    return (
      (!bInModal || modalLoaded) && <div className={`xly-workorder-list ${layoutStyle.tabContent}`} style={{ height: '100%' }}>
        <Spin spinning={pageLoading}  style={{ height: '100%', width: '100%' }}>
          <div style={{ height: '100%' }} ref={(ref) => { this.layoutRef = ref; }}>
            {
              showAllParam ?
               this.handleGetTabParams() :
                <CommonParamsComponent
                  {...this.props}
                  onGetRefIds={this.handleGetRefIds}
                  onSetRefIds={this.handleSetRefIds}
                  onGetInitLayout={this.handleGetInitLayout}
                  onGetParam={this.handleGetParam}
                  onSaveCopyData={this.handleSaveCopyData}
                  onSaveFormData={this.handleSaveFormData}
                  onChange={this.handleChange}
                />
            }
          </div>
          <div
            className={layoutStyle.mask}
            style={{ display: maskVisible ? "" : "none" }}
          >
            <div className="maskContent">
              <div
                className="maskSelectArea"
                ref={ref => {
                  this.selectAreaRef = ref;
                }}
              />
            </div>
          </div>
        </Spin>
      </div>
    );
  }
}

const CommonParamsComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData, masterConfig, sParamType } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form, masterConfig);
    // props.onSaveFormData(sParamType, obj);
    // console.log('=====obj', obj);
    return obj;
  },
})((props) => {
  const {
    slaveData,
    sParamType,
    processSelectedData,
    onGetInitLayout,
    onGetParam,
    onGetRefIds,
    onSetRefIds,
    onSaveCopyData,
    enabled,
  } = props;

  const sTypeName = `${sParamType}Param`;
  const sTypePanel = `${sParamType}Panel`;
  // 是否展示
  let bShown = false;
  if (commonUtils.isNotEmptyArr(slaveData)) {
    const sReportParam = slaveData[0][sTypeName];
    if (sReportParam && commonUtils.isJSON(sReportParam) && commonUtils.isNotEmptyObject(JSON.parse(sReportParam))) {
      bShown = true;
    }
  }

  if (!bShown) {
    return '';
  }
  
  const {  [`${sTypeName}Config`]: sReportParamConfig, [`${sTypeName}Data`]:sReportParamData,
    [`${sTypeName}ListConfig`]: paramListConfig,[`${sTypeName}ListColumn`]: paramListColumn,
    [`${sTypeName}ListData`] : paramListData, [`b${sTypeName}Table`]: bParamTable,
  } = onGetParam(sParamType, slaveData[0]);

  const sReportViewConfig = commonUtils.isNotEmptyObject(sReportParamConfig) && commonUtils.isNotEmptyArr(sReportParamConfig.gdsconfigformslave)
    ? sReportParamConfig.gdsconfigformslave.filter(item => item.bVisible) : [];

  let tableConfig = sReportViewConfig;
  const viewRow = commonUtils.isNotEmptyArr(sReportParamData) ? sReportParamData[0] : {};
  if (bParamTable) {
    tableConfig = [{
      bVisible: true,
      sName: 'sParamColumnConfig1'
    }];
  }
  let tempLayout = onGetInitLayout(tableConfig, slaveData[0][sTypePanel]);

  const sTableName = sTypeName +'List';
  const sTableConfig = sTypeName +'ListConfig';
  const sTableColumn = sTypeName +'ListColumn';
  const sTableData = sTypeName +'ListData';
  const key = 'sParamColumnConfig1';

  const paramListTableProps = {
    ...commonBusiness.getTableTypes(sTableName, {...props, [sTableConfig]: paramListConfig, [sTableColumn]: paramListColumn,
      [sTableData]: paramListData }),
    tableProps:{},
    // data: paramListData1,
  };

  onSaveCopyData(sParamType, { tempLayout, viewRow, tableConfig });

  const getAutoTableHeight = () => {
    if (props.bInModal) {
      return 385;
    } else {
      const oProcessTable = document.querySelector(`#${props.processTableId}`);
      if (oProcessTable) {
        const oBody = oProcessTable.querySelector('.ant-table-body');
        if (oBody) {
          return oBody.getBoundingClientRect().height;
        }
      }
    }
    return 'auto';
  }

  return bParamTable &&
    tableConfig.some(item => item.sName === "sParamColumnConfig1") ? (
    <div className="blankPanel">
      <StaticEditTable
        {...paramListTableProps}
        tableProps={{
          AutoTableHeight: getAutoTableHeight()
        }}
        setOpterationColumn="Y"
      />
    </div>
  ) : (
    <ReactGridLayout
      margin={[0, 0]}
      compactType="vertical"
      layout={tempLayout}
      cols={12}
      rowHeight={28}
      isDraggable={false}
      isResizable={false}
      isDroppable={false}
    >

      {
        bParamTable ?
          (<div
            key={key}
            id={key}
            className={enabled ? layoutStyle.editMode : ''}
            style={{ display: 'block', position: 'relative', overflow: 'hidden' }}
          >
            <div style={{ maxWidth: '100%' }}>
              <StaticEditTable
                {...paramListTableProps}
                setOpterationColumn='Y'
                layoutH={tempLayout.find(item => item.i === key) ? tempLayout.find(item => item.i === key).h : 2}
              />
            </div>
          </div>)
          :
        tableConfig.map((child) => {
        const iRowNum = child.iColValue === 1 ? 6 : 1; /* 1个字段占的网格个数 ，网格总个数是24 */
        const iColValue = sMemo ? 24 : child.iColValue * iRowNum; /* 产品部要求 备注设置成一行到底 */ /* 跨度 */
        const sMemo = child.sName.toLowerCase().endsWith('memo');
        let enabledNew = enabled && !child.bReadonly;
        if (child.iTag === 1) {
          enabledNew = false;
        } else if (child.iTag === 3) {
          enabledNew = true;
        }
        const sFormulaMemo = child.sName.toString() === 'sFormulaMemo' ? 'none' : 'block';
        if (child.iTag === 1) {
          enabledNew = false;
        } else if (child.iTag === 3) {
          enabledNew = true;
        }

        let w = 3;
        const iIndex = tempLayout.findIndex(item => item.i === child.sName);
        if (iIndex !== -1) {
          w = tempLayout[iIndex].w;
        }
        const flexWidth = w !== 1 ? (3 * 33) / w : 0;
        const formItemLayout = {
          labelCol: {
            flex: flexWidth + "%",
            style: {
              color: "rgba(0, 0, 0, 0.65)",
              backgroundColor: "#BFEFFF"
            }
          },
          wrapperCol: { flex: "auto" }
        };

        const showTypeProps = {
          name: sTypeName,
          form: props.form,
          getSqlDropDownData: props.getSqlDropDownData,
          getSqlCondition: props.getSqlCondition,
          handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
          getFloatNum: props.getFloatNum,
          onChange: props.onChange,
          showConfig: {...child, sName: `${child.sName}_${sTypeName}_${processSelectedData[0].sId}`},
          formItemLayout,
          textArea: sMemo,
          enabled: enabledNew,
          bTable: false,
          formRoute: props.formRoute,

          app: props.app,
          iColValue,
          record: viewRow,
          sId: viewRow.sId,
          bViewTable: true,
          onViewClick: props.handleViewClick,
          onFieldDoubleClick: props.handleFieldDoubleClick,
        };

        /* 如果包含sParamColumnConfig 则渲染表格，否则渲染为View */
        if (child.sName && child.sName.includes('sParamColumnConfig')) {
          const paramListConfigStr = child.showName;
          const paramListConfig = commonUtils.isJSON(paramListConfigStr) ? JSON.parse(paramListConfigStr) : {};
          let paramListColumn = [];
          if (commonUtils.isNotEmptyObject(paramListConfig)) {
            paramListColumn = commonFunc.getHeaderConfig(paramListConfig);
          }
          const paramListTableProps = {
            ...commonBusiness.getTableTypes('paramList', {...props, paramListConfig, paramListColumn }),
            tableProps:{},
            data: [],
          };
          return (
            <div
              key={child.sName}
              id={child.sName}
              style={{ display: sFormulaMemo, position: 'relative', overflow: 'hidden' }}
            >
              <StaticEditTable
                {...paramListTableProps}
                setOpterationColumn='Y'
                layoutH={tempLayout.find(config => config.i === child.sName).h}
              />
            </div>
          )
        } else {
          const refIds = onGetRefIds();
          if (
            refIds[sParamType] &&
            !refIds[sParamType].includes(child.sName)
          ) {
            refIds[sParamType].push(child.sName);
          } else {
            refIds[sParamType] = [child.sName];
          }
          onSetRefIds(refIds);
          const showType = (
            <ShowType
              key={`${child.sName}_${flexWidth}`}
              {...showTypeProps}
            />
          );
          return (
            <div
              key={child.sName}
              id={child.sName}
              className={layoutStyle.showType}
              style={{ display: sFormulaMemo, position: 'relative' }}
            >
              {w === 1 ? (
                <Tooltip placement="top" title={child.showName}>
                  <div>{showType}</div>
                </Tooltip>
              ) : (
                showType
              )}
              <div
                className={`divChecked ${layoutStyle.divChecked}`}
                style={{ display: "none" }}
              />
            </div>
          );
        }
      })}
    </ReactGridLayout>
  );
});

export default CommonListSelectParam;
