<template>
  <div class="layout_container">
    <header>
      <div style="height:25px;margin-bottom: 5px">
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <el-button :disabled="saveFlag"  icon="Check" type="primary" @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="warning"    icon="Money"  @click="openPos" >智能POS工具包</el-button>
      </div>
      <!-- <div style="text-align:center;font-weight: 700;margin-top: 15px;height:100px;r:1px solid red" id="qrcode"></div> -->
      <PatientBaseList ref="patientBaseListRef" :inOutFlag="1" @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>
        </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="130">
                      <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" >
                        <template #default="scope">
                          <span v-if="scope.row.settType ==='退款'" style="color: blue;font-size: 15px">{{scope.row.settType}}</span>
                          <span v-if="scope.row.settType !=='退款'" style="color: red;font-size: 15px">{{scope.row.settType}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column  property="depoType" label="类型" >
                        <template #default="scope">
                          <el-select v-model="scope.row.depoType" size="default" 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="large" style="width: 100px;"/>
                        </template>
                      </el-table-column>
                      <el-table-column  property="chequeNo" label="凭证号" >
                        <template #default="scope">
                          <el-input v-model="scope.row.chequeNo"   size="default" 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="交纳:" label-class-name="red-color">
                          <span style="color: red; font-size: 24px; font-weight: bold" >{{jkHj.jnZj}} </span>
                        </el-descriptions-item>
                        <el-descriptions-item label="退款:" label-class-name="blue-color">
                          <span style="color: blue; font-size: 24px; font-weight: bold">{{jkHj.tkZj}}  </span>
                        </el-descriptions-item>
                        <el-descriptions-item label="总计:">
                          <span style="font-size: 24px;font-weight: bold">{{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="240"  >
                      <template #default="scope">
                        <el-button v-if="scope.row.inpatientNo !=null && fpVersion==='1'" 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="downDzFp(scope.row)"></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)"></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 label="事务">
                    <template #default="{row}">
                      <span
                          :class="row.statusName === '结算补交'
                          ? 'red-color' : ''"
                      >
                        {{row.statusName}}
                      </span>
                    </template>
                  </el-table-column>
                  <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="直退合计:" label-class-name="red-color">
                     <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="450" center>
    <div style="width: 100%;clear: both;" ref="dzfphtml">
      <div  style="clear: both;">
        <div style="font-size:17px;float:left;width: 50%;">
          <div><svg id="barcode" height="20"></svg></div>
          <div style="margin-left: 3px;margin-top: 15px;">患者姓名：{{ dzfpData.name }}</div>
          <div style="margin-left: 3px;">结算金额：{{ dzfpData.fee }}</div>
          <div style="margin-left: 3px;">票据号码：{{ dzfpData.fpNo }}</div>
          <div style="margin-left: 3px;">票据代码：{{ dzfpData.fpCode }}</div>
          <div style="margin-left: 3px;">发票日期：{{ dzfpData.fpDate }}</div>
        </div>
        <div style="font-size:15px;float:left;width: 50%;">
          <div style="text-align:center;font-weight: 700;font-size:24px;padding-top: -14px">沭阳铭和医院</div>
          <div style="text-align:center;font-weight: 700;font-size:18px;margin-top: 5px;">电子发票信息</div>
          <div style="text-align:center;font-weight: 700;font-size:14px;margin-top: 25px;">扫码下载电子票据</div>
          <div style="text-align:center;font-weight: 700;margin-top: 15px;" id="qrcode"></div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="printZyFpToLodop">打印</el-button>
        <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,
  selectDzfpUploadAboutSerialNo,
  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 {getDateDiffToDay, getFormatDatetime} from "@/utils/date";
import router from "@/router";
import {queryHospitalName} from "@/api/zy-gl/zy-daily.js";
import {queryLastWindowsIpAddress} from "@/api/zy-gl/admission-registration.js";
import JsBarcode from 'jsbarcode'
import {qrcanvas} from 'qrcanvas'

const hospitalName = ref('')
const zyFpPrintVisible = ref(false)
const saveFlag = ref(false)
const qxFlag =ref(true)
const activeName = ref('one')
const patientInfo = ref({
  inpatientNo : "",
  admissTimes : null,
  ledgerSn : null,
  name : '',
  wardName : ''
}
)
const printCode = ref(-1)
const dzfpVisible = ref(false)
const dzfpSerialNo = ref(null)
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 dzfpData = ref({
  inpatientNo:'',
  admissTimes:'',
  fee:'',
  name:'',
  fpCode:'',
  fpNo:'',
  fpDate:'',
  qrcode:'',
})
const dzfphtml = ref(null)

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

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

//保存出纳操作
const saveCashData = ()=>{
  ElMessageBox.confirm('请确认是否要保存？', '提示', {
    type: 'warning',
    confirmButtonText: '是',
    cancelButtonText: '否',
  }).then(()=>{
    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=> {
        chongZhiData()
      })
  })
}
// 取消出纳
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){
      dzfpSerialNo.value=res[0].zySerialNo;
     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)
    qxFlag.value = true
    ElMessage.error('不存在病人已结算待出纳信息!')
    patientBaseListRef.value.showCashName('未结算')
  }else {
    qxFlag.value = true
    patientBaseListRef.value.showCashName('已结算')
  }
  if(zyLedgerFile && !stringIsBlank(zyLedgerFile.cashDate)){
   let tempCashDate = zyLedgerFile.cashDate.substring(0,10) +' 00:00:00'
   let days =  getDateDiffToDay(tempCashDate,new Date())
    if(days === 0){
      qxFlag.value = false
    }else {
      qxFlag.value = true
    }
    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);
      setShowFlag.value = true
    })
  }
}
const fpVersion = ref('0')
const userIdCode = ref('')
onMounted(()=>{
  initLodop()
  queryFpVersion().then((res)=>{
   fpVersion.value =res
  })
  queryHospitalName().then(res=>hospitalName.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
  })

  queryLastWindowsIpAddress().then(res=>{
    printCode.value = res.zyPrintIndex
  })
  
//  setTimeout(()=>{
//    const labelCanvas = qrcanvas({
//         data: "http://einvoice.jsczt.cn/d/4730209e87b15674ba6",
//         size: 50,
//       })
      
//       let src = canvasToBase64(labelCanvas);
      
//       let wxPayQrCardHtml =`<img src="${src}" style="width: 100px;height: 100px"/><div style="width: 140px;margin-top: 2px;"></img>`;
//       console.log("dzfpData",wxPayQrCardHtml)
//       document.getElementById('qrcode').innerHTML = '';
//       document.getElementById('qrcode').innerHTML = wxPayQrCardHtml
//  },1000)
})


