import { ref, reactive, computed, toRefs } from "vue";
import { Table } from "@/hooks/interface";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import { ALLOW_EDIT_STATE } from "@/config/index";
import { SaveMtrlDef, DeleteMtrlDef, BanMtrlDef, getMtrlType } from "@/api/modules/basicinfo";
import { getPriceList } from "@/api/modules/saleprice";
import { ElMessage, ElMessageBox } from "element-plus";
import { transformTreeData } from "@/utils/index";
interface defaultState {
  /**
   * @description 单据当前状态
   */
  orderStatus: string;
  /**
   * @description 列表Ref
   */
  VxeTableRef: any;
  /**
   * @description 详情页Ref
   */
  LjDetailRef: any;
  /**
   * @description 详情页明细表格Ref
   */
  VxeTableMxRef: any;
  copyFormVisible: boolean;
  copyFormOption: any[];
  copyFormCol: any;
  copyFormValue: any;
  priceListEnum: any[];
  priceListFormVisiable: boolean;
  priceListFormParams: any;
  priceListVisiable: boolean;
}

const state = reactive<defaultState>({
  orderStatus: "",
  VxeTableRef: null,
  LjDetailRef: null,
  VxeTableMxRef: null,
  copyFormVisible: false,
  copyFormOption: [
    {
      field: "price",
      title: "单价单位",
      datatype: "number",
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "priceunit",
      title: "单位",
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "shrinkage",
      title: "收缩率",
      datatype: "number",
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "thickness",
      title: "厚度",
      datatype: "number",
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "gram_weight",
      title: "克重",
      datatype: "number",
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    }
  ],
  copyFormCol: {},
  copyFormValue: "",
  priceListEnum: [],
  priceListFormVisiable: false,
  priceListFormParams: {
    pricelistid_from: 0 as number,
    pricelistid_to: 0 as number,
    rate: 1 as number
  },
  priceListVisiable: false
});
/**
 * @description 表格多选数据操作
 * @param {String} rowKey 当表格可以多选时，所指定的 id
 * */
export const useHooks = (t?: any) => {
  // 表格配置项
  const columns: ColumnProps<any>[] = [
    { type: "checkbox", width: 80, fixed: "left" },
    {
      field: "fjcnt",
      title: "附件",
      width: 80,
      basicinfo: {
        visible: false
      }
    },
    {
      field: "name",
      title: "物料名称",
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "price",
      title: "单价单位",
      datatype: "number",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "priceunit",
      title: "单位",
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "shrinkage",
      title: "收缩率",
      datatype: "number",
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "thickness",
      title: "厚度",
      datatype: "number",
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "gram_weight",
      title: "克重",
      datatype: "number",
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "if_inputqty",
      title: "固定厚度",
      datatype: "checkbox",
      basicinfo: {
        span: 1,
        editable: ALLOW_EDIT_STATE,
        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: "if_subspecs",
      title: "主副规格调整",
      datatype: "checkbox",
      basicinfo: {
        span: 1,
        editable: ALLOW_EDIT_STATE,
        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: "if_areaprice",
      title: "单价按面积",
      datatype: "checkbox",
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "createby",
      title: "登记人",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "createtime",
      title: "登记时间",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "erp_mtrlcode",
      title: "L1物料编码",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "erp_mtrlname",
      title: "L1物料名称",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "erp_mtrlmode",
      title: "L1物料规格",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "erp_unit",
      title: "L1物料单位",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "erp_mtrlengname",
      title: "L1英文名称",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "isuse",
      title: "有效",
      visible: false,
      basicinfo: {
        editable: ALLOW_EDIT_STATE,
        span: 2,
        render: (scope: any) => {
          const { column, searchParam } = scope;

          return (
            <>
              <div class="flx-align-center">
                <el-checkbox v-model={searchParam[column.field]} true-label={1} false-value={0} />
              </div>
            </>
          );
        }
      }
    },
    {
      field: "lastdate",
      title: "有效时间",
      visible: false,
      basicinfo: {
        el: "date-picker",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "handtype",
      title: "默认类别",
      visible: false,
      basicinfo: {
        el: "tree-select",
        span: 2,
        editable: ALLOW_EDIT_STATE
      },
      enum: async () => {
        const data = await getMtrlType();
        return transformTreeData(data.reList);
      },
      fieldNames: {
        label: "mtrltype",
        value: "mtrltypeid",
        children: "children"
      }
    },
    {
      field: "pricelistid",
      title: "价格表",
      visible: false,
      // limited: true,
      enum: async () => {
        const data = (await getPriceList()).list;
        state.priceListEnum = data;
        return { data };
      },
      basicinfo: {
        visible: false
      },
      search: {
        el: "select",
        key: "pricelistid",
        props: {
          clearable: false,
          filterable: false,
          defaultFirstOption: true,
          remote: true
        },
        defaultValue: 12
      },
      fieldNames: {
        label: "pricelistname",
        value: "pricelistid"
      }
    },
    {
      field: "dscrp",
      title: "备注",
      basicinfo: {
        el: "input",
        span: 4,
        editable: ALLOW_EDIT_STATE,
        props: { type: "textarea", rows: 5 },
        row: 3
      }
    }
  ];

  const columns_mx: ColumnProps<any>[] = [
    {
      field: "pricetype",
      title: "单价方式",
      filters: [
        { label: "直接单价", value: "0" },
        { label: "公式单价", value: "1" }
      ],
      editRender: {
        name: "VxeSelect",
        options: [
          { label: "直接单价", value: "0" },
          { label: "公式单价", value: "1" }
        ]
      }
    },
    {
      field: "price",
      title: "单价",
      editRender: {
        name: "$input",
        props: {}
      }
    },
    {
      field: "price_formula",
      title: "单价公式",
      editRender: {
        name: "$input",
        props: {}
      }
    },
    {
      field: "qty_formula",
      title: "用量公式",
      editRender: {
        name: "$input",
        props: {}
      }
    }
  ];

  // 保存
  const fSave = (param: any) => {
    return new Promise((resolve, reject) => {
      ElMessageBox.confirm("是否确定要保存吗?", "询问", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          SaveMtrlDef(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 { mtrlid: parseInt(item.mtrlid), name: item.name };
    });
    ElMessageBox.confirm("是否确定要删除吗?", "询问", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        DeleteMtrlDef({ list: delArr }).then(() => {
          ElMessage.success("删除成功！");
          state.VxeTableRef?.refresh();
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };

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

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