<template>
  <div class="emr-use-container">
    <div
      class="disBtn"
      :class="{ disLeftBtnNor: leftShow, disLeftBtnAct: !leftShow }"
      @click="disNode"
    >
      <img src="../../../../assets/icons/svg/foldup.svg" />
    </div>
    <div
      class="disBtn"
      :class="{ disRightBtnNor: rightShow, disRightBtnAct: !rightShow }"
      @click="disNode_R"
    >
      <img src="../../../../assets/icons/svg/foldup.svg" />
    </div>
    <transition name="el-zoom-in-left">
      <div class="template-tree-container" v-if="leftShow">
        <div class="search-box">
          <el-input placeholder="病历名称搜索..." v-model="queryParams.name">
            <template #append>
              <el-button @click="queryTemplateTree">查询</el-button>
            </template>
          </el-input>
        </div>
        <el-scrollbar class="template-tree-scrollbar">
          <el-tree
            ref="templateTree"
            :data="templateData"
            :props="defaultProps"
            auto-expand-parent
            node-key="id"
            @node-click="handleNodeClick"
            class="template-tree"
          ></el-tree>
        </el-scrollbar>
      </div>
    </transition>

    <div class="operate-container">
      <div class="operate-btns">
        <el-space>
          <!-- <el-button type="primary" @click="newEmr">新建</el-button> -->
          <el-button type="primary" @click="saveAsModel">存为模版</el-button>
          <el-button @click="refresh">刷新</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button type="primary" @click="print">打印</el-button>
        </el-space>
      </div>
      <div class="operate-main">
        <el-scrollbar class="template-tree-scrollbar">
          <div v-loading="loading" class="loading-container">
            <component
              :is="currentComponent"
              ref="emrComponentRef"
              :patientInfo="props.patientInfo"
              @submitOk="handleSubmitOk"
            />
          </div>
        </el-scrollbar>
      </div>
    </div>

    <transition name="el-zoom-in-left">
      <div class="quickly-container" v-if="rightShow">
        <el-tabs v-model="quicklyactiveName" type="card">
          <el-tab-pane label="历史" name="history">
            <History
              @historyClick="handleHistoryClick"
              ref="historyRef"
              v-model:definitionId="currentSelectTemplate.id"
              :selectedRecordId="selectedHistoryRecordId"
            />
          </el-tab-pane>
          <el-tab-pane label="模版" name="model">
            <Template
              @templateClick="handleTemplateClick"
              ref="templateRef"
              v-model:definitionId="currentSelectTemplate.id"
              @edit="templateEdit"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </transition>

    <TemplateEdit
      ref="templateEditRef"
      :formData="editTemplateForm"
      v-model:dialogVisible="templateEditVisible"
      @submitOk="templateEditSubmitOk"
    />
  </div>
</template>
<script setup>
import {nextTick, onMounted, ref, watch} from 'vue';
import {ElMessage} from 'element-plus';
import {getTreeList} from '@/views/basicmanage/caseTemplates/api';
import {addTemplate, getRecordByEncounterIdList, recordPrint, saveOrUpdateRecord} from './api';
import {patientInfo} from '../store/patient.js';
import dayjs from 'dayjs';
// 打印工具
import {PRINT_TEMPLATE, simplePrint} from '@/utils/printUtils.js';
import {getEncounterDiagnosis} from '../api';
import History from './components/history';
import Template from './components/template';
import TemplateEdit from './components/templateEdit.vue';

import useUserStore from '@/store/modules/user';

const { proxy } = getCurrentInstance();
const emits = defineEmits([]);
const props = defineProps({
  /** 患者信息 doctorStation  传递信息*/
  patientInfo: {
    type: Object,
    required: true,
  },
  activeTab: {
    type: String,
  },
});
const state = reactive({});
const userStore = useUserStore();
// 定义响应式变量
const templateData = ref([]);
const queryParams = ref({
  name: '',
  useRanges: [1, 2], // 0 暂不使用 1 全院 2 科室 3 个人
  organizationId: userStore.orgId,
});
const loading = ref(false); // 数据加载状态