// 查询发票和预交金
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 = (settData)=>{
  jzInfoList.value = []
  if(settData.ybJzJe && settData.ybJzJe != 0){
    jzInfoList.value.push({
      ybType : '医保记账',
      ybJzJe :settData.ybJzJe
    })
    jzInfoList.value.push({
      ybType : '记账总计',
      ybJzJe :settData.ybJzJe
    });
      jzInfoList.value.push({
          ybType : '医院负担金额',
          ybJzJe :settData.hospPartamt
      });
  }
}

// 新增交款信息
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 ? '退款' : '交纳';
  // let hospPartamt = val.hospPartamt ? val.hospPartamt : 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)=>{
  console.log("dzfpData",row)
  zyFpPrintVisible.value = true
  
  let params = {
    inpatientNo:row.inpatientNo,
    admissTimes:row.admissTimes,
    // serialNo:dzfpSerialNo.value
  }
  selectDzfpUploadAboutSerialNo(params).then(res=>{
    
    if(res.res_url){
      dzfpData.value={
        inpatientNo:row.inpatientNo,
        admissTimes:row.admissTimes,
        name:patientInfo.value.name,
        fee:row.totalCharge,
        fpCode:res.op_code,
        fpNo:res.fp_no,
        fpDate:res.blue_issue_date,
        qrcode:res.res_url
      }
      JsBarcode('#barcode',row.inpatientNo, {
        renderer: "svg",
        lineColor: '#000000', //线条颜色
        width: 1, //线宽
        height: 30, //条码高度
        displayValue: true, //是否显示文字信息
        fontSize: 18,
      });
      console.log("row",dzfpData.value.qrcode)
      const labelCanvas = qrcanvas({
        data: dzfpData.value.qrcode,
        size: 50,
      })

      let src = canvasToBase64(labelCanvas);
      
      let wxPayQrCardHtml =`<img src="${src}" style="width: 100px;height: 100px"/><div style="width: 140px;margin-top: 2px;"></img>`;
      console.log("dzfpData",wxPayQrCardHtml)
      document.getElementById('qrcode').innerHTML = '';
      document.getElementById('qrcode').innerHTML = wxPayQrCardHtml
      // console.log("dzfpData",dzfpData.value)
      // printZyFpToLodop()
        
    } else {
        ElMessage.error("未获取到电子发票，请重新上传发票！");
    }
    dzfpVisible.value = false
  })
}
const printZyFpToLodop = ()=>{
  console.log("dzfpData",dzfphtml.value.innerHTML)
  zyFpPrintVisible.value = false
  let LODOP = getLodop();
  LODOP.PRINT_INIT("检查检验申请单");
  LODOP.SET_PRINT_PAGESIZE(1, "120mm", "80mm", "CreateCustomPage");
  LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT", "Full-Width");
  LODOP.SET_PRINT_MODE("PRINT_START_PAGE", 1);
  LODOP.SET_PRINT_MODE("PRINT_END_PAGE", 1);
  LODOP.ADD_PRINT_HTM(0, '8mm', '100%', '100%', dzfphtml.value.innerHTML)
  // LODOP.ADD_PRINT_HTM("1mm", "1mm", "100%", "100%", dzfphtml.value);
  LODOP.PREVIEW();
  
}

