<template>
  <el-cascader
    v-model="modelValue"
    ref="cascaderPanelRef"
    :props="cascaderProps"
    :options="tableData"
    v-bind="$attrs"
    @change="handleChange"
  />
</template>

<script setup>
import { ref, defineProps, defineEmits, onMounted, watch, defineExpose, computed } from 'vue'
import { getApi } from '@/api/tobAcco_api.js'

// import { getItem } from '@/utils/storage'
// const ssdwid = ref(getItem('deptId').ssdwid)
const props = defineProps({
  /** 父级部门 (即只选该部门下的单位) */
  deptId: {
    type: String
  },
  /**省级是否可以选所有部位 */
  isCanSelectAll: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['change', 'update:ids', 'update:cName', 'clear'])
/** 级联内容 */
const tableData = ref([])
const cascaderPanelRef = ref(null)
const modelValue = ref()

/**@typedef {Object} tableDataItem
 * @property {String} id ID
 * @property {String} name 名称
 * @property {String} type 类型 01-单位 02-场所 03-建筑物 04-楼层 05-部位
 * @property {String} orgid 类型 所属单位
 * @property {String} partno 部位顺序
 * @property {String} jzwlx 建筑物类型
 * @property {Boolean} hasChildren 是否有子级
 * @property {Boolean} leaf 是否叶子节点（没有子级）
 * @property {String} departmentlevel 等级
 * @property {String} sitetype 场所类型
 * @property {Array[tableDataItem]} children 子级
 */
const cascaderProps = {
  children: 'children',
  value: 'id',
  label: 'name',
  isLeaf: 'leaf', // !hasChildren
  multiple: props.multiple,
  lazy: true,
  lazy: true,
  lazyLoad(node, resolve) {
    const { data, level } = node
    const removeDw = data => {
      if (!props.isCanSelectAll) return data.filter(item => item.type !== '01')
      return data
    }
    getList(data.id, data.type)
      .then(res => {
        /** @type {Array<tableDataItem>} tableDataItem */
        let resArr = Array.isArray(res) ? res : []
        // resArr = removeDw(resArr)
        resArr = resArr.map(item => {
          item.leaf = !item.hasChildren
          item.disabled = item.type !== '05' && !item.hasChildren // 禁用非部位(且没有子集的)
          item.children = []
          return item
        })
        resolve(resArr)
      })
      .finally(() => {
        resolve()
      })
  }
}

/**
 * 查询部位楼层建筑物等
 * @param parentid 上级ID，第一层可以不传入
 * @param type 查询下级的类型 默认查询单位 01.单位和场所02.建筑物 03.楼层 04.部位
 */
const getList = (parentid, type) => {
  return getApi({ parentid, type }, '/mosty-jcgl/site/querySceneTree')
}
const initData = async () => {
  let arr = await getList()
  let row = arr?.[0] || {}
  if (row.id) {
    getList(row.id, row.type).then(res2 => {
      let list = Array.isArray(res2) ? res2 : []
      if (!props.isCanSelectAll) list = list.filter(item => item.type !== '01') // 移除单位
      list = list.map(item => {
        item.leaf = !item.hasChildren
        item.disabled = item.type !== '05' && !item.hasChildren // 禁用非部位(且没有子集的)
        return item
      })
      tableData.value = list
    })
  }
}

const handleChange = (val, val2) => {
  const node0 = cascaderPanelRef.value.getCheckedNodes()[0]
  /** @type {Array[String]} 选择的名称数组例如['载客','大型'] */
  const pathLabels = node0.pathLabels
  const pathNodes = node0.pathNodes
  const pathData = pathNodes.map(item => {
    let data = item.data || {}
    return {
      id: data.id,
      name: data.name,
      type: data.type
    }
  })
  if (pathData.length == 3) {
    const obj = {
      siteid: pathData[0].id,
      sitename: pathData[0].name,
      buildingid: pathData[1].id,
      buildingname: pathData[1].name,
      floorid: '',
      floorname: '',
      partid: pathData[2].id,
      partname: pathData[2].name
    }
    emit('change', obj, pathData, pathLabels)
  } else if (pathData.length == 4) {
    const obj = {
      siteid: pathData[0].id,
      sitename: pathData[0].name,
      buildingid: pathData[1].id,
      buildingname: pathData[1].name,
      floorid: pathData[2].id,
      floorname: pathData[2].name,
      partid: pathData[3].id,
      partname: pathData[3].name
    }
    emit('change', obj, pathData, pathLabels)
  }
}
const setValByObj = res => {
  if (!res?.siteid) return
  const arr = res.floorid
    ? [res.siteid, res.buildingid, res.floorid, res.partid]
    : [res.siteid, res.buildingid, res.partid]
  modelValue.value = arr
}
/** 设置值 */
const setVal = val => {
  if (Array.isArray(val)) {
    modelValue.value = val
  } else if (typeof val === 'object') {
    setValByObj(val)
  }
}

onMounted(() => {
  initData()
})

defineExpose({
  setVal
})
</script>

<style scoped lang="scss">

</style>
