<template>
  <div class="app-continer">
    <div style="margin: 15px 0; padding: 0 20px">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="90px">
        <el-form-item label="患者姓名：" prop="searchKey">
          <el-input
            v-model="queryParams.searchKey"
            placeholder="患者姓名"
            clearable
            style="width: 240px"
            @keyup.enter="getClinicRecord"
          />
        </el-form-item>
        <el-form-item label="发票号：" prop="invoiceNo" label-width="120px">
          <el-input
            v-model="queryParams.invoiceNo"
            placeholder="发票号"
            clearable
            style="width: 240px"
            @keyup.enter="getClinicRecord"
          />
        </el-form-item>
        <el-form-item label="发票状态：" prop="invoiceStatus">
          <el-select
            v-model="queryParams.invoiceStatus"select
            placeholder="发票状态"
            clearable
            style="width: 240px"
            @keyup.enter="getClinicRecord"
          >
          <el-option v-for="item in invoiceStatusList" :key="item.value" :label="item.label"
                    :value="item.value">
          </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结算时间：" prop="activeFlag">
          <el-date-picker
            v-model="occurrenceTime"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 300px; margin-bottom: 10px; margin-left: 20px"
            value-format="YYYY-MM-DD"
            :clearable="false"
            @change="getClinicRecord"
          />
        </el-form-item>
        <div style="float: right">
          <el-button type="primary" plain @click="getClinicRecord">查询</el-button>
          <el-button type="warning" plain @click="handleReset">重置</el-button>
        </div>
      </el-form>
    </div>
    <div style="float: right; margin: 0 20px 10px 0">
      <span style="margin-right: 20px">
        {{ '总数：' + count + '/' + '成功：' + successCount }}
      </span>
      <el-button type="primary" :loading="loading" plain @click="handleBatchProcess">批量开具</el-button>
    </div>
    <el-table :data="clinicRecord" border>
      <!-- <el-table-column label="计算类型" align="center" prop="statusEnum_enumText" /> -->
      <el-table-column label="患者姓名" align="center" prop="patientName" :show-overflow-tooltip="true"/>
      <el-table-column label="支付状态" align="center" prop="statusEnum_dictText" :show-overflow-tooltip="true"/>
      <el-table-column label="费用类型" align="center" prop="paymentEnum_dictText" :show-overflow-tooltip="true"/>
      <el-table-column label="医保结算Id" align="center" prop="ybSettleIds" :show-overflow-tooltip="true"/>
      <el-table-column label="收费流水号" align="center" prop="paymentNo" width="280" :show-overflow-tooltip="true"/>
      <el-table-column label="发票号" align="center" prop="invoiceNo" :show-overflow-tooltip="true"/>
      <el-table-column
        label="结算金额"
        align="right"
        prop="tenderedAmount"
        header-align="center"
        width="100"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ scope.row.tenderedAmount + ' 元' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="支付金额"
        align="right"
        prop="displayAmount"
        header-align="center"
        width="100"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ scope.row.displayAmount + ' 元' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结算时间"
        align="center"
        key="billDate"
        prop="billDate"
       
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.billDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收款人" align="center" prop="entererName" :show-overflow-tooltip="true"/>
      <!-- <el-table-column label="医生" align="center" prop="paymentEnum_enumText" /> -->
      <el-table-column label="支付结果" align="center" prop="outcomeEnum_dictText" :show-overflow-tooltip="true"/>
      <el-table-column label="打印次数" align="center" prop="printCount" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" prop="paymentEnum_enumText" width="340">
        <template #default="scope">
          <!-- <el-button type="primary" link @click="handlePrint(scope.row)">单据</el-button> -->
          <!-- <el-button type="primary" link @click="handleEdit(scope.row)">冲红</el-button> -->
          <el-button type="primary" link @click="handleOpen(scope.row,4)">收费详情</el-button>
          <el-button type="primary" link @click="handleOpen(scope.row,1)" :disabled="scope.row.invoiceNo || scope.row.statusEnum == 3">开具电子发票</el-button>
          <el-button :disabled="!scope.row.relationId" type="primary" link @click="handleOpenReasonDialog(scope.row)">冲销发票</el-button>
          <el-button type="primary" link @click="handleOpen(scope.row,3)" :disabled="!scope.row.invoiceNo">调阅发票</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getLists"
    />
    <el-dialog title="收费详情" v-model="paymentDetailShow" width="1000" append-to-body style="height:90vh">
      <el-table :data="paymentDetailList" border style="height: 80vh">
      <el-table-column label="支付类型" align="center" prop="payEnum_dictText" :show-overflow-tooltip="true"/>
      <el-table-column label="金额" align="center" prop="amount" :show-overflow-tooltip="true"/>
      <el-table-column label="找零" align="center" prop="returnAmount" :show-overflow-tooltip="true"/>
      <el-table-column label="交款" align="center" prop="chargeAmount" :show-overflow-tooltip="true"/>
    </el-table>
    </el-dialog>
    <el-dialog title="请输入原因" v-model="reasonDialogVisible" width="30%">
      <el-form :model="reasonForm" label-width="80px">
        <el-form-item label="冲销原因">
          <el-input v-model="reasonForm.reason" placeholder="请输入原因" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reasonDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitReason">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ClinicRecord">
