<template>
  <el-container>
    <el-header height="50px">
      <el-tag effect="dark" size="small">患者姓名: {{ patient.name }}</el-tag>
      <el-tag effect="dark" size="small">住院号: {{ patient.inpatientNo }}</el-tag>
      <el-tag effect="dark" size="small">床号: {{ patient.bedNo }}</el-tag>
      <el-tag effect="dark" size="small">住院次数: {{ patient.admissTimes }}</el-tag>
      <el-tag effect="dark" size="small">性别: {{ cptSex(patient.sex) }}</el-tag>
      住院号：
      <el-input v-model="inpatientNo" clearable placeholder="住院号" style="width: 100px"></el-input>
      <el-button icon="Search" type="primary" @click="chaXunHuanZheXinXi">查询患者信息</el-button>
      <el-button icon="Close" style="margin-left: 20px" type="danger" @click="guanBiDialog">关闭</el-button>
      <el-button style="margin-left: 20px" type="warning" @click="chaoZuoZhiNan = true">操作指南</el-button>
    </el-header>
    <el-container>
      <el-main>
        <el-dialog v-model="chaoZuoZhiNan" title="操作指南">
          <el-collapse v-model="activeName" accordion>
            <el-collapse-item name="1" title="一、搜索">
              <div>1、搜索费用：项目名称一栏，可以根据编码、名称 、拼音首字母缩写查找（推荐使用编码查询这样会快一些，可选）
              </div>
              <div>2、录入日期：项目的录入时间范围（可选）， 日期排序-降序从大到小排序，升序-从小到大排序</div>
              <div>3、费用类型：你需要查找的费用是，项目还是药品（请不要选择项目后一直搜索药品，这样是找不到的 ヽ(ー_ー)ノ）</div>
              <div>4、录入类型：该费用是怎么产生，护士录入，医嘱，医技</div>
              <div>
                5、费用状态：未退-代表该费用没有被退，已退-代表费用是退费数据，被退-代表那些正的被退了
                <span
                    style="color: red">（该条件只对在本系统中有效,如果无效请点击退费匹配 (退费匹配就在本页面的关闭旁边)，或选择全部）</span><br/>
              </div>
              <div>6、点击查询即可查询费用（如提示没有数据，请检查搜索的条件）</div>
            </el-collapse-item>
            <el-collapse-item name="2" title=" 二、退费"> 1、选中表格中的多选按钮（小框框），然后点击退费即可，请仔细检查
            </el-collapse-item>
            <el-collapse-item name="3" title=" 三、撤销退费">
              <div>
                1、如果退费退错了，可以点击费用后面的撤销按钮，前提是该费用没有被上传到医保，如果已经上传了且你一定要把这一条费用完全删除，那请先要医保科撤销上传。
              </div>
              <div>2、如果需要撤销退费的权限，请向信息科，提供工号，该权限只能提供给护士长。</div>
            </el-collapse-item>
            <el-collapse-item name="4" title="  四、录入模板">
              <div>
                1、模板：进入系统会查询出您所在科室的模板（如果没有看见模板，请在个人中心中查看你的科室，如果不对请人资进行调整）
              </div>
              <div>
                2、取模板：点击模板的名字后，出现一个小表格，然后点击小表格中的多选按钮，你所选择的费用会显示在录入信息的表格中（无法重复添加）
              </div>
              <div>3、存模板：请在录入信息中添加你需要存的费用信息，然后点击存模板，会弹出一个对话框，输入名称，点击保存即可
              </div>
              <div>4、修改：取一个一模一样名称的模板，即可修改，前提是这个模板是你创建的。</div>
              <div>5、删除：点击模板名称后面的删除。</div>
            </el-collapse-item>
            <el-collapse-item name="5" title="五、录入费用">
              <div>1、请选择需要录入的费用（如果模板中没有，请点击新增，然后进行搜索，可根据 名称、编码、首字母缩写
                搜索，然后在下拉框中点击对应的费用）
              </div>
              <div>2、确认这些费用后点击保存即可</div>
              <div>
                3、修改执行科室，如果有费用需要录入到，别的科室可以点击表格中的执行科室修改，也可以一键修改，就在新增右边，在下拉框（这个可以根据中文来搜索）
                选择对应的科室后点击修改执行科室。
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-dialog>
        <el-tabs v-model="xmlrTabs">
          <el-tab-pane label="已录入项目" name="ylrxm">
            项目名称：
            <xc-combo-grid v-model="patient"
                           clearable
                           style="width: 220px"
                           code="chargeCode"
                           name="chargeName"
                           :query-data-func="getChargeCode">
              <el-table-column label="规格" prop="specification" width="250" show-overflow-tooltip/>
              <el-table-column label="厂家" prop="manufactor" width="250" show-overflow-tooltip/>
            </xc-combo-grid>
            医嘱号:
            <el-input v-model="patient.actOrderNo" clearable placeholder="医嘱号" style="width: 120px"/>
            录入日期：
            <el-date-picker
                v-model="dateRange"
                :shortcuts="shortcuts"
                end-placeholder="结束日期"
                placeholder="选择日期"
                range-separator="至"
                start-placeholder="开始日期"
                style="width: 280px"
                type="daterange"
            ></el-date-picker>
            <el-button :icon="riQiPaiXu === 'DESC' ? 'CaretBottom' : 'CaretTop'" type="success"
                       @click="riQiPaiXu === 'DESC' ? (riQiPaiXu = 'ASC') : (riQiPaiXu = 'DESC')"
            >{{ riQiPaiXu === 'DESC' ? '日期降序' : '日期升序' }}
            </el-button>
            <el-select v-model="feiYongLeiXingCode" style="width: 70px" @change="queryFeiYong">
              <el-option v-for="item in feiYongLeiXing" :key="item.code" :label="item.name" :value="item.code">
                <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
                <el-divider direction="vertical"></el-divider>
                <span>{{ item.name }}</span>
              </el-option>
            </el-select>
            <el-select v-model="patient.orderNo" style="width: 70px">
              <el-option v-for="item in yiZhuTuiFeiLeiXing" :key="item.code" :label="item.name" :value="item.code">
                <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
                <el-divider direction="vertical"></el-divider>
                <span>{{ item.name }}</span>
              </el-option>
            </el-select>
            <el-select v-model="patient.tuiFeiFlag" style="width: 70px">
              <el-option v-for="item in tuiFeiLeiXin" :key="item.code" :label="item.name" :value="item.code">
                <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
                <el-divider direction="vertical"></el-divider>
                <span>{{ item.name }}</span>
              </el-option>
            </el-select>
            <el-button icon="Search" type="primary" @click="queryFeiYong">查询</el-button>
            <el-button icon="Delete" type="danger" @click="xiangMuTuiFeiClick">退费</el-button>
            <!--     退费的费用详细       -->
            <refund-for-project-entry
                @refreshFee="queryFeiYong"
                :is-drug="feiYongLeiXingCode === 1"
                v-if="refundConfirmation.dialog"
                @uncheck="refundUncheck"
                :patient="patient"
                v-model="refundConfirmation.dialog"
                :list="refundConfirmation.data"/>
            <el-button v-if="store.state.user.info.roles.findIndex((i) => i === 1 || i === 8) > -1" type="warning"
                       @click="sheZhiWeiYiVBao">设为医保
            </el-button>
            <el-table :data="cptTableDataHuanZheFeiYong"
                      :height="tableHeight"
                      class="eltable"
                      highlight-current-row
                      row-key="rowId"
                      ref="elTableRef"
                      stripe @selection-change="handleSelectionChange">
              <el-table-column style="width: 100px" type="selection" :reserve-selection="true"></el-table-column>
              <el-table-column label="流水号" prop="detailSn" width="70px"></el-table-column>
              <el-table-column label="医嘱号" prop="orderNo" width="70px"></el-table-column>
              <el-table-column label="录入日期" prop="chargeDate" width="70px"></el-table-column>
              <el-table-column label="项目编码" prop="chargeCodeMx"></el-table-column>
              <el-table-column label="项目名称" prop="chargeName"></el-table-column>
              <el-table-column label="规格" v-if="feiYongLeiXingCode !== 1" prop="specification"></el-table-column>
              <el-table-column v-if="feiYongLeiXingCode === 1" label="药品名称" prop="drugname"></el-table-column>
              <el-table-column label="执行科室" prop="execDept"></el-table-column>
              <el-table-column label="申请科室" prop="deptCode"></el-table-column>
              <el-table-column label="金额" prop="chargeFee"></el-table-column>
              <el-table-column label="数量" prop="chargeAmount"></el-table-column>
              <el-table-column label="状态" prop="chargeStatus">
                <template #default="scope">
                  {{ costState(scope.row.chargeStatus) }}
                </template>
              </el-table-column>
              <el-table-column label="录入人" prop="opName"></el-table-column>
              <el-table-column label="账单码" prop="billItemName"></el-table-column>
              <el-table-column label="是否退费" prop="tuiFeiFlag">
                <template #default="scope">
                  <span v-html="conversionRefundFlag(scope.row.oriDetailSn)" style="color:red;"></span>
                  <br>
                  <span v-if="scope.row.oriDetailSn > 0">
                    <span style="color: #e6a23c">退费数据</span> <br/>
                    <span style="color: teal">
                      原流水号为 <br/>
                      【 {{ scope.row.oriDetailSn }} 】
                    </span>
                  </span>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
                :current-page="patient.currentPage"
                :page-size="patient.pageSize"
                :page-sizes="[20, 30, 40, 50]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                style="margin-top: 5px"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            ></el-pagination>
          </el-tab-pane>
          <!-- 项目录入 -->
          <el-tab-pane v-if="panDuanSFTongGuoBingShiJinRu" label="项目录入" name="xmlr">
            <el-row>
              <el-col :span="3">
                <HuoQuMuBan @selectionFeiYong="xuanZeXiangMuTable"></HuoQuMuBan>
              </el-col>
              <el-col :offset="1" :span="20">
                <el-row>
                  <el-col :span="24" style="margin-top: 10px">
                    <el-button icon="StarOff" type="warning" @click="baoCunMuBanDialog = true">存模板</el-button>
                    <el-button icon="Upload" type="primary" @click="shangChuanXiangMu">保存</el-button>
                    <el-button icon="Plus" type="success" @click="xinZhengXiangMuDialog = true">新增</el-button>
                    <el-select v-model="zhiXingKeShi" filterable style="width: 180px; margin: 0px 10px 0px 10px">
                      <el-option v-for="item in deptData" :key="item.code" :label="item.name" :value="item.code">
                        <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
                        <el-divider direction="vertical"></el-divider>
                        <span>{{ item.name }}</span></el-option
                      >
                    </el-select>
                    <el-button icon="Edit" type="warning" @click="xieGaiZhiXingKeShi">修改执行科室</el-button>
                  </el-col>
                  <el-col :span="24">
                    <!-- 这个下面查看录入的项目 -->
                    <el-table :data="muBanNeiRongData" :height="tableHeight - 27" class="eltable" highlight-current-row
                              stripe style="margin-top: 10px">
                      <el-table-column label="录入信息">
                        <el-table-column label="录入时间">
                          <template #default>
                            {{ getDatetime(new Date()) }}
                          </template>
                        </el-table-column>
                        <el-table-column label="项目编码" prop="chargeCodeMx"></el-table-column>
                        <el-table-column label="名称" prop="chargeName"></el-table-column>
                        <el-table-column label="执行科室" prop="deptCode">
                          <template #default="scope">
                            <el-select v-model="scope.row.deptCode" filterable style="width: 90%">
                              <el-option v-for="item in deptData" :key="item.code" :label="item.name"
                                         :value="item.code">
                                <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
                                <el-divider direction="vertical"></el-divider>
                                <span>{{ item.name }}</span></el-option
                              >
                            </el-select>
                          </template>
                        </el-table-column>
                        <el-table-column label="单价" prop="chargeAmount"></el-table-column>
                        <el-table-column label="数量" prop="amount" width="130">
                          <template #default="scope">
                            <!--precision 限制输入的精度 0 就是不带任何一位小数点  -->
                            <el-input-number v-model="scope.row.amount" :min="0" :precision="1"
                                             style="width: 120px"></el-input-number>
                          </template>
                        </el-table-column>
                      </el-table-column>
                      <el-table-column label="金额">
                        <template #default="scope">
                          {{ (scope.row.chargeAmount * scope.row.amount).toFixed(2) }}
                        </template>
                      </el-table-column>
                      <el-table-column label="账单码" prop="billItemName"></el-table-column>
                      <el-table-column label="规格" prop="descriptions"></el-table-column>
                      <el-table-column label="操作">
                        <template #default="scope">
                          <el-button type="danger" @click="shanChuXiangMuClick(scope.$index)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <el-tag> 项目总价：{{ xiangMuZongJia }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
        <el-dialog v-model="xinZhengXiangMuDialog" :width="1500" title="新增项目">
          <el-row>
            <el-col :span="24">
              搜索：
              <el-select v-model="chargePyCode" :remote-method="rmChargePyCode" clearable default-first-option
                         filterable remote @change="getDanGeXiangMu">
                <el-option
                    v-for="item in xiangMuData.slice((danGeXiangMuCurrentPage - 1) * 20, danGeXiangMuCurrentPage * 20)"
                    :key="item.chargeCode"
                    :label="item.chargeName"
                    :value="item.chargeCode"
                >
                  <span style="color: #ff0000; font-size: 12px">{{ item.chargeCode }}</span>
                  <el-divider direction="vertical"></el-divider>
                  <span> {{ item.chargeName }}
                    <span v-if="item.descriptions">
                         ({{ item.descriptions }})
                    </span>
                  </span>
                  <el-divider direction="vertical"></el-divider>
                  <span style="color: red"> {{ item.ybComment }}</span>
                  <el-divider direction="vertical"></el-divider>
                  <span style="color: #2eff00"> {{ item.chargeAmount }} 元</span>
                  <el-divider direction="vertical"></el-divider>
                </el-option>
                <el-pagination
                    :current-page="danGeXiangMuCurrentPage"
                    :page-size="20"
                    :pager-count="5"
                    :total="xiangMuData.length"
                    layout=" prev, pager, next,total"
                    small
                    style="margin-top: 5px"
                    @current-change="danGeXiangMuCurrentChange"
                ></el-pagination>
              </el-select>
              <el-button type="success" @click="danGeXiangMuBaoCun">保存</el-button>
            </el-col>
            <el-col :span="24">
              <el-table :data="danGeLuRuXiangMu" class="eltable">
                <el-table-column label="项目代码" prop="chargeCodeMx"></el-table-column>
                <el-table-column label="项目名称" prop="chargeName"></el-table-column>
                <el-table-column label="单位" prop="spec"></el-table-column>
                <el-table-column label="执行科室" prop="deptCode">
                  <template #default="scope">
                    <el-select v-model="scope.row.deptCode" filterable style="width: 90%">
                      <el-option v-for="item in deptData" :key="item.code" :label="item.name" :value="item.code">
                        <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
                        <el-divider direction="vertical"></el-divider>
                        <span>{{ item.name }}</span></el-option
                      >
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="国家编码" prop="nationalCode"></el-table-column>
                <el-table-column label="国家名称" prop="nationalName"></el-table-column>
                <el-table-column label="单价" prop="chargeAmount"></el-table-column>
                <el-table-column label="数量" prop="amount">
                  <template #default="scope">
                    <el-input-number v-model="scope.row.amount" :min="1" :precision="1"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="金额">
                  <template #default="scope">
                    {{ (scope.row.chargeAmount * scope.row.amount).toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column label="账单码" prop="billItemName"></el-table-column>
                <el-table-column label="规格" show-overflow-tooltip prop="descriptions"></el-table-column>
                <el-table-column label="删除">
                  <template #default="scope">
                    <el-button @click="danGeLuRuXiangMu.splice(scope.$index, 1)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-dialog>
        <el-dialog v-model="baoCunMuBanDialog" title="保存模板">
          <el-row>
            <el-col :span="24">
              模板名称：
              <el-input v-model="cunMuBanPojo.name" maxlength="15" show-word-limit @blur="zhuanPinYin"></el-input>
            </el-col>
            <el-col :span="12">
              拼音码：
              <el-input v-model="cunMuBanPojo.pyCode" maxlength="8" show-word-limit></el-input>
            </el-col>
            <el-col :span="12">
              五笔码：
              <el-input v-model="cunMuBanPojo.dcode" maxlength="8" show-word-limit></el-input>
            </el-col>
            <el-col :span="12">
              创建科室：
              <el-input v-model="cunMuBanPojo.dept" disabled></el-input>
            </el-col>
            <el-col :span="12">
              <el-button icon="Upload" style="margin-top: 10px" type="primary" @click="baoCunMuBan">保存</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-main>
    </el-container>
  </el-container>
</template>

<script name="xiangMuLuRu" setup>
import store from '@/store'
import {costState, cptSex, conversionRefundFlag} from '@/utils/computed'
import {shortcuts} from '@/data/shortcuts'
import {
  getChargeCode,
  getHuanZheFeiYong,
  getPyCode,
  queryDanGeXiangMu,
  shangChuanMuBan,
  xiangMuFeiYongShangChuan,
  xiuGaiZiFeiBiaoZhi,
} from '@/api/inpatient/xiang-mu-lu-ru'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getDateRangeFormatDate, getDatetime} from '@/utils/date'
import {clone} from '@/utils/clone'
import {getPatientInfo} from '@/api/inpatient/patient'
import {feiYongLeiXing, tuiFeiLeiXin, yiZhuTuiFeiLeiXing} from '@/data'
import HuoQuMuBan from '@/components/med-tec-mod/HuoQuMuBan.vue'
import {getDept} from '@/api/public-api'
import {baseinfo} from '@/data/inpatient'
import {listIsBlank} from '@/utils/blank-utils'
import Sleep from "@/utils/sleep";
import RefundForProjectEntry from "@/components/med-tec-mod/RefundForProjectEntry";
import XcComboGrid from "@/components/xiao-chan/combo-grid/XcComboGrid.vue";

const emit = defineEmits(['close-xmlr'])

const windowSize = store.state.app.windowSize
const tableHeight = windowSize.h - 170
const chaoZuoZhiNan = ref(false)

// 默认选中已录入项目
const xmlrTabs = ref('ylrxm')
const inpatientNo = ref('')
const zhiXingKeShi = ref('')
const dateRange = ref([])
// DESC 降 ASC 升
const riQiPaiXu = ref('DESC')
const activeName = ref('1')
const feiYongLeiXingCode = ref(0)

/**
 * 录入费用 表格
 */
const tableDataHuanZheFeiYong = ref([])

// 获取全部科室
const deptData = ref([])

// 患者信息
const patient = ref({})

/**
 * 判断这个操作员是否可以退费
 */
const panDuanSFTongGuoBingShiJinRu = ref(false)

// 弹框 输入住院号
const jinRuPanDuanSFXieDaiHuanZheXinXi = async () => {
  await Sleep(300)
  ElMessageBox.prompt('请输入患者住院号', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S/,
    inputErrorMessage: '患者住院号不能为空 (∩•̀ω•́)⊃-*⋆',
    type: 'warning',
  })
      .then(({value}) => {
        inpatientNo.value = value
        chaXunHuanZheXinXi()
      })
      .catch(() => {
        guanBiDialog()
      })
}

