<template>
  <div class="hospital-record-form">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="病案首页(一)" name="first">
        <medicalRecordFirst
          ref="firstRef"
          :formData="formData"
          @onCaseFirst="updateCaseFirstDatas"
        ></medicalRecordFirst>
      </el-tab-pane>
      <el-tab-pane label="病案首页(二)" name="second">
        <medicalRecordSecond
          :formData="formData"
          @onCaseSecond="updateCaseFirstDatas"
        ></medicalRecordSecond>
      </el-tab-pane>
      <el-tab-pane label="病案附页(三)" name="third">
        <medicalRecordThird
          :formData="formData"
          @onCaseThird="updateCaseFirstDatas"
        ></medicalRecordThird>
      </el-tab-pane>
    </el-tabs>

    <div class="form-footer">
      <!-- <button @click="printForm" class="print-btn">打印表单</button> -->
      <button @click="resetForm" class="reset-btn">重置表单</button>
    </div>
    <medicalRecordPrint v-if="isShowprintDom" ref="recordPrintRef"></medicalRecordPrint>
    <!-- <el-drawer v-model="drawer" size="100%">
      <medicalRecordPrint ref="recordPrintRef"></medicalRecordPrint>
    </el-drawer> -->
  </div>
</template>

<script setup>
defineOptions({
  name: 'HospitalRecordForm',
});
import {nextTick, reactive, ref} from 'vue';
import {ElMessage} from 'element-plus';
// import medicalRecordFirst from './components/medicalRecordFirst.vue';
import medicalRecordFirst from '@/views/hospitalRecord/components/medicalRecordFirst.vue';
import medicalRecordSecond from '@/views/hospitalRecord/components/medicalRecordSecond.vue';
import medicalRecordThird from '@/views/hospitalRecord/components/medicalRecordThird.vue';
import formDataJs from '../views/doctorstation/components/store/medicalpage';
import medicalRecordPrint from '../views/hospitalRecord/components/medicalRecordPrint.vue';
import {previewPrint} from '../utils/printUtils';
import {getEncounterDiagnosis, getTcmDiagnosis,} from '../views/inpatientDoctor/home/components/api';
import {cloneDeep} from 'lodash';

