/* eslint-disable */
import * as commonUtils from "@/utils/utils";
import * as commonFunc from "@/components/Common/commonFunc";

// 获取RGL布局参数
export function getReactGridLayout(
  sParamType,
  selectedData = {},
  sModelsId = "",
  formRoute = ""
) {
  const {
    [`${sParamType}Panel`]: panelOld,
    [`${sParamType}Param`]: param,
    sParams
  } = selectedData;

  // 获取params数据
  const recordDataAll = commonUtils.convertStrToObj(sParams, []);
  const recordItem =
    recordDataAll.find(item => item.sParamType === sParamType) || {};
  let record = recordItem.data || {};

  const recordDefault = {};

  // 拼接config
  const paramsConfig = {
    gdsconfigformslave: [
      {
        sName: "sId",
        showName: "sId",
        bVisible: false
      }
    ]
  };
  const paramData = commonUtils.convertStrToObj(param);
  Object.keys(paramData).forEach(key => {
    const keyInArr = ["sParam"];
    const keyOutArr = [
      "sParamColumnConfig",
      "sParamDropDown",
      "sParamDefault",
      "sParamNotEmpty",
      "sParamNotFirstEmpty",
      "sParamReadOnly",
      "sParamAssFieldName",
      "sParamFieldName",
      "sParamNotZero",
      "sParamDropDownType",
      "sParamAssignField",
      "sParamSqlCondition",
      "sParamKeyUpFilter"
    ];
    // key包含所有keyInArr 且 不包含keyOutArr
    if (
      !keyInArr.some(keyIn => !key.includes(keyIn)) &&
      !keyOutArr.some(keyOut => key.includes(keyOut))
    ) {
      const num = Number(key.replace("sParam", ""));
      let gdsItem = {
        sNameParam: commonUtils.isEmpty(paramData["sParamFieldName" + num])
          ? key
          : paramData["sParamFieldName" + num],
        sName: key,
        showName: paramData[key],
        bVisible: true
      };

      /* 判断是否是sql下拉 */

      gdsItem.sAssignField = commonUtils.isEmpty(
        paramData["sParamAssignField" + num]
      )
        ? ""
        : paramData["sParamAssignField" + num];
      if (paramData["sParamNotZero" + num]) {
        gdsItem.bNotZero = true;
      }

      const sqlDrownName = `sParamDropDown${num}`;
      if (!commonUtils.isEmpty(paramData[sqlDrownName])) {
        if (paramData["sParamDropDownType" + num] === "sql") {
          gdsItem.sDropDownType = "sql";
          gdsItem.showDropDown = paramData[sqlDrownName];
          gdsItem.sSqlCondition = paramData["sParamSqlCondition" + num];
          gdsItem.sKeyUpFilter = paramData["sParamKeyUpFilter" + num];
        } else {
          const conStr = JSON.stringify(paramData[sqlDrownName]);
          gdsItem = {
            ...gdsItem,
            ...{ sDropDownType: "const", showDropDown: conStr }
          };
        }
      }

      /* 判断是否是必填 */
      const bMustFieldName =
        ["12710101117313076578090", "12710101117054908553170"].includes(
          sModelsId
        ) || ["/indexPage/commonCostomTabBill"].includes(formRoute)
          ? "sParamNotFirstEmpty"
          : "sParamNotEmpty";
      const bNotEmptyName = `${bMustFieldName}${num}`;
      if (paramData[bNotEmptyName]) {
        gdsItem = {
          ...gdsItem,
          bNotEmpty: true
        };
      }

      /* 判断是否是只读 */
      const bReadOnlyName = `sParamReadOnly${num}`;
      if (paramData[bReadOnlyName]) {
        gdsItem = {
          ...gdsItem,
          bReadOnly: true
        };
      }

      /* 判断是否是有默认值 */
      const sParamDefault = `sParamDefault${num}`;
      if (paramData[sParamDefault]) {
        // if (record[key] === undefined) {
        recordDefault[key] = paramData[sParamDefault];
        const sParamFieldName = paramData[`sParamFieldName${num}`];
        if (sParamFieldName) {
          recordDefault[sParamFieldName] = paramData[sParamDefault];
        }
        // }
      }

      paramsConfig.gdsconfigformslave.push(gdsItem);
    }
  });

  record = commonUtils.isNotEmptyObject(record)
    ? record
    : { ...recordDefault, ...record };

  const configs = paramsConfig.gdsconfigformslave.filter(item => item.bVisible);
  const panel = commonUtils.convertStrToObj(panelOld, []);
  let layout = [];
  if (commonUtils.isEmptyArr(panel)) {
    // 如果没有保存过布局数据
    let flag = 0;
    layout = 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) * 6,
        y: flag,
        w: 6,
        h: minH,
        minH
      };
    });
  } else {
    // 如果保存过布局数据
    // 判断配置数据和布局数据的sName是否一致
    const arrAdd = configs.map(item => item.sName); // 新增的字段
    const arrDel = []; // 删除的字段
    const panelArr = 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)) {
      // 数据没有变化
      layout = 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) * 6,
          y: flag + newY,
          w: 6,
          h: minH,
          minH
        });
      });
    }
    layout = panelArr;
  }

  return { layout, configs, paramData, record, recordDefault };
}

