<template>
  <el-dialog
    title="添加中医诊断"
    v-model="props.openAddDiagnosisDialog"
    width="1300px"
    append-to-body
    destroy-on-close
    @open="handleOpen"
    @close="close"
  >
    <div class="main-content">
      <!-- 左侧疾病选择区 -->
      <div class="disease-section">
        <div class="section-title">诊断</div>
        <div class="search-box">
          <el-input v-model="searchDisease" placeholder="搜索疾病名称或编码" clearable>
            <template #prefix>
              <el-icon><search /></el-icon>
            </template>
          </el-input>
        </div>
        <el-table
          :data="conditionList"
          max-height="460"
          @row-click="handleClickRow"
          highlight-current-row
        >
          <el-table-column label="疾病名称" align="center" prop="name"></el-table-column>
          <el-table-column label="医保编码" align="center" prop="ybNo"></el-table-column>
        </el-table>
      </div>
      <!-- 中间疾病-证型关系区 -->
      <div class="syndrome-section">
        <div class="section-title">证候</div>
        <div class="search-box">
          <el-input v-model="searchDisease" placeholder="搜索疾病名称或编码" clearable>
            <template #prefix>
              <el-icon><search /></el-icon>
            </template>
          </el-input>
        </div>
        <div v-if="selectedDisease">
          <el-table
            :data="syndromeList"
            max-height="460"
            @row-click="clickSyndromeRow"
            highlight-current-row
          >
            <el-table-column label="证候名称" align="center" prop="name"></el-table-column>
            <el-table-column label="医保编码" align="center" prop="ybNo"></el-table-column>
          </el-table>
        </div>

        <div class="empty-state" v-else>
          <el-empty description="请从左侧选择疾病" />
        </div>
      </div>

      <!-- 右侧诊断详情区 -->
      <div class="diagnosis-section">
        <div class="section-title">诊断详情</div>
        <div class="diagnosis-list">
          <div v-for="(item, index) in tcmDiagonsisList" :key="index" class="history-item">
            <div class="history-diagnosis">
              <div>
                <strong>{{ item.conditionName }}</strong> - {{ item.syndromeName }}
              </div>
              <el-button
                size="small"
                type="danger"
                plain
                icon="close"
                @click="removeDiagnosis(item, index)"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  getTcmCondition,
  getTcmSyndrome,
  saveTcmDiagnosis,
  updateTcmDiagnosis,
  getTcmDiagnosis,
} from '@/views/doctorstation/components/api';

const props = defineProps({
  openAddDiagnosisDialog: {
    type: Boolean,
    default: false,
  },
  patientInfo: {
    type: Object,
    required: true,
  },
  updateZy: {
    type: Object,
    required: true,
  },
});

const conditionList = ref([]);
const syndromeList = ref([]);
const tcmDiagonsisList = ref([]);
const tcmDiagonsisSaveList = ref([]);
const syndromeSelected = ref(false); // 当前诊断是否选择对应证候
const timestamp = ref('');
const selectedDisease = ref(false);
const { proxy } = getCurrentInstance();
const emit = defineEmits(['close']);