const currentSelectTemplate = ref({
  id: '',
});
const currentComponent = ref('');
const emrComponentRef = ref(null);
const quicklyactiveName = ref('history');
const leftShow = ref(true);
const rightShow = ref(true);
const templateTree = ref(null);

// 树配置（模板树）
const defaultProps = {
  children: 'children',
  label: 'name',
  value: 'id',
};
/** 初始化病历模板树（按科室筛选） */
const queryTemplateTree = async () => {
  try {
    const res = await getTreeList(queryParams.value);
    templateData.value = res.data || [];

    // 组件挂载后，患者信息变化时会自动调用selectDefaultTemplate
    // 这里不再重复调用，避免重复操作
  } catch (error) {
    // ElMessage.error('获取模板树失败');
    templateData.value = [];
  }
};

// 处理节点点击，根据后台返回的路径加载组件
const handleNodeClick = (data, node) => {
  if (node.isLeaf) {
    // 存储当前节点数据
    currentSelectTemplate.value = data.document;

    // 在切换组件前先重置表单数据，避免显示之前的数据
    editForm.value = {
      id: '',
      definitionId: '',
      definitionBusNo: '',
      contentJson: '',
      statusEnum: 1,
      organizationId: 0,
      encounterId: '',
      patientId: '',
      recordTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      createBy: '',
      source: '',
    };

    // 先清空当前组件，再设置新组件，确保组件完全重新渲染
    currentComponent.value = '';

    // 使用 nextTick 确保 DOM 更新后再设置新组件
    nextTick(() => {
      currentComponent.value = currentSelectTemplate.value.vueRouter || '';
    });
  } else {
    currentSelectTemplate.value = {
      id: '',
    };
    // currentComponent.value = null;
  }

  // 确保组件状态更新后再查询历史记录
  nextTick(() => {
    setTimeout(() => {
      historyRef.value?.queryList();
      templateRef.value?.queryList();

      // 选择任何病历模板后，都加载该病历类型的最新历史记录
      if (node.isLeaf && props.patientInfo && props.patientInfo.patientId) {
        loadLatestMedicalRecord();
      }
    }, 100);
  });

  templateRef.value?.queryList();
};

const newEmr = () => {
  if (currentSelectTemplate.value) {
    currentComponent.value = currentSelectTemplate.value.vueRouter || '';
    return;
  }
  ElMessage.error('请选择模版！');
};

const saveAsModel = async () => {
  try {
    currentOperate.value = 'addTemplate';
    await emrComponentRef.value?.submit();
  } catch (error) {
    ElMessage.error('存为模版失败');
  }
};
const editForm = ref({
  id: '',
  definitionId: '',
  definitionBusNo: '',
  contentJson: '',
  statusEnum: 1, // 0草稿/暂存 1提交 2归档 3修改
  organizationId: 0,
  encounterId: '',
  patientId: '',
  recordTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  createBy: '',
  source: '',
});
const editTemplateForm = ref({
  id: '',
  name: '',
  displayOrder: 0,
  contextJson: '',
  definitionId: '',
  useRange: 2,
  organizationId: '',
  userId: '',
  remark: '',
});

const currentOperate = ref('add');
const handleSubmitOk = async (data) => {
  if (currentOperate.value === 'add') {
    //
    try {
      if (!patientInfo.value?.encounterId || !patientInfo.value?.patientId) {
        ElMessage.error('请先选择患者！');
        return;
      }
      editForm.value.definitionId = currentSelectTemplate.value.id;
      editForm.value.definitionBusNo = currentSelectTemplate.value.busNo;
      editForm.value.contentJson = JSON.stringify(data);
      editForm.value.encounterId = patientInfo.value.encounterId;
      editForm.value.patientId = patientInfo.value.patientId;
      editForm.value.recordTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
      // 提交病历
      await saveOrUpdateRecord(editForm.value);
      ElMessage.success('保存成功');

      // 刷新历史记录列表
      historyRef.value?.queryList();
      templateRef.value?.queryList();

      // 等待历史记录列表更新后，重新加载最新病历并更新选中状态
      setTimeout(() => {
        loadLatestMedicalRecord();
      }, 100);
    } catch (error) {
      ElMessage.error('提交失败');
      console.log(error);
    }
  } else if (currentOperate.value === 'addTemplate') {
    // 新增或修改模板
    editTemplateForm.value.name =
      currentSelectTemplate.value.name + dayjs().format('YYYY/MM/DD HH:mm');
    editTemplateForm.value.contextJson = JSON.stringify(data);
    editTemplateForm.value.definitionId = currentSelectTemplate.value.id;
    templateEditVisible.value = true;
  }
};

