<template>
  <div class="layout_container">
    <header>
      <el-date-picker
        v-model="month"
        :clearable="false"
        placeholder="出院日期"
        style="width: 110px"
        type="month"
      ></el-date-picker>
      <el-divider direction="vertical"></el-divider>
      <el-button type="primary" icon="Search" @click="getAnalyzedSheets(false)"
        >检索（省质控）</el-button
      >
      <el-button type="success" icon="Search" @click="getAnalyzedSheets(true)"
        >检索（HQMS）</el-button
      >
      <el-divider direction="vertical" />
      <el-button type="primary" icon="Download" @click="exportExcel"
        >导出csv</el-button
      >
    </header>
    <div class="layout_main layout_el-table">
      <el-table
        :data="
          cptSheets.slice(pageSize * (currentPage - 1), pageSize * currentPage)
        "
        stripe
      >
        <el-table-column width="33" label="剔除">
          <template #default="scope">
            <el-button
              icon="Minus"
              size="small"
              circle
              type="danger"
              @click.prevent="deleteRow(scope.$index, scope.row)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column type="expand">
          <template #default="props">
            <div style="display: flex">
              <div style="width: 40%">
                <div
                  style="
                    width: 100%;
                    padding: 4px;
                    background: rgb(128, 128, 128);
                    font-weight: bold;
                    color: white;
                  "
                >
                  出院诊断
                </div>
                <div
                  style="
                    display: flex;
                    font-size: 13px;
                    font-weight: bold;
                    padding: 4px 0;
                  "
                >
                  <div style="width: 10%">序号</div>
                  <div style="width: 30%">诊断编码</div>
                  <div>诊断名称</div>
                </div>
                <div v-for="item in props.row.disdiagList">
                  <div
                    style="
                      display: flex;
                      padding: 4px 0;
                      border-bottom: 1px dashed lightskyblue;
                    "
                  >
                    <div style="width: 10%">{{ item.no }}</div>
                    <div style="width: 30%">{{ item.code }}</div>
                    <div>{{ item.name }}</div>
                  </div>
                </div>
              </div>
              <div
                v-show="props.row.surgeryList.length > 0"
                style="width: 55%; margin-left: 30px"
              >
                <div
                  style="
                    width: 100%;
                    padding: 4px;
                    background: rgb(128, 128, 128);
                    font-weight: bold;
                    color: white;
                  "
                >
                  手术记录
                </div>
                <div
                  style="
                    display: flex;
                    font-size: 13px;
                    font-weight: bold;
                    padding: 4px 0;
                  "
                >
                  <div style="width: 10%">序号</div>
                  <div style="width: 25%">手术时间</div>
                  <div style="width: 20%">手术编码</div>
                  <div>手术名称</div>
                </div>
                <div v-for="item in props.row.surgeryList">
                  <div
                    style="
                      display: flex;
                      padding: 4px 0;
                      border-bottom: 1px dashed lightskyblue;
                    "
                  >
                    <div style="width: 10%">{{ item.no }}</div>
                    <div style="width: 25%">{{ item.date }}</div>
                    <div style="width: 20%">{{ item.code }}</div>
                    <div>{{ item.name }}</div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="bah" width="100">
          <template #header>
            <el-input
              v-model="patNo"
              size="small"
              placeholder="住院号"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="admissTimes"
          label="次数"
          width="50"
        ></el-table-column>
        <el-table-column prop="name" label="姓名" width="100"></el-table-column>
        <el-table-column prop="sex" label="性别" width="50"></el-table-column>
        <el-table-column prop="socialNo" label="身份证号"></el-table-column>
        <el-table-column
          prop="birthDate"
          label="出生日期"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="phone"
          label="电话"
          width="100"
        ></el-table-column>
        <el-table-column prop="admissDate" label="入院时间"></el-table-column>
        <el-table-column prop="admissDept" label="入院科室"></el-table-column>
        <el-table-column prop="dismissDate" label="出院时间"></el-table-column>
        <el-table-column prop="dismissDept" label="出院科室"></el-table-column>
        <el-table-column
          prop="admissDoctorName"
          label="入院医生"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="mainDoctorName"
          label="主治医生"
          width="100"
        ></el-table-column>
      </el-table>
    </div>
    <div>
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 30, 50, 100]"
        :total="sheets.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script setup name="FrontSheetExport">
import { ElMessage } from "element-plus";
import { formatMonth } from "@/utils/date";
import { fetchSheets } from "@/api/case-front-sheet";
import { exportCSV,exportCharCSV } from "@/utils/ExportCVS";
import {
  DATEFORMAT,
  formatDateToStr,
} from "@/utils/moment-utils";
import env from "@/utils/setting";

const month = ref(null);

const patNo = ref("");
const sheets = ref([]);