const firstRef = ref();
const commpoentType = 'medicalRecord';
const emit = defineEmits(['submitOk']);
const drawer = ref(false);
// 表单数据
const formData = reactive({
  //医院信息
  hospitalInfo: {
    //组织机构代码
    orgCode: '41275054-700000',
    //医疗付款方式
    medicalPaymentCode: '',
  },
  //患者信息
  patientInfo: {
    // 健康卡号
    healthCardNo: '',
    // 患者姓名
    patientName: '',
    // 患者性别
    gender: '',
    // 出生日期
    birthDate: '',
    // 年龄
    age: '',
    // 国籍
    nationality: '中国',
    // 籍贯
    nativePlace: '',
    // 民族
    ethnicity: '汉族',
    // 身份证号
    idCardNo: '',
    // 户口住址
    householdAddress: '',
    // 工作单位地址
    workUnitAddress: '',
    // 联系人姓名
    contactName: '',
    // 关系
    contactRelation: '',
    // 联系人地址
    contactAddress: '',
    // 联系人电话
    contactPhone: '',
  },
  // 住院信息
  admission: {
    // 第几次住院
    times: 1,
    // 住院号
    hospitalNo: '',
    // 病案号
    medicalRecordNo: '',
    // 入院途径
    admissionRoute: '',
    // 入院时间
    admitTime: '',
    // 入院科室
    department: '',
    // 病房
    ward: '',
    // 确诊日期
    confirmDate: '',
    // 出院时间
    dischargeTime: '',
    // 出院科室
    dischargeDepartment: '',
    // 病房
    dischargeWard: '',
    // 实际住院天数
    hospitalDays: '',
  },
  // 诊断信息
  diagnosis: {
    // 主要诊断
    mainDiagnosis: '',
    // 其他诊断
    otherDiagnosis: '',
  },
  // 医疗信息
  medicalInfo: {
    // 是否输血
    bloodTransfusion: '2',
    // 血型
    bloodType: '',
    // rh类型
    rhType: '',
    // 药物过敏史
    drugAllergy: '1',
  },
  // 医师信息
  doctorInfo: {
    // 科主任
    departmentDirector: '',
    // 副主任
    chiefPhysician: '',
    // 主治医师
    attendingPhysician: '',
    // 住院医师
    residentPhysician: '',
    // 责任护士
    chargeNurse: '',
    // 住院总医师
    chiefResident: '',
    // 实习医师
    intern: '',
    // 病案质量
    recordQuality: '1',
    // 编码员
    coder: '',
    // 控制日期
    qualityControlDate: '',
  },
  // 病案首页2
  medicalSecond: {
    // 手术方式
    surgeryType: '',
    // 离院方式
    leaveType: '',
    // 是否计划出院
    isPlan: '',
    // 目的
    purpose: '',
    //昏迷时间---入院前
    comaDurationTime_before: '',
    //昏迷时间---入院后
    comaDurationTime_after: '',
    // 肿瘤分期
    tumorStaging: '',
    // T
    tumor_T: '',
    // N
    tumor_N: '',
    // M
    tumor_M: '',
    // 判断依据
    judgmentBase: '',
    // 分化程度
    degreeDifferentiation: '',
    // 临床路径
    enterPath: '',
    // 变异
    mutation: '',
    // 退出路径
    outPath: '',
    // 特级护理
    nursingLevel_spec: '',
    // 1级护理
    nursingLevel_1: '',
    // 2级护理
    nursingLevel_2: '',
    // 3级护理
    nursingLevel_3: '',
    // 呼吸机使用
    ventilatorUse: '',
    // 有创呼吸机使用小时
    ventilatorUseTime: '',
    // 手术表
    tableData_top: [],
  },
  // 病案首页3
  // 住院费用
  hospitalization: {
    // 总费用
    hosCharges: '',
    // 自付金额
    hosCharges_self: '',
  },
  // 综合医疗服务类
  medicalServices: {
    // 一般医疗服务类
    medicalServices_1: '',
    // 一般治疗操作费
    medicalServices_2: '',
    // 护理费
    medicalServices_3: '',
    // 其他费用
    medicalServices_4: '',
  },
  // 诊断类
  diagnosisClass: {
    // 病理诊断
    diagnosis_5: '',
    // 实验室诊断
    diagnosis_6: '',
    // 影像学诊断
    diagnosis_7: '',
    // 临床诊断
    diagnosis_8: '',
  },
  // 治疗类
  treatmentClass: {
    // 非手术治疗项目费
    treatment_9: '',
    // 临床物理治疗
    treatment_9_1: '',
    // 手术治疗费
    treatment_10: '',
    // 麻醉费
    treatment_10_1: '',
    // 手术费
    treatment_10_2: '',
  },
  // 康复类
  recoveryClass: {
    // 康复费
    recovery_11: '',
  },
  // 中医类
  TCMClass: {
    // 中医治疗费
    TCM_12: '',
  },
  // 西药类
  WesternClass: {
    // 西药费
    Western_13: '',
    // 抗菌药物费
    Western_13_1: '',
  },
  // 中药类
  chineseClass: {
    //中成药
    chinese_14: '',
    // 中草药
    chinese_15: '',
  },
  // 血液和血液制品类
  bloodClass: {
    // 血费
    blood_16: '',
    // 蛋白类制品费
    blood_17: '',
    // 球蛋白制品费
    blood_18: '',
    // 凝血因子制品费
    blood_19: '',
    // 细胞因子制品费
    blood_20: '',
  },
  // 耗材类
  consumablesClass: {
    // 检查用一次性医用材料费
    consumables_21: '',
    // 治疗用一次性医用材料费
    consumables_22: '',
    // 手术用一次性医用材料费
    consumables_23: '',
  },
  // 其他类
  otherClass: {
    // 其他费用
    other_24: '',
  },
  // 其他诊断及手术附加页
  tableData_sub: [],
  // 手术操作数组
  tableData_top: [],
});

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

const activeName = ref('first');
const recordPrintRef = ref();
const isShowprintDom = ref(false);

// 打印表单
const printForm = () => {
  drawer.value = true;
  // // 创建一个新的打印窗口
  // const printWindow = window.open('', '_blank');
  // let printContent;
  // // 获取模板字符串并替换转义的插值标记
  // if (activeName.value == 'first') {
  //   printContent = medicalRecordFirstPrint.printContent;
  // } else if (activeName.value == 'second') {
  //   printContent = medicalRecordSecondPrint.printContent;
  // } else {
  //   printContent = medicalRecordThirdPrint.printContent;
  // }
  // // 这里可以进行实际的数据替换操作
  // printContent = printContent.replace(/\$\{([^}]+)\}/g, (match, expr) => {
  //   // 简单示例：实际应根据expr内容进行数据提取
  //   return eval(expr); // 注意：实际使用中应避免eval，这里仅为示例
  // });
  // // 将内容写入打印窗口并打印
  // printWindow.document.write(printContent);
  // printWindow.document.close();
};

