<template>
  <el-tree
    v-model="modelValue"
    ref="treeRef"
    :props="treeProps"
    :data="tableData"
    :load="loadNode"
    lazy
    show-checkbox
    node-key="id"
    @check-change="handleCheckChange"
    v-bind="$attrs"
  />
</template>

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

const props = defineProps({
  deptId: {
    type: String
  },
  isCanSelectAll: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['change', 'update:ids', 'update:cName', 'clear'])

const tableData = ref([])
const treeRef = ref(null)
const modelValue = ref()

const treeProps = {
  children: 'children',
  label: 'name',
  disabled: 'disabled',
  isLeaf: 'leaf'
}
/**@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 loadNode = (node, resolve) => {
  // if (node.level === 0) {
  //   initData().then(() => resolve(tableData.value))
  //   return
  // }

  getList(node.data.id, node.data.type)
    .then(res => {
      let resArr = Array.isArray(res) ? res : []
      resArr = resArr.map(item => {
        item.leaf = !item.hasChildren
        item.disabled = item.type !== '05'
        return item
      })
      resolve(resArr)
    })
    .catch(() => resolve([]))
}

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 : []
      list = list.filter(item => item.type !== '01')
      list = list.map(item => {
        item.leaf = !item.hasChildren
        item.disabled = item.type !== '05'
        return item
      })
      tableData.value = list
    })
  }
}

const handleCheckChange = (data, checked, indeterminate) => {
  console.log('modelValue: ', modelValue)
  if (checked) {
    treeRef.value.setCheckedKeys([data.id])
    const nodes = treeRef.value.getCheckedNodes()
    const node = nodes.find(n => n.id === data.id)
    if (node) {
      const pathNodes = getPathNodes(node)
      const pathLabels = pathNodes.map(n => n.name)
      const pathData = pathNodes.map(n => ({
        id: n.id,
        name: n.name,
        type: n.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 getPathNodes = node => {
  const path = []
  let current = node
  while (current) {
    path.unshift(current)
    current = current.parent
  }
  return path
}

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>