/**
 * 这个是 用户没有选择患者 就进来执行的
 */
const chaXunHuanZheXinXi = () => {
  getPatientInfo(inpatientNo.value)
      .then((res) => {
        patient.value = res
        setDefault()
        queryFeiYong()
        if (patient.value.ward === store.state.user.info.deptCode) {
          panDuanSFTongGuoBingShiJinRu.value = true
        } else {
          xmlrTabs.value = 'ylrxm'
          panDuanSFTongGuoBingShiJinRu.value = false
        }
      })
      .catch(() => {
        patient.value = {}
        jinRuPanDuanSFXieDaiHuanZheXinXi()
      })
}

const total = ref(0)
const elTableRef = ref()
/**
 * 查询
 */
const queryFeiYong = () => {
  elTableRef.value.clearSelection()
  let dateR = getDateRangeFormatDate(dateRange.value);
  patient.value.startTime = dateR.startTime
  patient.value.endTime = dateR.endTime
  patient.value.riQiPaiXu = riQiPaiXu.value
  patient.value.feiYongLeiXingCode = feiYongLeiXingCode.value
  patient.value.currentPage = 1
  patient.value.total = 0
  getHuanZheFeiYong(patient.value)
      .then(async (res) => {
        tableDataHuanZheFeiYong.value = []
        cptTableDataHuanZheFeiYong.value = []
        await Sleep(100)
        tableDataHuanZheFeiYong.value = res
        cptTableDataHuanZheFeiYong.value = res.records
        total.value = res.total
        if (patient.value.admissWard === store.state.user.info.deptCode) {
          panDuanSFTongGuoBingShiJinRu.value = true
        }
      })
      .catch(() => {
        tableDataHuanZheFeiYong.value = []
        cptTableDataHuanZheFeiYong.value = []
        patient.value.total = 0
      })
}

