import { ref, reactive, computed, toRefs } from "vue";
import { isNullOrUnDef } from "@/utils/is";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import { ALLOW_EDIT_STATE } from "@/config/index";
import { SaveMtrlType, DeleteMtrlType, getMtrlType } from "@/api/modules/basicinfo";
import { GetERPMtrlTypeList } from "@/api/modules/common";
import { ElMessage, ElMessageBox } from "element-plus";
interface defaultState {
  /**
   * @description 单据当前状态
   */
  orderStatus: string;
  /**
   * @description 类别树Ref
   */
  LjTreeRef: any;
  /**
   * @description 详情页Ref
   */
  LjDetailRef: any;
}

const state = reactive<defaultState>({
  orderStatus: "",
  LjTreeRef: null,
  LjDetailRef: null
});
/**
 * @description 表格多选数据操作
 * @param {String} rowKey 当表格可以多选时，所指定的 id
 * */
export const useHooks = (t?: any) => {
  // 表格配置项
  const columns: ColumnProps<any>[] = [
    {
      field: "parentid",
      title: "上级类别",
      basicinfo: {
        el: "select",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "typecode",
      title: "类别编号",
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "mtrltype",
      title: "类别名称",
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "dannum1_rate",
      title: "损耗率：散单系数浮动数",
      basicinfo: {
        el: "input",
        props: {
          type: "number"
        },
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "dannum2_rate",
      title: "损耗率：标准系数浮动数",
      basicinfo: {
        el: "input",
        props: {
          type: "number"
        },
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "dannum3_rate",
      title: "损耗率：大单系数浮动数",
      basicinfo: {
        el: "input",
        props: {
          type: "number"
        },
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "dannum4_rate",
      title: "损耗率：小单系数浮动数",
      basicinfo: {
        el: "input",
        props: {
          type: "number"
        },
        span: 2,
        editable: ALLOW_EDIT_STATE
      }
    }
  ];

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

  // 删除
  const fDelete = (param: any) => {
    return new Promise((resolve, reject) => {
      if (isNullOrUnDef(param)) {
        ElMessage.error("请选择要删除的节点！");
        return;
      }
      ElMessageBox.confirm("是否确定要删除选择的节点吗?", "询问", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          DeleteMtrlType({ list: [param] }).then(() => {
            ElMessage.success("删除成功！");
            resolve({});
          });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    });
  };

  const gMtrltypeList = async () => {
    const data = await getMtrlType();

    let arr = data.reList;
    arr.unshift({
      value: -1,
      text: "全部",
      data: {
        mtrltypeid: -1,
        typecode: "",
        mtrltype: "全部",
        inuse: 1,
        parentid: 0,
        dannum1_rate: 0,
        dannum2_rate: 0,
        dannum3_rate: 0,
        dannum4_rate: 0
      }
    });
    return transformTreeData(data.reList);
  };

  const transformTreeData = (data: any) => {
    return data.map(node => ({
      ...node.data,
      children: node.children ? transformTreeData(node.children) : []
    }));
  };

  /**
   * 生成物料上级类别的枚举
   * @param list
   */
  const fnSelMtrlTypeEnum = (tree: any[]) => {
    const result = [{ value: 0, label: "" }];

    function traverse(node, parentLabel = "") {
      const label = parentLabel ? `${parentLabel} >> ${node.mtrltype}` : node.mtrltype;
      const item = { value: node.mtrltypeid, label: label };
      result.push(item);

      if (node.children && node.children.length > 0) {
        node.children.forEach(child => traverse(child, label));
      }
    }

    tree.forEach(node => traverse(node));
    return result;
  };

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