<template>
  <el-input v-model="filterText" placeholder="节点过滤" @input="filterChange" clearable/>
  <el-radio-group v-model="templateType" @change="typeChange">
    <el-radio-button :label="0">全院模板</el-radio-button>
    <el-radio-button :label="1">科室模板</el-radio-button>
    <el-radio-button :label="2">患者数据</el-radio-button>
  </el-radio-group>
  <el-tree :data="treeData"
           :props="defaultProps"
           @node-click="handleNodeClick"
           node-key="_id"
           ref="treeRef"
           :filter-node-method="filterNode"
           default-expand-all>
  </el-tree>
</template>

<script setup name='EmrSidebar'>
import {getEmrTree} from "@/api/zhu-yuan-yi-sheng/emr-api";
import {huanZheXinXi} from "@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng";
import {getPatientData} from "@/api/zhu-yuan-yi-sheng/emr-patient";

const emit = defineEmits(['nodeClick', 'typeChange'])

let treeData = $ref([])
let returnData = $ref([])
let filterText = $ref('')
let treeRef = $ref('')

const defaultProps = {
  children: 'children',
  label: 'name',
}

let templateType = $ref(0)

const handleNodeClick = (val) => {
  emit('nodeClick', val, templateType)
}

const typeChange = (val) => {
  switch (val) {
    case 0 :
      return treeData = returnData.emrTree;
    case 1:
      return treeData = [];
    case 2:
      return treeData = returnData.patientTree;
  }
  emit("typeChange", val)
}

const queryHistory = async (times) => {
  templateType = 2
  returnData.patientTree = await getPatientData(huanZheXinXi.value.inpatientNo, times)
  treeData = returnData.patientTree
}

const filterChange = (val) => {
  treeRef.filter(val)
}

const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}

const changeTemplateType = (val) => {
  templateType = val
  typeChange(val)
}

defineExpose({queryHistory, changeTemplateType})

onMounted(() => {
  nextTick(() => {
    getEmrTree(huanZheXinXi.value.inpatientNo, huanZheXinXi.value.admissTimes).then((res) => {
      treeData = res.emrTree
      returnData = res
    })
  })
})

</script>

<style scoped>

</style>