const handleQueryFeiYong = () => {
  let dateR = getDateRangeFormatDate(dateRange.value)
  patient.value.startTime = dateR.startTime
  patient.value.endTime = dateR.endTime
  patient.value.riQiPaiXu = riQiPaiXu.value
  patient.value.feiYongLeiXingCode = feiYongLeiXingCode.value
  patient.value.total = total.value
  getHuanZheFeiYong(patient.value)
      .then(async (res) => {
        tableDataHuanZheFeiYong.value = []
        cptTableDataHuanZheFeiYong.value = []
        await Sleep(100)
        tableDataHuanZheFeiYong.value = res
        cptTableDataHuanZheFeiYong.value = res.records
        if (patient.value.admissWard === store.state.user.info.deptCode) {
          panDuanSFTongGuoBingShiJinRu.value = true
        }
      })
      .catch(() => {
        tableDataHuanZheFeiYong.value = []
        cptTableDataHuanZheFeiYong.value = []
        patient.value.total = 0
      })
}

/**
 * 分页
 */
const handleSizeChange = (val) => {
  patient.value.pageSize = val
  handleQueryFeiYong()
}

const handleCurrentChange = (val) => {
  patient.value.currentPage = val
  handleQueryFeiYong()
}

/**
 * 获取多选框的值
 */
