import moment from "moment";

let modules = {};
modules = {
  data() {
    return {
      timerMap: {},
    };
  },
  beforeDestroy() {
    for (let timer in this.timerMap) {
      this.clearInterval(timer);
    }
  },
  methods: {
    getMoment(date) {
      return moment(date);
    },
    getMomentUtil() {
      return moment;
    },
    utcToCst(utcStr) {
      if (!utcStr) return utcStr;
      return moment.utc(utcStr).local().format("YYYY-MM-DD HH:mm:ss");
    },
    cstToUtc(localTime) {
      if (!localTime) return localTime;
      return moment(localTime).utc().format("YYYY-MM-DD HH:mm:ss");
    },
    addFormatDateTime(date, num, type, format) {
      if (!date) return date;
      if (!type) type = "days";
      if (!format) format = "YYYY-MM-DD HH:mm:ss";
      return moment(date).add(num, type).format(format);
    },
    addFormatDate(date, num) {
      if (!date) return date;
      return moment(date).add(num, "days").format("YYYY-MM-DD");
    },
    formatDate(date) {
      if (!date) return date;
      return moment(date).format("YYYY-MM-DD");
    },
    formatDateTime(date, format = "YYYY-MM-DD HH:mm:ss") {
      if (!date) return date;
      return moment(date).format(format);
    },
    getFormEntityData(reqFormData) {
      let formRef = this.getFormRef ? this.getFormRef() : this;
      let formConfig = formRef.formConfig;
      let entity = formConfig.entity;
      if (!reqFormData) reqFormData = this.getReqFormData();
      return reqFormData.data[entity];
    },
    getReqFormData() {
      let formRef = this.getFormRef ? this.getFormRef() : this;
      let formConfig = formRef.formConfig;
      let entity = formConfig.entity;
      if (!entity) return;
      let dataId = formRef?.dataId;
      let reportTemplate = formRef?.reportTemplate;
      let formCode = reportTemplate?.formCode;

      let formData = this.$baseLodash.cloneDeep(formRef.getRealFormData());
      let mainData = formData[formCode] || {};
      delete formData[formCode];
      formData[entity] = mainData;

      delete mainData._createNickName;
      delete mainData._createMobile;
      delete mainData._modifyNickName;
      delete mainData._modifyMobile;
      delete mainData._createBy;
      delete mainData._modifyBy;

      let reqData = {
        formCode: formCode,
        formVersion: reportTemplate.formVersion,
        taBm: entity,
        data: formData,
      };
      return reqData;
    },
    saveDefaultHandle(option) {
      let formRef = this.getFormRef ? this.getFormRef() : this;
      let formConfig = formRef.formConfig;
      let entity = formConfig.entity;
      if (!entity) return;
      let dataId = formRef?.dataId;
      let reportTemplate = formRef?.reportTemplate;
      let formCode = reportTemplate?.formCode;
      let scriptCode = formConfig.saveScriptCode || "saveUpdate";
      let config = option?.config;
      // formRef.clearValidate();
      // formRef.$forceUpdate();
      // let formDataModel = formRef.formDataModel;

      formRef.validate((valid) => {
        if (valid) {
          let reqData = this.getReqFormData();
          this.formHttp({
            // url: "/" + reportTemplate.serviceName + "/form_ins/saveUpdate",
            scriptCode: scriptCode,
            data: reqData,
            successMsg: true,
            isConfirm: true,
            confirmText: this.$t1("您确定要保存吗？"),
            success: (res) => {
              let editFormCode = formConfig.editFormCode;
              let updateParam = {
                dataId: res.objx,
              };
              if (editFormCode) {
                updateParam.formCode = editFormCode;
              }

              formRef.reloadForm({
                updateParam,
              });
            },
            ...config,
          });
        }
      });
    },
    setInterval(callback, millis) {
      let timer = setInterval(callback, millis);
      this.timerMap[timer] = timer;
    },
    clearInterval(timer) {
      clearInterval(timer);
      delete this.timerMap[timer];
    },
    getGlobalConfig() {
      let that = this.getFormRef ? this.getFormRef() : this;
      return that.globalConfig;
    },
    getFormParam() {
      let that = this.getFormRef ? this.getFormRef() : this;
      return that.param;
    },
    setGlobalParam(key, value) {
      let that = this.getFormRef ? this.getFormRef() : this;
      that.globalParam[key] = value;
    },
    getGlobalParam(key) {
      let that = this.getFormRef ? this.getFormRef() : this;
      return that.globalParam[key];
    },

    //1个数组的行号处理 begin
    /**
     * 删除列表中的行并刷新序列
     * @param {Array} list - 数据数组
     * @param {number} deleteIndex - 要删除的索引
     * @param {string} [seqField='seq'] - 序列字段名
     * @returns {Array} 更新后的数组
     */
    deleteNumRows(list, deleteIndex, seqField = "seq") {
      if (deleteIndex < 0 || deleteIndex >= list.length) {
        return [...list]; // 返回副本
      }

      // 创建副本避免修改原数组
      const newList = [...list];

      // 删除指定行
      newList.splice(deleteIndex, 1);

      // 重新计算序列
      newList.forEach((item, index) => {
        item[seqField] = index + 1;
      });

      return newList;
    },

    /**
     * 在列表中插入新行并刷新序列
     * @param {Array} list - 数据数组
     * @param {Array|Object} newItems - 要插入的新项（单个或多个）
     * @param {number} [insertIndex] - 插入位置（默认末尾）
     * @param {string} [seqField='seq'] - 序列字段名
     * @returns {Array} 更新后的数组
     */
    insertNumRows(list, newItems, insertIndex = list.length, seqField = "seq") {
      // 参数标准化
      const itemsArray = Array.isArray(newItems) ? newItems : [newItems];

      // 边界检查
      insertIndex = Math.max(0, Math.min(insertIndex, list.length));

      // 创建副本
      const newList = [...list];

      // 准备要插入的项（移除可能的旧序列）
      const itemsToInsert = itemsArray.map((item) => {
        const newItem = { ...item };
        if (newItem[seqField] !== undefined) {
          delete newItem[seqField];
        }
        return newItem;
      });

      // 插入新项
      newList.splice(insertIndex, 0, ...itemsToInsert);

      // 重新计算所有序列
      newList.forEach((item, index) => {
        item[seqField] = index + 1;
      });

      return newList;
    },
    //1个数组的行号处理 end

    //2个数组的行号处理 begin
    /**
     * 通用新增方法（支持单条/多条）
     * @param {Array} list1 - 主数据数组
     * @param {Array} list2 - 关联数据数组
     * @param {Array|Object} newItems - 要插入的新项（单个对象或多个对象的数组）
     * @param {Array|Array[]} subItems - 关联数据（单个数组或多个数组的数组）
     * @param {number} [insertIndex] - 插入位置（默认末尾）
     * @param {string} [seqField='seq'] - list1中的序列字段名
     * @param {string} [superSeqField='super_seq'] - list2中的关联字段名
     * @returns {Object} 包含更新后的list1和list2
     */
    insertRelRows(
      list1,
      list2,
      newItems,
      subItems = [],
      insertIndex,
      seqField = "seq",
      superSeqField = "super_seq"
    ) {
      // 参数标准化
      const itemsArray = Array.isArray(newItems) ? newItems : [newItems];
      const subItemsArray =
        Array.isArray(subItems) &&
        subItems.length > 0 &&
        Array.isArray(subItems[0])
          ? subItems
          : [subItems];

      if (insertIndex === null || insertIndex === undefined) {
        insertIndex = list1.length;
      }
      // 边界检查
      insertIndex = Math.max(0, Math.min(insertIndex, list1.length));

      // 创建副本
      const newList1 = [...list1];
      const newList2 = [...list2];

      // 1. 插入新项（不设置序列）
      const itemsToInsert = itemsArray.map((item) => {
        const newItem = { ...item };
        if (newItem[seqField] !== undefined) {
          delete newItem[seqField]; // 确保不保留旧序列
        }
        return newItem;
      });

      newList1.splice(insertIndex, 0, ...itemsToInsert);

      // 2. 重新计算序列并创建映射表
      const seqMapping = {};
      newList1.forEach((item, index) => {
        const newSeq = index + 1;
        const oldSeq = item[seqField];

        // 记录旧序列到新序列的映射
        if (oldSeq !== undefined) {
          seqMapping[oldSeq] = newSeq;
        }

        // 更新当前项序列
        item[seqField] = newSeq;
      });

      // 3. 获取新插入项的序列
      const newSeqs = [];
      for (let i = 0; i < itemsArray.length; i++) {
        newSeqs.push(insertIndex + i + 1);
      }

      // 4. 更新现有关联字段
      newList2.forEach((item) => {
        const currentSuperSeq = item[superSeqField];
        if (seqMapping[currentSuperSeq] !== undefined) {
          item[superSeqField] = seqMapping[currentSuperSeq];
        }
      });

      // 5. 添加新关联数据
      subItemsArray.forEach((subItems, idx) => {
        const superSeq = newSeqs[idx];
        if (Array.isArray(subItems) && subItems.length > 0) {
          subItems.forEach((item) => {
            const newItem = { ...item };
            newItem[superSeqField] = superSeq;
            newList2.push(newItem);
          });
        }
      });

      return { list1: newList1, list2: newList2 };
    },

    /**
     * 删除关联行（从属数据打平传参）
     * @param {Array} masters - 主数据数组
     * @param {Array} slaves - 从属数据数组（打平的一维数组）
     * @param {number} rowIdx - 要删除的主数据行索引
     * @param {string} [seqField='seq'] - 行号字段名
     * @param {string} [refField='super_seq'] - 关联字段名
     * @returns {Object} 包含更新后的masters和slaves
     */
    deleteRelRows(
      masters,
      slaves,
      rowIdx,
      seqField = "seq",
      refField = "super_seq"
    ) {
      // 边界检查
      if (rowIdx < 0 || rowIdx >= masters.length) {
        return { masters: [...masters], slaves: [...slaves] };
      }

      // 创建副本
      const newMasters = [...masters];
      const newSlaves = [...slaves];

      // 1. 删除主行并获取序列值
      const [deleted] = newMasters.splice(rowIdx, 1);
      const deletedSeq = deleted[seqField];

      // 2. 删除关联的从属行
      for (let i = newSlaves.length - 1; i >= 0; i--) {
        if (newSlaves[i][refField] === deletedSeq) {
          newSlaves.splice(i, 1);
        }
      }

      // 3. 重新计算主数据序列
      const seqMap = {};
      newMasters.forEach((master, idx) => {
        const oldSeq = master[seqField];
        const newSeq = idx + 1;
        seqMap[oldSeq] = newSeq;
        master[seqField] = newSeq;
      });

      // 4. 更新从属数据引用
      newSlaves.forEach((slave) => {
        const ref = slave[refField];
        if (seqMap[ref] !== undefined) {
          slave[refField] = seqMap[ref];
        }
      });

      return { list1: newMasters, list2: newSlaves };
    },
    //2个数组的行号处理 end
  },
};
export default modules;