const refresh = () => {
  queryTemplateTree();
  historyRef.value?.queryList();
  templateRef.value?.queryList();
};

const save = async () => {
  try {
    if (editForm.value && editForm.value.printCount && editForm.value.printCount > 0) {
      ElMessage.warning('该病历已打印，不允许修改');
      return;
    }
    currentOperate.value = 'add';
    await emrComponentRef.value?.submit();
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

// 重置表单数据
const resetForm = async () => {
  try {
    // 重置editForm为初始值
    editForm.value = {
      id: '',
      definitionId: '',
      definitionBusNo: '',
      contentJson: '',
      statusEnum: 1,
      organizationId: 0,
      encounterId: '',
      patientId: '',
      recordTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      createBy: '',
      source: '',
    };

    // 先将组件设置为空，强制卸载
    const currentComponentName = currentComponent.value;
    if (currentComponentName) {
      currentComponent.value = '';

      // 等待DOM更新
      await nextTick();

      // 重新加载组件
      currentComponent.value = currentComponentName;

      // 再次等待DOM更新后设置空数据
      await nextTick();
    }

    // 重置动态组件表单数据
    if (emrComponentRef.value && emrComponentRef.value.setFormData) {
      emrComponentRef.value.setFormData({});
    }

    ElMessage.success('表单已重置');
  } catch (error) {
    ElMessage.error('重置表单失败');
  }
};

const historyRef = ref(null);
const handleHistoryClick = (data) => {
  newEmr();
  editForm.value = data;
  nextTick(() => {
    emrComponentRef.value?.setFormData(JSON.parse(editForm.value.contentJson));
  });
};

// 默认选中门诊病历模板
const selectOutpatientMedicalRecordTemplate = async () => {
  if (!templateData.value || templateData.value.length === 0) {
    await queryTemplateTree();
  }

  // 查找门诊病历模板
  const findOutpatientTemplate = (nodes) => {
    for (const node of nodes) {
      if (node.children && node.children.length > 0) {
        const found = findOutpatientTemplate(node.children);
        if (found) return found;
      }
      if (
        node.document &&
        node.document.name &&
        (node.document.name.includes('门诊病历') ||
          node.document.name === '门诊病历 (1.0.0)' ||
          node.document.name === '门诊病历(1.0.0)')
      ) {
        return node;
      }
    }
    return null;
  };

  const outpatientTemplateNode = findOutpatientTemplate(templateData.value);
  if (outpatientTemplateNode) {
    //选中节点
    nextTick(() => {
      if (templateTree.value && outpatientTemplateNode.id) {
        templateTree.value.setCurrentKey(outpatientTemplateNode.id);
      }

      // 选中门诊病历模板
      handleNodeClick(outpatientTemplateNode, {
        isLeaf: true,
        data: outpatientTemplateNode,
      });

      // 等待模板加载完成，然后获取并回显最新病历数据
      setTimeout(() => {
        historyRef.value?.queryList();
        loadLatestMedicalRecord();
      }, 500);
    });
  } else {
    ElMessage.info('未找到门诊病历模板');
  }
};

// 当前选中的历史病历ID，用于在History组件中高亮显示
const selectedHistoryRecordId = ref('');

// 加载最新的病历数据并回显
const loadLatestMedicalRecord = async () => {
  if (!patientInfo.value.encounterId || !currentSelectTemplate.value.id) return;

  loading.value = true;
  try {
    // 获取患者的历史病历记录
    const res = await getRecordByEncounterIdList({
      isPage: 0,
      encounterId: patientInfo.value.encounterId,
      patientId: patientInfo.value.patientId,
      definitionId: currentSelectTemplate.value.id,
    });

    const historyRecords = res.data || [];
    if (historyRecords.length > 0) {
      // 按时间排序，获取最新的病历记录
      historyRecords.sort((a, b) => new Date(b.recordTime) - new Date(a.recordTime));
      const latestRecord = historyRecords[0];

      // 保存最新病历ID，用于在History组件中高亮显示
      selectedHistoryRecordId.value = latestRecord.id;

      // 自动回显最新病历数据到模板
      editForm.value = latestRecord;
      nextTick(() => {
        if (emrComponentRef.value) {
          // 确保动态组件已加载完成后再设置数据
          if (latestRecord.contentJson) {
            try {
              const parsedData = JSON.parse(latestRecord.contentJson);
              emrComponentRef.value.setFormData(parsedData);
            } catch (parseError) {
              console.error('解析病历数据失败:', parseError);
              // 解析失败时仍然尝试设置空数据以清空之前的残留数据
              emrComponentRef.value.setFormData({});
            }
          } else {
            // 如果没有内容数据，也要清空组件中的数据
            emrComponentRef.value.setFormData({});
          }
        }

        // 通知History组件更新选中状态
        if (historyRef.value && typeof historyRef.value.updateSelectedRecord === 'function') {
          historyRef.value.updateSelectedRecord(latestRecord.id);
        }
      });
    } else {
      // 清空选中状态
      selectedHistoryRecordId.value = '';
      // 当没有历史记录时，也要清空当前表单数据，避免显示之前患者的数据
      editForm.value = {
        id: '',
        definitionId: '',
        definitionBusNo: '',
        contentJson: '',
        statusEnum: 1,
        organizationId: 0,
        encounterId: '',
        patientId: '',
        recordTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        createBy: '',
        source: '',
      };

      nextTick(() => {
        if (emrComponentRef.value) {
          emrComponentRef.value.setFormData({});
        }
      });
    }
  } catch (error) {
    ElMessage.error('加载最新病历数据失败');
    // 出错时也清空选中状态
    selectedHistoryRecordId.value = '';
    // 出错时也要清空表单数据，避免显示之前患者的数据
    editForm.value = {
      id: '',
      definitionId: '',
      definitionBusNo: '',
      contentJson: '',
      statusEnum: 1,
      organizationId: 0,
      encounterId: '',
      patientId: '',
      recordTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      createBy: '',
      source: '',
    };

    nextTick(() => {
      if (emrComponentRef.value) {
        emrComponentRef.value.setFormData({});
      }
    });
  } finally {
    loading.value = false;
  }
};
const templateRef = ref(null);

const handleTemplateClick = (data) => {
  newEmr();
  editForm.value = data;
  editForm.value.id = '';
  editForm.value.recordTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
  nextTick(() => {
    emrComponentRef.value?.setFormData(JSON.parse(editForm.value.contextJson));
  });
};
const templateEdit = (data) => {
  editTemplateForm.value = data;
  templateEditVisible.value = true;
};
// ====dialog
const templateEditVisible = ref(false);
// const templateEditSubmitOk = () => {};

// 定义病历模板类型与打印模板的映射关系
const templateToPrintTemplateMap = {
  // 手术记录相关模板
  手术记录: PRINT_TEMPLATE.OPERATIVE_RECORD,
  '手术记录(1.0.0)': PRINT_TEMPLATE.OPERATIVE_RECORD,
  tySurgicalRecord: PRINT_TEMPLATE.OPERATIVE_RECORD,
  // 门诊病历相关模板
  门诊病历: PRINT_TEMPLATE.HQOUTPATIENT_MEDICAL_RECORD,
  '门诊病历(1.0.0)': PRINT_TEMPLATE.HQOUTPATIENT_MEDICAL_RECORD,
  测试新增: PRINT_TEMPLATE.HQOUTPATIENT_MEDICAL_RECORD,
};

// 根据模板名称获取对应的打印模板
const getPrintTemplateByTemplateName = (templateName) => {
  // 默认使用门诊病历模板
  let printTemplate = PRINT_TEMPLATE.OUTPATIENT_MEDICAL_RECORD;

  if (templateName) {
    for (const [key, value] of Object.entries(templateToPrintTemplateMap)) {
      if (templateName.includes(key)) {
        printTemplate = value;
        break;
      }
    }
  }

  return printTemplate;
};

// 打印
const print = async () => {
  try {
    if (!currentSelectTemplate.value || !currentSelectTemplate.value.id) {
      ElMessage.warning('请先选择病历模板');
      return;
    }
    // 检查是否已保存
    if (!editForm.value.id || editForm.value.id === '') {
      ElMessage.warning('请先保存病历后再进行打印');
      return;
    }

    // 获取当前病历组件的表单数据
    const formData = emrComponentRef.value?.formData || {};

    // 获取诊断数据
    let diagnosisList = [];
    let diagnosisText = '';
    if (props.patientInfo && props.patientInfo.encounterId) {
      try {
        const diagnosisRes = await getEncounterDiagnosis(props.patientInfo.encounterId);
        diagnosisList = diagnosisRes.data || [];
        // 格式化诊断文本，区分主诊断和其他诊断
        diagnosisText = diagnosisList
          .map((item) => {
            const prefix = item.maindiseFlag === 1 ? '[主]' : '';
            return `${prefix}${item.name || ''}`;
          })
          .join('；');
      } catch (error) {
        ElMessage.error('获取诊断数据失败');
      }
    }

    // 获取当前模板名称
    const templateName = currentSelectTemplate.value.name || '';

    // 根据模板名称获取对应的打印模板
    const selectedPrintTemplate = getPrintTemplateByTemplateName(templateName);

    // 打印数据
    const printData = {
      // 模板信息
      templateName: currentSelectTemplate.value.name || '住院病历',
      templateId: currentSelectTemplate.value.id || '',

      // 医生信息
      doctorName: userStore.nickName,

      // 患者信息
      patientName: props.patientInfo.patientName || '',
      patientId: props.patientInfo.patientId || '',
      medicalRecordNo: props.patientInfo.medicalRecordNo || '',
      gender: props.patientInfo.gender || '',
      age: props.patientInfo.age || '',
      genderEnum_enumText: props.patientInfo.genderEnum_enumText || '',
      idCard: props.patientInfo.idCard || '',
      phone: props.patientInfo.phone || '',
      registerTime: props.patientInfo.registerTime || '',
      // 就诊信息
      encounterId: props.patientInfo.encounterId || '',
      department: props.patientInfo.department || '',
      attendingDoctor: props.patientInfo.attendingDoctor || '',

      // 诊断信息
      diagnosisList: JSON.stringify(diagnosisList),
      diagnosisText: diagnosisText,

      // 病历信息
      documentName: currentSelectTemplate.value.name || '住院病历',
      documentId: currentSelectTemplate.value.id || '',
      recordTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      printTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),

      //病历号
      busNo: props.patientInfo.busNo || '',
      //费用类型
      contractName: props.patientInfo.contractName || '',

      // 表单数据 - 需要将嵌套结构展开
      ...flattenObject(formData),
    };
    console.log('打印数据:', printData);

    // 执行打印，使用根据模板类型选择的打印模板
    await simplePrint(selectedPrintTemplate, printData);

    // 调用打印记录接口
    try {
      await recordPrint(editForm.value.id);

      // 刷新历史记录列表，确保删除按钮状态根据最新的printCount值更新
      historyRef.value?.queryList();
    } catch (printLogError) {
      ElMessage.error('保存打印记录失败');
      // 打印记录失败不影响打印成功提示
    }

    ElMessage.success('打印成功');
  } catch (error) {
    ElMessage.error('打印失败: ' + (error.message || '未知错误'));
  }
};
// 辅助函数：将嵌套对象扁平化为单层结构
const flattenObject = (obj, prefix = '') => {
  const flattened = {};

  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      const newKey = prefix ? `${prefix}_${key}` : key;

      if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
        // 递归处理嵌套对象
        Object.assign(flattened, flattenObject(obj[key], newKey));
      } else if (Array.isArray(obj[key])) {
        // 数组转换为字符串
        flattened[newKey] = JSON.stringify(obj[key]);
      } else {
        // 基本类型直接赋值
        flattened[newKey] = obj[key];
      }
    }
  }

  return flattened;
};