const handleSelectionChange = (val) => {
  patient.value.list = val
}
/** */
const cptTableDataHuanZheFeiYong = ref([])

/**
 *  项目退费
 */
let refundConfirmation = $ref({
  dialog: false,
  data: []
})

/**
 * 退费取消选中
 * @param val
 */
const refundUncheck = (val) => {
  elTableRef.value.toggleRowSelection(val, false)
}

const xiangMuTuiFeiClick = () => {
  refundConfirmation.data = elTableRef.value.getSelectionRows()
  if (refundConfirmation.data.length === 0) {
    ElMessage.error('请先选择退费数据')
  } else {
    refundConfirmation.dialog = true
  }
}

//////////////////////////////////// 以上全部是 已录入项目 //////////////////////////////////////////////////////////////////////////////

/**
 * 获取项目模板详情的数据
 */
const muBanNeiRongData = ref([])
// 保存 code 不要重复添加
let muBanCode = []
const xuanZeXiangMuTable = (param) => {
  let val = param.val
  for (let i = 0; i < val.length; i++) {
    let code = val[i].chargeCodeMx
    if (muBanCode.indexOf(code) === -1) {
      muBanCode.push(code)
      val[i].deptCode = patient.value.zkWard
      muBanNeiRongData.value.push(val[i])
    }
  }
}

