<template>
  <div class="layout_container">
    <header>
      <PatientBaseList ref="patientBaseListRef" @selectPatientInfo="selectPatient"></PatientBaseList>
    </header>
    <div class="layout_main">
      <el-container>
        <el-header style="height: 90px">
          <div style="width: 100%" >
          <el-form label-width="100px" size="large">
            <el-row style="width: 100%">
              <el-col  :span="4" >
                <el-form-item v-show="setShowFlag" label="结算类型:">
                  <el-input v-model="settData.settleTypeName" disabled style="width: 100px"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4" >
                <el-form-item v-show="setShowFlag" label="自付:">
                  <el-input v-model="settData.zfJe" disabled style="width: 100px"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4" >
                <el-form-item v-show="setShowFlag" :label="settData.settleName">
                  <el-input v-model="settData.settle" disabled style="width: 100px"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4" >
                <el-form-item v-show="setShowFlag" label="实收:">
                  <el-input-number v-model="settData.ssJe" :controls="false" :precision="2" :min="0" />
                </el-form-item>
              </el-col>
              <el-col :span="4" >
                <el-form-item v-show="setShowFlag" label="找还:">
                  <el-input v-model="settData.zhje" disabled style="width: 80px"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4" v-if="fpVersion ==='0'">
                <el-form-item label="当前发票号:">
                  <span  style="display: inline-block;width: 110px;background-color: #0f5e0f;text-align: center;color: #2eff00;font-size: 18px">{{settData.currentNoStr}}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
            <div style="height:25px">
              <el-button :disabled="saveFlag" icon="Check" type="success" @click="saveCashData">保存</el-button>
              <el-button :disabled="qxFlag"  icon="Minus" type="danger" @click="cancelCash">取消出纳</el-button>
              <el-button  type="primary" icon="RefreshLeft"  @click="chongZhiData" >重置</el-button>
              <el-button  type="primary" icon="Money"  @click="openPos" >智能POS工具包</el-button>
            </div>
          </div>
        </el-header>
        <el-container>
          <el-aside style="width: 60%">
              <div  style="height: 60%">
                <div class="border_solid layout_overflow_auto" style="float: left;width: 40%;height: 100%">
                  <el-divider border-style="dashed" content-position="left" >记账信息</el-divider>
                    <el-table :data="jzInfoList" style="width: 100%"  height="200">
                      <el-table-column  property="ybType" label="类型" />
                      <el-table-column  property="ybJzJe" label="金额" />
                    </el-table>
                </div>

                <div class="border_solid layout_overflow_auto" style="float: right;width: 58%;height: 100%">
                  <el-divider border-style="dashed" content-position="left" >交款信息</el-divider>
                    <el-table :data="jkInfoList" style="width: 100%"  height="180">
                      <el-table-column width="80"  label="操作" >
                        <template #default="scope">
                          <el-button v-if="scope.row.settType ==='交纳' && (scope.row.depoType==='3' || scope.row.depoType==='O') "  type="primary" @click="shuaKa(scope.row,scope.$index)">刷卡/扫码</el-button>
                        </template>
                      </el-table-column>
                      <el-table-column  property="settType" width="50" />
                      <el-table-column  property="depoType" label="类型" >
                        <template #default="scope">
                          <el-select v-model="scope.row.depoType" style="width: 100px">
                            <el-option v-for="item in zdChequeTypes" :key="item.code" :label="item.name" :value="item.code"></el-option>
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column  property="depoAmount" label="金额" width="120">
                        <template #default="scope">
                          <el-input-number v-model="scope.row.depoAmount" @blur="calcJkJe" :controls="false" :precision="2" :min="0" size="small" style="width: 100px"/>
                        </template>
                      </el-table-column>
                      <el-table-column  property="chequeNo" label="凭证号" >
                        <template #default="scope">
                          <el-input v-model="scope.row.chequeNo"   size="small" style="width: 100px"/>
                        </template>
                      </el-table-column>
                      <el-table-column  >
                        <template #default="scope">
                          <el-button icon="Plus" @click="addJkInfo"></el-button>
                          <el-button icon="Minus"   @click="delJkInfo(scope.$index)" ></el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <div v-if="jkInfoList.length > 0" style="width: 200px;margin-left: 100px" class="layout_overflow_auto">
                      <el-descriptions size="large" :column="1" border  >
                        <el-descriptions-item label="交纳:">
                          <span class="f-size" style="color: blue" >{{jkHj.jnZj}} </span>
                        </el-descriptions-item>
                        <el-descriptions-item label="退款:">
                          <span class="f-size" style="color: red">{{jkHj.tkZj}}  </span>
                        </el-descriptions-item>
                        <el-descriptions-item label="总计:">
                          <span class="f-size">{{jkHj.zj}} </span>
                        </el-descriptions-item>
                      </el-descriptions>
                    </div>
                </div>
              </div>
              <div  style="height: 30%">
                <el-divider border-style="dashed" content-position="left" >发票信息</el-divider>
                <div class="border_solid layout_overflow_auto" style="float: left;width: 50%;height: 100%">
                  <el-table :data="zyInfoList" style="width: 100%" highlight-current-row  @row-click="fetchZyData"  height="180">
                    <el-table-column  property="ledgerSn" label="账页" />
                    <el-table-column  property="accountDate" label="结算日期" />
                    <el-table-column   label="类型" >
                      <template #default="scope">
                        {{getZySettType(scope.row)}}
                      </template>
                    </el-table-column>
                    <el-table-column  property="cashDate" label="出纳日期" />
                    <el-table-column  property="responceTypeName" label="结账身份" />
                  </el-table>
                </div>
                <div class="border_solid layout_overflow_auto" style="float: right;width: 49%;height: 100%">
                  <el-table :data="zyFpInfoList" style="width: 100%"  height="180">
                    <el-table-column   label="操作" width="200"  >
                      <template #default="scope">
                        <el-button v-if="scope.row.inpatientNo !=null && fpVersion==='0'" icon="Printer" type="success" @click="selectPrintZyFp(scope.row)">打印</el-button>
                        <el-button v-if="scope.row.inpatientNo !=null && fpVersion==='1'" icon="Upload" title="上传电子发票" type="primary" @click="uploadZyFp(scope.row,3)"></el-button>
                        <el-button v-if="scope.row.inpatientNo !=null && fpVersion==='1'" icon="Download" title="下载电子发票" type="primary" @click="openDzfp(scope.row,3)"></el-button>
                        <el-button v-if="scope.row.inpatientNo !=null && fpVersion==='1'" icon="Delete" title="作废电子发票" type="danger" @click="uploadZyFp(scope.row,4)"></el-button>
                        <el-button v-if="scope.row.inpatientNo !=null && fpVersion==='1'" icon="Download" title="下载已作废电子发票" type="danger" @click="downDzFp(scope.row,4,'0')"></el-button>
                      </template>
                    </el-table-column>
                    <el-table-column  property="ledgerSn" label="账页" />
                    <el-table-column v-if="fpVersion === '0'"  property="receiptNo" label="发票号" />
                    <el-table-column  property="responceUnitName" label="类型" />
                    <el-table-column  property="totalCharge" label="发票金额" />
                  </el-table>
                </div>
              </div>
          </el-aside>
          <el-main  style="width: 40%">
            <el-tabs v-model="activeName" @tab-change="tabClick">
              <el-tab-pane label="已交押金" name="one">
                <el-table :data="yjYjList" style="width: 100%;" :height="350">
                  <el-table-column  property="ledgerSn" label="账页" />
