<template>
  <el-input v-model="search" style="width: 220px" @input="handleKeyUp" placeholder="这里可以搜索项目">
    <template #append>
      <el-button icon="Refresh" @click="refreshData"/>
    </template>
  </el-input>
  <el-tree
      ref="treeRef"
      :data="props.yjyc === 'jc' ? jcTree : jyTree"
      accordion
      :filter-node-method="filterNode"
      @node-click="nodeClick"
      :props="config">
    <template #default="{node, data}">
      <div style="width: 100%">
        <el-icon>
          <FolderOpened v-if="data?.code === null || data?.code.length < 5"/>
          <Document v-else/>
        </el-icon>
        <span :title="showName(data)">
         {{ showName(data) }}
        </span>
      </div>
    </template>
  </el-tree>
</template>

<script setup lang="ts">
import {jcTree, jyTree} from "@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng";
import {Ref, ref, watch} from "vue";
import {ElTree} from "element-plus";
import {Document, FolderOpened} from "@element-plus/icons-vue";
import XEUtils from "xe-utils";
import {notNullAndLike} from "@/utils/list-utlis";
import {useCompRef} from "@/utils/useCompRef";
import {getJyJcZdTree} from "@/api/zhu-yuan-yi-sheng/jian-yan-jian-cha-shen-qing";

const props = defineProps({
  yjyc: {
    type: String
  }
})

const emit = defineEmits(['node-click'])

const config = {
  value: 'code',
  label: 'name',
  children: 'children'
}

interface Tree {
  name: string,
  code: string,
  children?: Tree[]
}

const search: Ref<string> = ref('')
const treeRef = useCompRef(ElTree)

function handleKeyUp(val) {
  if (val) {
    treeRef.value!.filter(val)
  } else {
    for (let key in treeRef.value?.store.nodesMap) {
      treeRef.value.store.nodesMap[key].expanded = false;
    }
  }
}


const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return notNullAndLike(data, value)
}

const nodeClick = (data: Tree) => {
  if (!data.children) {
    emit('node-click', data)
  }
}

const showName = (data) => {
  if (props.yjyc === 'jy') {
    return data.name + ' ' + (data?.inspectStuffName === null ? '' : data?.inspectStuffName)
  }
  return data.name;
}

function refreshData() {
  getJyJcZdTree().then((res) => {
    jyTree.value = res.jy
    jcTree.value = res.jc
  })
}


</script>

<style scoped lang="scss">

</style>