/**
 * 删除项目
 */
const shanChuXiangMuClick = (index) => {
  muBanNeiRongData.value.splice(index, 1)
  muBanCode.splice(index, 1)
}
/**
 * 获取项目的总价
 */
const xiangMuZongJia = computed(() => {
  let sum = 0
  for (let i = 0; i < muBanNeiRongData.value.length; i++) {
    sum += muBanNeiRongData.value[i].chargeAmount * muBanNeiRongData.value[i].amount
  }
  return sum.toFixed(2)
})

//以下全部是  新增项目 对话框功能

/**
 * 新增项目
 */
const xinZhengXiangMuDialog = ref(false)

// 项目拼音的code
const chargePyCode = ref('')
// 项目数据
const xiangMuData = ref([])

/**
 * 远程搜索
 */
const rmChargePyCode = (val) => {
  if (val.length >= 2) {
    queryDanGeXiangMu(val, 0).then((res) => {
      xiangMuData.value = res
    })
  }
}
const danGeXiangMuCurrentPage = ref(1)

const danGeXiangMuCurrentChange = (val) => {
  danGeXiangMuCurrentPage.value = val
}
/**
 * 用来获取新增对画框中选择的项目
 */
const danGeLuRuXiangMu = ref([])

const getDanGeXiangMu = () => {
  xiangMuData.value.filter((item) => {
    if (item.chargeCode === chargePyCode.value) {
      item.deptCode = patient.value.zkWard
      danGeLuRuXiangMu.value.push(item)
    }
  })
}

