<template>
  <div style="width: 215px">
    <el-input v-model="filterText" placeholder="节点过滤"
              style="width: 100%"
              @input="filterChange" clearable/>
    <el-radio-group v-model="templateType" @change="typeChange">
      <el-radio-button :disabled="!editor" :label="0">全院模板</el-radio-button>
      <el-radio-button :disabled="!editor" :label="1">科室模板</el-radio-button>
      <el-radio-button :label="2">患者数据</el-radio-button>
    </el-radio-group>
    <div :style="{maxHeight : maxHeight - 100 + 'px'}"
         style="overflow: auto; "
         class="down-tree">
      <el-tree :data="treeData"
               :props="defaultProps"
               @node-click="handleNodeClick"
               node-key="_id"
               ref="treeRef"
               highlight-current
               :filter-node-method="filterNode"
               default-expand-all>
        <template #default="{ node, data }">
          <el-icon v-if="data.submit">
            <Lock/>
          </el-icon>
          <el-icon v-else>
            <Folder v-if="data.children"/>
            <Document v-else/>
          </el-icon>
          <span :title="fileName(data)">
               {{ fileName(data) }}
          </span>
        </template>
      </el-tree>
    </div>
  </div>
</template>

<script setup name='EmrSidebar'>
import {
  getEmrTree,
  getPatientDataTree,
  queryWhetherThePatientHasASpecifiedMedicalRecord
} from "@/api/zhu-yuan-yi-sheng/emr-patient";
import {BizException, ExceptionEnum} from "@/utils/BizException";
import {emrConfig} from '@/views/hospitalization/zhu-yuan-yi-sheng/electronic-medical-record/emr-editor/emr-init'
import {stringIsBlank} from "@/utils/blank-utils";
import {getAllWards} from "@/api/zhu-yuan-yi-sheng/resident-doctor";

const props = defineProps({
  maxHeight: {
    type: Number
  },
  huanZheXinXi: {
    type: Object
  }
})

let editor = emrConfig.value.editor

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

let returnData = $ref({
  emrTree: [],
  dept: [],
  patientTree: []
})
let filterText = $ref('')
let treeRef = $ref('')

let key = ''
let wardList = []

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

let templateType = $ref(0)

const treeData = computed(() => {
  switch (templateType) {
    case 0 :
      return returnData.emrTree;
    case 1:
      return returnData.deptTree;
    case 2:
      return returnData.patientTree;
  }
})


const handleNodeClick = async (val, property, event) => {
  let temp = {}
  if (templateType === 0 || templateType === 1) {
    temp = {
      documentId: null,
      categoryCode: val.code,
      categoryId: val._id,
      patientId: null,
      name: val.name,
      createId: null
    }
    if (!wardList.includes(props.huanZheXinXi.ward)) {
      BizException(ExceptionEnum.LOGICAL_ERROR, "无法创建病历，患者不属于您的科室")
    }
  } else if (templateType === 2) {
    temp = {
      documentId: val.emrDocumentId,
      categoryCode: val.emrCategoryCode,
      categoryId: null,
      patientId: null,
      name: val.name ? val.name : val.emrName,
      createId: val.createId,
      createName: val.createName
    }
  }
  let str = JSON.stringify(val)
  if (val.children) {
    return
  }
  if (val.labels) {
    // 根据 这个编码来限制是不是唯一一个
    if (val.labels.includes('唯一') && templateType !== 2) {
      let flag = await queryWhetherThePatientHasASpecifiedMedicalRecord({
        patNo: props.huanZheXinXi.inpatientNo,
        times: props.huanZheXinXi.admissTimes,
        emrCategoryCode: val.code
      })
      if (flag) {
        BizException(ExceptionEnum.LOGICAL_ERROR, '此病历只能创建一次。')
      }
    }
  }
  if (val.jump) {
    temp.code = val.code
    temp.value = val.value
    emit('nodeClick', temp, true, templateType);
    key = str
  } else {
    if (key !== str) {
      key = str
      emit('nodeClick', temp, false, templateType);
    }
  }

}

const typeChange = (val) => {
  emit("typeChange", val)
}

const queryHistory = async (times) => {
  templateType = 2
  returnData.patientTree = await getPatientDataTree(props.huanZheXinXi.inpatientNo, times)
}

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)
}

const deleteTheSpecifiedNode = (id) => {
  for (let i = 0, len = returnData.patientTree.length; i < len; i++) {
    let item = returnData.patientTree[i]
    if (item.emrDocumentId === id) {
      returnData.patientTree.splice(i, 1)
      return
    }
    if (item.children) {
      for (let j = 0; j < item.children.length; j++) {
        let child = item.children[j]
        if (child.emrDocumentId === id) {
          item.children.splice(i, 1)
          return
        }
      }
    }
  }
}

let findNode = false
const diseaseDurationRecordTime = (id, list) => {
  findNode = false
  findMedicalRecordById(id, list, returnData.patientTree)
}

const findMedicalRecordById = (id, roundTimes, list) => {
  for (let i = 0, len = list.length; i < len; i++) {
    if (findNode) return;
    let item = list[i]
    if (item.emrDocumentId === id) {
      findNode = true
      item.children = roundTimes
      return
    }

    if (item.children) {
      findMedicalRecordById(id, roundTimes, item.children)
    }
  }
}


const queryData = () => {
  getPatientDataTree(props.huanZheXinXi.inpatientNo, props.huanZheXinXi.admissTimes).then((res) => {
    if (res?.length > 0) {
      templateType = 2
      emit('patientMedicalRecord')
    }
    returnData.patientTree = res
  })
}

const fileName = (val) => {
  if (templateType === 2) {
    return val.name + nullToEmpty(val.createName) + nullToEmpty(val.createDate)
  } else {
    return val.name
  }
}

const nullToEmpty = (val) => {
  return stringIsBlank(val) ? '' : ' \\ ' + val
}

onMounted(() => {
  queryData()
  if (editor) {
    getAllWards().then((res) => {
      if (res.length > 0) {
        for (let i = 0, len = res.length; i < len; i++) {
          wardList.push(res[i].code)
        }
      }
    })
    getEmrTree().then((res) => {
      returnData.emrTree = res.all
      returnData.deptTree = res.dept
    })
  } else {
    templateType = 2
  }

})

defineExpose({
  queryHistory,
  changeTemplateType,
  deleteTheSpecifiedNode,
  diseaseDurationRecordTime,
  queryData
})


</script>

<style scoped lang="scss">
.down-tree {
  :deep(.el-tree-node.is-expanded > .el-tree-node__children) {
    display: inline;
  }
}
</style>
