<template>
  <div class="form-item-box" :style="{ width: width }">
    <el-cascader ref="cascaderPanelRef" style="width: 100%" class="el-cascader-zj" :show-all-levels="false"
      :placeholder="props.modelValue ? placeholder : '请选择部门'" :props="endProps" :options="tableData"
      :disabled="isEditDisabled" v-model="props.modelValue" @change="handleChange" clearable
      :before-filter="inputChange" :filter-method="filterMethod" />
  </div>
</template>

<script setup>
import { COMPONENT_WIDTH } from "@/constant";
import { ref, defineProps, defineEmits, watch, watchEffect, onMounted } from "vue";
import { selectDept, getDept } from "@/api/user-manage";
const props = defineProps({
  //获取组件传值
  placeholder: {
    default: "请选择部门",
    type: String
  },
  isEditDisabled: {
    default: false,
    type: Boolean
  },
  multiple: {
    default: false,
    type: Boolean
  },
  filterable: {
    default: false,
    type: Boolean
  },
  isAll: {
    default: 100,
    type: Number
  },
  modelValue: {
    type: Array || String,
    default: []
  },
  width: {
    default: COMPONENT_WIDTH,
    type: String
  },
  deptType: {
    default: '02',
    type: String
  },
  // 查询当前部门下的人员
  deptId: {
    type: String,
    default: null
  },
  // 01.查询所有层级（默认） 02.查询所有省、市公司 03.查询所有省、市、县公司
  // 04.仅仅查询本部门同级数据(安全部门查询同级，其他只查询本部门)
  // 05.查询各单位的类型为40的收购线、点
  searchType: {
    type: String,
    default: "04"
  }
});
const emits = defineEmits(["update:modelValue", "depitem", "ok"]);
const tableData = ref([]);
//回调显示懒加载得部门
const cascaderPanelRef = ref(null);
const loadedTime = ref(0);
const listQuery = ref({
  deptCode: "",
  parentid: "",
  searchType: props.searchType
});

watch(
  () => props.deptId,
  (newVal) => {
    if (newVal) {
      if (props.searchType == '04') {
        listQuery.value.parentid = props.deptId ? props.deptId : null;
        if (props.deptType == '01') {
          getDept({ searchType: props.searchType, parentid: props.deptId }).then((res) => {
            if (res.length > 0) {
              listQuery.value.parentid = props.deptId ? props.deptId : null;
              listQuery.value.deptCode = null
              inputChange()
            } else {
              listQuery.value.parentid = null
              listQuery.value.deptCode = props.deptId ? props.deptId.replace("XN", "") : null;
              inputChange()
            }
          })
        } else {
          selectDept({ searchType: props.searchType, parentid: props.deptId }).then((res) => {
            if (res.length > 0) {
              listQuery.value.parentid = props.deptId ? props.deptId : null;
              listQuery.value.deptCode = null
              inputChange()
            } else {
              listQuery.value.parentid = null
              listQuery.value.deptCode = props.deptId ? props.deptId.replace("XN", "") : null;
              inputChange()
            }
          })
        }


      }
    }
  },
  { deep: true, immediate: true }
);
//配置项
const endProps = ref({
  children: "childDeptList",
  value: "id",
  label: "orgName",
  isLeaf: "leaf",
  multiple: props.multiple,
  lazy: true,
  lazyLoad(node, resolve) {
    if (node.data.id) {
      listQuery.value.parentid = node.data.id
    } else {
      if (props.searchType && props.searchType !== '01') {
        listQuery.value.deptCode = node.data.id
        // listQuery.value.parentid = null
      } else {
        listQuery.value.parentid = props.deptId ? props.deptId : node.data.id;
      }
    }

    // 区分调用不同接口
    if (props.deptType == '01') {
      getDept(listQuery.value).then((res) => {
        //处理部门是否包含下级
        for (let i = 0; i < res.length; i++) {
          res[i].leaf = !res[i].hasChildren;
        }
        resolve(res);
      });
    } else {
      // 第1,2次加载时，有个转圈，所以先这样让他不转圈
      if (loadedTime.value < 2) {
        loadedTime.value++;
        resolve([])
      }
      selectDept(listQuery.value).then((res) => {
        //处理部门是否包含下级
        for (let i = 0; i < res.length; i++) {
          res[i].leaf = !res[i].hasChildren;
        }
        resolve(res);
      });
    }
  }
})


const getSysMenuTree = async () => {
  let res;
  if (props.deptType == '01') {
    res = await getDept(listQuery.value);
  } else {
    res = await selectDept(listQuery.value);
  }
  for (let i = 0; i < res.length; i++) {
    res[i].leaf = !res[i].hasChildren;
  }
  tableData.value = res;
};

//防抖处理
const filterMethod = (node, keyword) => {
  return true;
};

//搜索查询
async function inputChange(node) {
  listQuery.value.orgName = node;
  if (props.deptType == '01') {
    await getDept(listQuery.value).then((res) => {
      for (let i = 0; i < res.length; i++) {
        res[i].leaf = !res[i].hasChildren;
      }
      tableData.value = res;
    });
  } else {
    await selectDept(listQuery.value).then((res) => {
      for (let i = 0; i < res.length; i++) {
        res[i].leaf = !res[i].hasChildren;
      }
      tableData.value = res;
    });
  }
  return true;
}
// 初始化
onMounted(() => {
  listQuery.value.searchType = props.searchType
});

const handleChange = (e) => {
  if (props.multiple === true) {
    const data = e.map((item) => {
      return item[item.length - 1];
    });
    emits("update:modelValue", data);
    emits("change", data);
  } else {
    const data = e ? e[e.length - 1] : "";
    emits("update:modelValue", data);
    let obj = {};
    let item = cascaderPanelRef.value.getCheckedNodes()[0] ? cascaderPanelRef.value.getCheckedNodes()[0].data : "";
    obj.orgCode = item.id;
    obj.orgName = item.orgName;
    emits("depitem", obj);
    emits("change", obj);
  }
};
</script>

<style lang="scss" scoped>
.el-cascader-zj {
  width: 100%;
}
</style>