// 获取表格布局参数
export function getTableParams(sParamType, selectedData = {}, xlyTableRef) {
  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
    }
  ];

  if (xlyTableRef.current) {
    gdsconfigformslave[gdsconfigformslave.length - 1].iFitWidth =
      xlyTableRef.current.getBoundingClientRect().width - 238;
  }

  const config = {
    sId: commonUtils.createSid(),
    bisMutiSelect: false,
    bMutiSelect: false,
    gdsconfigformslave
  };

  const column = commonFunc.getHeaderConfig(config);
  const data = [];

  const params = commonUtils.isNotEmptyObject(selectedData)
    ? selectedData[`${sParamType}Param`]
    : "";

  const sParamJsonObj = commonUtils.convertStrToObj(params);
  console.log("=====sParamJsonObj", sParamJsonObj);
  Object.keys(sParamJsonObj).forEach(key => {
    const keyInArr = ["sParam"];
    const keyOutArr = [
      "DropDown",
      "Default",
      "NotEmpty",
      "ReadOnly",
      "AssFieldName",
      "FieldName",
      "NotZero",
      "DropDownType",
      "SqlCondition",
      "KeyUpFilter"
    ];
    // key包含所有keyInArr 且 不包含keyOutArr
    if (
      !keyInArr.some(keyIn => !key.includes(keyIn)) &&
      !keyOutArr.some(keyOut => key.includes(keyOut))
    ) {
      const obj = {
        sId: commonUtils.createSid(),
        sParamKey: key,
        sParamName: sParamJsonObj[key]
      };
      /* 找到数字 找到下拉数据源 */
      const num = key.replace(/[^\d]/g, "").trim();
      const number = Number(num);
      if (number) {
        const sParamDropDownKey = `sParamDropDown${number}`;
        obj.sDropDownData = sParamJsonObj[sParamDropDownKey]; /* 下拉 */
        const sParamDefaultKey = `sParamDefault${number}`;
        obj.sParamValue = sParamJsonObj[sParamDefaultKey]; /* 默认值 */
        // 如果保存过值了，取保存后的值
        // 获取params数据
        const recordDataAll = commonUtils.convertStrToObj(
          selectedData.sParams,
          []
        );
        const recordItem =
          recordDataAll.find(item => item.sParamType === sParamType) || {};
        const record = recordItem.data || {};
        if (record[key] !== undefined) {
          obj.sParamValue = record[key];
        }
      }
      data.push(obj);
    }
  });

  return {
    [`${sParamType}Config`]: config,
    [`${sParamType}Column`]: column,
    [`${sParamType}Data`]: data
  };
}