function handleClick() {
  console.log('住院记录表单点击事件触发');
}

const resetFun = (data) => {
  Object.keys(data).forEach((key) => {
    if (data[key] instanceof Array) {
      data[key].length = 0;
    } else {
      data[key] = '';
    }
  });
};
// 重置表单
const resetForm = () => {
  if (activeName.value == 'first') {
    // resetFun(firstRef.value.formData.hospitalInfo);
    // resetFun(firstRef.value.formData.patientInfo);
    firstRef.value.formData.patientInfo.napl = ''; //籍贯
    firstRef.value.formData.patientInfo.certno = ''; //身份证号
    firstRef.value.formData.patientInfo.resd_addr = ''; //户口地址
    firstRef.value.formData.patientInfo.empr_addr = ''; //工作单位
    firstRef.value.formData.patientInfo.coner_name = ''; //联系人
    firstRef.value.formData.patientInfo.coner_rlts_code = ''; //关系
    firstRef.value.formData.patientInfo.coner_addr = ''; //联系人地址
    firstRef.value.formData.patientInfo.coner_tel = ''; //联系人电话
    resetFun(firstRef.value.formData.admission);
    resetFun(firstRef.value.formData.diagnosis);
    resetFun(firstRef.value.formData.medicalInfo);
    resetFun(firstRef.value.formData.doctorInfo);
  } else if (activeName.value == 'second') {
    resetFun(firstRef.value.formData.medicalSecond);
  } else {
    resetFun(firstRef.value.formData.hospitalization);
    resetFun(firstRef.value.formData.medicalServices);
    resetFun(firstRef.value.formData.diagnosisClass);
    resetFun(firstRef.value.formData.treatmentClass);
    resetFun(firstRef.value.formData.recoveryClass);
    resetFun(firstRef.value.formData.TCMClass);
    resetFun(firstRef.value.formData.WesternClass);
    resetFun(firstRef.value.formData.chineseClass);
    resetFun(firstRef.value.formData.bloodClass);
    resetFun(firstRef.value.formData.consumablesClass);
    resetFun(firstRef.value.formData.otherClass);
    firstRef.value.formData.tableData_sub.length = 0;
    firstRef.value.formData.tableData_top.length = 0;
  }
};
//自定义事件更新主数据
const updateCaseFirstDatas = (newDatas) => {
  Object.assign(formData, newDatas);
};

const getList = () => {
  getEncounterDiagnosis(props.patientInfo.encounterId).then((res) => {
    if (res.code == 200) {
      console.log('getEncounterDiagnosis=======>', JSON.stringify(res.data));
      formDataJs.diagnosisList = res.data;
    }
  });
  getTcmDiagnosis({ encounterId: props.patientInfo.encounterId }).then((res) => {
    if (res.code == 200) {
      // if (res.data.illness.length > 0) {
      //   diagnosisNetDatas.value = res.data.illness;
      //   res.data.illness.forEach((item, index) => {
      //     form.value.diagnosisList.push({
      //       name: item.name + '-' + res.data.symptom[index].name,
      //       ybNo: item.ybNo,
      //       medTypeCode: item.medTypeCode,
      //     });
      //   });
      // }
    }
  });
};
// 点击历史数据回传布局
const setFormData = (data) => {
  if (Object.keys(data).length > 0) {
    Object.assign(firstRef.value.formData, data);
  } else {
    resetForm();
  }
  getList();
};
//保存数据方法
const submit = () => {
  /*
  {
    "encounterId": "1987758365116919809",
    "statusEnum": 5,
    "busNo": "ZY202511100001",
    "inHospitalTime": "2025-11-10 13:47:08",
    "outHospitalTime": null,
    "patientId": "1981311362744872962",
    "patientName": "王海明",
    "genderEnum": 0,
    "genderEnum_enumText": "男性",
    "birthDate": "1999-06-18 00:00:00",
    "age": "26岁",
    "wardName": "内科病区1",
    "houseName": "内科病房2",
    "bedName": "002",
    "inOrgTime": "2025-11-10 19:36:28",
    "inHospitalDays": 2,
    "inHospitalOrgId": "1950367917287616513",
    "inHospitalOrgName": "住院内科",
    "contractNo": "0000",
    "contractName": "自费",
    "regDiagnosisName": "感冒",
    "accountId": "1987759000528809985"
}
  */
  // const isOk = verifyMethod(formDataJs);
  if (1) {
    const cloneParams = cloneDeep(formDataJs);

    // 病例二表
    const medicalSecondTable = cloneParams.medicalSecond.surgery_tableData.filter((obj) => {
      return obj.isChoose;
    });
    // 病例三表第一张表
    const other_tableData = cloneParams.other_tableData.filter((obj) => {
      return obj.isChoose;
    });
    // 病例三表第二张表
    const surgery_tableData = cloneParams.surgery_tableData.filter((obj) => {
      return obj.isChoose;
    });
    // 数据整理
    let params = {
      ...cloneParams,
      other_tableData,
      surgery_tableData,
    };
    params.medicalSecond.surgery_tableData = medicalSecondTable;
    console.log('cloneParams========>', JSON.stringify(params));
    emit('submitOk', params);
  }
};