const cptSheets = computed(() => {
  return sheets.value.filter(item => {
    return item.bah.indexOf(patNo.value) !== -1;
  });
});

const pageSize = ref(30);
const currentPage = ref(1);
const handleSizeChange = val => {
  pageSize.value = val;
};
const handleCurrentChange = val => {
  currentPage.value = val;
};

const getAnalyzedSheets = isHqms => {
  if (!month.value) {
    ElMessage({
      message: "请先选择出院日期",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  month.value = formatMonth(month.value);
  fetchSheets(month.value, isHqms).then(res => {
    sheets.value = res;
  });
};

function deleteRow(index, row) {
  if (sheets.value[index] !== row) {
    index = sheets.value.findIndex(item => {
      return item === row;
    });
  }
  sheets.value.splice(index, 1);
}

const exportExcel = () => {
  // console.log("export", formatDateToStr(sheets.value[0].dismissDate,DATEFORMAT.DATE_TIME))
  // return
  if (sheets.value.length === 0) {
    ElMessage({
      message: "没有可以导出的数据！",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
  } else {
    sheets.value.forEach(itm => {
      itm.instituionCode = env.VITE_SHEET_HOSPITAL_CODE;
      itm.instituionName = env.VITE_HOSPITAL_NAME;
      itm.certtype = itm.country === "CHN" ? "1" : "9";
      // itm.unitinfo = itm.unitName + "/" + itm.unitPlace;
      itm.unitinfo = itm.unitPlace;
      itm.admissDate = formatDateToStr(itm.admissDate,DATEFORMAT.DATE_TIME_TILT);
      itm.dismissDate = formatDateToStr(itm.dismissDate,DATEFORMAT.DATE_TIME_TILT);
      itm.birthDate = formatDateToStr(itm.birthDate,DATEFORMAT.DATE_TILT);
      itm.qualityControlDate = formatDateToStr(itm.qualityControlDate,DATEFORMAT.DATE_TILT);
      itm.surgeryDate0 = formatDateToStr(itm.surgeryDate0,DATEFORMAT.DATE_TILT);
      itm.daytimeSurgery = 0;
      itm.blank = "-";
      // console.log("DATE_TILT",itm)


      const diagList = itm.disdiagList;
      itm.otherDisdiagSize = diagList.length - 1;
      for (let i = 0; i < diagList.length; i++) {
        itm["disdiagCode" + i] = diagList[i].code;
        itm["disdiagName" + i] = diagList[i].name;
        itm["disdiagAdms" + i] = diagList[0].admissStatus;
        itm["disdiagDiss" + i] = diagList[0].dismissStatus;
      }

      const surgeryList = itm.surgeryList;
      if (surgeryList.length === 0) {
        itm.surgeryCode0 = "";
        itm.surgeryName0 = "";
        itm.surgeryDate0 = "";
        itm.surgeryLevel0 = "";
        itm.surgeryLasttime0 = "";
        itm.surgeryOptor0 = "";
        itm.surgeryAst10 = "";
        itm.surgeryAst20 = "";
        itm.surgeryWjwCh0 = "";
        itm.surgeryAnae0 = "";
        // itm.surgeryAnaeLevel0 = "";
        // itm.surgeryAnaeName0 = "";
      } else {
        for (let i = 0; i < surgeryList.length; i++) {
          itm["surgeryCode" + i] = surgeryList[i].code;
          itm["surgeryName" + i] = surgeryList[i].name;
          itm["surgeryDate" + i] = surgeryList[i].date;
          itm["surgeryLevel" + i] = surgeryList[i].level;
          itm["surgeryLasttime" + i] = "";
          itm["surgeryOptor" + i] = surgeryList[i].operatorName;
          itm["surgeryAst1" + i] = surgeryList[i].assistantOneName;
          itm["surgeryAst2" + i] = surgeryList[i].assistantTwoName;
          itm["surgeryWjwCh" + i] = surgeryList[i].wjwCutHeal;
          itm["surgeryAnae" + i] = surgeryList[i].anaesthesia;
          itm["surgeryAnaeLevel" + i] = "";
          itm["surgeryAnaeName" + i] = surgeryList[i].anaesthesiaorName;
        }
      }
    });

    const title = {
      instituionCode: "A01",
      instituionName: "A02",
      bah: "A48",
      admissTimes: "A49",
      admissDate: "B12",
      dismissDate: "B15",
      healthCardNo: "A47",
      payMethod: "A46C",
      name: "A11",
      sex: "A12C",
      birthDate: "A13",
      age: "A14",
      country: "A15C",
      marriage: "A21C",
      occupation: "A38C",
      nation: "A19C",
      certtype: "A20N",
      socialNo: "A20",
      birthPlaceName: "A22",
      nativePlace: "A23C",
      hkPlaceName: "A24",
      hkZipCode: "A25C",
      livePlace: "A26",
      phone: "A27",
      addrZipCode: "A28C",
      unitinfo: "A29",
      unitPhone: "A30",
      unitZipCode: "A31C",
      contactName: "A32",
      contactRelation: "A33C",
      contactAddrName: "A34",
      contactPhone: "A35",
      daytimeSurgery: "B38",
      zyAdmissWay: "B11C",
      admissDeptCode: "B13C",
      admissWard: "B14",
      zkWard: "B21C",
      dismissDeptCode: "B16C",
      dismissWard: "B17",
      admissDays: "B20",
      clinicDiagCode: "C01C",
      clinicDiagStr: "C02N",
      rysqk: "F01",
      ryzdbm: "F02C",
      ryzdmc: "F03N",
      ryhqzrq: "F04",
      disdiagCode0: "C03C",
      disdiagName0: "C04N",
      disdiagAdms0: "C05C",
      disdiagDiss0: "F05",
    };

    const titleConnetOne = {
      // 理想情况是在这里做其他诊断的插入
      pathologicDiagCode: "C09C",
      pathologicDiagStr: "C10N",
      blh: "C11",
      hurtReasonCode: "C12C",
      hurtReasonName: "C13N",
      allergy: "C24C",
      allergicMedicine: "C25",
      hbsAg: "F10",
      hcvAb: "F11",
      hivAb: "F12",
      deptLeader: "B22C",
      deptLeaderName: "B22",
      leaderDoctor: "B23C",
      leaderDoctorName: "B23",
      mainDoctor: "B24C",
      mainDoctorName: "B24",
      admissDoctor: "B25C",
      admissDoctorName: "B25",
      dutyNurse: "B26C",
      dutyNurseName: "B26",
      studyDoctorName: "B27",
      internshipDoctorName: "B28",
      coderName: "B29",
      qualityControlLevel: "B30C",
      qualityControlDoctorName: "B31",
      qualityControlNurseName: "B32",
      qualityControlDate: "B33",
      autopsy: "C34C",
      bloodType: "C26C",
      rh: "C27C",
      surgeryCode0: "C14x01C",
      surgeryName0: "C15x01N",
      surgeryDate0: "C16x01",
      surgeryLevel0: "C17x01",
      surgeryLasttime0: "F13",
      surgeryOptor0: "C18x01",
      surgeryAst10: "C19x01",
      surgeryAst20: "C20x01",
      surgeryWjwCh0: "C21x01C",
      surgeryAnae0: "C22x01C",
      surgeryAnaeLevel0: "F15",
      surgeryAnaeName0: "C23x01",

      
      admissAgainInOneMonth:"B36C",
      admissAgainPurpose:"B37",
      zyDismissWay:"B34C",
      dismissDestination:"B35",
      totalCost:"D01",
      selfPay:"D09",
    };

    const titleChar = {
      instituionCode: "组织机构代码",
      instituionName: "医疗机构名称",
      bah: "病案号",
      admissTimes: "住院次数",
      admissDate: "入院时间",
      dismissDate: "出院时间",
      healthCardNo: "健康卡号",
      payMethod: "医疗付费方式",
      name: "姓名",
      sex: "性别",
      birthDate: "出生日期",
      age: "年龄（岁）",
      country: "国籍",
      marriage: "婚姻",
      occupation: "职业",
      nation: "民族",
      certtype: "证件类别",
      socialNo: "证件号码",
      birthPlaceName: "出生地址",
      nativePlace: "籍贯省（自治区、直辖市）",
      hkPlaceName: "户口地址",
      hkZipCode: "户口地址邮政编码",
      livePlace: "现住址",
      phone: "现住址电话",
      addrZipCode: "现住址邮政编码",
      unitinfo: "工作单位及地址",
      unitPhone: "工作单位电话",
      unitZipCode: "工作单位邮政编码",
      contactName: "联系人姓名",
      contactRelation: "联系人关系",
      contactAddrName: "联系人地址",
      contactPhone: "联系人电话",
      daytimeSurgery: "是否为日间手术",
      zyAdmissWay: "入院途径",
      admissDeptCode: "入院科别",
      admissWard: "入院病房",
      zkWard: "转科科别",
      dismissDeptCode: "出院科别",
      dismissWard: "出院病房",
      admissDays: "实际住院（天）",
      clinicDiagCode: "门（急）诊诊断编码",
      clinicDiagStr: "门（急）诊诊断名称",
      rysqk: "入院时情况",
      ryzdbm: "入院诊断编码",
      ryzdmc: "入院诊断名称",
      ryhqzrq: "入院后确诊日期",
      disdiagCode0: "出院主要诊断编码",
      disdiagName0: "出院主要诊断名称",
      disdiagAdms0: "出院主要诊断入院病情",
      disdiagDiss0: "主要诊断出院情况",
    };

     const titleCharConnectOne = {
      // 理想情况是在这里做其他诊断的插入
      pathologicDiagCode: "病理诊断编码",
      pathologicDiagStr: "病理诊断名称",
      blh: "病理号",
      hurtReasonCode: "损伤、中毒外部原因编码",
      hurtReasonName: "损伤、中毒外部原因名称",
      allergy: "有无药物过敏",
      allergicMedicine: "过敏药物名称",
      hbsAg: "HBsAg",
      hcvAb: "HCV-Ab",
      hivAb: "HIV-Ab",
      deptLeader: "科主任编码",
      deptLeaderName: "科主任",
      leaderDoctor: "主（副主）任医师编码",
      leaderDoctorName: "主（副主）任医师",
      mainDoctor: "主治医师编码",
      mainDoctorName: "主治医师",
      admissDoctor: "住院医师编码",
      admissDoctorName: "住院医师",
      dutyNurse: "责任护士编码",
      dutyNurseName: "责任护士",
      studyDoctorName: "进修医师",
      internshipDoctorName: "实习医师",
      coderName: "编码员",
      qualityControlLevel: "病案质量",
      qualityControlDoctorName: "质控医师",
      qualityControlNurseName: "质控护师",
      qualityControlDate: "质控日期",
      autopsy: "死亡患者尸检",
      bloodType: "ABO血型",
      rh: "Rh血型",
      surgeryCode0: "主要手术操作编码",
      surgeryName0: "主要手术操作名称",
      surgeryDate0: "主要手术操作日期",
      surgeryLevel0: "主要手术操作级别",
      surgeryLasttime0: "主要手术持续时间",
      surgeryOptor0: "主要手术操作术者",
      surgeryAst10: "主要手术操作Ⅰ助",
      surgeryAst20: "主要手术操作Ⅱ助",
      surgeryWjwCh0: "主要手术操作切口愈合等级",
      surgeryAnae0: "主要手术操作麻醉方式",
      surgeryAnaeLevel0: "主要手术麻醉分级",
      surgeryAnaeName0: "主要手术操作麻醉医师",

      admissAgainInOneMonth:"是否有出院31天内再住院计划",
      admissAgainPurpose:"出院31天内再住院计划目的",
      zyDismissWay:"离院方式",
      dismissDestination:"医嘱转院、转社区卫生服务机构/乡镇卫生院名称",
      totalCost:"住院总费用",
      selfPay:"住院总费用其中自费金额",
    };

    for (let i = 1; i < 41; i++) {
      let mark = ("0" + i).slice(-2);
      title["disdiagCode" + i] = `C06x${mark}C`;
      title["disdiagName" + i] = `C07x${mark}N`;
      title["disdiagAdms" + i] = `C08x${mark}C`;
      title["disdiagDiss" + i] = `F06x${mark}`;

      titleChar["disdiagCode" + i] = `出院其他诊断编码${mark}`;
      titleChar["disdiagName" + i] = `出院其他诊断名称${mark}`;
      titleChar["disdiagAdms" + i] = `出院其他诊断入院病情${mark}`;
      titleChar["disdiagDiss" + i] = `其他诊断出院情况${mark}`;
    }

    // for (let i = 1; i < 41; i++) {
    //   let mark = ("0" + i).slice(-2);
    //   title["surgeryCode" + i] = `C35x${mark}C`;
    //   title["surgeryName" + i] = `C36x${mark}N`;
    //   title["surgeryDate" + i] = `C37x${mark}`;
    //   title["surgeryLevel" + i] = `C38x${mark}`;
    //   title["surgeryLasttime" + i] = `F14x${mark}`;
    //   title["surgeryOptor" + i] = `C39x${mark}`;
    //   title["surgeryAst1" + i] = `C40x${mark}`;
    //   title["surgeryAst2" + i] = `C41x${mark}`;
    //   title["surgeryWjwCh" + i] = `C42x${mark}C`;
    //   title["surgeryAnae" + i] = `C43x${mark}C`;
    //   title["surgeryAnaeLevel" + i] = `F16x${mark}`;
    //   title["surgeryAnaeName" + i] = `C44x${mark}`;
    // }

    const yearMonth = month.value.split("-");
    // const fileName = `${env.VITE_UNIFIED_SOCIAL_CREDIT_CODE_CODE}_${env.VITE_HOSPITAL_NAME}_${yearMonth[0]}_${yearMonth[1]}.csv`;
    const fileName = `hqmsts_${env.VITE_HOSPITAL_NAME}_${yearMonth[0]}_${yearMonth[1]}.csv`;
    exportCharCSV(sheets.value, Object.assign(title,titleConnetOne),Object.assign(titleChar,titleCharConnectOne), fileName, ",");
  }
};
</script>