const { proxy } = getCurrentInstance();
import { getList ,invoiceMzInvoice,invoiceReissue,invoiceWriteoff,invoiceOpen,paymentDetail} from './components/api.js';
import { formatDate } from '@/utils/index';
const occurrenceTime = ref([formatDate(new Date()),formatDate(new Date())]);
const total = ref(0);
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  billDateSTime:"",
  billDateETime:"",
  searchKey:"",
  invoiceStatus:1,
  kinsEnum: 1
});
const invoiceStatusList = ref([
    { value: 1, label: '已开具' },
    { value: 0, label: '未开具' },
  ]);
const paymentDetailShow = ref(false)
const clinicRecord = ref([]);
const successCount = ref(0);
const count = ref(0);
const reasonDialogVisible = ref(false);
const reasonForm = ref({
  reason: ''
});
const currentRow = ref(null);
const paymentDetailList = ref([])
getLists();
function getClinicRecord() {
  queryParams.value.billDateSTime =
  occurrenceTime.value && occurrenceTime.value.length == 2
    ? occurrenceTime.value[0] + " 00:00:00"
    : "";
  queryParams.value.billDateETime =
    occurrenceTime.value && occurrenceTime.value.length == 2
      ? occurrenceTime.value[1] + " 23:59:59"
      : "";
  queryParams.value.pageNo = 1;
  getLists()
}
function getLists(){
  getList(queryParams.value).then((res) => {
    total.value = res.data.total;
    clinicRecord.value = res.data.records;
  });
}
function handleOpenReasonDialog(row) {
  // 可选：保存当前行数据以便后续使用
  currentRow.value = row;
  reasonForm.value.reason = ''; // 清空上次输入
  reasonDialogVisible.value = true;
}
// 提交原因
function submitReason() {
  if (!reasonForm.value.reason.trim()) {
    proxy.$message.warning('请输入原因');
    return;
  }

  invoiceWriteoff({paymentId:currentRow.value.relationIdStr,reason:reasonForm.value.reason}).then((res) => {
    if (res.data) {
      if(res.data.includes(" 电子票据红冲失败")){
        proxy.$message.error(res.data);
      }else{
          proxy.$message.success('红冲成功');
          // 关闭弹窗
            reasonDialogVisible.value = false;

          // 可选：重置表单
          reasonForm.value.reason = '';
        window.open(res.data)
      }
    }
    getLists();
  }).catch((err)=>{
  })
}
/** 清空条件按钮操作 */
function handleReset() {
  // 清空查询条件
  occurrenceTime.value = ""
  queryParams.value.billDateSTime = ""
  queryParams.value.billDateETime = ""
  proxy.resetForm("queryRef");
  getLists();
}
// function handlePrint(row){

// }
// function handleEdit(row){
  
// }

const loading = ref(false)
async function handleBatchProcess() {
  // 遍历list并异步执行invoiceReissue方法
  let list = clinicRecord.value.filter(item =>{
    return item.statusEnum == 1 && (item.invoiceNo == undefined || item.invoiceNo == null)
  })
  loading.value = true
  count.value = list.length;
  for (const item of list) {
    try {
      const res = await invoiceReissue({
        paymentId: item.id,
        encounterId: item.encounterId ? item.encounterId : ""
      });
      
      if (res.data) {
        // 门诊电子发票开具失败 住院电子发票开具失败 电子发票类型不明确
        if (
          res.data.includes(" 挂号电子发票开具失败") ||
          res.data.includes(" 住院电子发票开具失败") ||
          res.data.includes(" 门诊电子发票开具失败") ||
          res.data.includes(" 电子发票类型不明确")
        ) {
          // proxy.$message.error(res.data);
        } else {
          successCount.value++;
          // window.open(res.data);
        }
      }
      if (res.code == 200) {
        // getLists();
      } else {
        // proxy.$message.error(res.data);
      }
    } catch (err) {
      console.error(err);
    }
  }
  loading.value = false
  getLists()
}

function handleOpen(row,type){
  if(type==1){
    invoiceReissue({paymentId:row.id,encounterId:row.encounterId?row.encounterId:""}).then((res) => {
      if (res.data) {
        // 门诊电子发票开具失败 住院电子发票开具失败 电子发票类型不明确
        if(res.data.includes(" 挂号电子发票开具失败")||res.data.includes(" 住院电子发票开具失败")||res.data.includes(" 门诊电子发票开具失败")||res.data.includes(" 电子发票类型不明确")){
          proxy.$message.error(res.data);
        }else{
          window.open(res.data)
        }
      }
      if(res.code == 200) {
        getLists();
      }
      proxy.$message.error(res.data);
    }).catch((err)=>{
    })
  }else if(type==2) {
    invoiceWriteoff({paymentId:row.id,encounterId:row.encounterId?row.encounterId:""}).then((res) => {
      if (res.data) {
        if(res.data.includes(" 电子票据红冲失败")){
          proxy.$message.error(res.data);
        }else{
          window.open(res.data)
        }
      }
    }).catch((err)=>{
    })
  }else if(type==3){
    // 调阅电子发票
    invoiceOpen(row.invoiceId?row.invoiceId:"").then((res) => {
      if (res.data) {
        window.open(res.data)
      }
    }).catch((err)=>{
    })
  }else{
    paymentDetail({id:row.id?row.id:""}).then((res) => {
      if (res.data) {
        paymentDetailShow.value = true
        paymentDetailList.value = res.data
      }
    }).catch((err)=>{
    })
  }
   
}
</script>
<style scoped>
.el-dialog{
  height: 90vh!important;
}
.dialog-footer {
  text-align: right;
}
.el-textarea__inner {
  resize: none;
}
</style>