<template>
  <el-tree-select
      ref="treeSelectRef"
      v-model="modelValue"
      :data="tree"
      :props="{
      value: type !== 'label' ? 'DICTIONARIES_ID' : 'BUS_LABEL_FACTORY_ID',
      children: type !== 'label' ? 'nodes' : 'children',
      label: 'NAME',
      isLeaf: 'isLeaf',
    }"
      :node-key="type !== 'label' ? 'DICTIONARIES_ID' : 'BUS_LABEL_FACTORY_ID'"
      :render-after-expand="false"
      accordion
      check-strictly
      :lazy="type !== 'label'"
      :load="fnLoad"
      :clearable="true"
      show-checkbox
      multiple
      :collapse-tags="collapseTags"
  />
</template>

<script setup>
import {nextTick, ref} from "vue";
import {useVModel} from "@vueuse/core";
import {layoutFnGetLevelsAndChildrenNumber} from "@/assets/js/data_dictionary.js";
import {getThreeInstitutionalLibrariesLabel} from "@/request/three_institutional_libraries.js";

defineOptions({
  name: "LayoutThreeInstitutionalLibraries",
});
const props = defineProps({
  modelValue: {
    type: String,
    required: true,
    default: "",
  },
  type: {
    type: String,
    required: true,
    default: "",
    validator: (value) => {
      // regulations: 规程属性
      // type: 类型
      // industry: 国民经济行业类型
      // label: 标签
      const typeList = ["regulations", "type", "industry", "label"];
      if (typeList.includes(value)) {
        return true;
      } else {
        throw new Error(`type必须是${typeList.join("、")}之一`);
      }
    },
  },
  pathName: {
    type: String,
    default: "",
  },
  collapseTags: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(["update:modelValue", "update:checkList"]);
const modelValue = useVModel(props, "modelValue", emits);
const treeSelectRef = ref(null);
const fnLoad = async (node, resolve) => {
  if (props.type === "label") return;
  const resData = await layoutFnGetLevelsAndChildrenNumber(
      node.data.DICTIONARIES_ID || id
  );
  resolve(
      resData.value.map((item) => {
        return {
          DICTIONARIES_ID: item.DICTIONARIES_ID,
          BIANMA: item.BIANMA,
          NAME: item.NAME,
          isLeaf: item.zcount === 0,
        };
      })
  );
};
const getCheckedNodes = async () => {
  await nextTick();
  return treeSelectRef.value.getCheckedNodes();
};
defineExpose({
  getCheckedNodes,
});
let tree = [];
let id = "";
const idByPathName = {
  safety_production_responsibility_system: "5a7c94b2b9514285b433759edd848b4a",
  safety_production_management_system: "675ed73a7d7d42a488491f6e0e9c8fd5",
  safety_operating_procedures: "ca4e4a7597f8485d8be323bd6876c40b",
};
if (props.type === "regulations") id = "84254cb5b2ae40eb9f451509b2d370ae";
if (props.type === "type") id = idByPathName[props.pathName];
if (props.type === "industry") id = "f2598ba72e864eadabf0ca4b664d26b9";
if (props.type === "label") {
  const resData = await getThreeInstitutionalLibrariesLabel({loading: false});
  tree = resData.tree;
}
</script>

<style scoped></style>