function handleOpen() {
  // 获取诊断列表
  getTcmCondition().then((res) => {
    conditionList.value = res.data.records;
  });
  
  // 清空数据
  tcmDiagonsisSaveList.value = [];
  tcmDiagonsisList.value = [];
  syndromeSelected.value = true; // 设置为true，允许添加新的诊断
  
  // 如果是修改模式，加载传入的诊断数据
  if (props.updateZy.length > 0) {
    props.updateZy.forEach((item) => {
      let updateIds = item.updateId.split("-");
      let name = item.name.split("-");
      tcmDiagonsisSaveList.value.push(
        {
          conditionId: updateIds[0],
          definitionId: item.illnessDefinitionId,
          ybNo: item.ybNo,
          syndromeGroupNo: item.syndromeGroupNo,
          verificationStatusEnum: 4,
          medTypeCode: item.medTypeCode || undefined,  // 使用已保存的值
          diagSrtNo: item.diagSrtNo,
          isExisting: true // 标记为已存在
        },
        {
          conditionId: updateIds[1],
          definitionId: item.symptomDefinitionId,
          ybNo: item.symptomYbNo,
          syndromeGroupNo: item.syndromeGroupNo,
          diagSrtNo: item.diagSrtNo,
          isExisting: true // 标记为已存在
        }
      );
      tcmDiagonsisList.value.push({
        conditionName: name[0],
        syndromeName: name[1],
        syndromeGroupNo: item.syndromeGroupNo,
        isExisting: true // 标记为已存在
      });
      syndromeSelected.value = true;
    });
  } else {
    // 不是修改模式，加载已保存的中医诊断
    if (props.patientInfo && props.patientInfo.encounterId) {
      getTcmDiagnosis({ encounterId: props.patientInfo.encounterId }).then((res) => {
        if (res.code === 200 && res.data.illness && res.data.illness.length > 0) {
          res.data.illness.forEach((item, index) => {
            const symptom = res.data.symptom[index];
            if (symptom) {
              // 添加到显示列表
              tcmDiagonsisList.value.push({
                conditionName: item.name,
                syndromeName: symptom.name,
                syndromeGroupNo: item.syndromeGroupNo,
                isExisting: true // 标记为已存在
              });
              
              // 添加到保存列表
              tcmDiagonsisSaveList.value.push(
                {
                  conditionId: item.conditionId,
                  definitionId: item.definitionId,
                  ybNo: item.ybNo,
                  syndromeGroupNo: item.syndromeGroupNo,
                  verificationStatusEnum: item.verificationStatusEnum || 4,
                  medTypeCode: item.medTypeCode || undefined,  // 使用已保存的值
                  diagSrtNo: item.diagSrtNo,
                  isExisting: true // 标记为已存在
                },
                {
                  conditionId: symptom.conditionId,
                  definitionId: symptom.definitionId,
                  ybNo: symptom.ybNo,
                  syndromeGroupNo: item.syndromeGroupNo,
                  diagSrtNo: item.diagSrtNo,
                  isExisting: true // 标记为已存在
                }
              );
            }
          });
        }
      }).catch(err => {
        console.error('加载已保存的中医诊断失败:', err);
      });
    }
  }
}

// 点击诊断列表处理，点击以后才显示证候列表
function handleClickRow(row) {
  if (syndromeSelected.value || tcmDiagonsisList.value.length == 0) {
    syndromeSelected.value = false;
    selectedDisease.value = true;
    timestamp.value = Date.now();
    getTcmSyndrome().then((res) => {
      syndromeList.value = res.data.records;
    });
    
    // 添加新的诊断
    tcmDiagonsisSaveList.value.push({
      definitionId: row.id,
      ybNo: row.ybNo,
      syndromeGroupNo: timestamp.value,
      verificationStatusEnum: 4,
      medTypeCode: undefined,  // 不设默认值
      isExisting: false // 标记为新增
    });
    tcmDiagonsisList.value.push({
      conditionName: row.name,
      syndromeGroupNo: timestamp.value,
      isExisting: false // 标记为新增
    });
  }
}

function clickSyndromeRow(row) {
  // 检查是否已存在完全相同的诊断和证候
  let flag = true;
  const currentConditionName = tcmDiagonsisList.value[tcmDiagonsisList.value.length - 1].conditionName;
  
  tcmDiagonsisList.value.forEach(item => {
    if (item.conditionName === currentConditionName && item.syndromeName === row.name) {
      proxy.$modal.msgWarning('不能存在完全相同的诊断和证候');
      flag = false;
    }
  });
  
  if (flag) {
    tcmDiagonsisSaveList.value.push({
      definitionId: row.id,
      ybNo: row.ybNo,
      syndromeGroupNo: timestamp.value,
      isExisting: false // 标记为新增
    });
    tcmDiagonsisList.value[tcmDiagonsisList.value.length - 1].syndromeName = row.name;
    syndromeSelected.value = true;
  }
}

// 删除诊断
function removeDiagnosis(row, index) {
  tcmDiagonsisList.value.splice(index, 1);
  tcmDiagonsisSaveList.value = tcmDiagonsisSaveList.value.filter((item) => {
    return item.syndromeGroupNo !== row.syndromeGroupNo;
  });
  
}

function save() {
  // 只保存新增的诊断，过滤掉已存在的
  const newDiagnosisList = tcmDiagonsisSaveList.value.filter(item => !item.isExisting);
  
  if (newDiagnosisList.length === 0) {
    proxy.$modal.msgWarning('没有新增的诊断需要保存');
    return;
  }
  
  if (props.updateZy.length > 0) {
    // 修改模式
    updateTcmDiagnosis({
      patientId: props.patientInfo.patientId,
      encounterId: props.patientInfo.encounterId,
      diagnosisChildList: newDiagnosisList,
    }).then((res) => {
      if (res.code == 200) {
        emit('close');
        proxy.$modal.msgSuccess('诊断已保存');
      }
    });
  } else {
    // 新增模式
    saveTcmDiagnosis({
      patientId: props.patientInfo.patientId,
      encounterId: props.patientInfo.encounterId,
      diagnosisChildList: newDiagnosisList,
    }).then((res) => {
      if (res.code == 200) {
        emit('close');
        proxy.$modal.msgSuccess('诊断已保存');
      }
    });
  }
}

