<template>
  <div class="form-item-box" :style="{ width: width }">
    <el-cascader
      style="width: 100%"
      class="el-cascader-zj"
      :show-all-levels="false"
      clearable
      filterable
      :placeholder="modelValue ? placeholder : '请选择部门'"
      :options="tableData"
      v-model="oldmodelValue"
      @change="handleChange"
      :props="endProps"
    />
  </div>
</template>

<script setup>
import { COMPONENT_WIDTH } from "@/constant";
import { qcckPost, qcckGet, qcckFlvGet } from "@/api/qcckApi.js";
import { ref, defineProps, defineEmits, defineExpose, computed, onMounted, watch } from "vue";
import { selectDeptPage } from "@/api/user-manage";
const props = defineProps({
  //获取组件传值
  placeholder: {
    default: "请选择",
    type: String
  },
  multiple: {
    default: false,
    type: Boolean
  },
  isAll: {
    default: 100,
    type: Number
  },
  modelValue: {
    type: Array || String,
    default: []
  },
  width: {
    default: COMPONENT_WIDTH,
    type: String
  }
});
const modelShow = ref(false);
const oldmodelValue = ref([]);
const listQuery = ref({
  deptname: "",
  deptcode: "",
  parentid: ""
});
const depList = ref([])
//配置项
const endProps = {
  children: "childDeptList",
  value: "orgCode",
  label: "orgName",
  checkStrictly: true,
  multiple: props.multiple,
  lazy: true,
  lazyLoad(node, resolve) {
    listQuery.value.parentid = node.data.id;
    selectDeptPage(listQuery.value).then((res) => {
      depList.value = depList.value.concat(res)
      //处理部门是否包含下级
      for (let i = 0; i < res.length; i++) {
        res[i].leaf = !res[i].hasChildren;
      }
      resolve(res);
    });
  }
};
const tableData = ref([]);
const getSysMenuTree = async () => {
  const res = await selectDeptPage(listQuery.value);
  tableData.value = res;
  depList.value = res
};

onMounted(() => {
  getSysMenuTree();
});
watch(
  () => props.modelValue,
  (val) => {
    console.log(val,'val');
    oldmodelValue.value = val;
  },
  { deep: true, immediate: true }
);
const emits = defineEmits(["update:modelValue",'getDepValue']);
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 ? e[e.length - 1] : "";
    emits("update:modelValue", data);
    let obj = depList.value.find(item=>{ return item.orgCode == data})
    emits("getDepValue", obj);
  }
};
</script>

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