<template>
  <div>
    <div>
      <el-input placeholder="住院号/姓名">
        <template #append>
          <el-button icon="Search" @click="getPatientList" />
        </template>
      </el-input>
    </div>
    <el-tree
      ref="treeRef"
      :load="loadNode"
      lazy
      show-checkbox
      node-key="id"
      default-expand-all
      :props="{ label: 'name', children: 'children' }"
      @node-click="handleNodeClick"
      @check="handleCheckChange"
      @node-expand="onNodeExpand"
    >
      <template #default="{ node, data }">
        <div class="custom-tree-node" v-if="node.level === 2">
          <span>{{ data.bedName + ' / ' + node.label }}</span>
          <span class="tree-node-actions">
            {{ data.genderEnum_enumText + ' / ' + data.age }}
          </span>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<script setup>
import {getPatientList, getWardList} from './api';
import {updatePatientInfoList} from '../store/patient';
import {nextTick} from 'vue';

const treeRef = ref(null);
const allNodesLoaded = ref(false);
// 树节点加载完成后的回调
function onTreeLoaded() {
  if (!allNodesLoaded.value && treeRef.value) {
    // 等待DOM更新后设置全选
    nextTick(() => {
      // 获取所有节点并设置为选中状态
      const allNodes = getAllNodes(treeRef.value.store.root.childNodes);
      const allKeys = allNodes.map((node) => node.key);

      treeRef.value.setCheckedKeys(allKeys, true); // 第二个参数设为true表示级联选中
      allNodesLoaded.value = true;
    });
  }
}

// 递归获取所有节点
function getAllNodes(nodes) {
  let result = [];
  if (nodes && nodes.length > 0) {
    nodes.forEach((node) => {
      result.push(node);
      if (node.childNodes && node.childNodes.length > 0) {
        result = result.concat(getAllNodes(node.childNodes));
      }
    });
  }
  return result;
}

function loadNode(node, resolve) {
  // 初始加载：获取所有病区（父级节点）
  if (node.level === 0) {
    getWardList().then((res) => {
      // 确保病区节点不是叶子节点
      const wards = res.map((ward) => ({
        ...ward,
        leaf: false,
      }));
      return resolve(wards);
    });
  }
  // 展开病区节点时：获取该病区下的患者列表
  else if (node.level === 1) {
    const wardId = node.data.id;
    getPatientList({ wardId: wardId }).then((res) => {
      let children = res.data.records.map((item) => {
        return {
          leaf: true, // 患者节点为叶子节点
          ...item,
          name: item.patientName,
        };
      });
      return resolve(children);
    });
  }
  // 更深层级直接返回空数组
  else {
    return resolve([]);
  }
}

// 获取所有选中的子节点（叶子节点）
function getCheckedLeafNodes() {
  if (!treeRef.value) return [];

  // 获取所有选中的节点key
  const checkedKeys = treeRef.value.getCheckedKeys();
  // 获取所有半选中的节点key（父节点）
  const halfCheckedKeys = treeRef.value.getHalfCheckedKeys();

  // 获取所有选中的节点数据
  const checkedNodes = treeRef.value.getCheckedNodes();

  // 只返回叶子节点（患者节点）
  return checkedNodes.filter((node) => node.leaf === true);
}

// 处理节点选中状态变化
function handleCheckChange(data, checked) {
  // 可以在这里处理选中状态变化的逻辑
  let list = getCheckedLeafNodes();
  console.log(list, '2345678');

  updatePatientInfoList(list);
  handleGetPrescription();
}
const handleGetPrescription = inject('handleGetPrescription');
</script>

<style scoped lang="scss">
.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.tree-node-actions {
  display: flex;
  align-items: center;
}

:deep(.el-tree-node__content) {
  height: 35px;
}
</style>