<template>
  <div class="departmentTree-box" :style="{ width: width, height: '100%' }">
    <div class="depar_foot">
      <el-tree ref="treeRef" class="filter-tree" :props="endProps" node-key="id"
        :default-expanded-keys="defaultExpandedKeys" highlight-current @node-click="nodeClick"
        :filter-node-method="filterNode" :data="treeData">
        <template #default="{ node }">
          <span class="prefix" :class="{ 'is-leaf': node.isLeaf }">
            <SvgIcon :icon="'article-ranking'" style=" color: var(--el-color-primary) !important;"></SvgIcon>
          </span>
          <span :title="node.label">{{ node.label }}</span>
        </template>
      </el-tree>
    </div>
  </div>
</template>

<script setup>
import { COMPONENT_WIDTH } from "@/constant";
import SvgIcon from "@/components/SvgIcon/index.vue";
import { ref, defineProps, defineEmits, watch, onBeforeUnmount, onMounted, nextTick } from "vue";
import {
  getDept,
} from "@/api/user-manage";
import { getApi } from "@/api/tobAcco_api.js";
const props = defineProps({
  //获取组件传值
  placeholder: {
    default: "请选择",
    type: String
  },
  multiple: {
    default: false,
    type: Boolean
  },
  filterable: {
    default: true,
    type: Boolean
  },
  modelValue: {
    type: String
  },
  // 安委会
  awhType: {
    type: Boolean,
    default: false
  },
  // 法律法规标准库
  flfgType: {
    type: Boolean,
    default: false
  },
  // 车辆信息 驾驶员信息
  carInfo: {
    type: Boolean,
    default: false
  },
  width: {
    default: COMPONENT_WIDTH,
    type: String
  },
  deptcode: {
    type: String,
    default: ""
  },
  // 查询层级 01.查询所有层级(默认) 02.查询所有省、市公司 03.查询所有省、市、县公司
  searchType: {
    type: String,
    default: ""
  },
  /** 默认部门（目前默认是不带本级的部门(XN), 要本级这里需赋值:"benji"） */
  defaultOrg: {
    type: String,
    default: ""
  }
});
const highlightColor = ref("var(--el-color-primary)")
const listQuery = ref({
  type: props.searchType
});
const treeRef = ref(null);
const node_had = ref([]);
const resolve_had = ref([]);
const defaultExpandedKeys = ref([])
const treemrData = ref(null);
const emits = defineEmits(["update:modelValue", "getdeptId", "getdeptData"]);
//防抖处理
// const filterTextChange = debounce(inputChange, 500);
onMounted(() => { getTreeData() });
onBeforeUnmount(() => {
  clearTimeout(treemrData.value)
  treemrData.value = null
})
function getBenjiOrgcode(ele) {
  let firstOrgcode = ele?.children?.[0]?.orgcode;
  if (typeof firstOrgcode === "string" && firstOrgcode.includes('XN')) return firstOrgcode
  return ele.orgcode
}
//获取部门数据
function getTreeData() {
  treemrData.value = []
  // 非安委会
  let url = "/mosty-base/deptFeign/getDeptAndJgbm"
  // 安委会
  if (props.awhType) url = "/mosty-base/deptFeign/getMeetingDeptAndJgbm"
  // 法律法规标准库
  if (props.flfgType) url = "/mosty-base/deptFeign/getDirectlyOrg"
  // 车辆信息管理 驾驶员信息管理
  if (props.carInfo) url = "/mosty-base/deptFeign/getTempDeptAndJgbm"
  getApi(listQuery.value, url).then((res) => {
    if (res.length == 1) {
      res.forEach((element) => {
        // treemrData.value = setTimeout(() => { treeRef.value.setCurrentKey(element.id) }, 200)
        treemrData.value = [element.id]
        defaultExpandedKeys.value = [element.id]
        /**本级orgcode */
        let eleObj = undefined
        if (element && props.defaultOrg === 'benji') {
          const benJiOrg = getBenjiOrgcode(element)
          eleObj = {
            ...element,
            id: benJiOrg,
            orgcode: benJiOrg
          }
          nextTick(() => {
            treeRef.value?.setCurrentKey?.(benJiOrg)
          })
        }

        emits("getdeptData", eleObj || element);
      });
    }
    for (let i = 0; i < res.length; i++) {
      res[i].leaf = !res[i].hasChildren;
    }
    if (res.length > 0) treeData.value = res;
  });
}

//根据外部传入ID查询部门信息
watch(
  () => props.deptcode,
  (newVal) => {
    if (newVal) {
      listQuery.value.deptcode = newVal;
      getTreeData();
    }
  },
  { deep: true, immediate: true }
);
const endProps = {
  children: "children",
  value: "id",
  label: "orgname",
};

const treeData = ref([]);
//懒加载方法
async function loadNode(node, resolve) {
  listQuery.value.parentid = node.data.id;
  if (node.level === 0) {
    node_had.value = node;
    resolve_had.value = resolve;
    getTreeData();
  }
  if (node.level >= 1) {

    getDept(listQuery.value).then((res) => {
      for (let i = 0; i < res.length; i++) {
        res[i].leaf = !res[i].hasChildren;
      }
      resolve(res);
    });
  }
}
const filterNode = (value, data) => {
  if (!value) return true;
  return data.orgName.includes(value);
};

const nodeClick = (node) => {
  const id = node.id;
  emits("update:modelValue", id);
  emits("getdeptId", id);
  emits("getdeptData", node);
  highlightColor.value = ""
};

const handleChange = (e) => {
  if (props.multiple === true) {
    const data = e.map((item) => {
      return item[item.length - 1];
    });
    emits("update:modelValue", data);
  } else {
    const data = e[0];
    emits("update:modelValue", data);
  }
};
defineExpose({ getTreeData })
</script>

<style lang="scss" scoped>
.depar_hear {
  height: 32px;
}

.prefix {
  margin-right: 5px;
}

.depar_foot {
  // height: calc(100% - 8px);
  height: 100%;
  overflow-y: overlay;
  // width: 380px;
}

.departmentTree-box {
  height: 80vh;
  // overflow-y: scroll;
}
</style>
<style>
/* .is-expanded > .el-tree-node__content {
  background: var(--el-color-primary) !important  ;
} */
/* .el-tree-node__children {
  background: #fff;
} */
.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
  background-color: var(--el-color-primary) !important;
  color: #fff !important;
}
</style>
