<!--
 * @Author: X_bo v-hss@tbpartners.local
 * @Date: 2025-08-15 10:00:37
 * @LastEditTime: 2025-08-15 14:18:01
 * @LastEditors: X_bo v-hss@tbpartners.local
 * @Description: 
 * @FilePath: \openhis-ui-vue3\src\views\inHospitalManagement\charge\settleAccounts\index.vue
-->
<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="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>
    <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="400">
        <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="handleRefund(scope.row)" :disabled="scope.row.paymentEnum != 0 || scope.row.outcomeEnum == 3">退费</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>
    <!-- 退费原因弹窗 -->
    <el-dialog title="退费原因" v-model="refundDialogVisible" width="30%">
      <el-form :model="refundForm" label-width="80px">
        <el-form-item 
          label="退费原因" 
          prop="reason"
          :rules="[
            { required: true, message: '请输入退费原因', trigger: 'blur' },
            { min: 1, max: 200, message: '长度在1到200个字符之间', trigger: 'blur' }
          ]"
        >
          <el-input v-model="refundForm.reason" placeholder="请输入退费原因" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRefund">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ClinicRecord">
const { proxy } = getCurrentInstance();
import { getList ,invoiceMzInvoice,invoiceReissue,invoiceWriteoff,invoiceOpen,paymentDetail,inpaUnPay} from './components/api.js';
import { formatDate } from '@/utils/index';
const occurrenceTime = ref([
  formatDate(new Date(new Date().getFullYear(), new Date().getMonth() - 1, new Date().getDate())),
  formatDate(new Date())
]);

const total = ref(0);
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  billDateSTime:"",
  billDateETime:"",
  searchKey:"",
  kinsEnum: 2
});

// 初始化时设置时间参数
queryParams.value.billDateSTime = occurrenceTime.value[0] + " 00:00:00";
queryParams.value.billDateETime = occurrenceTime.value[1] + " 23:59:59";

const paymentDetailShow = ref(false)
const clinicRecord = ref([]);
const reasonDialogVisible = ref(false);
const reasonForm = ref({
  reason: ''
});
const currentRow = ref(null);
const paymentDetailList = ref([])
const refundDialogVisible = ref(false);
const refundForm = ref({
  reason: '',
  paymentId: '',
  encounterId: ''
});
const currentRefundRow = ref(null);

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){
  
// }
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)=>{
    })
  }
   
}

function handleRefund(row) {
  currentRefundRow.value = row;
  refundForm.value.reason = '';
  refundForm.value.paymentId = row.paymentId || row.id;
  refundForm.value.encounterId = row.encounterId || '';
  refundDialogVisible.value = true;
}

function submitRefund() {
  // 使用表单验证
  if (!refundForm.value.reason || refundForm.value.reason.trim() === '') {
    proxy.$message.warning('请输入退费原因');
    return;
  }
  
  if (refundForm.value.reason.length > 200) {
    proxy.$message.warning('退费原因长度不能超过200个字符');
    return;
  }

  const refundData = {
    id: refundForm.value.paymentId,
    reason: refundForm.value.reason,
    encounterId: refundForm.value.encounterId ? refundForm.value.encounterId : ""
  };

  inpaUnPay(refundData).then((res) => {
    if (res.code == 200) {
      proxy.$message.success('退费成功');
      refundDialogVisible.value = false;
      getLists();
    }else {
      proxy.$message.error(res.data);
    }
  }).catch((err) => {
    console.error(err);
  });
}

</script>
<style scoped>
.el-dialog{
  height: 90vh!important;
}
.dialog-footer {
  text-align: right;
}
.el-textarea__inner {
  resize: none;
}
</style>