/**
 * 单个项目保存
 */
const danGeXiangMuBaoCun = () => {
  if (danGeLuRuXiangMu.value.length === 0) {
    ElMessage.error('请选择需要添加的项目')
    return
  }
  for (let i = 0; i < muBanNeiRongData.value.length; i++) {
    if (muBanNeiRongData.value[i].chargeCodeMx === danGeLuRuXiangMu.value[0].chargeCodeMx) {
      ElMessage.error({
        message: '已存在相同项目请勿重复添加',
        showClose: true,
      })
      return
    }
  }
  muBanCode.push(clone(danGeLuRuXiangMu.value[0].chargeCodeMx))
  muBanNeiRongData.value.push(clone(danGeLuRuXiangMu.value[0]))
  danGeLuRuXiangMu.value = []
  chargePyCode.value = ''
}
//以上全部是  新增项目 对话框功能

// 下面就是上传 项目
const shangChuanXiangMu = () => {
  if (muBanNeiRongData.value.length === 0) {
    ElMessage.error({
      message: '请先选择需要上传的费用',
      showClose: true,
    })
    return
  }
  for (let i = 0; i < muBanNeiRongData.value.length; i++) {
    if (muBanNeiRongData.value[i].deptCode === '') {
      ElMessage.error({
        message: '【' + muBanNeiRongData.value[i].chargeName + '】的执行科室为空',
        showClose: true,
      })
      return
    }
  }
  let shangChuanFeiYong = {
    inpatientNo: patient.value.inpatientNo,
    admissTimes: patient.value.admissTimes,
    ledgerSn: patient.value.ledgerSn,
    dept: patient.value.admissDept,
    zySerialNo: patient.value.zySerialNo,
    ward: patient.value.zkWard,
    referPhysician: patient.value.referPhysician,
    list: muBanNeiRongData.value,
    orderNo: 0,
  }
  // 在此处上传
  ElMessageBox.confirm('共上传【' + muBanNeiRongData.value.length + '】条', '请认真核对', {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
  })
      .then(() => {
        xiangMuFeiYongShangChuan(shangChuanFeiYong).then(() => {
          muBanNeiRongData.value = []
          muBanCode = []
        })
      })
      .catch(() => {
      })
}

