<template>
  <div class="medical-form">
    <div class="patient-name">
      患者姓名：{{ patient?.patientName || '未知' }} &nbsp;&nbsp; 病历号：{{
        patient?.busNo || '未知'
      }}
    </div>
    <h2 style="text-align: center">长春市朝阳区中医院</h2>
    <h2 style="text-align: center">出院诊断病历</h2>

    <!-- 滚动内容区域 -->
    <div class="form-scroll-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        label-align="left"
        class="medical-full-form"
      >
        <h4 class="section-title">一、基础信息</h4>
        <!-- 1. 基础信息：单行自适应排列 -->
        <el-form-item class="form-section">
          <div class="single-row-layout">
            <el-form-item label="姓名" prop="patientName" class="row-item">
              <div class="input-with-unit">
                <el-input
                  disabled
                  v-model="formData.patientName"
                  type="text"
                  placeholder="请输入"
                />
              </div>
            </el-form-item>
            <el-form-item label="年龄" prop="age" class="row-item">
              <div class="input-with-unit">
                <el-input disabled v-model="formData.age" type="text" placeholder="请输入" />
              </div>
            </el-form-item>
            <el-form-item label="性别" prop="gender" class="row-item">
              <div class="input-with-unit">
                <el-input v-model="formData.gender" type="text" placeholder="请输入" />
              </div>
            </el-form-item>

            <el-form-item label="住院号" prop="busNo" class="row-item">
              <div class="input-with-unit">
                <el-input disabled v-model="formData.busNo" type="text" placeholder="请输入" />
              </div>
            </el-form-item>
            <el-form-item label="职业" prop="temperature" class="row-item">
              <div class="input-with-unit">
                <el-input v-model="formData.temperature" type="text" placeholder="请输入" />
              </div>
            </el-form-item>
            <el-form-item label="入院日期" prop="admissionDate" class="row-item">
              <el-date-picker
                v-model="formData.admissionDate"
                type="date"
                placeholder="选择入院日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="出院日期" prop="dischargeDate" class="row-item">
              <el-date-picker
                v-model="formData.dischargeDate"
                type="date"
                placeholder="选择出院日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="住院天数" prop="hospitalDays" class="row-item">
              <div class="input-with-unit">
                <el-input disabled v-model="formData.hospitalDays" placeholder="请输入" />
              </div>
            </el-form-item>
          </div>
        </el-form-item>

        <h4 class="section-title">二、诊断</h4>
        <!-- 3. 出院诊断（必填） -->
        <el-form-item label="出院诊断" prop="DischargeDiagnosis" class="required form-item-single">
          <el-input
            v-model="formData.DischargeDiagnosis"
            type="textarea"
            placeholder="请输入出院诊断"
            :autosize="{ minRows: 1 }"
            style="resize: none; padding-right: 10px"
          />
        </el-form-item>
        <!-- 4. 出院病情摘要及诊疗经过 -->
        <el-form-item
          label="出院病情摘要及诊疗经过"
          prop="SummaryAndDiagnosisAndTreatmentProcess"
          class="form-item-single"
        >
          <el-input
            v-model="formData.SummaryAndDiagnosisAndTreatmentProcess"
            type="textarea"
            placeholder="请输入出院病情摘要及诊疗经过"
            :autosize="{ minRows: 1 }"
            style="resize: none; padding-right: 10px"
          />
        </el-form-item>

        <el-form-item
          label="出院后要求及注意事项"
          prop="RequirementsAndPrecautionsAfterDischarge"
          class="form-item-single"
        >
          <el-input
            v-model="formData.RequirementsAndPrecautionsAfterDischarge"
            type="textarea"
            placeholder="请输入出院后要求及注意事项"
            :autosize="{ minRows: 1 }"
            style="resize: none; padding-right: 10px"
          />
        </el-form-item>

        <el-form-item
          label="中医调护"
          prop="TraditionalChineseMedicineNursing"
          class="form-item-single"
        >
          <el-input
            v-model="formData.TraditionalChineseMedicineNursing"
            type="textarea"
            placeholder="请输入中医调护"
            :autosize="{ minRows: 1 }"
            style="resize: none; padding-right: 10px"
          />
        </el-form-item>
      </el-form>
    </div>
  </div>
  <DisDiagnMedicalRecord v-if="isShowprintDom" ref="recordPrintRef"></DisDiagnMedicalRecord>