// 重新添加被覆盖的函数定义
const templateEditSubmitOk = () => {
  templateEditVisible.value = false;
  historyRef.value?.queryList();
  templateRef.value?.queryList();
};

// 选择默认模板 - 获取门诊病历分类下的第一个模板
const selectDefaultTemplate = () => {
  nextTick(() => {
    if (!templateData.value || templateData.value.length === 0) {
      console.log('模板数据为空，无法选择默认模板');
      return;
    }

    // 查找门诊病历分类节点，然后获取其下的第一个模板
    const findOutpatientRecordCategoryAndFirstTemplate = (nodes) => {
      for (const node of nodes) {
        // 检查是否是门诊病历分类节点
        if (!node.document && node.name && node.name.includes('门诊病历')) {
          // 这是一个分类节点，检查是否有子节点
          if (node.children && node.children.length > 0) {
            // 返回第一个有document属性的子节点（即第一个模板）
            for (const child of node.children) {
              if (child.document) {
                return child;
              }
            }
          }
        }
        // 递归查找子节点
        if (node.children && node.children.length > 0) {
          const found = findOutpatientRecordCategoryAndFirstTemplate(node.children);
          if (found) {
            return found;
          }
        }
      }
      return null;
    };

    const defaultTemplate = findOutpatientRecordCategoryAndFirstTemplate(templateData.value);
    if (defaultTemplate) {
      nextTick(() => {
        templateTree.value?.setCurrentKey(defaultTemplate.id);
        // 模拟点击节点
        const mockNode = {
          isLeaf: true,
        };
        handleNodeClick(defaultTemplate, mockNode);

        // 直接加载最新病历数据，不再使用额外的setTimeout延迟
        // 因为handleNodeClick中已经有nextTick和setTimeout处理组件渲染
        loadLatestMedicalRecord();
      });
    } else {
      console.log('未找到门诊病历模板');
    }
  });
};
// 监听患者信息变化，实现联动显示
watch(
  () => props.patientInfo,
  (newPatientInfo) => {
    // 当患者信息变化时，默认选中门诊病历模板并加载最新病历数据
    if (newPatientInfo && newPatientInfo.patientId && Object.keys(newPatientInfo).length > 0) {
      // 重置当前组件和表单数据，确保不会显示之前患者的数据
      currentComponent.value = '';
      editForm.value = {
        id: '',
        definitionId: '',
        definitionBusNo: '',
        contentJson: '',
        statusEnum: 1,
        organizationId: 0,
        encounterId: '',
        patientId: '',
        recordTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        createBy: '',
        source: '',
      };

      // 确保模板树已经加载
      if (templateData.value && templateData.value.length > 0) {
        // 优先尝试使用更精确的selectDefaultTemplate函数
        selectDefaultTemplate();
      } else {
        // 重新加载模板树
        queryTemplateTree().then(() => {
          // 使用nextTick确保DOM更新，移除setTimeout避免多次渲染
          nextTick(() => {
            selectDefaultTemplate();
          });
        });
      }
    } else {
      // 如果没有患者信息，也要重置组件和表单数据
      currentComponent.value = '';
      editForm.value = {
        id: '',
        definitionId: '',
        definitionBusNo: '',
        contentJson: '',
        statusEnum: 1,
        organizationId: 0,
        encounterId: '',
        patientId: '',
        recordTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        createBy: '',
        source: '',
      };
    }
  },
  { deep: true, immediate: true }
);