// 上面就是上传 项目

// 下面就是保存的模板信息
const cunMuBanPojo = ref({
  pyCode: '',
  dcode: '',
  name: '',
  paiXu: '',
  dept: '',
  deptCode: store.state.user.info.deptCode,
  list: [],
})

const baoCunMuBanDialog = ref(false)
const baoCunMuBan = () => {
  if (muBanNeiRongData.value.length === 0) {
    ElMessage.error({
      message: '请先选择项目',
      showClose: true,
    })
    return
  }
  if (cunMuBanPojo.value.name === '' || cunMuBanPojo.value.pyCode === '' || cunMuBanPojo.value.dcode === '') {
    ElMessage.error({
      message: '模板名称，拼音码，五笔码不能为空',
      showClose: true,
    })
    return
  }
  cunMuBanPojo.value.list = clone(muBanNeiRongData.value)
  // 开始上传
  shangChuanMuBan(cunMuBanPojo.value).then(() => {
    cunMuBanPojo.value = {}
  })
}

// 获取到保存模板的拼音码和五笔码
const zhuanPinYin = () => {
  getPyCode(cunMuBanPojo.value.name).then((res) => {
    cunMuBanPojo.value.pyCode = res.pyCode
    cunMuBanPojo.value.dcode = res.wbCode
  })
}

// 上面就是保存的模板信息

/** 关闭 对话框 */
const guanBiDialog = () => {
  emit('close-xmlr')
}

/**
 * 设置患者默认值
 */
const setDefault = () => {
  patient.value.currentPage = 1
  patient.value.pageSize = 40
  patient.value.total = 0
  patient.value.tuiFeiFlag = 3
  patient.value.orderNo = 2
  patient.value.deptCode = store.state.user.info.deptCode
  zhiXingKeShi.value = patient.value.zkWard
}

onMounted(async () => {
  if (!baseinfo().inpatientNo) {
    await jinRuPanDuanSFXieDaiHuanZheXinXi()
  } else {
    patient.value = clone(baseinfo())
    panDuanSFTongGuoBingShiJinRu.value = true
    await nextTick()
    setDefault()
    queryFeiYong()
  }

  getDept().then((res) => {
    deptData.value = res
  })
})


const xieGaiZhiXingKeShi = () => {
  for (let i = 0; i < muBanNeiRongData.value.length; i++) {
    muBanNeiRongData.value[i].deptCode = zhiXingKeShi.value
  }
}

const sheZhiWeiYiVBao = () => {
  if (listIsBlank(patient.value.list)) {
    ElMessage.error('请先选择需要修改的数据')
    return
  }
  ElMessageBox.confirm('请仔细检查.', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        xiuGaiZiFeiBiaoZhi(patient.value)
      })
      .catch(() => {
      })
}

</script>

<style></style>