</template>

<script setup>
import { reactive, ref, onMounted, watch, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { previewPrint } from '../utils/printUtils';
import DisDiagnMedicalRecord from '../views/hospitalRecord/components/disDiagnMedicalRecord.vue';

defineOptions({
  name: 'DischargeDiagnosisCertificate',
});

// Props与事件
const props = defineProps({
  patientInfo: {
    type: Object,
    required: true,
  },
});

const recordPrintRef = ref();
const isShowprintDom = ref(false);

const patient = props.patientInfo;

// const props = defineProps({});
const emits = defineEmits(['submitOk']);

// 数据初始化
// const patient = ref(null);

// 表单数据
const formData = reactive({
  patientName: '', // 姓名
  age: '', // 年龄
  gender: '', // 性别
  busNo: '', // 住院号
  admissionDate: '', // 入院日期
  dischargeDate: '', // 出院日期
  hospitalDays: '', // 住院天数
  DischargeDiagnosis: '', // 出院诊断
  SummaryAndDiagnosisAndTreatmentProcess: '', // 出院病情摘要及诊疗经过
  RequirementsAndPrecautionsAfterDischarge: '', // 出院后要求及注意事项
  TraditionalChineseMedicineNursing: '', // 中医调护
});

// 表单校验规则
const rules = reactive({
  dischargeDiagnosis: [
    {
      required: true,
      message: '请填写出院诊断',
      trigger: ['blur', 'submit'],
    },
  ],
});

// 提交函数
const submit = () => {
  emits('submitOk', formData);
};
// 表单数据赋值
const setFormData = (data) => {
  if (data) {
    Object.assign(formData, data);
  }
};

// 生命周期
onMounted(() => {
  // patient.value = patientInfo.value;
  // 组件挂载时自动填充患者信息
  // fillPatientInfo(patientInfo.value);
  if (!formData.patientName) {
    formData.patientName = patient?.patientName || '';
  }
  if (!formData.gender) {
    formData.gender = patient?.genderEnum_enumText || '';
  }
  if (!formData.age) {
    formData.age = patient?.age || '';
  }
  if (!formData.department) {
    formData.department = patient?.inHospitalOrgName || '';
  }
  if (!formData.bedNo) {
    formData.bedNo = patient?.houseName + '-' + patient?.bedName;
  }
  if (!formData.busNo) {
    formData.busNo = patient?.busNo || '';
  }
  if (!formData.admissionDate) {
    formData.admissionDate = patient?.inHospitalTime || '';
  }
  if (!formData.hospitalDays) {
    formData.hospitalDays = patient?.inHospitalDays;
  }
  console.log('patientInfo========>', JSON.stringify(props.patientInfo));
});

// 监听患者信息变化，实现联动显示和自动填充
// watch(
//   () => patientInfo.value,
//   (newPatientInfo) => {
//     patient.value = newPatientInfo;
//     // 患者信息变化时自动填充
//     fillPatientInfo(newPatientInfo);
//   },
//   { deep: true }
// );

// 自动填充患者信息到表单
const fillPatientInfo = (patientData) => {
  if (!patientData) {
    ElMessage.warning('未获取到患者信息，请确保已选择患者');
    return;
  }

  try {
    // 填充基本信息，处理可能的数据缺失情况
    formData.patientName = patientData.patientName || '';
    formData.age = patientData.age || '';
    formData.gender = patientData.genderEnum_enumText || '';
    formData.busNo = patientData.busNo || '';
    formData.hospitalDays = patientData.inHospitalDays || '';
  } catch (error) {
    console.error('填充患者信息时发生错误:', error);
    ElMessage.error('自动填充患者信息失败，请检查数据源格式');
  }
};

// 打印方法
const printFun = () => {
  isShowprintDom.value = true;
  nextTick(() => {
    recordPrintRef?.value.setData(formData);
    nextTick(() => {
      previewPrint(recordPrintRef?.value.getDom());
      isShowprintDom.value = false;
    });
  });
};

// 暴露接口
defineExpose({ formData, submit, setFormData, fillPatientInfo, printFun });
</script>

<style scoped>
/* 表单外层容器 */
.medical-form {
  max-width: 1200px;
  width: 100%;
  min-height: 800px;
  height: auto;
  margin: 15px auto;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-family: Arial, sans-serif;
  box-sizing: border-box;
  overflow: hidden; /* 防止内部内容溢出 */
  position: relative;
}

/* 顶部姓名样式 */
.patient-name {
  display: inline-block;
  margin-bottom: 15px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

/* 滚动内容容器 */
.form-scroll-container {
  width: 100%;
  max-height: 55vh;
  overflow-y: auto;
  overflow-x: hidden;
  scrollbar-width: thin;
  scrollbar-color: #ccc #f5f5f5;
  position: relative;
}
.form-scroll-container::-webkit-scrollbar {
  width: 6px;
}
.form-scroll-container::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 3px;
}
.form-scroll-container::-webkit-scrollbar-track {
  background-color: #f5f5f5;
}

/* 完整表单容器 */
.medical-full-form {
  width: 100%;
  min-width: 0; /* 防止内容强制拉伸容器 */
  box-sizing: border-box;
}

/* 区域通用样式 */
.form-section {
  margin-bottom: 20px;
}
.section-title {
  margin: 0 0 12px;
  padding-bottom: 6px;
  border-bottom: 1px solid #f0f0f0;
  color: #333;
  font-size: 16px;
  font-weight: bold;
}

/* 通用单行自适应布局（基础信息+病史信息共用） */
.single-row-layout {
  display: flex;
  flex-wrap: wrap; /* 自动换行 */
  align-items: flex-start; /* 顶部对齐，适配文本域高度 */
  gap: 15px; /* 统一元素间距 */
  width: 100%;
  box-sizing: border-box;
}
.row-item {
  margin-bottom: 0; /* 取消底部间距，避免换行重叠 */
  display: flex;
  flex-direction: column;
}

/* 基础信息项：适配短输入框 */
.row-item:not(.history-item) {
  min-width: 160px; /* 基础信息项最小宽度 */
}

/* 带单位的输入框样式 */
.input-with-unit {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}
.input-with-unit .el-input {
  flex: 1;
}
.unit {
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  font-size: 14px;
}

/* 单行表单项样式（主诉、查体等） */
.form-item-single {
  margin: 18px 0;
}

/* 必填项红色星号 */
.required .el-form-item__label::before {
  content: '* ';
  color: #ff4d4f;
}

/* 输入框统一样式 */
.el-form-item .el-input,
.el-form-item .el-input__wrapper {
  width: 100%;
  box-sizing: border-box;
}
.el-form-item .el-input__inner {
  font-size: 14px;
  padding: 8px 12px;
}

/* 确保textarea的rows属性生效 */
.el-textarea__inner {
  min-height: auto !important;
  height: auto !important;
  resize: none;
}

/* 根据rows属性设置高度 */
.el-input--textarea {
  height: auto;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .medical-form {
    height: 80vh;
    padding: 10px;
    overflow: hidden;
  }
  .form-scroll-container {
    height: calc(100% - 35px);
    max-height: none;
  }
  .el-form {
    label-width: 70px !important;
  }
  .row-item:not(.history-item) {
    min-width: 130px;
  }
  .history-item {
    min-width: 100%; /* 移动端病史信息全屏宽度，单行显示 */
  }
  .form-item-single,
  .form-section {
    margin-bottom: 15px;
  }
}
</style>
