import { ref, reactive, nextTick, toRefs } from "vue";
import { Table } from "@/hooks/interface";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import { ALLOW_EDIT_STATE } from "@/config/index";
import {
  SaveConfigureType,
  SaveConfigureCode,
  SaveConfigureCodeMx,
  SaveConfigureBomList,
  DeleteConfigureType,
  DeleteConfigureCode,
  DeleteConfigureCodeMx,
  CopyConfigureCodeMxList,
  DeleteConfigureBomList
} from "@/api/modules/basicinfo";
import { ElMessage, ElMessageBox } from "element-plus";
import { useClipboardStore } from "@/stores/modules/copy";
import ErpMtrlPriceSelect from "@/views/system/selector/erpMtrlPrice/select.vue";
interface defaultState {
  /**
   * @description 单据当前状态
   */
  orderStatus: string;
  /**
   * @description 列表Ref
   */
  VxeTableLeftRef: any;
  /**
   * @description 列表Ref
   */
  VxeTableMidRef: any;
  /**
   * @description 列表Ref
   */
  VxeTableRightRef: any;
  /**
   * @description 列表Ref
   */
  VxeTableBottomRef: any;
  /**
   * @description 详情页Ref
   */
  LjDetailLeftRef: any;
  /**
   * @description 详情页Ref
   */
  LjDetailMidRef: any;
  /**
   * @description 详情页Ref
   */
  LjDetailRightRef: any;
  /**
   * @description 详情页Ref
   */
  LjDetailBottomRef: any;
  /**
   * @description 详情页明细表格Ref
   */
  VxeTableMxRef: any;
  MtrldefDialogRef: any;
  MtrldefDialogProps: any;
}

const state = reactive<defaultState>({
  orderStatus: "",
  VxeTableLeftRef: null,
  VxeTableMidRef: null,
  VxeTableRightRef: null,
  VxeTableBottomRef: null,
  LjDetailLeftRef: null,
  LjDetailMidRef: null,
  LjDetailRightRef: null,
  LjDetailBottomRef: null,
  VxeTableMxRef: null,
  MtrldefDialogRef: null,
  MtrldefDialogProps: {}
});
const ClipboardStore = useClipboardStore();
const COPY_KEY = "configure_codemx";
/**
 * @description 表格多选数据操作
 * @param {String} rowKey 当表格可以多选时，所指定的 id
 * */