<!--                  <el-table-column   label="打印操作" >-->
<!--                    <template #default="scope">-->
<!--                      <el-button v-if="scope.row.status ==='1'"  icon="Printer" type="success" @click="printFp(scope.row)">打印</el-button>-->
<!--                    </template>-->
<!--                  </el-table-column>>-->
                  <el-table-column  property="depoDate" label="日期" />
                  <el-table-column  property="statusName" label="事务" />
                  <el-table-column  property="depoAmount" label="金额" />
                  <el-table-column  property="receiptNo" label="收据" />
                  <el-table-column  property="depoTypeName" label="类型" />
                  <el-table-column  property="chequeNo" label="支票号" />
                  <el-table-column  property="opIdCodeName" label="操作员" />
                </el-table>
                <div>
                  <el-descriptions size="large" :column="2" border style="width:100%;" >
                    <el-descriptions-item label="预交张数:">
                      <span class="f-size">{{yjHz.yjZs}}  </span>
                    </el-descriptions-item>
                    <el-descriptions-item label="预交合计:">
                      <span class="f-size">{{yjHz.yjHj}} </span>
                    </el-descriptions-item>
                    <el-descriptions-item >

                    </el-descriptions-item>
                    <el-descriptions-item label="直退合计:">
                     <span class="f-size" style="color: red">
                       {{yjHz.ztHj}}
                     </span>
                    </el-descriptions-item>
                    <el-descriptions-item >

                    </el-descriptions-item>
                    <el-descriptions-item label="实际预交:">
                      <span class="f-size">{{yjHz.sjYj}} </span>
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </el-tab-pane>
              <el-tab-pane label="可出纳列表" name="two">
                  <div class="layout_overflow_auto" style="width: 100%;height: 100%">
                    <el-table :data="kcnList" highlight-current-row @row-click="fetchCnPatient" style="width: 100%;" :height="450">
                      <el-table-column  property="actFlagName" label="在院/出院" />
                      <el-table-column  property="inpatientNo" label="住院号" />
                      <el-table-column  property="admissTimes" label="住院次数" />
                      <el-table-column  property="name" label="姓名" />
                      <el-table-column  property="bedNo" label="床号" />
                      <el-table-column  property="settle" label="补/退" />
                      <el-table-column  property="wardName" label="病房" />
                      <el-table-column  property="accountDate" label="结算时间" />
                      <el-table-column  property="admissDate" label="入院日期" />
                    </el-table>
                  </div>
              </el-tab-pane>
            </el-tabs>
          </el-main>
        </el-container>
      </el-container>
    </div>
  </div>
  <PosTransaction ref="posTransactionRef"></PosTransaction>
  <el-dialog v-model="zyFpPrintVisible" title="发票打印" width="800" center>
    <div style="width: 100%;height: 60px">
      <el-row>
        <el-col :span="12">
          起始发票号:  <span  style="display: inline-block;width: 110px;background-color: #0f5e0f;text-align: center;color: #2eff00;font-size: 18px">{{settData.currentNoStr}}</span>
        </el-col>
        <el-col :span="6">
          <el-checkbox v-model="printFlag">更新发票号</el-checkbox>
        </el-col>
        <el-col :span="6">
         <el-button type="success" icon="Printer" @click="printZyFp">打印</el-button>
        </el-col>
      </el-row>
    </div>
    <div id="zyFpId"  style="width: 640px;">
      <div style="width: 640px;border: 1px white solid">
      <div id="headDiv">
        <p  style="margin-left: 478px;margin-top: 40px">
          {{settData.currentNoStr}}
        </p>
        <p  style="margin-left: 170px;margin-top: -10px;">
          {{printZyFpInfo.responceTypeName}}
        </p>
        <p  style="margin-left: 165px;margin-top: -10px">
            住院总费用：{{printZyFpInfo.totalCharge}}，其中医保统筹支付：{{printZyFpInfo.ybTcZfJe}}元，
        </p>
        <p  style="margin-left: 165px;margin-top: -10px">
          个人自付金额{{printZyFpInfo.grZfJe}}，个人账户支付{{printZyFpInfo.grZhZfJe}}元
        </p>
      </div>
      <div  style="height: 20px">
        <div  style="margin-left: 40px">
          {{printZyFpInfo.name}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          {{printZyFpInfo.sexName}} <span style="display: inline-block;width: 270px"></span>
          {{printZyFpInfo.wardName}} <span style="display: inline-block;width: 40px"></span>
          {{printZyFpInfo.inpatientNo}}
        </div>
      </div>
      <div  style="margin-left: 19px">
        {{getYeay(printZyFpInfo.startDate)}} <span style="display: inline-block;width: 25px"></span>
        {{getMoth(printZyFpInfo.startDate)}}<span style="display: inline-block;width: 29px"></span>
        {{getDay(printZyFpInfo.startDate)}}<span style="display: inline-block;width: 70px"></span>
        {{getYeay(printZyFpInfo.endDate)}}<span style="display: inline-block;width: 25px"></span>
        {{getMoth(printZyFpInfo.endDate)}}<span style="display: inline-block;width: 29px"></span>
        {{getDay(printZyFpInfo.endDate)}}<span style="display: inline-block;width: 65px"></span>
        {{printZyFpInfo.zyTs}}<span style="display: inline-block;width: 65px"></span>
        {{getYeay(getFormatDatetime(new Date()))}}<span style="display: inline-block;width: 25px"></span>
        {{getMoth(getFormatDatetime(new Date()))}}<span style="display: inline-block;width: 29px"></span>
        {{getDay(getFormatDatetime(new Date()))}}
      </div>
      <div class="comH"></div>
      <div class=" comH comM">
        <span class=" spanW " v-if="printZyFpInfo.charge1 !==0">{{printZyFpInfo.charge1}}</span>
        <span v-else class="spanW"></span>
        <span  class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge9 !==0">{{printZyFpInfo.charge9}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge17 !==0">{{printZyFpInfo.charge17}}</span>
        <span v-else class="spanW"></span>
        <span  class="comSpan"></span>
        <span class="spanW"  v-if="printZyFpInfo.charge25 !==0">{{printZyFpInfo.charge25}}</span>
        <span v-else class="spanW"></span>
        <span  class="comSpan"></span>
      </div>

      <div class=" comH comM" >
        <span class=" spanW" v-if="printZyFpInfo.charge2 !==0">{{printZyFpInfo.charge2}}</span>
        <span v-else class="spanW"></span>
        <span  class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge10 !==0">{{printZyFpInfo.charge10}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge18 !==0">{{printZyFpInfo.charge18}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"  v-if="printZyFpInfo.charge26 !==0">其他</span>
        <span v-else class="comSpan"></span>
        <span class="spanW"  v-if="printZyFpInfo.charge26 !==0">{{printZyFpInfo.charge26}}</span>
        <span v-else class="spanW"></span>
        <span  class="comSpan"></span>
        <span class="spanW"  v-if="printZyFpInfo.ysHjJe !==0">{{printZyFpInfo.ysHjJe}}</span>
        <span v-else class="spanW"></span>
      </div>

      <div class=" comH comM" >
        <span class=" spanW" v-if="printZyFpInfo.charge3 !==0">{{printZyFpInfo.charge3}}</span>
        <span v-else class="spanW"></span>
        <span  class="comSpan"></span>
        <span class=" spanW" v-if="printZyFpInfo.charge11 !==0">{{printZyFpInfo.charge11}}</span>
        <span v-else class="spanW"></span>
        <span  class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge19 !==0">{{printZyFpInfo.charge19}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan "  v-if="printZyFpInfo.charge27 !==0">材料费</span>
        <span v-else class="comSpan"></span>
        <span class="spanW"  v-if="printZyFpInfo.charge27 !==0">{{printZyFpInfo.charge27}}</span>
        <span v-else class="spanW"></span>
      </div>

      <div class=" comH comM" >
        <span class=" spanW" v-if="printZyFpInfo.charge4 !==0">{{printZyFpInfo.charge4}}</span>
        <span v-else class="spanW"></span>
        <span  class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge12 !==0">{{printZyFpInfo.charge12}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge20 !==0">{{printZyFpInfo.charge20}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"  v-if="printZyFpInfo.charge28 !==0">中成药</span>
        <span v-else class="comSpan"></span>
        <span class="spanW"  v-if="printZyFpInfo.charge28 !==0">{{printZyFpInfo.charge28}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"></span>
        <span class="spanW"  v-if="printZyFpInfo.bsHjJe !==0">{{printZyFpInfo.bsHjJe}}</span>
        <span v-else class="spanW"></span>
      </div>

      <div class=" comH comM" >
        <span class=" spanW" v-if="printZyFpInfo.charge5 !==0">{{printZyFpInfo.charge5}}</span>
        <span v-else class="spanW"></span>
        <span  class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge13 !==0">{{printZyFpInfo.charge13}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge21 !==0">{{printZyFpInfo.charge21}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"  ></span>
        <span class="spanW"  ></span>
        <span class="comSpan"></span>
        <span class="spanW"  ></span>
      </div>

      <div class=" comH comM" >
        <span class=" spanW" v-if="printZyFpInfo.charge6 !==0">{{printZyFpInfo.charge6}}</span>
        <span v-else class="spanW"></span>
        <span  class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge14 !==0">{{printZyFpInfo.charge14}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge22 !==0">{{printZyFpInfo.charge22}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"  ></span>
        <span class="spanW"  ></span>
        <span class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.tkHjJe !==0">{{printZyFpInfo.tkHjJe}}</span>
        <span v-else class="spanW"></span>
      </div>

      <div class=" comH comM" >
        <span class=" spanW" v-if="printZyFpInfo.charge7 !==0">{{printZyFpInfo.charge7}}</span>
        <span v-else class="spanW"></span>
        <span  class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge15 !==0">{{printZyFpInfo.charge15}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge23 !==0">{{printZyFpInfo.charge23}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"  ></span>
        <span class="spanW"  ></span>
        <span class="comSpan"></span>
        <span class="spanW"  ></span>
      </div>

      <div class=" comH comM" >
        <span class=" spanW" v-if="printZyFpInfo.charge8 !==0">{{printZyFpInfo.charge8}}</span>
        <span v-else class="spanW"></span>
        <span  class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge16 !==0">{{printZyFpInfo.charge16}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"></span>
        <span class="spanW" v-if="printZyFpInfo.charge24 !==0">{{printZyFpInfo.charge24}}</span>
        <span v-else class="spanW"></span>
        <span class="comSpan"  ></span>
        <span class="spanW"  ></span>
        <span class="comSpan"></span>
        <span class="spanW"  ></span>
      </div>
      <div style="margin-left: 100px">
        个人支付合计：{{printZyFpInfo.grZfHjJe}}<br/>
        {{printZyFpInfo.grZfHjJeChinese}}
      </div>
      </div>
      </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="zyFpPrintVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
      v-model="dzfpVisible"
      width="400"
      title="下载电子发票"
      @closed="clearSelectDzfp"
  >
    <template #footer>
      <div class="dialog-footer">
        <el-button type="success" @click="downDzFp(selectDzfpRow,selectDzfpTypeFlag,'1')">打印电子发票二维码</el-button>
        <el-button type="primary" @click="downDzFp(selectDzfpRow,selectDzfpTypeFlag,'0')">打印电子发票pdf文件</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup >
import PatientBaseList from "@/components/zfsf/PatientInfoHead.vue"
import PosTransaction from "@/components/zfsf/PosTransaction.vue"
import {ref} from "vue";
import {queryCurrentNo} from '@/api/zfsf/sfbillno.js'
import {queryCashierProcessInfo,
  queryPatientZyLedgerFile,
  checkCashierProcess,
  queryKyCashierList,
  queryZyReceipt,
  queryZyDepositFileList,
  saveCashierData,
  queryZdChequeType,
  cancelCashierData,
  queryPrintZyFpData,
  updatePrintZyFpData,
  downDzInvoice,
  queryFpVersion

} from '@/api/zfsf/cashier-process.js'
import {getLodop, initLodop} from '@/utils/c-lodop'
import {consume} from '@/api/zfsf/pos-transaction.js'

import {stringIsBlank} from "@/utils/blank-utils";
import { ElMessage, ElMessageBox } from 'element-plus'
import {getDateTiffDays, getFormatDatetime} from "@/utils/date";
import router from "@/router";


const zyFpPrintVisible = ref(false)
const saveFlag = ref(false)
const qxFlag =ref(false)
const activeName = ref('one')
const patientInfo = ref({
  inpatientNo : "",
  admissTimes : null,
  ledgerSn : null,
  name : '',
  wardName : ''
}
)
const dzfpVisible = ref(false)
const setShowFlag = ref(false)
const patientBaseListRef = ref(null)
const posTransactionRef = ref(null)
// 支付方式字典集合
const zdChequeTypes = ref([])
// 结算数据
const settData = ref({
  settleTypeName:'',
  zfJe:0,
  settle:0,
  settleName:'',
  zhje:0,
  ssJe:0,
  currentNoStr:'',
})

const openPos = ()=>{
  posTransactionRef.value.openOuter()
}

const chongZhiData = ()=>{
  clearData(true)
  patientBaseListRef.value.clearAllData()
}

//保存出纳操作
const saveCashData = ()=>{
  ElMessageBox.confirm('请确认是否要保存？', '提示', {
    type: 'warning',
    confirmButtonText: '是',
    cancelButtonText: '否',
  }).then(()=>{
    console.log('patientInfo',patientInfo.value)
    let param = {
      inpatientNo : patientInfo.value.inpatientNo,
      admissTimes : patientInfo.value.admissTimes,
      ledgerSn : patientInfo.value.ledgerSn,
      opId : userIdCode.value,
      depositFileList :[]
    }
    if(jzInfoList.value.length > 0){
      let ob = {
        status : '4',
        windowNo : '2',
        depoAmount : jzInfoList.value[jzInfoList.value.length-1].ybJzJe,
        depoType : '2',
        chequeNo : '',
        psordnum : '',
        agtordnum : '',
        transDate : '',
        parChannel : '',
        traceNo : '',
        receiptNo : '',
      }
      param.depositFileList.push(ob);
    }
    for (let i = 0; i < jkInfoList.value.length; i++) {
        let obj = {
          status : jkInfoList.value[i].settType === '退款' ? '2' : '4',
          windowNo : '2',
          depoAmount : jkInfoList.value[i].depoAmount,
          depoType : jkInfoList.value[i].depoType,
          chequeNo : jkInfoList.value[i].chequeNo,
          psordnum : '',
          agtordnum : '',
          transDate : '',
          parChannel : '',
          traceNo : '',
          receiptNo : '',
        }
      param.depositFileList.push(obj)
    }
      saveCashierData(param).then(res=> {
         queryFpAndYjj(param)
        selectPrintZyFp(param)
      })
  })
}
// 取消出纳
const cancelCash = ()=>{
  ElMessageBox.confirm('请确认是否要取消出纳？', '提示', {
    type: 'warning',
    confirmButtonText: '是',
    cancelButtonText: '否',
  }).then(()=>{
      cancelCashierData(patientInfo.value).then(res=>{
         chongZhiData()
      })
  })

}


const getYeay = (val)=>{
 return  val.substring(0,4)
}

const getMoth = (val)=>{
  return val.substring(5,7)
}

const getDay = (val)=>{
  return val.substring(8,10)
}

// 刷卡 支付
const shuaKa = (row,index)=>{
  let obj = {
    chequeType : row.depoType,
    amt : row.depoAmount,
    type : 1
  }
  consume(obj).then(res=>{
    jkInfoList.value[index].psordnum = res.refNo
    jkInfoList.value[index].agtordnum = res.wxAliPayOrderNo
    jkInfoList.value[index].transDate = res.transDate
    jkInfoList.value[index].parChannel = res.payChannel
    jkInfoList.value[index].traceNo = res.traceNo
    jkInfoList.value[index].receiptNo = res.lsOrderNo
  })
}


const selectPatient =(val)=>{
  if(fpVersion.value ==='0'){
    queryCurrentNo({cashId:userIdCode.value}).then(res=>{
      settData.value.currentNoStr = res.currentNoStr
    })
  }
  // 查询账页信息
  queryPatientZyLedgerFile(val).then(res=>{
    zyInfoList.value = res
    if( res.length > 0){
     let index = getSettInfoIndex(res)
      if(index === -1){
        dealSettData(res[res.length-1].inpatientNo,res[res.length-1].admissTimes,res[res.length-1].ledgerSn)
      }else {
        dealSettData(res[index].inpatientNo,res[index].admissTimes,res[index].ledgerSn)
      }
    }else {
      ElMessage.error('没有结算账页信息!')
    }
  })

}
// 检查是否有结算信息 未出纳的 下标
const getSettInfoIndex = (val)=>{
  for (let i = 0; i < val.length; i++) {
       if(!stringIsBlank(val[i].accountDate) && stringIsBlank(val[i].cashDate)){
          return i
       }
  }
  return -1;
}

const fetchZyData = (row)=>{
  dealSettData(row.inpatientNo,row.admissTimes,row.ledgerSn)
}

// 选择出纳病人
const fetchCnPatient = (row)=>{
  ElMessageBox.confirm('是否要进行出纳操作？', '提示', {
    type: 'warning',
    confirmButtonText: '是',
    cancelButtonText: '否',
  }).then(()=>{
    patientBaseListRef.value.fetchPatientData({inpatientNo:row.inpatientNo,admissTimes:row.admissTimes,inOutStatusFlag:row.actFlag})
  })
}

const dealSettData = (inpatientNo,admissTimes,ledgerSn)=>{
    let param = {
      inpatientNo : inpatientNo,
      admissTimes : admissTimes,
      ledgerSn : ledgerSn
    }
    checkCashierProcess(param).then(res =>{
      if(res.mzByJz != null){
        ElMessageBox.confirm(`该病人存在门诊欠款${res.mzByJz}是否继续出纳`, {
          distinguishCancelAndClose: true,
          cancelButtonText: '否',
          confirmButtonText: '是',
        }).then(() => {
          getCashierProcessInfo(param,res.zyLedgerFile,res)
            })
            .catch(action=>{
              if(action === 'cancel'){
                clearData(true)
              }
            })
      }else {
        getCashierProcessInfo(param,res.zyLedgerFile,res)
      }
    })
}

const getCashierProcessInfo = (param,zyLedgerFile,checkParam)=>{
  if(zyLedgerFile && stringIsBlank(zyLedgerFile.accountDate)){
    setShowFlag.value = false
    clearData(false)
    ElMessage.error('不存在病人已结算待出纳信息!')
    patientBaseListRef.value.showCashName('未结算')
  }else {
    patientBaseListRef.value.showCashName('已结算')
  }
  if(zyLedgerFile && !stringIsBlank(zyLedgerFile.cashDate)){
    setShowFlag.value = false
    clearData(false)
    patientBaseListRef.value.showCashName('已出纳')
    ElMessage.error(`该病人已经在${zyLedgerFile.cashDate}做过出纳处理`)
  }
  if(checkParam.zYTotalFee != null){
    setShowFlag.value = false
    clearData(true)
    ElMessage.error(`该病人账页总费用${checkParam.zYTotalFee}和明细总费用${checkParam.mxTotalFee}不一致请重新结算再做出纳处理`)
    return
  }
  patientInfo.value.inpatientNo = param.inpatientNo
  patientInfo.value.admissTimes = param.admissTimes
  patientInfo.value.ledgerSn = param.ledgerSn
  queryFpAndYjj(param)
  if(!stringIsBlank(zyLedgerFile.accountDate) &&  stringIsBlank(zyLedgerFile.cashDate)){
    queryCashierProcessInfo(param).then(res=>{
      setSettData(res.settData)
      setJkInfoList(res.settData)
      setJzInfo(res.settData.ybJzJe)
      setShowFlag.value = true
    })
  }
}
const fpVersion = ref('0')
const userIdCode = ref('')
onMounted(()=>{
  initLodop()
  queryFpVersion().then((res)=>{
   fpVersion.value =res
  })
  try {
    let patInfo = JSON.parse(window.atob(router.currentRoute.value.params.patientInfo))
    userIdCode.value = patInfo.userIdCode
  }catch (e){

  }
  queryZdChequeType().then(res=>{
    zdChequeTypes.value = res
  })
})


// 查询发票和预交金
const queryFpAndYjj = (param)=>{
  queryZyReceipt(param).then(res=>{
    zyFpInfoList.value =  res
  })
  queryZyDepositFileList(param).then(res=>{
    yjYjList.value = res.yjYj
    yjHz.value.sjYj = res.sjYj
    yjHz.value.yjZs = res.yjZs
    yjHz.value.ztHj = res.ztHj
    yjHz.value.yjHj = res.yjHj
    patientInfo.value.name = res.patInfo.name
    patientInfo.value.wardName = res.patInfo.wardName
  })
}


const clearData = (zyFlag)=>{
  if(zyFlag){
    zyInfoList.value = []
  }
  jkHj.value.zj = 0
  jkHj.value.tkZj = 0
  jkHj.value.jnZj = 0
  jzInfoList.value = []
  jkInfoList.value = []
  zyFpInfoList.value = []
  yjYjList.value = []

  settData.value.settleTypeName = ''
  settData.value.zfJe = 0
  settData.value.settle = 0
  settData.value.settleName = ''
  settData.value.zhje = 0.00
  settData.value.ssJe = 0.00

  patientInfo.value.inpatientNo = ''
  patientInfo.value.admissTimes = null
  patientInfo.value.ledgerSn = null
  patientInfo.value.name = ''
  patientInfo.value.wardName = ''

  yjHz.value.sjYj = 0
  yjHz.value.yjHj = 0
  yjHz.value.yjZs = 0
  yjHz.value.ztHj = 0

}



const  setSettData = (val)=>{
  settData.value.settleName = val.settleName
  settData.value.settleTypeName = val.settleTypeName
  settData.value.zhje = 0.00
  settData.value.ssJe = 0.00
  settData.value.settle = Math.abs(val.settle)
  settData.value.zfJe = val.lastBalance

}

const setJzInfo = (ybJzJe)=>{
  jzInfoList.value = []
  if(ybJzJe && ybJzJe != 0){
    jzInfoList.value.push({
      ybType : '医保记账',
      ybJzJe :ybJzJe
    })
    jzInfoList.value.push({
      ybType : '记账总计',
      ybJzJe :ybJzJe
    })
  }
}

// 新增交款信息
const addJkInfo = ()=>{
  let obj = {
    settType : '',
    depoType : 'A',
    depoAmount : 0,
    chequeNo : '',
    psordnum : '',
    agtordnum : '',
    transDate : '',
    parChannel : '',
    traceNo : '',
    receiptNo : '',
  }

  let tkZj= jkInfoList.value.filter(item=>item.settType === '退款').reduce((pre,cur)=>{
    return pre + cur.depoAmount ;
  },0)

  let jnZj= jkInfoList.value.filter(item=>item.settType === '交纳').reduce((pre,cur)=>{
    return pre + cur.depoAmount ;
  },0)

  if(settData.value.settleName === '补交:'){
    if((jnZj - tkZj) <= Math.abs(settData.value.settle)){
      obj.settType ='交纳'
      obj.depoAmount = Math.abs(jnZj - tkZj -Math.abs(settData.value.settle))
    }else {
      obj.settType ='退款'
      obj.depoAmount = Math.abs(jnZj - tkZj -Math.abs(settData.value.settle))
    }
  }else {
     if((tkZj - jnZj) >= Math.abs(settData.value.settle)){
       obj.settType ='交纳'
       obj.depoAmount = Math.abs(tkZj - jnZj -Math.abs(settData.value.settle))
     }else {
       obj.settType ='退款'
       obj.depoAmount = Math.abs(tkZj - jnZj -Math.abs(settData.value.settle))
     }
  }

  jkInfoList.value.push(obj)
  calcJkJe()
}
const delJkInfo = (index)=>{
  if(jkInfoList.value.length === 1){
    ElMessage.error("交款信息不能为空")
    return
  }
  jkInfoList.value.splice(index, 1)
  calcJkJe()
}

const jkHj = ref({
  jnZj : 0,
  tkZj : 0,
  zj : 0
})

const calcJkJe = ()=>{
  let tkZj= jkInfoList.value.filter(item=>item.settType === '退款').reduce((pre,cur)=>{
    return pre + cur.depoAmount ;
  },0)

  let jnZj= jkInfoList.value.filter(item=>item.settType === '交纳').reduce((pre,cur)=>{
    return pre + cur.depoAmount ;
  },0)
  jkHj.value.jnZj = parseFloat(Number(jnZj).toFixed(2))
  jkHj.value.tkZj = parseFloat(Number(tkZj).toFixed(2))
  jkHj.value.zj =  parseFloat(Number(Math.abs(jkHj.value.jnZj - jkHj.value.tkZj)).toFixed(2))

}



const setJkInfoList = (val)=>{
  jkInfoList.value = []
    let obj = {
      settType : '',
      depoType : 'A',
      depoAmount : 0,
      chequeNo : '',
      psordnum : '',
      agtordnum : '',
      transDate : '',
      parChannel : '',
      traceNo : '',
      receiptNo : '',
    }
  obj.settType = val.settle > 0 ? '退款' : '交纳'
  obj.depoAmount = Math.abs(val.settle)
  jkInfoList.value.push(obj)
  calcJkJe()
}

// 记账信息数据
const jzInfoList = ref([])
// 交款信息
const jkInfoList = ref([])
// 账页信息
const zyInfoList = ref([])
// 账页发票信息
const zyFpInfoList = ref([])
// 已交押金
const yjYjList = ref([])
// 预交汇总
const yjHz = ref({
  yjZs : 0,
  sjYj : 0,
  yjHj : 0,
  ztHj : 0,
})
// 可出纳数据
const kcnList = ref([])

const tabClick = ()=>{
  if(activeName.value ==='two'){
    let startDate = getDateTiffDays(1).substring(0,10) + ' 00:00:00'
    let endDate = getDateTiffDays(1).substring(0,10) + ' 23:59:59'
    queryKyCashierList({startDate:startDate,endDate:endDate}).then(res=>{
      kcnList.value = res
    })
  }
}


//打印发票
// const printFp = (row)=>{
//
//  let LODOP = getLodop();
//   LODOP.PRINT_INIT('预交金')
//   LODOP.SET_PRINT_PAGESIZE(2, 0, 0, '')
//   LODOP.SET_PRINT_STYLE('FontSize', 9)
//   LODOP.ADD_PRINT_TEXT('8mm', '50mm', '220mm', '7mm', patientInfo.value.wardName)
//   LODOP.ADD_PRINT_TEXT('14mm', '50mm', '220mm', '7mm', patientInfo.value.name)
//   LODOP.ADD_PRINT_TEXT('20mm', '50mm', '220mm', '7mm', '紧急联系人：13908453983')
//   LODOP.ADD_PRINT_TEXT('30mm', '50mm', '220mm', '7mm', getYeay(row.depoDate)+'.'+getMoth(row.depoDate)+'.'+getDay(row.depoDate))
//   LODOP.ADD_PRINT_TEXT('40mm', '50mm', '220mm', '7mm', row.opIdCodeName)
//   LODOP.PREVIEW()
//
// }

const zyFpCss = `
#zyFpId{ width: 640px;}

#headDiv  p {
  line-height: 10px;
}
.comSpan{
  display: inline-block;
  width: 60px;
}

.spanW{
  display: inline-block;
  width: 60px;
}

.comH {
  height: 24px;
}

.comM{
  margin-left: 90px;
}`

const printZyFp = ()=>{
  let param = {
    inpatientNo :printZyFpInfo.value.inpatientNo,
    admissTimes :printZyFpInfo.value.admissTimes,
    ledgerSn :printZyFpInfo.value.ledgerSn,
    printFlag :printFlag.value ? '1' : '0',
    receiptNo : settData.value.currentNoStr,
    opId : userIdCode.value
  }
  updatePrintZyFpData(param).then(res=>{
    let LODOP = getLodop()
    LODOP.PRINT_INIT('住院发票') // 初始化打印机 名字
    LODOP.SET_PRINT_PAGESIZE(1, '256mm', '156mm', '') // 设置纸张大小
    LODOP.SET_PRINT_MODE('FULL_WIDTH_FOR_OVERFLOW', true) // 整宽不变形
    LODOP.ADD_PRINT_HTM('1mm', '3mm', '100%', '100%', '<style>' + zyFpCss + '</style>' + '<body>' + document.getElementById('zyFpId').innerHTML + '</body>') //要打印的内容
    LODOP.PREVIEW() // 关闭
  })
}

const printZyFpInfo = ref({})
const selectPrintZyFp = (row)=>{
  queryPrintZyFpData(row).then(res=>{
    zyFpPrintVisible.value = true
    printZyFpInfo.value = res
  })
}

const selectDzfpRow = ref({})
const selectDzfpTypeFlag = ref(null)
const openDzfp = (row,typeFlag)=>{
  selectDzfpRow.value = row
  selectDzfpTypeFlag.value = typeFlag
  dzfpVisible.value = true
}

const uploadZyFp=(row,typeFlag)=>{
  row['typeFlag'] = typeFlag
  let typeFlagStr = typeFlag == 3 ? '上传' : '作废'
  ElMessageBox.confirm("请确认是否"+typeFlagStr+"电子发票", {
    cancelButtonText: "取消",
    confirmButtonText: "确定",
  })
      .then(() => {
        queryPrintZyFpData(row).then(res=>{
          ElMessage.error(typeFlagStr+"电子发票成功！");
        })
      })
}

const clearSelectDzfp = ()=>{
  selectDzfpRow.value = {}
  selectDzfpTypeFlag.value = null
}

const downDzFp = (row,typeFlag,type)=>{
  row['typeFlag'] = typeFlag
  downDzInvoice(row).then(res=>{
    let LODOP = getLodop();
    if(stringIsBlank(type) || type === '0'){
      // const link = document.createElement("a");
      // // 获取数据量
      // const blob = new Blob([base64ToArrayBuffer(res.pdfFileStr)]);
      // // 下载文件
      // const objectUrl = URL.createObjectURL(blob);
      // link.href = objectUrl;
      // var timestamp = Date.parse(new Date());
      // link.download = timestamp + ".pdf";
      // link.click();
      // URL.revokeObjectURL(objectUrl);
      // link.remove();
      let height = "175mm"
      let  bkimgWidth = "110mm"
      LODOP.PRINT_INITA(6, 0, bkimgWidth, height, "泰和门诊电子发票二维码打印");
      //设置默认打印机
      LODOP.SET_PRINTER_INDEX(-1);
      LODOP.SET_SHOW_MODE("BKIMG_WIDTH", bkimgWidth);
      LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", height);
      LODOP.SET_PRINT_PAGESIZE(2,bkimgWidth, height, "CreateCustomPage");
      LODOP.SET_PRINT_MODE("CREATE_CUSTOM_PAGE_NAME", "门诊电子发票二维码");//对新建的纸张重命名
      LODOP.SET_PRINT_STYLE("FontSize", 11); //字体大小
      LODOP.ADD_PRINT_PDF(0,0,"100%","100%",res.pdfFileStr);
      LODOP.PRINT();
      // LODOP.PREVIEW();
    }else {
      //打印二维码
      let height = "70mm"
      let  bkimgWidth = "110mm"
      LODOP.PRINT_INITA(6, 0, bkimgWidth, height, "泰和住院电子发票二维码打印");
      //设置默认打印机
      LODOP.SET_PRINTER_INDEX(-1);
      LODOP.SET_SHOW_MODE("BKIMG_WIDTH", bkimgWidth);
      LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", height);
      LODOP.SET_PRINT_PAGESIZE(1,bkimgWidth, height, "CreateCustomPage");
      LODOP.SET_PRINT_MODE("CREATE_CUSTOM_PAGE_NAME", "住院电子发票二维码");//对新建的纸张重命名
      LODOP.SET_PRINT_STYLE("FontSize", 11); //字体大小
      LODOP.ADD_PRINT_TEXT("6mm", "3mm", "60mm", "3mm", "湖南泰和医院管理有限公司发票二维码");
      LODOP.ADD_PRINT_IMAGE("10mm", "3mm", "50mm", "50mm", "data:image/png;base64,"+res.qrcode);
      LODOP.PRINT();
    }
    dzfpVisible.value = false
  })
}


const base64ToArrayBuffer = (base64) => {
  var bloBString = window.atob(base64);

  var bloBLen = bloBString .length;

  var bytes = new Uint8Array(bloBLen);

  for (var i = 0; i < bloBLen; i++) {
    var ascii = bloBString .charCodeAt(i);

    bytes[i] = ascii;
  }

  return bytes;
};

const printFlag = ref(true)





const getZySettType= (row)=>{
  console.log('row',row)
  if(stringIsBlank(row.accountDate)){
    return '未结算'
  }else {
     if(stringIsBlank(row.cashDate)){
       return '未出纳'
     }else {
       return '已出纳'
     }
  }
}


</script>
<style scoped >
.border_solid{
  border: 1px #808080  solid
}

.f-size{
  font-size: 18px;
}

.comSpan{
  display: inline-block;
  width: 60px;
}

.spanW{
  display: inline-block;
  width: 60px;
}

.comH {
  height: 24px;
}

.comM{
  margin-left: 90px;
}
#zyFpId p {
  line-height: 10px;
}

</style>