// 公共校验方法
const verifyMethod = (data) => {
  let message = '';
  if (!data) return false;
  if (!data.hospitalInfo.orgCode) {
    message = '请填写组织机构代码';
  } else if (!data.hospitalInfo.medicalPaymentCode) {
    message = '请选择医疗付费方式';
  } else if (!data.patientInfo.healthCardNo) {
    message = '请填写健康卡号';
  } else if (!data.patientInfo.patientName) {
    message = '请填患者姓名';
  } else if (!data.patientInfo.gender) {
    message = '请选择患者性别';
  } else if (!data.patientInfo.birthDate) {
    message = '请选择出生日期';
  } else if (!data.patientInfo.age) {
    message = '请填写患者年龄';
  } else if (!data.patientInfo.nationality) {
    message = '请填写国籍';
  } else if (!data.patientInfo.nativePlace) {
    message = '请填写籍贯';
  } else if (!data.patientInfo.ethnicity) {
    message = '请填写民族';
  } else if (!data.patientInfo.idCardNo) {
    message = '请填写身份证号';
  } else if (!data.patientInfo.householdAddress) {
    message = '请填写户口地址';
  } else if (!data.patientInfo.workUnitAddress) {
    message = '请填写工作单位及地址';
  } else if (!data.patientInfo.contactName) {
    message = '请填写联系人姓名';
  } else if (!data.patientInfo.contactRelation) {
    message = '请填写与联系人关系';
  } else if (!data.patientInfo.contactAddress) {
    message = '请填写地址';
  } else if (!data.patientInfo.contactPhone) {
    message = '请填写电话';
  } else if (!data.admission.times) {
    message = '请填写第几次住院';
  } else if (!data.admission.hospitalNo) {
    message = '请填写住院号';
  } else if (!data.admission.medicalRecordNo) {
    message = '请填写病案号';
  } else if (!data.admission.admissionRoute) {
    message = '请填写入院途径';
  } else if (!data.admission.admitTime) {
    message = '请填写入院时间';
  } else if (!data.admission.department) {
    message = '请填写入院科室';
  } else if (!data.admission.ward) {
    message = '请填写病房';
  } else if (!data.admission.confirmDate) {
    message = '请填写确诊日期';
  } else if (!data.admission.dischargeTime) {
    message = '请填写出院时间';
  } else if (!data.admission.dischargeDepartment) {
    message = '请填写出院科室';
  } else if (!data.admission.dischargeWard) {
    message = '请填写病房';
  } else if (!data.admission.hospitalDays) {
    message = '请填写实际住院天数';
  } else if (!data.diagnosis.mainDiagnosis) {
    message = '请填写主要诊断';
  } else if (!data.diagnosis.otherDiagnosis) {
    message = '请填写其他诊断';
  } else if (!data.medicalInfo.bloodTransfusion) {
    message = '请选择是否输血';
  } else if (!data.medicalInfo.bloodType) {
    message = '请选择血型';
  } else if (!data.medicalInfo.rhType) {
    message = '请选择rh类型';
  } else if (!data.medicalInfo.drugAllergy) {
    message = '请选择药物过敏史';
  } else if (!data.doctorInfo.departmentDirector) {
    message = '请填写科主任';
  } else if (!data.doctorInfo.chiefPhysician) {
    message = '请填写主任(副主任)医师';
  } else if (!data.doctorInfo.attendingPhysician) {
    message = '请填写主治医师';
  } else if (!data.doctorInfo.residentPhysician) {
    message = '请填写住院医师';
  } else if (!data.doctorInfo.chargeNurse) {
    message = '请填写责任护士';
  } else if (!data.doctorInfo.chiefResident) {
    message = '请填写住院总医师';
  } else if (!data.doctorInfo.intern) {
    message = '请填写实习医师';
  } else if (!data.doctorInfo.recordQuality) {
    message = '请填写病案质量';
  } else if (!data.doctorInfo.coder) {
    message = '请填写编码员';
  } else if (!data.doctorInfo.qualityControlDate) {
    message = '请选择质控日期';
  } else if (!data.medicalSecond.tableData_top) {
    message = '请添加手术操作表';
  } else if (!data.medicalSecond.surgeryType) {
    message = '请填写手术方式';
  } else if (!data.medicalSecond.leaveType) {
    message = '请选择离院方式';
  } else if (!data.medicalSecond.isPlan) {
    message = '请选择是否有出院31天内再住院计划';
  } else if (!data.medicalSecond.purpose) {
    message = '请填写目的';
  } else if (!data.medicalSecond.comaDurationTime_before) {
    message = '请选择颅脑损伤患者昏迷时间-入院前';
  } else if (!data.medicalSecond.comaDurationTime_after) {
    message = '请选择颅脑损伤患者昏迷时间-入院后';
  } else if (!data.medicalSecond.tumorStaging) {
    message = '请填写肿瘤分期';
  } else if (!data.medicalSecond.tumor_T) {
    message = '请填写T';
  } else if (!data.medicalSecond.tumor_N) {
    message = '请填写N';
  } else if (!data.medicalSecond.tumor_M) {
    message = '请填写M';
  } else if (!data.medicalSecond.judgmentBase) {
    message = '请填写判断依据';
  } else if (!data.medicalSecond.degreeDifferentiation) {
    message = '请选择分化程度';
  } else if (!data.medicalSecond.enterPath) {
    message = '请填写临床路径-进入路径';
  } else if (!data.medicalSecond.mutation) {
    message = '请选择是否变异';
  } else if (!data.medicalSecond.outPath) {
    message = '请选择退出路径';
  } else if (!data.medicalSecond.nursingLevel_spec) {
    message = '请填写特级护理';
  } else if (!data.medicalSecond.nursingLevel_1) {
    message = '请填写1级护理';
  } else if (!data.medicalSecond.nursingLevel_2) {
    message = '请填写2级护理';
  } else if (!data.medicalSecond.nursingLevel_3) {
    message = '请填写3级护理';
  } else if (!data.medicalSecond.ventilatorUse) {
    message = '请选择是否使用呼吸机使用';
  } else if (!data.medicalSecond.ventilatorUseTime) {
    message = '请填写有创呼吸机使用时间（小时）';
  }
  if (message.length > 0) {
    ElMessage({
      message,
      type: 'error',
    });
    return false;
  }
  return true;
};
// 打印方法
const printFun = () => {
  isShowprintDom.value = true;
  nextTick(() => {
    recordPrintRef?.value.setData();
    previewPrint(recordPrintRef?.value.getDom());
    isShowprintDom.value = false;
  });
};

