import { ref, reactive, computed, toRefs, nextTick, inject } from "vue";
import { Table } from "@/hooks/interface";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import { ALLOW_EDIT_STATE, sys_arry_formulatype } from "@/config/index";
import { CommonDynamicSelect } from "@/api/modules/common";
import { useUserStore } from "@/stores/modules/user";
import MtrldefSelect from "@/views/system/selector/mtrldef/select.vue";
import { handleRowAccordingToProp } from "@/utils";
import { ElButton, ElMessage, ElPopconfirm } from "element-plus";
import { Minus, Plus, InfoFilled } from "@element-plus/icons-vue";
import { DwnameEnum } from "@/enums/dwnameEnum";
import { isArray } from "@/utils/is";
import { calculateFormula } from "@/utils/index";
import { cloneDeep, defaultsDeep } from "lodash-es";
import { TYPE, useToast, POSITION } from "vue-toastification";
import ToastFormula from "@/components/ToastWidget/Formula/index.vue";
import ToastHistoryPrice from "@/components/ToastWidget/HistoryPrice/index.vue";

interface defaultState {
  /**
   * @description 单据当前状态
   */
  orderStatus: string;
  LjDetailRef: any;
  MtrldefDialogRef: any;
  MtrldefDialogProps: any;
  initParams: any;
}
/**
 * @description 表格多选数据操作
 * @param {String} rowKey 当表格可以多选时，所指定的 id
 * */