onMounted(async () => {
  await queryTemplateTree();
  // 组件挂载完成后，如果已有患者信息，默认选中门诊病历模板
  if (
    props.patientInfo &&
    props.patientInfo.patientId &&
    Object.keys(props.patientInfo).length > 0
  ) {
    // 使用nextTick确保模板树数据已更新
    nextTick(() => {
      selectDefaultTemplate();
    });
  }
});

// defineExpose({ state }); // state未使用

const disNode = () => {
  leftShow.value = !leftShow.value;
};
const disNode_R = () => {
  rightShow.value = !rightShow.value;
};
</script>
<style lang="scss" scoped>
.emr-use-container {
  display: flex;
  height: 100%;
  img {
    width: 200%;
    height: 200%;
  }
  .disBtn {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    overflow: hidden;
  }
  .disLeftBtnNor {
    cursor: pointer;
    position: absolute;
    top: 40%;
    left: 18%;
    width: 20px;
    height: 60px;
    z-index: 1111;
    img {
      transform: rotate(-90deg);
    }
  }
  .disLeftBtnAct {
    cursor: pointer;
    position: absolute;
    top: 40%;
    left: 0;
    width: 20px;
    height: 60px;
    z-index: 1111;
    img {
      transform: rotate(90deg);
    }
  }
  .disRightBtnNor {
    cursor: pointer;
    position: absolute;
    top: 40%;
    right: 18.5%;
    width: 20px;
    height: 60px;
    z-index: 1111;
    img {
      transform: rotate(90deg);
    }
  }
  .disRightBtnAct {
    cursor: pointer;
    position: absolute;
    top: 40%;
    right: 0;
    width: 20px;
    height: 60px;
    z-index: 1111;
    img {
      transform: rotate(-90deg);
    }
  }

  .template-tree-container {
    border-right: 1px solid #ebeef5;
    width: 300px;
    flex: none;
    height: 100%;
    padding: 0 8px 8px 0;
    display: flex;
    flex-direction: column;

    .search-box {
      height: 40px;
      display: flex;
      align-items: center;
      flex: none;
      border-bottom: 1px solid #ebeef5;
    }

    .template-tree-scrollbar {
      height: calc(100% - 48px);
      flex: auto;
      overflow-y: auto;
    }
  }

  .operate-container {
    width: 100%;
    //width: 300px;
    //flex: auto;
    display: flex;
    flex-direction: column;
    padding: 0 8px 8px 8px;

    .operate-btns {
      height: 40px;
      flex: none;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ebeef5;
    }

    .operate-main {
      flex: 1;
      min-height: 0; /* 允许flex子项高度收缩 */
      display: flex;
      flex-direction: column;
    }
    .operate-main .template-tree-scrollbar {
      flex: 1;
      overflow-y: auto;
      min-height: 0;
      /* 确保滚动条样式正常 */
      -ms-overflow-style: auto;
      scrollbar-width: auto;
    }
    /* 确保动态加载的组件不会破坏布局 */
    .operate-main .template-tree-scrollbar > .loading-container {
      width: 100%;
      min-height: 100%;
      box-sizing: border-box;
    }
    /* 确保组件内部内容不会溢出 */
    .operate-main .template-tree-scrollbar > * {
      max-width: 100%;
      box-sizing: border-box;
    }
  }

  .quickly-container {
    border-left: 1px solid #ebeef5;
    width: 300px;
    padding: 0 8px 8px 8px;
    flex: none;
    .el-tabs {
      height: 100%;
    }
  }
}

@layer utilities {
  .transition-width {
    transition-property: width;
    transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
    transition-duration: 300ms;
  }
}

/* 加载状态样式 */
.loading-container {
  min-height: 400px;
  position: relative;
}
</style>
