<template>
  <div class="layout_container">
    <header class="round-header">
      <el-input
        v-model="patientId"
        style="width: 100px"
        clearable
        placeholder="门诊ID"
      >
      </el-input>
      <el-select
        v-model="medType"
        style="width: 110px"
        placeholder="医疗类别"
        @change="handleMedTypeChange"
      >
        <el-option
          v-for="item in medTypes"
          :key="item.code"
          :value="item.code"
          :label="item.name"
        ></el-option>
      </el-select>
      <el-cascader
        v-model="admdvsCascader"
        clearable
        filterable
        placeholder="参保地区"
        :options="allAdmdvses"
        @change="handleAdmdvsChange"
        :disabled="injuryMode === true"
        style="width: 160px"
      ></el-cascader>
      <el-select v-model="acctUsedFlag" style="width: 118px">
        <el-option label="不使用个账" value="0"></el-option>
        <el-option label="使用本人个账" value="1"></el-option>
        <el-option label="使用共济人个账" value="2"></el-option>
      </el-select>
      <el-select v-model="patMedInsPaused" style="width: 110px">
        <el-option label="患者正常参保" value="normal"></el-option>
        <el-option label="患者已停保" value="paused"></el-option>
      </el-select>
      <el-dropdown
        trigger="click"
        @command="receiptsOpts"
        style="margin-left: 8px"
      >
        <el-button type="primary">
          处方&nbsp;
          <el-icon>
            <ArrowDown />
          </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="Document" command="require"
              >获取门诊处方</el-dropdown-item
            >
            <el-dropdown-item icon="Delete" command="delete"
              >删除所有处方</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <ReadCard :pat-no="patientId" @success="afterReadCard" />
      <el-dropdown trigger="click" @command="register">
        <el-button type="primary">
          登记&nbsp;
          <el-icon>
            <ArrowDown />
          </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="CreditCard" command="execute"
              >医保登记</el-dropdown-item
            >
            <el-dropdown-item icon="RefreshLeft" command="revoke"
              >取消登记</el-dropdown-item
            >
            <el-dropdown-item divided icon="Help" command="emergencyRescue"
              >急诊抢救</el-dropdown-item
            >
            <el-dropdown-item icon="Refresh" command="rvkEmergencyRescue"
              >急诊抢救撤销</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-dropdown
        trigger="click"
        @command="receiptsOpts"
        style="margin-left: 8px"
      >
        <el-button type="primary">
          上传&nbsp;
          <el-icon>
            <ArrowDown />
          </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="Upload" command="upload"
              >医保处方上传</el-dropdown-item
            >
            <el-dropdown-item icon="RefreshLeft" command="retract"
              >撤销处方上传</el-dropdown-item
            >
            <el-dropdown-item divided icon="Edit" command="diags"
              >医保诊断补录</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-dropdown
        trigger="click"
        @command="settlement"
        style="margin-left: 8px"
      >
        <el-button type="primary">
          结算&nbsp;
          <el-icon>
            <ArrowDown />
          </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="SetUp" command="preSettlement"
              >试算</el-dropdown-item
            >
            <el-dropdown-item icon="Stamp" command="realSettlement"
              >结算</el-dropdown-item
            >
            <el-dropdown-item
              divided
              icon="RefreshLeft"
              command="cancelSettlement"
              >取消结算</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-button style="margin-left: 8px" type="success" @click="seeMzBlRecord"
        >门诊病历</el-button
      >
      <el-button type="danger" icon="Refresh" @click="clearinfo">
        重置</el-button
      >
    </header>
    <div class="layout_main layout_container layout-horizontal">
      <aside style="display: flex">
        <div>
          <el-table
            ref="timesTable"
            :data="unPaidReceipts"
            highlight-current-row
            @row-click="clickTimes"
            empty-text="无"
            height="100%"
          >
            <el-table-column
              label="次数"
              prop="times"
              width="50"
            ></el-table-column>
            <el-table-column label="诊间" width="50">
              <template #default="scope">
                <span v-html="isMztczf(scope.row)"></span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div>
          <el-table
            ref="ordersTable"
            :data="orderNos"
            highlight-current-row
            @row-click="clickOrderNo"
            empty-text="无"
            height="100%"
          >
            <el-table-column label="处方" width="50">
              <template #default="scope">
                <span v-html="colorStatus(scope.row)"></span>
              </template>
            </el-table-column>
            <el-table-column label="金额" width="60">
              <template #default="scope">
                {{ scope.row.totalFee.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160">
              <template #default="scope">
                <button @click="markMzFees" :disabled="scope.row.status">
                  生成
                </button>
                <button
                  @click="unmarkMzFees(scope.row)"
                  :disabled="!scope.row.status"
                >
                  撤销
                </button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </aside>
      <div class="layout_main">
        <div style="height: 100%; padding: 30px; position: relative">
          <img
            v-if="mzVisit.settledFlag === 1"
            :src="mzSettled"
            alt=""
            class="tip-img"
          />
          <img
            v-if="mzVisit.vipFlag === '1'"
            :src="selfpayreceipt"
            alt=""
            class="tip-img"
          />
          <mz-receipt
            :mz-visit="mzVisit"
            :receipts="currentReceipts"
            show-checkbox
          />
        </div>
      </div>
    </div>
  </div>
  <el-dialog title="个人信息" v-model="showInsuinfo" width="65%">
    <el-tag>{{ injuryMode ? "工伤信息" : "参保信息" }}</el-tag>
    <div v-if="injuryMode">
      <el-table
        :data="injuryinfo"
        height="180"
        stripe
        @row-click="handleClickInjuryinfo"
      >
        <el-table-column label="证件号码" prop="aac002"></el-table-column>
        <el-table-column label="姓名" prop="aac003"></el-table-column>
        <el-table-column label="单位名称" prop="aab004"></el-table-column>
        <el-table-column label="受伤时间" prop="alc020"></el-table-column>
        <el-table-column label="认定申请时间" prop="alc017"></el-table-column>
        <el-table-column label="认定ID" prop="aaz127"></el-table-column>
        <el-table-column label="个人编号" prop="aac001"></el-table-column>
        <el-table-column label="参保统筹区" prop="baa027Name"></el-table-column>
      </el-table>
    </div>
    <div v-else>
      <el-table :data="psnBaseinfo.insuinfo" @row-click="handleClickInsuinfo">
        <el-table-column property="balc" label="余额"></el-table-column>
        <el-table-column label="险种类型" prop="insutypeName"></el-table-column>
        <el-table-column label="人员类别" prop="psnTypeName"></el-table-column>
        <el-table-column
          label="参保状态"
          prop="psnInsuStasName"
        ></el-table-column>
        <el-table-column
          property="psnInsuDate"
          label="个人参保日期"
        ></el-table-column>
        <el-table-column
          property="pausInsuDate"
          label="暂停参保日期"
        ></el-table-column>
        <el-table-column
          property="cvlservFlagName"
          label="公务员标志"
        ></el-table-column>
        <el-table-column
          property="insuplcAdmdvs"
          label="参保地医保区划"
        ></el-table-column>
        <el-table-column
          property="insuplcAdmdvsName"
          label="参保地名称"
        ></el-table-column>
        <el-table-column property="empName" label="单位名称"></el-table-column>
      </el-table>
      <div style="height: 16px"></div>
      <el-tag>身份信息</el-tag>
      <el-table :data="psnBaseinfo.idetinfo" stripe height="180">
        <el-table-column
          label="人员身份类别"
          prop="psnIdetTypeName"
        ></el-table-column>
        <el-table-column
          label="人员类别等级"
          prop="psnTypeLv"
        ></el-table-column>
        <el-table-column label="备注" prop="memo"></el-table-column>
        <el-table-column label="开始时间" prop="begntime"></el-table-column>
        <el-table-column label="结束时间" prop="endtime"></el-table-column>
      </el-table>
    </div>
  </el-dialog>
  <el-dialog
    title="请选择（慢特病备案信息）"
    v-model="showSpcChrAccts"
    width="40%"
  >
    <el-table :data="spcChrDiseAccts" @row-click="uploadFees">
      <el-table-column
        property="opspDiseCode"
        label="病种编码"
      ></el-table-column>
      <el-table-column
        property="opspDiseName"
        label="病种名称"
      ></el-table-column>
      <el-table-column property="begndate" label="生效日期"></el-table-column>
      <el-table-column property="enddate" label="失效日期"></el-table-column>
    </el-table>
  </el-dialog>
  <el-dialog title="请选择生育病种" v-model="showMatnDises" width="60%">
    <el-table :data="matnDises" @row-click="uploadFees" stripe height="360">
      <el-table-column property="code" label="病种编码"></el-table-column>
      <el-table-column property="name" label="病种名称"></el-table-column>
      <el-table-column property="insutype" label="险种类型"></el-table-column>
      <el-table-column property="limitAmt" label="疾病限额"></el-table-column>
    </el-table>
  </el-dialog>
  <el-dialog
    title="医保诊断补录"
    v-model="showInputDiags"
    width="60%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <outpatient-diagnose-supply
      :med-type="medType"
      :mz-visit="mzVisit"
      @close="showInputDiags = false"
    ></outpatient-diagnose-supply>
  </el-dialog>
  <el-dialog v-model="showMdtrtGrpType" title="跨省患者请选择" width="360px">
    <div>
      &nbsp;&nbsp;&nbsp;&nbsp;就诊人群类型：
      <el-select v-model="expContent.MDTRT_GRP_TYPE" style="width: 160px">
        <el-option
          v-for="item in mdtrtGrpTypes"
          :key="item.key"
          :label="item.name"
          :value="item.code"
        ></el-option>
      </el-select>
    </div>
    <div style="margin-top: 12px">
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;外伤标志：
      <el-select v-model="expContent.TRUM_FLAG" style="width: 160px">
        <el-option label="无" value="" key="trumFlag-N"></el-option>
        <el-option label="非外伤" value="0" key="trumFlag-0"></el-option>
        <el-option label="外伤" value="1" key="trumFlag-1"></el-option>
      </el-select>
    </div>
    <div style="margin-top: 12px">
      涉及第三方标志：
      <el-select v-model="expContent.REL_TTP_FLAG" style="width: 160px">
        <el-option label="无" value="" key="relTtpFlag-N"></el-option>
        <el-option label="涉及" value="0" key="relTtpFlag-0"></el-option>
        <el-option label="不涉及" value="1" key="relTtpFlag-1"></el-option>
      </el-select>
    </div>
    <div style="margin-top: 12px">
      门急诊转诊标志：
      <el-select v-model="expContent.OTP_ER_REFL_FLAG" style="width: 160px">
        <el-option label="无" value="" key="otpErReflFlag-N"></el-option>
        <el-option label="急诊" value="1" key="otpErReflFlag-1"></el-option>
        <el-option label="转诊" value="2" key="otpErReflFlag-2"></el-option>
        <el-option
          label="转诊合并急诊"
          value="3"
          key="otpErReflFlag-3"
        ></el-option>
      </el-select>
    </div>
    <div style="margin-top: 20px; width: 100%; text-align: right">
      <el-button @click="afterChooseMdtrtGrpType" type="primary" size="default"
        >确定</el-button
      >
    </div>
  </el-dialog>

  <mz-bl-record
    v-if="showMzBlRecord"
    :patient-id="patientId"
    :times="times"
    @closed="showMzBlRecord = false"
  ></mz-bl-record>

  <EmergencyRescue ref="emergencyRef" :param="emergencyParams" />
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { allAdmdvses } from "@/data/admdvs";
import {
  deleteAllMzReceipts,
  deleteMzReceipt,
  getMzReceipts,
  insertSiMzFees,
  outpatientPreSettlement,
  outpatientRegistration,
  revokeOutpatientFeeDetails,
  revokeOutpatientRegistration,
  uploadOutpatientFeeDetails,
  outpatientSettlement,
  revokeOutpatientSettlement,
} from "@/api/medical-insurance/si-outpatient";
import { ElMessageBox, ElSelect } from "element-plus";
import {
  obtainBasicPersonInfo,
  querySpecialChronicDiseasesAccreditation,
  queryMzMatnDises,
} from "@/api/medical-insurance/si-query";
import { getMedTypesByFlag } from "@/api/medical-insurance/si-dict";
import ReadCard from "@/components/medical-insurance/readcard/Index.vue";
import mzSettled from "@/assets/mz-settled.png";
import selfpayreceipt from "@/assets/selfpayreceipt.png";
import OutpatientDiagnoseSupply from "@/components/medical-insurance/outpatient-diagnose-supply/Index.vue";
import {
  employeeInfoInquiry2,
  injuryOutpatientFeeUpload,
  injuryOutpatientRegister,
  injuryOutpatientSettlement,
  revokeInjuryOutpatientFee,
  revokeInjuryOutpatientRegistration,
  revokeInjuryOutpatientSettlement,
} from "@/api/medical-insurance/si-injury";
import MzBlRecord from "@/components/outpatient/MzBlRecord.vue";
import MzReceipt from "@/components/outpatient/MzReceipt.vue";
import { useUserStore } from "@/pinia/user-store";
import { CyMessageBox } from "@/utils/cy-message-box";
import { xcMessage } from "@/utils/xiaochan-element-plus";
import { checkGeneratedFees } from "@/api/medical-insurance/emergency-rescue";
import EmergencyRescue from "@/views/medical-insurance/outpatient/component/EmergencyRescue.vue";

const medType = ref(null);
const admdvs = ref(null);
const certainAdmdvs = ref("");
const medTypes = ref([]);
const patientId = ref("");
const times = ref(null);
const unPaidReceipts = ref([]);
const showInsuinfo = ref(false);
const psnBaseinfo = ref({});
const mzVisit = ref({});
const receipts = ref({});
const orderNos = ref([]);
const currentReceipts = ref([]);
const timesTable = ref(null);
const ordersTable = ref(null);
const currentOrder = ref({});
const spcChrDiseAccts = ref([]);
const showSpcChrAccts = ref(false);
const matnDises = ref([]);
const showMatnDises = ref(false);
const showInputDiags = ref(false);

const showMdtrtGrpType = ref(false);
const patMedInsPaused = ref("normal");
const expContent = reactive({
  MDTRT_GRP_TYPE: "",
  TRUM_FLAG: "",
  REL_TTP_FLAG: "",
  OTP_ER_REFL_FLAG: "",
});
const mdtrtGrpTypes = [
  { code: "", name: "普通患者", key: "mdtrtGrpTypes-N" },
  { code: "1", name: "新冠肺炎确诊患者", key: "mdtrtGrpTypes-1" },
  { code: "2", name: "其他国家突发公共事件", key: "mdtrtGrpTypes-2" },
  { code: "3", name: "新冠肺炎疑似患者", key: "mdtrtGrpTypes-3" },
  { code: "4", name: "无症状感染者", key: "mdtrtGrpTypes-4" },
];

const injuryMode = computed(() => {
  return medType.value === "41" || medType.value === "46";
});

const injuryinfo = ref([]);

const handleClickInjuryinfo = row => {
  row.patNo = patientId.value;
  row.times = times.value;
  row.ledgerSn = 0;
  row.aka130 = medType.value;
  if (row.aka130 === "41") {
    row.bka003 = "410";
  } else if (row.aka130 === "46") {
    row.bka003 = "461";
  }
  injuryOutpatientRegister(row).then(() => {
    showInsuinfo.value = false;
    xcMessage.success("登记成功");
  });
};

const nullPatientId = () => {
  if (!patientId.value) {
    xcMessage.warning("请输入门诊id号！");
    return true;
  }
  return false;
};

const clearExpContent = () => {
  expContent.MDTRT_GRP_TYPE = "";
  expContent.TRUM_FLAG = "";
  expContent.REL_TTP_FLAG = "";
  expContent.OTP_ER_REFL_FLAG = "";
};

const nullMedType = () => {
  if (!medType.value) {
    xcMessage.warning("请先选择医疗类别！");
    return true;
  }
  return false;
};

const admdvsCascader = ref([]);
const handleMedTypeChange = val => {
  if (val === "41") {
    admdvsCascader.value = [];
    admdvs.value = null;
  }
};

const invalidateTips = () => {
  return nullPatientId() || nullTimes() || nullMedType();
};

const register = command => {
  if (invalidateTips()) {
    return;
  }
  clearExpContent();
  const param = {
    patNo: patientId.value,
    medType: medType.value,
    admdvs: admdvs.value,
    times: times.value,
    legderSn: 0,
    needSaving: 1,
    mdtrtCertType: readCardData.mdtrtCertType,
    readCardResult: readCardData.readCardResult,
    busCardInfo: readCardData.busCardInfo
  };
  if (command === "execute") {
    beforeRegister(param);
  } else if (command === "revoke") {
    revokeRegister(param);
  } else if (command === "emergencyRescue") {
    beforeEmergencyRescue(param);
  } else {
    revokeEmergencyRescue(param);
  }
};

function beforeEmergencyRescue(param) {
  if (param.medType !== "1301") {
    xcMessage.error("医疗类别请选择【急诊抢救】。");
    return;
  }
  checkGeneratedFees(param).then(() => {
    obtainBasicPersonInfo(param).then(res => {
      times.value = res.times;
      psnBaseinfo.value = res;
      showInsuinfo.value = true;
    });
  });
}

function beforeRegister(param) {
  if (param.medType === "1301") {
    xcMessage.error("医疗类别为【急诊抢救】的患者，请选择急诊抢救专用通道。");
    return;
  }
  if (injuryMode.value) {
    employeeInfoInquiry2(param).then(res => {
      injuryinfo.value = res;
      showInsuinfo.value = true;
    });
  } else {
    obtainBasicPersonInfo(param).then(res => {
      times.value = res.times;
      psnBaseinfo.value = res;
      showInsuinfo.value = true;
    });
  }
}

function revokeRegister(param) {
  if (injuryMode.value) {
    revokeInjuryOutpatientRegistration(param).then(res => {
      xcMessage.success(res);
    });
  } else {
    revokeOutpatientRegistration(param).then(res => {
      xcMessage.success(res);
    });
  }
}

const nullTimes = () => {
  if (!times.value) {
    xcMessage.warning("请先获取门诊处方！");
    return true;
  }
  return false;
};

const receiptsOpts = command => {
  if (nullPatientId()) {
    return;
  }
  if (command !== "require") {
    if (nullTimes()) {
      return;
    }
  }
  const param = {
    patNo: patientId.value,
    times: times.value,
  };
  switch (command) {
    case "require":
      fetchReceipts(param);
      break;
    case "delete":
      deleteAllMzReceipts(param).then(res => {
        xcMessage.success(res);
        fetchReceipts(param);
      });
      break;
    case "upload":
      if (injuryMode.value) {
        const param = {
          patNo: patientId.value,
          times: times.value,
          ledgerSn: 0,
          calType: 0,
        };
        injuryOutpatientFeeUpload(param).then(() => {
          injuryOutpatientSettlement(param).then(res => {
            const message =
              "处方总费用：" +
              res.totalCost +
              "，工伤报销金额：" +
              res.fundPay +
              "。";
            ElMessageBox.alert(message, "提示", {
              type: "success",
              showCancelButton: false,
            }).then(() => {});
          });
        });
      } else {
        qrySpcChrDiseAcct(param);
      }
      break;
    case "retract":
      if (injuryMode.value) {
        const param = {
          patNo: patientId.value,
          times: times.value,
          ledgerSn: 0,
        };
        revokeInjuryOutpatientFee(param).then(res => {
          xcMessage.success(res);
        });
      } else {
        revokeOutpatientFeeDetails(param).then(res => {
          xcMessage.success(res);
        });
      }
      break;
    case "diags":
      showInputDiags.value = true;
      break;
  }
};

const fetchReceipts = param => {
  clearReadCardData();
  getMzReceipts(param)
    .then(res => {
      unPaidReceipts.value = res;
      setTimeout(() => {
        timesTable.value.setCurrentRow(res[0]);
        clickTimes(res[0]);
      }, 100);
    })
    .catch(() => {
      unPaidReceipts.value = [];
      orderNos.value = [];
      currentReceipts.value = [];
    });
};

const markMzFees = () => {
  if (currentReceipts.value.length === 0) {
    xcMessage.warning("请先选择要保存的处方！");
    return;
  }
  ElMessageBox.confirm("是否将选中处方生成医保处方？", "提示", {
    type: "warning",
    confirmButtonText: "生成",
    cancelButtonText: "取消",
  })
    .then(() => {
      insertSiMzFees(currentReceipts.value).then(() => {
        currentOrder.value.status = true;
        xcMessage.success("已成功生成医保处方。");
      });
    })
    .catch(() => {});
};

const qrySpcChrDiseAcct = param => {
  if (medType.value === "51") {
    queryMzMatnDises().then(res => {
      matnDises.value = res;
      showMatnDises.value = true;
    });
  } else if (medType.value === "1401" || medType.value === "1402") {
    querySpecialChronicDiseasesAccreditation(param).then(res => {
      spcChrDiseAccts.value = res;
      showSpcChrAccts.value = true;
    });
  } else {
    uploadFees(param);
  }
};

const uploadFees = row => {
  if (medType.value === "51") {
    row.patNo = patientId.value;
    row.times = times.value;
    row.opspDiseCode = row.code;
    row.opspDiseName = row.name;
  }
  uploadOutpatientFeeDetails(row).then(res => {
    times.value = res.times;
    showSpcChrAccts.value = false;
    showMatnDises.value = false;
    if (patMedInsPaused.value === "normal") {
      mzPreSetl();
    } else {
      CyMessageBox.alert({
        type: "success",
        message: "上传成功",
      });
    }
  });
};

const readCardData = reactive({
  mdtrtCertType: null,
  readCardResult: null,
  readCardBizType: null,
  busCardInfo: null,
});

const clearReadCardData = () => {
  readCardData.mdtrtCertType = null;
  readCardData.readCardResult = null;
  readCardData.readCardBizType = null;
};

const afterReadCard = result => {
  readCardData.mdtrtCertType = result.mdtrtCertType;
  readCardData.readCardResult = result.readCardResult;
  readCardData.busCardInfo = result.busCardInfo;
  readCardData.readCardBizType = result.readCardBizType;
};

const emergencyRef = ref(null);
const emergencyParams = ref({});
const handleClickInsuinfo = row => {
  certainAdmdvs.value = row.insuplcAdmdvs;
  const param = {
    patNo: patientId.value,
    times: times.value,
    name: mzVisit.value.name,
    insutype: row.insutype,
    medType: medType.value,
    psnType: row.psnType,
    insuplcAdmdvs: row.insuplcAdmdvs,
    insuplcAdmdvsName: row.insuplcAdmdvsName,
    empName: row.empName,
    balc: row.balc,
    mdtrtCertType: readCardData.mdtrtCertType,
    readCardResult: readCardData.readCardResult,
    busCardInfo: readCardData.busCardInfo,
    readCardBizType: readCardData.readCardBizType,
  };
  if (param.medType === "1301") {
    emergencyRescueProcess(param);
  } else {
    normalOutpatientRegister(param);
  }
};

function emergencyRescueProcess(param) {
  showInsuinfo.value = false;
  emergencyParams.value = param;
  nextTick().then(() => {
    emergencyRef.value.start();
  });
}

function revokeEmergencyRescue(param) {
  if (param.medType !== "1301") {
    xcMessage.error("医疗类别请选择【急诊抢救】。");
    return;
  }
  emergencyParams.value = param;
  nextTick().then(() => {
    emergencyRef.value.revoke();
  });
}

function normalOutpatientRegister(param) {
  outpatientRegistration(param).then(res => {
    showInsuinfo.value = false;
    xcMessage.success(res);
  });
}

const clickOrderNo = row => {
  currentOrder.value = row;
  currentReceipts.value = receipts.value[row.orderNo];
  mzVisit.value.totalFee = row.totalFee.toFixed(2);
};

const clickTimes = row => {
  mzVisit.value = row.mzVisit;
  certainAdmdvs.value = mzVisit.value.admdvs;
  receipts.value = row.mzReceipts;
  orderNos.value = row.orderNos;
  times.value = row.times;
  currentReceipts.value = [];
  setTimeout(() => {
    ordersTable.value.setCurrentRow(orderNos.value[0]);
    clickOrderNo(orderNos.value[0]);
  }, 100);
};

const colorStatus = row => {
  return row.status
    ? `<span style="color: green">第${row.orderNo}张</span>`
    : `<span style="color: red">第${row.orderNo}张</span>`;
};

const unmarkMzFees = row => {
  ElMessageBox.confirm("是否将选中处方从医保处方中删除？", "提示", {
    type: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(() => {
      deleteMzReceipt(row).then(() => {
        currentOrder.value.status = false;
        xcMessage.success("已成功删除医保处方。");
      });
    })
    .catch(() => {});
};

const currentCommand = ref(null);
const settlement = command => {
  if (nullPatientId() || nullTimes()) {
    return;
  }
  if (command === "cancelSettlement") {
    revokeMzSettle();
  } else {
    if (injuryMode.value) {
      const param = {
        patNo: patientId.value,
        times: times.value,
        ledgerSn: 0,
        calType: command === "preSettlement" ? 0 : 1,
      };
      injuryOutpatientSettlement(param).then(res => {
        const title = command === "preSettlement" ? "试算成功" : "结算成功";
        const message =
          "处方总费用：" +
          res.totalCost +
          "，工伤报销金额：" +
          res.fundPay +
          "。";
        ElMessageBox.alert(message, title, {
          type: "success",
          showCancelButton: false,
        }).then(() => {});
      });
    } else {
      if (certainAdmdvs.value && certainAdmdvs.value.startsWith("43")) {
        command === "preSettlement" ? mzPreSetl() : mzSettle();
      } else {
        currentCommand.value = command;
        showMdtrtGrpType.value = true;
      }
    }
  }
};

const afterChooseMdtrtGrpType = () => {
  if (currentCommand.value) {
    currentCommand.value === "preSettlement" ? mzPreSetl() : mzSettle();
  }
  showMdtrtGrpType.value = false;
};

const userStore = useUserStore();
const mzPreSetl = () => {
  const param = {
    staffId: userStore.userInfo.code,
    patNo: patientId.value,
    times: times.value,
    acctUsedFlag: acctUsedFlag.value,
    mdtrtCertType: readCardData.mdtrtCertType,
    readCardResult: readCardData.readCardResult,
    readCardBizType: readCardData.readCardBizType,
    expContent: JSON.stringify(expContent),
  };
  outpatientPreSettlement(param).then(res => {
    const message =
      "医保处方总费用：" +
      res.totalCost +
      "，医保报销金额：" +
      res.fundPay +
      "。";
    ElMessageBox.alert(message, "试算成功", {
      type: "success",
      showCancelButton: false,
    }).then(() => {});
  });
};

const acctUsedFlag = ref("1");

const mzSettle = () => {
  const param = {
    patNo: patientId.value,
    times: times.value,
    acctUsedFlag: acctUsedFlag.value,
    mdtrtCertType: readCardData.mdtrtCertType,
    readCardResult: readCardData.readCardResult,
    readCardBizType: readCardData.readCardBizType,
    busCardInfo: readCardData.busCardInfo,
    expContent: JSON.stringify(expContent),
  };
  outpatientSettlement(param).then(res => {
    clearReadCardData();
    const message =
      "医保处方总费用：" +
      res.totalCost +
      "，医保报销金额：" +
      res.fundPay +
      "。";
    ElMessageBox.alert(message, "结算成功", {
      type: "success",
      showCancelButton: false,
    }).then(() => {});
  });
};

const revokeMzSettle = () => {
  const param = {
    patNo: patientId.value,
    times: times.value,
    ledgerSn: 0,
  };
  if (injuryMode.value) {
    revokeInjuryOutpatientSettlement(param).then(res => {
      ElMessageBox.alert(res, "提示", {
        type: "success",
        showCancelButton: false,
      });
    });
  } else {
    revokeOutpatientSettlement(param).then(res => {
      ElMessageBox.alert("撤销门诊结算成功", "提示", {
        type: "success",
        showCancelButton: false,
      });
    });
  }
};

const isMztczf = row => {
  return row.zgmztczf === 1
    ? `<span style="color: green">医保</span>`
    : `<span>自费</span>`;
};

const clearinfo = () => {
  patientId.value = "";
  times.value = null;
  unPaidReceipts.value = [];
  psnBaseinfo.value = {};
  mzVisit.value = {};
  receipts.value = {};
  orderNos.value = [];
  currentReceipts.value = [];
  timesTable.value = null;
  ordersTable.value = null;
  currentOrder.value = {};
  spcChrDiseAccts.value = [];
};

const handleAdmdvsChange = val => {
  admdvs.value = val ? val[1] : null;
};

const showMzBlRecord = ref(false);
function seeMzBlRecord() {
  if (nullTimes()) {
    return;
  }
  showMzBlRecord.value = true;
}

onMounted(() => {
  getMedTypesByFlag("clinic").then(res => {
    medTypes.value = res;
  });
});
</script>

<style scoped lang="scss">
.tip-img {
  z-index: 999;
  width: 230px;
  position: absolute;
  top: 160px;
  left: 260px;
  background: rgba(255, 255, 255, 0.5);
}
</style>