export const useHooks = (t?: any) => {
  const state = reactive<defaultState>({
    orderStatus: "",
    LjDetailRef: null,
    MtrldefDialogRef: null,
    MtrldefDialogProps: null,
    initParams: { billid: 0 }
  });

  state.orderStatus = inject("orderStatus", "");

  const getData_mx = (params: any) => {
    console.log("getData params :>> ", params);
    let newParams: any = {};
    params.pageNum && (newParams.pageindex = params.pageNum);
    params.pageSize && (newParams.pagesize = params.pageSize);
    delete params.pageNum;
    delete params.pageSize;
    newParams.queryParams = params;
    console.log("params :>> ", params);
    newParams.dsname = "web_mattress_mx";
    return CommonDynamicSelect(newParams, DwnameEnum.mattressQuoteMx);
    // return [];
  };

  const dataCallback = (data: any) => {
    console.log("dataCallback data :>> ", data);
    return {
      list: data.datatable,
      tableinfo: data.tableinfo,
      total: data.totalcnt,
      pageNum: data.pageindex,
      pageSize: data.pagesize
    };
  };

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

      let _params = {
        keyword: "",
        arg_mtrltype: params.mtrltype,
        arg_pricelistid: params.pricelistid
      };
      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, label);
    });
  };

  /**
   * @description 数据赋值：物料信息
   * @param data 当前数据
   * @param item 当前选择的数据
   */
  const rModelSetMtrl = (data: any, item: any) => {
    console.log("rModelSetMtrl data :>> ", data);
    console.log("rModelSetMtrl item :>> ", item);
    if (item) {
      data.mattressid = state.LjDetailRef._mainData.mattressid;
      data.mattressmxid = 0;
      data.mtrlid = item.mtrlid;
      data.price = item.pricelistprice;
      data.gram_weight = item.gram_weight;
      data.cloth_width = item.cloth_width;
      data.if_inputqty = Number(item.if_inputqty);
      data.if_areaprice = item.if_areaprice;
      data.mtrlname = item.mtrlname;
      data.priceunit = item.priceunit;
      data.shrinkage = item.price;
      Number(item.thickness) > 0 && (data.thickness = item.thickness);
      data.price_formula = item.price_formula;
    }
  };

  const rModelClearMtrl = (data: any) => {
    console.log("rModelClearMtrl data :>> ", data);
    data.mattressid = state.LjDetailRef._mainData.mattressid;
    data.mattressmxid = 0;
    data.mtrlid = 0;
    data.price = 0;
    data.gram_weight = 0;
    data.cloth_width = 0;
    data.if_inputqty = 0;
    data.if_areaprice = 0;
    data.mtrlname = "";
    data.priceunit = "";
    data.shrinkage = 0;
    data.thickness = 0;
    data.price_formula = "";
    data.qty = "";
  };

  /**
   * @description 面料-裥大、小侧，增加物料
   */
  const funcAddMxSide = async (params: any, data: any, targetRef?: any) => {
    // arg_array_formulakind
    let newParams: any = {};
    newParams.queryParams = params;
    newParams.dsname = "web_mattress_formulalist";
    let res = await CommonDynamicSelect(newParams);
    console.log("funcAddBigSide res :>> ", res);

    if (res.datatable) {
      if (targetRef) {
        const $table = targetRef.element;
        if ($table) {
          res.datatable.map(itm => {
            let records: any = {
              formulatype: itm.formulatype,
              if_mtrl: Number(itm.if_mtrl),
              formulaid: itm.formulaid,
              sortcode: data.label,
              chastr: data.label,
              formulakind: Number(itm.formulakind),
              formula: itm.formula,
              useformula: itm.useformula,
              gydscrp: itm.gydscrp
            };

            if (records.if_mtrl > 1) {
              records.addmx = "+";
              records.delmx = "-";
            }

            $table.insertAt(records, -1);
          });
        }
      } else {
        let arr = [];
        res.datatable.map(itm => {
          let records: any = {
            formulatype: itm.formulatype,
            if_mtrl: Number(itm.if_mtrl),
            formulaid: itm.formulaid,
            sortcode: data.label,
            chastr: data.label,
            formulakind: Number(itm.formulakind),
            formula: itm.formula,
            useformula: itm.useformula,
            gydscrp: itm.gydscrp
          };

          if (records.if_mtrl > 1) {
            records.addmx = "+";
            records.delmx = "-";
          }

          arr.push(records);
        });
        return arr;
      }
    } else {
      return [];
    }
  };

  /**
   * @description 明细，新增
   */
  const funcAddMtrlMx = async (data: any) => {
    console.log("state.LjDetail. :>> ", state.LjDetailRef);
    console.log("funcAddMtrlMx data :>> ", data);
    let { tabsActive } = state.LjDetailRef;
    let { row, rowIndex, visibleData } = data;
    let nextRow = visibleData[rowIndex + 1];
    if (!nextRow) {
      nextRow = visibleData[visibleData.length - 1];
    }

    let _target = tabsActive == "fabricMx" ? state.fabricMxTabs : tabsActive;

    let currentTab = state.fabricMxTabList.find(t => t.name == _target);
    const $table = state[currentTab.ref].element;
    if ($table) {
      const records = {
        addmx: "+",
        delmx: "-",
        formulatype: row.formulatype,
        if_mtrl: row.if_mtrl,
        formulaid: row.formulaid,
        sortcode: row.sortcode,
        formulakind: row.formulakind,
        formula: row.formula,
        thickness: 0,
        mtrlid: 0
      };

      const { row: newRow } = await $table.insertAt(records, nextRow);
      await $table.setEditCell(newRow, "mtrlname");
      await $table.setCurrentRow(newRow);
    }
  };

  /**
   * @description 明细，删除
   */
  const funcDelMtrlMx = (data: any) => {
    let { row } = data;
    let { tabsActive } = state.LjDetailRef;

    // let _target = tabsActive == "fabricMx" ? state.fabricMxTabs : tabsActive;

    // let currentTab = state.fabricMxTabList.find(t => t.name == _target);
    // const $table = state[currentTab.ref].element;
    // if ($table) {
    //   $table.remove(row);
    // }
  };

  // 表格配置项
  const columns: ColumnProps<any>[] = [
    { type: "checkbox", width: 50, fixed: "left" },
    { title: "#", field: "pid", fixed: "left", width: 80 },
    {
      field: "billcode",
      title: "报价唯一码",
      align: "left",
      table: "u_semi_finished_product",
      search: {
        el: "input",
        props: {
          placeholder: "唯一码/编码/名称"
        },
        order: 0
      },
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "semi_finished_code",
      title: "半成品编码",
      align: "left",
      table: "u_semi_finished_product",
      search: {
        el: "input",
        props: {
          placeholder: "唯一码/编码/名称"
        },
        order: 0
      },
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "semi_finished_name",
      title: "半成品名称",
      align: "left",
      table: "u_semi_finished_product",
      search: {
        el: "input",
        props: {
          placeholder: "唯一码/编码/名称"
        },
        order: 0
      },
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "flag",
      title: "审核"
    },
    {
      field: "opemp",
      title: "登记人"
    },
    {
      field: "opdate",
      title: "登记时间"
    },
    {
      field: "auditemp",
      title: "审核人"
    },
    {
      field: "auditdate",
      title: "审核时间"
    }
  ];

  const columnsMx: ColumnProps<any>[] = [
    { title: "#", type: "seq", fixed: "left", width: 80 },
    {
      title: "计算成功?",
      field: "if_success",
      datatype: "checkbox",
      limited: () => {
        const { userInfo } = useUserStore();
        return userInfo.usermode != 0;
      }
    },
    {
      title: "+",
      field: "addmx",
      width: 80,
      render: (scope: any) => {
        let _if_mtrl = Number(scope.row.if_mtrl);
        if (_if_mtrl > 1) {
          if (state.orderStatus) {
            return (
              <>
                <ElPopconfirm
                  width="220"
                  icon={InfoFilled}
                  title={t("business.tips.mattress.addMx")}
                  confirm-button-text={t("common.addText")}
                  onConfirm={() => funcAddMtrlMx(scope)}
                >
                  {{
                    reference: () => {
                      return <ElButton type="primary" plain circle icon={Plus}></ElButton>;
                    }
                  }}
                </ElPopconfirm>
              </>
            );
            // return <ElButton type="primary" plain circle icon={Plus} onClick={() => funcAddMtrlMx(scope)}></ElButton>;
          } else {
            return <>+</>;
          }
        } else {
          return <></>;
        }
      }
    },
    {
      title: "-",
      field: "delmx",
      width: 80,
      render: (scope: any) => {
        let _if_mtrl = Number(scope.row.if_mtrl);
        if (_if_mtrl > 1) {
          if (state.orderStatus) {
            return (
              <>
                <ElPopconfirm
                  width="220"
                  icon={InfoFilled}
                  title={t("business.tips.mattress.delMx")}
                  confirm-button-text={t("common.delText")}
                  confirm-button-type="danger"
                  onConfirm={() => funcDelMtrlMx(scope)}
                >
                  {{
                    reference: () => {
                      return <ElButton type="danger" plain circle icon={Minus} />;
                    }
                  }}
                </ElPopconfirm>
              </>
            );
            // return <ElButton type="danger" plain circle icon={Minus} onClick={() => funcDelMtrlMx(scope)}></ElButton>;
          } else {
            return <>-</>;
          }
        } else {
          return <></>;
        }
      }
    },
    {
      title: "位置",
      field: "chastr"
    },
    {
      title: "公式名",
      field: "formulakind",
      table: "u_mattress_formula",
      align: "left",
      isFilterEnum: true,
      fieldNames: { value: "value", label: "label" },
      // enum: async () => {
      //   let res = await CommonDynamicSelect({
      //     dsname: "_Mapper_formulakind",
      //     queryparams: {}
      //   });
      //   return { data: res.datatable };
      // }
      render: (scope: any) => {
        const { column, row, status } = scope;
        let itmName = state.formulaKindEnum.find(t => t.value == row.formulakind)?.label ?? "";
        return <>{itmName}</>;
      }
    },
    {
      title: "按物料？",
      field: "if_mtrl",
      table: "u_mattress_formula",
      enum: [
        {
          value: "0",
          label: "无物料"
        },
        {
          value: "1",
          label: "单物料"
        },
        {
          value: "2",
          label: "多物料"
        }
      ]
    },
    {
      title: "厚度cm",
      field: "thickness",
      datatype: "number",
      editRender: {
        name: "$input"
      }
    },
    {
      title: "物料",
      field: "mtrlname",
      editRender: {},
      editColRender: (scope: any) => {
        console.log("mtrlname hooks render scope :>> ", scope);
        console.log("mtrlname hooks render LjDetailRef.value._mainData :>> ", state.LjDetailRef);
        const { column, row, status } = scope;
        let field = column.field;
        let _label = column.title;
        // if (column?.format) {
        //   _label = handleRowAccordingToProp(searchParam, field, column?.format);
        // }
        let _deptid = state.LjDetailRef._mainData.deptid;
        let deptEnum = state.LjDetailRef.enumMap.get("deptid");
        let _pricelistid = 0;
        console.log("deptEnum :>> ", deptEnum);
        if (deptEnum) {
          let depItem = deptEnum.find((item: any) => item.value == _deptid);
          console.log("depItem :>> ", depItem);
          if (depItem) {
            _pricelistid = Number(depItem.pricelistid);
          }
        }
        console.log("_pricelistid :>> ", _pricelistid, row.formulakind);

        console.log("state.mtrltypeTabList :>> ", state.mtrltypeTabList);

        let _mtrltypeItem = state.mtrltypeTabList.find(t => t.formulakinds.includes(Number(row.formulakind)));
        !_mtrltypeItem && (_mtrltypeItem = { value: -1 });

        let params = {
          mtrltype: _mtrltypeItem.value,
          pricelistid: _pricelistid
        };

        return (
          <>
            <MtrldefSelect
              value={row.mtrlid}
              {...params}
              clearable
              placeholder={_label}
              onOpenModal={() => fModelChoseMtrl(row, params, _mtrltypeItem.label)}
              onSelect={(val: any) => rModelSetMtrl(row, val)}
              onClear={() => rModelClearMtrl(row)}
            />
          </>
        );
      }
    },
    {
      title: "数量/长度",
      field: "qty",
      datatype: "number",
      editRender: {
        name: "input"
      }
    },
    {
      title: "物料单价",
      field: "price",
      datatype: "number",
      limited: () => {
        const { userInfo } = useUserStore();
        return userInfo.usermode != 0;
      }
    },
    {
      title: "单位",
      field: "priceunit"
    },
    {
      title: "收缩率",
      field: "shrinkage",
      datatype: "number",
      limited: () => {
        const { userInfo } = useUserStore();
        return userInfo.usermode != 0;
      }
    },
    {
      title: "克重",
      field: "gram_weight",
      datatype: "number",
      limited: () => {
        const { userInfo } = useUserStore();
        return userInfo.usermode != 0;
      }
    },
    {
      title: "幅宽",
      field: "cloth_width",
      datatype: "number",
      limited: () => {
        const { userInfo } = useUserStore();
        return userInfo.usermode != 0;
      }
    },
    {
      title: "固定厚度?",
      field: "if_inputqty",
      datatype: "checkbox",
      limited: () => {
        const { userInfo } = useUserStore();
        return userInfo.usermode != 0;
      }
    },
    {
      title: "按面积单价？",
      field: "if_areaprice",
      datatype: "checkbox",
      limited: () => {
        const { userInfo } = useUserStore();
        return userInfo.usermode != 0;
      }
    },
    {
      title: "成本金额",
      field: "costamt",
      datatype: "number",
      limited: () => {
        const { userInfo } = useUserStore();
        return userInfo.usermode != 0;
      }
    },
    {
      title: "金额文本公式",
      field: "formula",
      limited: () => {
        const { userInfo } = useUserStore();
        return userInfo.usermode != 0;
      }
    },
    {
      title: "金额数字公式",
      field: "replace_formula",
      limited: () => {
        const { userInfo } = useUserStore();
        return userInfo.usermode != 0;
      }
    },
    {
      title: "清单用量",
      field: "useqty",
      datatype: "number",
      limited: () => {
        const { userInfo } = useUserStore();
        return userInfo.usermode != 0;
      }
    },
    {
      title: "用量文本公式",
      field: "useformula",
      limited: () => {
        const { userInfo } = useUserStore();
        return userInfo.usermode != 0;
      }
    },
    {
      title: "用量数字公式",
      field: "replace_useformula",
      limited: () => {
        const { userInfo } = useUserStore();
        return userInfo.usermode != 0;
      }
    },
    {
      title: "工艺填写说明",
      field: "gydscrp"
    }
  ];

  return {
    ...toRefs(state),
    columns,
    columnsMx
  };
};
