<template>
  <div>
    <el-input v-model="filterText" placeholder="节点过滤" @input="filterChange" clearable/>
    <div :style="{maxHeight : maxHeight - 40 + 'px'}" style="overflow: auto;max-width: 294px" class="down-tree">
      <el-tree :data="snippetData"
               :props="defaultProps"
               @node-click="handleNodeClick"
               node-key="_id"
               ref="treeRef"
               highlight-current
               :filter-node-method="filterNode"
               @node-contextmenu="fragmentPreview"
               :expand-on-click-node="false"
               default-expand-all>
        <template #default="{ node, data }">
          <el-icon>
            <Folder v-if="data.children"/>
            <Document v-else/>
          </el-icon>
          {{ data.name }}
        </template>
      </el-tree>
    </div>
    <el-dialog v-model="dialog" title="效果预览" top="2%" width="60%">
      <div>
        <iframe src="/emr/runtime/#/editor"
                style="width: 100%"
                :style="{height: getWindowSize.h / 1.2 + 'px'}"
                ref="emrRef"/>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name='EmrSnippet'>

import {getWindowSize} from "@/utils/window-size";
import {emrConfig, EMRInteractive} from "@/views/hospitalization/zhu-yuan-yi-sheng/electronic-medical-record/emr-editor/emr-init";
import {getSnippetTree} from "@/api/zhu-yuan-yi-sheng/emr-patient";


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

const emit = defineEmits(['nodeClick'])
let patientData = {}

let snippetData = $ref([])
let dialog = $ref(false)
let selectedData = {}
let filterText = $ref('')
let treeRef = $ref('')


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


const editorEvents = {
  'ready': (event) => {
    currentEmr.value.callMethod('setDocument', selectedData, true, true)
  }
}

const emrRef = ref(null)
const currentEmr = ref(null)

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

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

const handleNodeClick = (node, object, event) => {
  if (node.content) {
    emit('nodeClick', node)
  }
}

const fragmentPreview = (event, data, node) => {
  selectedData = data
  dialog = true
  if (currentEmr.value !== null) {
    currentEmr.value.callMethod('setDocument', selectedData, true, true)
  } else {
    nextTick(() => {
      currentEmr.value = new EMRInteractive(patientData, editorEvents);
      emrRef.value.parentElement.emr = currentEmr.value
    });

  }
}

const setPatientData = (val) => {
  patientData = val
}


onMounted(() => {
  if (emrConfig.value.editor) {
    getSnippetTree().then((res) => {
      snippetData = res
    })
  }
})

defineExpose({
  setPatientData
})

</script>

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