const canvasToBase64=(canvas, type = 'image/png', quality = 0.92)=> {
  try {
    // 检查是否是有效的canvas元素
    if (!(canvas instanceof HTMLCanvasElement)) {
      throw new Error('传入的不是Canvas元素');
    }
    
    // toDataURL()方法参数:
    // 第一个参数是图像格式，默认为'image/png'
    // 第二个参数是质量，仅对'image/jpeg'和'image/webp'有效，范围0-1
    const base64String = canvas.toDataURL(type, quality);
    
    // 如果需要纯Base64字符串（去掉dataURL前缀），可以这样处理:
    // const pureBase64 = base64String.split(',')[1];
    
    return base64String;
  } catch (error) {
    console.error('转换Canvas到Base64失败:', error);
    return null;
  }
}

const selectDzfpRow = ref({})
const selectDzfpTypeFlag = ref(null)
const openDzfp = (row,typeFlag)=>{
  console.log("selectDzfpRow",JSON.stringify(row))
  selectDzfpRow.value = row
  selectDzfpTypeFlag.value = typeFlag
  dzfpVisible.value = true
}

const uploadZyFp=(row,typeFlag)=>{
  row['typeFlag'] = typeFlag
  let typeFlagStr = typeFlag == 3 ? '上传' : '作废'
  ElMessageBox.prompt("备注", "提示", {
    type: "warning",
    confirmButtonText: "确定"+typeFlagStr,
    cancelButtonText: "取消",
  })
      .then(({value}) => {
        row['remark'] = value
        queryPrintZyFpData(row).then(res=>{
          ElMessage.success(typeFlagStr+"电子发票成功！");
        })
      })
}

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

const downDzFp = (row)=>{
  
  console.log("downDzFp",row)
  let params = {
    inpatientNo:row.inpatientNo,
    admissTimes:row.admissTimes
  }
  selectDzfpUploadAboutSerialNo(params).then(res=>{
    // console.log("row",JSON.stringify(res))
    if(res.res_url){
        window.open(res.res_url)
    } else {
        ElMessage.error("未获取到电子发票，请重新上传发票！");
    }
    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)=>{
  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>