import { ref, reactive, computed, toRefs, nextTick } from "vue";
import { Table } from "@/hooks/interface";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import { ALLOW_EDIT_STATE } from "@/config/index";
import MtrldefSelect from "@/views/system/selector/mtrldefNoPrice/select.vue";
import { SaveMattressFormula, DeleteMattressFormula } from "@/api/modules/basicinfo";
import { ElMessage, ElMessageBox } from "element-plus";
import { useHooks as useHooks_mtrltype } from "@/views/baseinfo/mtrltype/hooks/index";
const { gMtrltypeList } = useHooks_mtrltype();

interface defaultState {
  /**
   * @description 单据当前状态
   */
  orderStatus: string;
  /**
   * @description 列表Ref
   */
  VxeTableRef: any;
  /**
   * @description 详情页Ref
   */
  LjDetailRef: any;
  MtrldefDialogRef: any;
  MtrldefDialogProps: any;
}

const state = reactive<defaultState>({
  orderStatus: "",
  VxeTableRef: null,
  LjDetailRef: null,
  MtrldefDialogRef: null,
  MtrldefDialogProps: {}
});
/**
 * @description 表格多选数据操作
 * @param {String} rowKey 当表格可以多选时，所指定的 id
 * */
export const useHooks = (t?: any) => {
  // 表格配置项
  const columns: ColumnProps<any>[] = [
    { type: "checkbox", width: 80, fixed: "left" },
    {
      field: "formulatype",
      title: "类别",
      basicinfo: {
        el: "select",
        order: 1,
        span: 3,
        editable: ALLOW_EDIT_STATE,
        rules: [{ required: true }]
      }
    },
    {
      field: "sortcode",
      title: "类别序号",
      basicinfo: {
        el: "input",
        order: 2,
        span: 3,
        editable: ALLOW_EDIT_STATE,
        rules: [{ required: true }]
      }
    },
    {
      field: "formulakind",
      title: "公式名",
      cellType: "number",
      basicinfo: {
        el: "select",
        order: 5,
        span: 3,
        editable: ALLOW_EDIT_STATE,
        rules: [{ required: true }]
      }
    },
    {
      field: "if_mtrl",
      title: "按物料",
      basicinfo: {
        el: "select",
        order: 7,
        span: 3,
        editable: ALLOW_EDIT_STATE,
        rules: [{ required: true }]
      }
    },
    {
      field: "usetype",
      title: "公式应用分类",
      basicinfo: {
        el: "select",
        order: 6,
        span: 3,
        editable: ALLOW_EDIT_STATE,
        rules: [{ required: true }]
      }
    },
    {
      field: "formula",
      title: "金额公式",
      basicinfo: {
        el: "input",
        order: 12,
        span: 6,
        editable: ALLOW_EDIT_STATE,
        props: { type: "textarea", rows: 3 }
      }
    },
    {
      field: "useformula",
      title: "用量公式",
      basicinfo: {
        el: "input",
        order: 13,
        span: 6,
        editable: ALLOW_EDIT_STATE,
        props: { type: "textarea", rows: 3 }
      }
    },
    {
      field: "if_packtype0",
      title: "压包",
      basicinfo: {
        editable: ALLOW_EDIT_STATE,
        order: 8,
        span: 1,
        render: (scope: any) => {
          const { column, searchParam } = scope;

          return (
            <>
              <el-checkbox v-model={searchParam[column.field]} true-label="1" false-label="0" class="mr-8" />
            </>
          );
        }
      }
    },
    {
      field: "if_packtype1",
      title: "卷包",
      basicinfo: {
        editable: ALLOW_EDIT_STATE,
        order: 9,
        span: 1,
        render: (scope: any) => {
          const { column, searchParam } = scope;

          return (
            <>
              <el-checkbox v-model={searchParam[column.field]} true-label="1" false-label="0" class="mr-8" />
            </>
          );
        }
      }
    },
    {
      field: "if_packtype2",
      title: "国内",
      basicinfo: {
        editable: ALLOW_EDIT_STATE,
        order: 10,
        span: 1,
        render: (scope: any) => {
          const { column, searchParam } = scope;

          return (
            <>
              <el-checkbox v-model={searchParam[column.field]} true-label="1" false-label="0" class="mr-8" />
            </>
          );
        }
      }
    },
    {
      field: "default_mtrlid",
      title: "默认物料",
      basicinfo: {
        el: "select",
        order: 4,
        span: 3,
        editable: ALLOW_EDIT_STATE,
        render: (scope: any) => {
          const { column, searchParam: row, status } = scope;
          let field = column.basicinfo?.key ?? column.field;
          let _label = row[field];

          const mtrltype = row["mtrltype"];
          let params = {
            mtrltype
          };
          return (
            <>
              <MtrldefSelect
                value={row.default_mtrlname}
                {...params}
                placeholder={_label}
                onOpenModal={() => fModelChoseMtrl(row, params, mtrltype)}
                onSelect={(val: any) => rModelSetMtrl(row, val)}
              />
            </>
          );
        }
      }
    },
    {
      field: "mtrltype",
      title: "物料类别",
      basicinfo: {
        el: "tree-select",
        order: 3,
        span: 3,
        editable: ALLOW_EDIT_STATE
      },
      enum: gMtrltypeList,
      fieldNames: {
        label: "mtrltype",
        value: "mtrltypeid",
        children: "children"
      }
    },
    // {
    //   field: "createby",
    //   title: "登记人",
    //   editHidden: true
    // },
    // {
    //   field: "createtime",
    //   title: "登记时间",
    //   editHidden: true
    // },
    {
      field: "gydscrp",
      title: "工艺说明",
      basicinfo: {
        el: "input",
        order: 11,
        span: 6,
        editable: ALLOW_EDIT_STATE,
        props: { type: "textarea", rows: 3 }
      }
    }
  ];

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

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

  /**
   * @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) => {
    data.default_mtrlid = Number(item.mtrlid);
    data.default_mtrlname = item.mtrlname;
  };

  return {
    ...toRefs(state),
    columns,
    fSave,
    fDelete
  };
};