export const useHooks = (t?: any) => {
  // 表格配置项
  const columns_left: ColumnProps<any>[] = [
    { type: "checkbox", width: 40, fixed: "left" },
    {
      field: "contfigtypename",
      title: "类型名称",
      basicinfo: {
        el: "input",
        span: 4,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "flag",
      title: "审核",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "auditemp",
      title: "审核人",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "auditdate",
      title: "审核时间",
      basicinfo: {
        visible: false
      }
    }
  ];
  const columns_mid: ColumnProps<any>[] = [
    { type: "checkbox", width: 40, fixed: "left" },
    {
      field: "pzcode",
      title: "配置项编号",
      width: 100,
      basicinfo: {
        el: "input",
        span: 4,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "name",
      title: "配置项名称",
      basicinfo: {
        el: "input",
        span: 4,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "inputtype",
      title: "录入类型",
      width: 100,
      basicinfo: {
        el: "select",
        span: 3,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "ifnum",
      title: "数值",
      basicinfo: {
        editable: ALLOW_EDIT_STATE,
        span: 1,
        render: (scope: any) => {
          const { column, searchParam } = scope;

          const _disabled = Number(searchParam.inputtype) === 0;

          return (
            <>
              <el-checkbox v-model={searchParam[column.field]} true-value={1} false-value={0} disabled={_disabled} />
            </>
          );
        }
      }
    },
    {
      field: "ifcross",
      title: "混搭",
      basicinfo: {
        editable: ALLOW_EDIT_STATE,
        span: 1,
        render: (scope: any) => {
          const { column, searchParam } = scope;

          const _disabled = Number(searchParam.inputtype) === 0;

          return (
            <>
              <el-checkbox v-model={searchParam[column.field]} true-value={1} false-value={0} disabled={_disabled} />
            </>
          );
        }
      }
    },
    {
      field: "ifcheck",
      title: "必填",
      basicinfo: {
        editable: ALLOW_EDIT_STATE,
        span: 1,
        render: (scope: any) => {
          const { column, searchParam } = scope;

          const _disabled = Number(searchParam.inputtype) === 0;

          return (
            <>
              <el-checkbox v-model={searchParam[column.field]} true-value={1} false-value={0} disabled={_disabled} />
            </>
          );
        }
      }
    },
    {
      field: "ifuse",
      title: "有效",
      basicinfo: {
        editable: ALLOW_EDIT_STATE,
        span: 1,
        render: (scope: any) => {
          const { column, searchParam } = scope;

          return (
            <>
              <div class="flx-align-center">
                <el-checkbox v-model={searchParam[column.field]} true-value={1} false-value={0} />
              </div>
            </>
          );
        }
      }
    },
    {
      field: "maxnum",
      title: "最大数",
      basicinfo: {
        el: "input",
        span: 4,
        editable: (scope: any) => {
          return Number(scope.searchParam.inputtype) > 0;
        }
      }
    },
    {
      field: "minnum",
      title: "最小数",
      basicinfo: {
        el: "input",
        span: 4,
        editable: (scope: any) => {
          return Number(scope.searchParam.inputtype) > 0;
        }
      }
    },
    {
      field: "pricestr",
      title: "差价公式",
      basicinfo: {
        el: "input",
        span: 4,
        editable: (scope: any) => {
          return Number(scope.searchParam.inputtype) > 0;
        }
      }
    },
    {
      field: "priceratestr",
      title: "差价比例公式",
      basicinfo: {
        el: "input",
        span: 4,
        editable: (scope: any) => {
          return Number(scope.searchParam.inputtype) > 0;
        }
      }
    }
  ];
  const columns_right: ColumnProps<any>[] = [
    { type: "checkbox", width: 40, fixed: "left" },
    {
      field: "pzcodemx",
      title: "明细编号",
      width: 100,
      basicinfo: {
        el: "input",
        span: 4,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "namemx",
      title: "明细名称",
      basicinfo: {
        el: "input",
        span: 4,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "ifuse",
      title: "有效",
      basicinfo: {
        editable: ALLOW_EDIT_STATE,
        span: 1,
        render: (scope: any) => {
          const { column, searchParam } = scope;

          return (
            <>
              <div class="flx-align-center">
                <el-checkbox v-model={searchParam[column.field]} true-value={1} false-value={0} />
              </div>
            </>
          );
        }
      }
    }
  ];

  const columns_bottom: ColumnProps<any>[] = [
    {
      field: "mtrlname",
      title: "物料名称",
      basicinfo: {
        el: "select",
        span: 3,
        row: 1,
        order: 1,
        editable: ALLOW_EDIT_STATE,
        render: (scope: any) => {
          const { column, searchParam: row, status } = scope;
          let params = {};
          return (
            <>
              <ErpMtrlPriceSelect
                value={row.mtrlid}
                {...params}
                clearable
                placeholder={row.mtrlname}
                onOpenModal={() => fModelChoseMtrl(row, params)}
                onSelect={(val: any) => rModelSetMtrl(row, val)}
                onClear={() => rModelClearMtrl(scope.searchParam)}
              >
                {{
                  label: () => row.mtrlname
                }}
              </ErpMtrlPriceSelect>
            </>
          );
        }
      }
    },
    {
      field: "unit",
      title: "单位",
      basicinfo: {
        span: 1,
        row: 1,
        order: 2
      }
    },
    {
      field: "default_length",
      title: "默认长",
      basicinfo: {
        el: "input",
        span: 2,
        row: 1,
        order: 5,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "default_width",
      title: "默认宽",
      basicinfo: {
        el: "input",
        span: 2,
        row: 1,
        order: 6,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "default_qty",
      title: "默认数量",
      basicinfo: {
        el: "input",
        span: 2,
        row: 1,
        order: 7,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "sonscale",
      title: "用料量",
      basicinfo: {
        el: "input",
        span: 2,
        row: 1,
        order: 8,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "mng_cost_rate",
      title: "管理费用率",
      basicinfo: {
        el: "input",
        span: 2,
        row: 1,
        order: 9,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "profit_rate",
      title: "利润率",
      basicinfo: {
        el: "input",
        span: 2,
        row: 1,
        order: 10,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "sonloss",
      title: "损耗率",
      basicinfo: {
        el: "input",
        span: 2,
        row: 1,
        order: 11,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "sondecloss",
      title: "损附加",
      basicinfo: {
        el: "input",
        span: 2,
        row: 1,
        order: 12,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "sonscale_formula",
      title: "用料量公式",
      basicinfo: {
        el: "input",
        span: 4,
        row: 1,
        order: 13,
        editable: ALLOW_EDIT_STATE,
        props: { type: "textarea", rows: 3 }
      }
    },
    {
      field: "sonloss_formula",
      title: "损耗率公式",
      basicinfo: {
        el: "input",
        span: 4,
        row: 1,
        order: 14,
        editable: ALLOW_EDIT_STATE,
        props: { type: "textarea", rows: 3 }
      }
    },
    {
      field: "sondecloss_formula",
      title: "损附加公式",
      basicinfo: {
        el: "input",
        span: 4,
        row: 1,
        order: 15,
        editable: ALLOW_EDIT_STATE,
        props: { type: "textarea", rows: 3 }
      }
    },
    {
      field: "cost",
      title: "成本价",
      basicinfo: {
        span: 1,
        row: 1,
        order: 16,
        visible: false
      }
    },
    {
      field: "cost_emp",
      title: "成本价统计人",
      basicinfo: {
        span: 1,
        row: 1,
        order: 17,
        visible: false
      }
    },
    {
      field: "cost_date",
      title: "成本价统计时间",
      basicinfo: {
        span: 1,
        row: 1,
        order: 18,
        visible: false
      }
    },
    {
      field: "realqty",
      title: "物料清单总用量",
      basicinfo: {
        span: 1,
        row: 1,
        order: 19,
        visible: false
      }
    },
    {
      field: "deptid_scll",
      title: "默认领用部门",
      basicinfo: {
        span: 1,
        row: 1,
        order: 20,
        visible: false
      }
    }
  ];

  const getSaveFun = (type: Number) => {
    switch (type) {
      case 0:
        return SaveConfigureType;
      case 1:
        return SaveConfigureCode;
      case 2:
        return SaveConfigureCodeMx;
      case 3:
        return SaveConfigureBomList;
    }
  };

  const getDelFun = (type: Number) => {
    switch (type) {
      case 0:
        return DeleteConfigureType;
      case 1:
        return DeleteConfigureCode;
      case 2:
        return DeleteConfigureCodeMx;
      case 3:
        return DeleteConfigureBomList;
    }
  };

  const getTableRef = (type: Number) => {
    switch (type) {
      case 0:
        return state.VxeTableLeftRef;
      case 1:
        return state.VxeTableMidRef;
      case 2:
        return state.VxeTableRightRef;
      case 3:
        return state.VxeTableBottomRef;
    }
  };

  // 保存
  const fSave = (type, param: any) => {
    return new Promise((resolve, reject) => {
      ElMessageBox.confirm("是否确定要保存吗?", "询问", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          getSaveFun(type)(param).then(() => {
            ElMessage.success("保存成功！");
            getTableRef(type)?.refresh();
            resolve({});
          });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    });
  };

  // 删除
  const fDelete = (type: Number) => {
    const checkDate = getTableRef(type)?.element.getCheckboxRecords();
    if (checkDate.length === 0) {
      ElMessage.error("请选择要删除的数据！");
      return;
    }
    const delArr = checkDate.map((item: any) => {
      if (type === 0) return { contfigtypeid: parseInt(item.contfigtypeid) };
      if (type === 1) return { typeid: parseInt(item.typeid), pzid: parseInt(item.pzid) };
      return { pzid: parseInt(item.pzid), printid: parseInt(item.printid) };
    });
    ElMessageBox.confirm("是否确定要删除吗?", "询问", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        getDelFun(type)({ list: delArr }).then(() => {
          ElMessage.success("删除成功！");
          getTableRef(type)?.refresh();
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };

  const fCopy = () => {
    const checkDate = getTableRef(2)?.element.getCheckboxRecords();
    if (checkDate.length === 0) {
      ElMessage.error("请勾选要复制的数据！");
      return;
    }
    ClipboardStore.copy(
      checkDate.map((item: any) => ({
        pzcodemx: item.pzcodemx,
        namemx: item.namemx
      })),
      { key: COPY_KEY }
    );
    ElMessage.success("复制成功！");
  };

  const fPaste = async (type: number) => {
    const checkDate = getTableRef(1)?.element.getCurrentRecord();
    const copyData = ClipboardStore.getLatest<Array<{ pzcodemx: string; namemx: string }>>(COPY_KEY);

    if (!copyData?.length) {
      ElMessage.error("没有可粘贴的内容,请先执行复制功能");
      return;
    }

    try {
      if (type === 1) {
        await handleOverwritePaste(checkDate, copyData, type);
      } else {
        await handleAppendPaste(checkDate, copyData, type);
      }

      ElMessage.success("粘贴成功！");
      getTableRef(2)?.refresh();
    } catch (error) {
      if (error !== "cancel") {
        console.error("粘贴操作出错:", error);
      }
    }
  };

  const handleOverwritePaste = async (subject: any, mxList: any[], type: number) => {
    try {
      await ElMessageBox.confirm("粘贴功能将清空原有的数据,是否继续?", "询问", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      });
      await CopyConfigureCodeMxList({ subject, mxList, type });
    } catch {
      ElMessage({ type: "info", message: "操作取消" });
      throw "cancel"; // 特殊标记取消操作
    }
  };

  const handleAppendPaste = async (subject: any, mxList: any[], type: number) => {
    const tableData = getTableRef(2)?.element.getTableData().fullData;
    const duplicateSet = new Set();
    const duplicates = tableData.filter(a => {
      const key = `${a.pzcodemx}|${a.namemx}`;
      const isDuplicate = mxList.some(b => b.pzcodemx === a.pzcodemx && b.namemx === a.namemx);

      if (isDuplicate && !duplicateSet.has(key)) {
        duplicateSet.add(key);
        return true;
      }
      return false;
    });

    if (duplicates.length > 0) {
      try {
        const duplicateList = duplicates.map(d => `${d.pzcodemx} ${d.namemx}`).join("、");
        await ElMessageBox.confirm(`当前部件选配项值已有(${duplicateList}),补充黏贴后会出现重复数据,是否继续?`, "询问", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning"
        });
        await CopyConfigureCodeMxList({ subject, mxList, type });
      } catch {
        ElMessage({ type: "info", message: "操作取消" });
        throw "cancel"; // 特殊标记取消操作
      }
    } else {
      await CopyConfigureCodeMxList({ subject, mxList, type });
    }
  };

  /**
   * @description 弹窗模块：客户选择
   * @param data 当前数据
   * @param status 当前订单状态
   * @returns Promise
   */
  const fModelChoseMtrl = (data: any, params: any) => {
    return new Promise((resolve, reject) => {
      // if (!ALLOW_EDIT_STATE.includes(status)) return;

      let _params = {
        keyword: ""
      };
      state.MtrldefDialogProps = {
        onSubmit: (res: any) => {
          // submit
          console.log("openCustDialog res", res);
          nextTick(() => {
            rModelSetMtrl(data, res.value[0]);
            resolve(1);
          });
        },
        onCancel: (error: any) => {
          // cancel 回调
          console.log("openCustDialog error", error);
        }
      };
      state.MtrldefDialogRef.show(_params);
    });
  };

  /**
   * @description 数据赋值: 联系人
   * @param data 当前数据
   * @param item 当前选择的数据
   */
  const rModelSetMtrl = (data: any, item: any) => {
    data.mtrlid = Number(item.mtrlid);
    data.mtrlname = item.mtrlname;
    data.mtrlcode = item.mtrlcode;
    data.mtrlmode = item.mtrlmode;
    data.unit = item.unit;
    data.price = item.price;
  };

  const rModelClearMtrl = (data: any) => {
    data.mtrlid = 0;
    data.mtrlname = "";
    data.mtrlcode = "";
    data.mtrlmode = "";
    data.unit = "";
    data.price = 0;
  };

  return {
    ...toRefs(state),
    columns_left,
    columns_mid,
    columns_right,
    columns_bottom,
    fSave,
    fDelete,
    fCopy,
    fPaste
  };
};