function submit() {
  // 检查是否有新增的诊断
  const hasNewDiagnosis = tcmDiagonsisSaveList.value.some(item => !item.isExisting);
  
  if (!hasNewDiagnosis) {
    // 如果没有新增诊断，直接关闭
    emit('close');
    return;
  }
  
  if (syndromeSelected.value || tcmDiagonsisSaveList.value.length % 2 == 0) {
    save();
  } else {
    proxy.$modal.msgWarning('请选择证候');
  }
}
function close() {
  emit('close');
}
</script>

<style scoped>
:deep(.pagination-container .el-pagination) {
  right: 20px !important;
}

.app-container {
  max-width: 1400px;
  margin: 20px auto;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.08);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--el-border-color);
  margin-bottom: 20px;
}

.header h1 {
  color: var(--el-color-primary);
  font-size: 24px;
  font-weight: 600;
}

.patient-info {
  background: var(--el-color-primary-light-9);
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.patient-info .info-row {
  display: flex;
  margin-bottom: 8px;
}

.patient-info .info-label {
  width: 100px;
  color: var(--el-text-color-secondary);
  font-weight: 500;
}

.main-content {
  display: grid;
  grid-template-columns: 1fr 1fr 1.2fr;
  gap: 20px;
  margin-bottom: 25px;
}

.disease-section,
.syndrome-section,
.diagnosis-section {
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  padding: 20px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-color-primary);
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--el-border-color);
}

.disease-list {
  max-height: 400px;
  overflow-y: auto;
}

.disease-item {
  padding: 12px 15px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 4px;
}

.disease-item:hover {
  background-color: var(--el-color-primary-light-9);
}

.disease-item.active {
  background-color: var(--el-color-primary-light-8);
  border-left: 3px solid var(--el-color-primary);
}

.disease-name {
  font-weight: 500;
  margin-bottom: 5px;
}

.disease-code {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.search-box {
  margin-bottom: 15px;
}

.disease-categories {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.category-tag {
  cursor: pointer;
  padding: 5px 12px;
  border-radius: 15px;
  background: var(--el-fill-color-light);
  font-size: 13px;
  transition: all 0.3s;
}

.category-tag.active {
  background: var(--el-color-primary);
  color: white;
}

.relation-container {
  text-align: center;
  padding: 30px 0;
  border: 2px dashed var(--el-border-color);
  border-radius: 8px;
  margin: 20px 0;
  background: var(--el-fill-color-lighter);
}

.relation-icon {
  margin-bottom: 15px;
  color: var(--el-color-primary);
}

.relation-text {
  font-size: 18px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.syndrome-details {
  padding: 15px;
  background: var(--el-color-primary-light-9);
  border-radius: 8px;
  border: 1px solid var(--el-color-primary-light-5);
}

.detail-item {
  margin-bottom: 12px;
}

.detail-label {
  font-weight: 500;
  color: var(--el-text-color-secondary);
  margin-bottom: 3px;
}

.actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color);
}

.empty-state {
  text-align: center;
  padding: 40px 0;
  color: var(--el-text-color-secondary);
}

.diagnosis-history {
  margin-top: 20px;
  border-top: 1px solid var(--el-border-color);
  padding-top: 20px;
}

.history-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
  color: var(--el-text-color-primary);
}

.history-item {
  padding: 12px;
  border-left: 3px solid var(--el-border-color);
  margin-bottom: 10px;
  background: var(--el-fill-color-lighter);
  border-radius: 0 4px 4px 0;
}

.diagnosis-list {
  max-height: 520px;
  overflow-y: auto;
}

.history-date {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 5px;
}

.history-diagnosis {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  margin-bottom: 5px;
}

.history-note {
  font-size: 13px;
  color: var(--el-text-color-secondary);
  padding-top: 5px;
  border-top: 1px dashed var(--el-border-color);
  margin-top: 5px;
}

.empty-list {
  padding: 20px 0;
  text-align: center;
}
</style>