defineExpose({
  submit,
  commpoentType,
  setFormData,
  printFun,
});
</script>

<style scoped>
/*max-width: 1000px;*/
.hospital-record-form {
  font-family: 'SimSun', serif;
  width: 100%;
  margin: 0 auto;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: white;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.hospital-name {
  font-size: 24px;
  margin-bottom: 10px;
}

.form-title {
  font-size: 20px;
  padding-bottom: 10px;
  margin-bottom: 20px;
  display: inline-block;
}

.section {
  margin-bottom: 30px;
  border: 1px solid #ccc;
  padding: 15px;
  border-radius: 5px;
}

.section-title {
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid #ccc;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.form-item {
  flex: 1;
  min-width: 200px;
  margin-right: 15px;
  margin-bottom: 8px;
}

.form-item.full-width {
  flex: 0 0 100%;
  min-width: 100%;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  font-size: 14px;
}

input,
select,
textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-family: inherit;
  font-size: 14px;
}

textarea {
  min-height: 80px;
  resize: vertical;
}

.form-footer {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.print-btn,
.reset-btn {
  padding: 10px 20px;
  margin: 0 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.print-btn {
  background-color: #4caf50;
  color: white;
}

.reset-btn {
  background-color: #f44336;
  color: white;
}

/* 打印样式 */
@media print {
  body {
    margin: 0;
    padding: 0;
    background-color: white;
  }

  .hospital-record-form {
    box-shadow: none;
    padding: 0;
  }

  .form-footer {
    display: none;
  }

  @page {
    size: A4;
    margin: 2cm;
  }
}
</style>
