<!--
 * @Author: sjjh
 * @Date: 2025-09-18 15:41:10
 * @Description: 病历使用首页
-->
<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 type="primary" @click="save">保存</el-button>
        </el-space>
      </div>
      <div class="operate-main">
        <el-scrollbar class="template-tree-scrollbar">
          <component :is="currentComponent" ref="emrComponentRef" @submitOk="handleSubmitOk" />
        </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"
            />
          </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 { getCurrentInstance, onBeforeMount, onMounted, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus';
import { getTreeList } from '@/views/basicmanage/caseTemplates/api';
import { addRecord, addTemplate } from './api';
import { patientInfo } from '../store/patient.js';
import dayjs from 'dayjs';
// 移除未使用的变量
// const { proxy } = getCurrentInstance();
const emits = defineEmits([]);
const props = defineProps({});
const state = reactive({});
import History from './components/history';
import Template from './components/template';
import TemplateEdit from './components/templateEdit.vue';
// 定义响应式变量
const templateData = ref([]);
const queryParams = ref({
  name: '',
});
const currentSelectTemplate = ref({
  id: '',
});
const currentComponent = ref('');
const emrComponentRef = ref(null);
const quicklyactiveName = ref('history');
const leftShow = ref(true);
const rightShow = ref(true);


// 树配置（模板树）
const defaultProps = {
  children: 'children',
  label: 'name',
  value: 'id',
};

/** 初始化病历模板树（按科室筛选） */
const queryTemplateTree = async () => {
  try {
    const res = await getTreeList(queryParams.value);
    templateData.value = res.data || [];
  } catch (error) {
    ElMessage.error('获取模板树失败');
    templateData.value = [];
  }
};

// 处理节点点击，根据后台返回的路径加载组件
const handleNodeClick = (data, node) => {
  if (node.isLeaf) {
    // 存储当前节点数据
    currentSelectTemplate.value = data.document;
    currentComponent.value = currentSelectTemplate.value.vueRouter || '';
    // currentComponent.value = data.document.vueRouter || '';
  } else {
    currentSelectTemplate.value = {
      id: '',
    };
    // currentComponent.value = null;
  }
  historyRef.value?.queryList();
  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 addRecord(editForm.value);
      ElMessage.success('病历保存成功');
      historyRef.value?.queryList();
      templateRef.value?.queryList();
    } catch (error) {
      ElMessage.error('提交失败');
      console.log(error);
    }
  } else if (currentOperate.value === 'addTemplate') {
    // 新增或者编辑模板
    // editTemplateForm.value.id=
    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 deleteEmr = async () => {
  try {
    // 这里应该添加实际的删除逻辑
    ElMessage.success('删除成功！');
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

const save = async () => {
  try {
    currentOperate.value = 'add';
    await emrComponentRef.value?.submit();
  } 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 templateRef = ref(null);

const handleTemplateClick = (data) => {
  newEmr();
  editForm.value = data;
  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 = () => {
  templateEditVisible.value = false;
  historyRef.value?.queryList();
  templateRef.value?.queryList();
};
// onBeforeMount(() => {});
onMounted(() => {
  queryTemplateTree();
});

defineExpose({ 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;
    }
  }

  .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 {
      height: calc(100% - 40px);
      flex: auto;
    }
  }

  .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;
  }
}
</style>
