<template>
  <div class="home-container">
    <nav-bar />

    <!-- 登录弹窗 -->
    <van-popup v-model="showPasswordModal" position="center" :style="{ width: '90%', maxWidth: '400px', borderRadius: '16px', overflow: 'hidden' }">
      <div class="modal-login">
        <div class="modal-login__header">
          <h3 class="modal-login__title">身份验证</h3>
          <p class="modal-login__desc">请输入账号密码以使用收费室功能</p>
        </div>
        <div class="modal-login__form">
          <van-field
            v-model="username"
            placeholder="请输入账号"
            class="form-input"
            maxlength="20"
            @keyup.enter="validatePassword"
            left-icon="user"
          />
          <van-field
            v-model="password"
            placeholder="请输入密码"
            class="form-input"
            type="password"
            maxlength="20"
            @keyup.enter="validatePassword"
            left-icon="lock"
          />
          <div class="form-remember">
            <van-checkbox v-model="rememberPassword" class="remember-checkbox">记住密码</van-checkbox>
          </div>
          <div v-if="passwordError" class="form-error">账号或密码错误，请重新输入</div>
        </div>
        <div class="modal-login__footer">
          <van-button type="primary" @click="validatePassword" class="btn-login">登录</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 核心内容（验证通过后显示） -->
    <div v-if="passwordVerified" class="content-wrapper">
      <!-- 余额信息卡片组 -->
      <div class="balance-card-group">
        <div class="balance-card">
          <div class="balance-card__label">预估微信账户剩余余额</div>
          <div class="balance-card__amount">{{ wxBalance.toFixed(2) }} 元</div>
        </div>
        <div class="balance-card">
          <div class="balance-card__label">今日线上已退费金额</div>
          <div class="balance-card__amount refund-amount">{{ todayRefundAmount.toFixed(2) }} 元</div>
        </div>
      </div>

      <!-- 主要功能按钮 -->
      <div class="function-button-group">
        <van-button type="primary" round @click="showRefundTicketDialog" class="func-btn">线上退号退费</van-button>
        <van-button type="primary" round @click="showRefundOutpatientDialog" class="func-btn">线上门诊医保退费</van-button>
        <van-button type="primary" round @click="showRefundSelfDialog" class="func-btn">线上门诊自费退费</van-button>
        <van-button type="primary" round @click="showRefundNoHisDialog" class="func-btn">线上退钱不退his</van-button>
        <van-button type="primary" round @click="showRefundBaDialog" class="func-btn">线上病案退费</van-button>
      </div>
    </div>

    <!-- 退号退费弹窗 - 输入就诊人ID -->
    <van-popup v-model="showRefundTicket" position="center" :style="{ width: '90%', maxWidth: '400px', borderRadius: '16px' }">
      <div class="modal-common">
        <h3 class="modal-common__title">退号退费</h3>
        <p class="modal-common__desc">请输入就诊人ID</p>
        <div class="modal-common__form">
          <van-field
            v-model="patientId"
            placeholder="请输入就诊人ID"
            class="form-input"
            maxlength="20"
            inputType="number"
            :rules="[{ required: true, message: '请输入就诊人ID' }]"
            left-icon="id-card"
          />
        </div>
        <div class="modal-common__btns">
          <van-button @click="showRefundTicket = false" class="btn-cancel">取消</van-button>
          <van-button type="primary" @click="searchRegistrationInfo" class="btn-confirm" :disabled="!patientId">确认</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 可滑动的挂号信息弹窗 -->
    <van-popup v-model="showRegistrationList" position="bottom" :style="{ height: '80%', borderRadius: '16px 16px 0 0' }" :close-on-click-overlay="false">
      <div class="modal-table">
        <div class="modal-table__header">
          <h3 class="modal-table__title">挂号信息</h3>
          <van-button icon="cross" type="default" size="small" @click="showRegistrationList = false" class="btn-close" />
        </div>
        <div class="modal-table__scroll">
          <table class="data-table">
            <thead>
              <tr>
                <th>就诊人</th>
                <th>挂号时间</th>
                <th>订单号</th>
                <th>科室</th>
                <th>就诊医生</th>
                <th>退款金额</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr 
                v-for="(item, index) in registrationList" 
                :key="index"
                :class="{ 'table-row--selected': selectedIndex === index }"
                @click="selectRegistration(index)"
              >
                <td>{{ item.patientName }}</td>
                <td>{{ item.registerTime }}</td>
                <td>{{ item.orderno }}</td>
                <td>{{ item.department }}</td>
                <td>{{ item.doctor }}</td>
                <td class="table-amount">{{ item.refundAmount }}</td>
                <td>
                  <van-button type="danger" size="small" @click.stop="confirmRefund(index)" class="btn-operate">退号</van-button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </van-popup>

    <!-- 门诊退费弹窗 -->
    <van-popup v-model="showRefundOutpatient" position="center" :style="{ width: '90%', maxWidth: '400px', borderRadius: '16px' }">
      <div class="modal-common">
        <h3 class="modal-common__title">门诊医保退费</h3>
        <p class="modal-common__desc">请输入就诊人ID</p>
        <div class="modal-common__form">
          <van-field
            v-model="patientId"
            placeholder="请输入就诊人ID"
            class="form-input"
            maxlength="20"
            inputType="number"
            :rules="[{ required: true, message: '请输入就诊人ID' }]"
            left-icon="id-card"
          />
        </div>
        <div class="modal-common__btns">
          <van-button @click="showRefundOutpatient = false" class="btn-cancel">取消</van-button>
          <van-button type="primary" @click="searchRegistrationInfo2" class="btn-confirm" :disabled="!patientId">确认</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 医保缴费信息弹窗 -->
    <van-popup v-model="showYbPaymentList" position="bottom" :style="{ height: '80%', borderRadius: '16px 16px 0 0' }" :close-on-click-overlay="false">
      <div class="modal-table">
        <div class="modal-table__header">
          <h3 class="modal-table__title">医保缴费信息</h3>
          <van-button icon="cross" type="default" size="small" @click="showYbPaymentList = false" class="btn-close" />
        </div>
        <div class="modal-table__scroll">
          <table class="data-table">
            <thead>
              <tr>
                <th>患者ID</th>
                <th>医保订单号</th>
                <th>订单时间</th>
                <th>总金额</th>
                <th>个人支付</th>
                <th>个账金额</th>
                <th>基金支付</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in ybPaymentList" :key="index" class="table-row">
                <td>{{ item.patId }}</td>
                <td>{{ item.hospOutTradeNo }}</td>
                <td>{{ item.orderDate }}</td>
                <td>{{ item.feeSumamt }}</td>
                <td>{{ item.ownPayAmt }}</td>
                <td>{{ item.psnAcctPay }}</td>
                <td>{{ item.fundPay }}</td>
                <td>
                  <van-button type="danger" size="small" @click.stop="confirmYbRefund(index)" class="btn-operate">退费</van-button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </van-popup>

    <!-- 门诊自费退费弹窗 - 输入就诊人ID -->
    <van-popup v-model="showRefundSelf" position="center" :style="{ width: '90%', maxWidth: '400px', borderRadius: '16px' }">
      <div class="modal-common">
        <h3 class="modal-common__title">门诊自费退费</h3>
        <p class="modal-common__desc">请输入就诊人ID</p>
        <div class="modal-common__form">
          <van-field
            v-model="patientId"
            placeholder="请输入就诊人ID"
            class="form-input"
            maxlength="20"
            inputType="number"
            :rules="[{ required: true, message: '请输入就诊人ID' }]"
            left-icon="id-card"
          />
        </div>
        <div class="modal-common__btns">
          <van-button @click="showRefundSelf = false" class="btn-cancel">取消</van-button>
          <van-button type="primary" @click="searchRegistrationInfo3" class="btn-confirm" :disabled="!patientId">确认</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 线上退钱不退his弹窗 - 输入订单号和金额 -->
    <van-popup v-model="showRefundNoHis" position="center" :style="{ width: '90%', maxWidth: '400px', borderRadius: '16px' }">
      <div class="modal-common">
        <h3 class="modal-common__title">线上退钱不退his</h3>
        <div class="modal-common__form">
          <van-field
            v-model="refundNoHisOrderNo"
            placeholder="请输入订单号"
            class="form-input"
            maxlength="60"
            :rules="[{ required: true, message: '请输入订单号' }]"
            left-icon="order"
          />
          <van-field
            v-model="refundNoHisAmount"
            placeholder="请输入金额"
            class="form-input"
            maxlength="10"
            inputType="number"
            :rules="[{ required: true, message: '请输入金额' }]"
            left-icon="balance"
          />
        </div>
        <div class="modal-common__btns">
          <van-button @click="showRefundNoHis = false" class="btn-cancel">取消</van-button>
          <van-button type="primary" @click="confirmRefundNoHis" class="btn-confirm" :disabled="!refundNoHisOrderNo || !refundNoHisAmount">确认</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 线上病案退费弹窗 - 输入患者ID或住院号 -->
    <van-popup v-model="showRefundBa" position="center" :style="{ width: '90%', maxWidth: '400px', borderRadius: '16px' }">
      <div class="modal-common">
        <h3 class="modal-common__title">线上病案退费</h3>
        <p class="modal-common__desc">请输入患者ID或住院号（二选一）</p>
        <div class="modal-common__form">
          <van-field
            v-model="refundBaPatientId"
            placeholder="请输入患者ID"
            class="form-input"
            maxlength="20"
            left-icon="id-card"
          />
          <van-field
            v-model="refundBaHosNum"
            placeholder="请输入住院号"
            class="form-input"
            maxlength="20"
            left-icon="hospital"
          />
        </div>
        <div class="modal-common__btns">
          <van-button @click="showRefundBa = false" class="btn-cancel">取消</van-button>
          <van-button type="primary" @click="searchBaInfo" class="btn-confirm" :disabled="!refundBaPatientId && !refundBaHosNum">确认</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 线上病案退费记录表格弹窗 -->
    <van-popup v-model="showBaList" position="bottom" :style="{ height: '80%', borderRadius: '16px 16px 0 0' }" :close-on-click-overlay="false">
      <div class="modal-table">
        <div class="modal-table__header">
          <h3 class="modal-table__title">病案记录</h3>
          <van-button icon="cross" type="default" size="small" @click="showBaList = false" class="btn-close" />
        </div>
        <div class="modal-table__scroll">
          <table class="data-table">
            <thead>
              <tr>
                <th>微信ID</th>
                <th>患者ID</th>
                <th>患者名字</th>
                <th>代取人名字</th>
                <th>订单号</th>
                <th>金额</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in baList" :key="index" class="table-row">
                <td>{{ item.userId }}</td>
                <td>{{ item.patientId }}</td>
                <td>{{ item.patientName }}</td>
                <td>{{ item.reName }}</td>
                <td>{{ item.orderno }}</td>
                <td>{{ item.amount }}</td>
                <td>
                  <van-button type="danger" size="small" @click.stop="confirmBaRefund(index)" class="btn-operate">退费</van-button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </van-popup>

    <!-- 门诊自费退费记录表格弹窗 -->
    <van-popup v-model="showSelfPaymentList" position="bottom" :style="{ height: '80%', borderRadius: '16px 16px 0 0' }" :close-on-click-overlay="false">
      <div class="modal-table">
        <div class="modal-table__header">
          <h3 class="modal-table__title">门诊自费缴费记录</h3>
          <van-button icon="cross" type="default" size="small" @click="showSelfPaymentList = false" class="btn-close" />
        </div>
        <div class="modal-table__scroll">
          <table class="data-table">
            <thead>
              <tr>
                <th>就诊人ID</th>
                <th>订单号</th>
                <th>科室</th>
                <th>医生</th>
                <th>支付金额</th>
                <th>支付时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in selfPaymentList" :key="index" class="table-row">
                <td>{{ item.patientId }}</td>
                <td>{{ item.orderNo }}</td>
                <td>{{ item.department }}</td>
                <td>{{ item.doctor }}</td>
                <td class="table-amount">¥{{ item.amount.toFixed(2) }}</td>
                <td>{{ item.payTime }}</td>
                <td>
                  <van-button type="danger" size="small" @click.stop="confirmSelfRefund(index)" class="btn-operate">退费</van-button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import Vue from "vue";
import {
selectGuaHaoList,
apiopBillsPayedRefund,
selectYbByPatientId,
refundOrderOnline,
selectOrderList,
WxRefundOrder,
apiGetBAList2,
SumWxBalance,
DelWxBalance
} from "@/request/api.js";
import {Dialog, Toast, Popup, Field, Button, Checkbox} from "vant";
export default {
  components: {
    [Button.name]: Button,
    [Field.name]: Field,
    [Checkbox.name]: Checkbox
  },
  data() {
    return {
      showRefundTicket: false,
      showRefundOutpatient: false,
      showRefundSelf: false, // 门诊自费退费弹窗控制
      showRegistrationList: false,
      showYbPaymentList: false,
      showSelfPaymentList: false, // 门诊自费退费记录弹窗控制
      showRefundNoHis: false, // 线上退钱不退his弹窗控制
      showRefundBa: false, // 线上病案退费弹窗控制
      showBaList: false, // 线上病案退费记录弹窗控制
      patientId: '',
      orderNumber: '',
      refundNoHisOrderNo: '', // 退钱不退his订单号
      refundNoHisAmount: '', // 退钱不退his金额
      refundBaPatientId: '', // 线上病案退费患者ID
      refundBaHosNum: '', // 线上病案退费住院号
      baList: [], // 线上病案退费记录数据
      selectedIndex: -1,
      registrationList: [],
      ybPaymentList: [],
      selfPaymentList: [], // 门诊自费退费记录数据
      show: false, // 用于控制加载状态
      loadingInstance: null, // 加载提示实例
      
      // 登录相关
      showPasswordModal: false,
      username: '',
      password: '',
      rememberPassword: false,
      passwordVerified: false,
      passwordError: false,
      wxBalance: 0, // 微信账户预计余额
      todayRefundAmount: 0, // 今日线上已退费金额
      balanceTimer: null,
    }
    
  },
  mounted() {

    // 页面加载时检查缓存中是否有已验证的登录状态
    const verified = localStorage.getItem('tui_password_verified');
    this.passwordVerified = verified === 'true';
    
    // 从本地存储读取账号密码（如果有）
    const savedUsername = localStorage.getItem('tui_username');
    const savedPassword = localStorage.getItem('tui_password');
    const savedRememberPassword = localStorage.getItem('tui_remember_password') === 'true';
    
    if (savedUsername && savedPassword) {
      this.username = savedUsername;
      this.password = savedPassword;
      this.rememberPassword = savedRememberPassword;
    }
    //调用后端接口，判断微信账户有多少钱？
    this.getWxBalance();
    
    // 如果未验证，则显示登录弹窗
    if (!this.passwordVerified) {
      this.showPasswordModal = true;
    }
    
    // 设置定时器，每10秒调用一次 getWxBalance()
    this.balanceTimer = setInterval(() => {
      this.getWxBalance();
    }, 10000);
  },
  beforeDestroy() {
    // 清除定时器
    if (this.balanceTimer) {
      clearInterval(this.balanceTimer);
    }
    // 清除登录相关的缓存，确保再次登录需要重新输入密码
    localStorage.removeItem('tui_password_verified');
    localStorage.removeItem('tui_username');
    localStorage.removeItem('tui_password');
    localStorage.removeItem('tui_remember_password');
  },
  
  methods: {
    getWxBalance() {
      // 调用 SumWxBalance 获取微信账户余额
      SumWxBalance().then(res => {
        if (res.code === 200) {
          // 后端返回的是 Map 集合，需要计算所有金额的总和
          const balanceMap = res.data;
          let totalBalance = 0;
          
          // 遍历 Map 中的所有值并相加
          for (const key in balanceMap) {
            if (balanceMap.hasOwnProperty(key)) {
              const amount = Number(balanceMap[key]);
              if (!isNaN(amount)) {
                totalBalance += amount;
              }
            }
          }
          
          this.wxBalance = totalBalance;
        }
      });
      
      // 同时调用 DelWxBalance 获取今日线上已退费金额
      this.DelWxBalance();
    },
    
    DelWxBalance() {
      DelWxBalance().then(res => {
        if (res.code === 200) {
          // 后端返回的是 Map 集合，需要计算所有金额的总和
          const balanceMap = res.data;
          let totalBalance = 0;
          
          // 遍历 Map 中的所有值并相加
          for (const key in balanceMap) {
            if (balanceMap.hasOwnProperty(key)) {
              const amount = Number(balanceMap[key]);
              if (!isNaN(amount)) {
                totalBalance += amount;
              }
            }
          }
          
          this.todayRefundAmount = totalBalance;
        }
      });
    },
    
   
    // 登录验证
    validatePassword() {
      if (!this.username || !this.password) {
        this.passwordError = true;
        return;
      }
      // 账号密码验证：账号是 wjyy，密码是 sfs
      if (this.username === 'wjyy' && this.password === 'sfs') {
        this.passwordError = false;
        this.passwordVerified = true;
        this.showPasswordModal = false;
        
        // 保存登录状态到localStorage缓存中
        localStorage.setItem('tui_password_verified', 'true');
        
        // 如果勾选了记住密码，则保存账号密码
        if (this.rememberPassword) {
          localStorage.setItem('tui_username', this.username);
          localStorage.setItem('tui_password', this.password);
          localStorage.setItem('tui_remember_password', 'true');
        } else {
          // 否则清除保存的账号密码
          localStorage.removeItem('tui_username');
          localStorage.removeItem('tui_password');
          localStorage.removeItem('tui_remember_password');
        }
      } else {
        this.passwordError = true;
      }
    },
    
    // 显示退号退费弹窗
    showRefundTicketDialog() {
      this.patientId = '';
      this.showRefundTicket = true;
    },
    
    // 显示门诊退费弹窗
    showRefundOutpatientDialog() {
      this.orderNumber = '';
      this.showRefundOutpatient = true;
    },
    
    // 显示门诊自费退费弹窗
    showRefundSelfDialog() {
      this.patientId = '';
      this.showRefundSelf = true;
    },
    
    // 显示线上退钱不退his弹窗
    showRefundNoHisDialog() {
      this.refundNoHisOrderNo = '';
      this.refundNoHisAmount = '';
      this.showRefundNoHis = true;
    },
    
    // 确认线上退钱不退his
    confirmRefundNoHis() {
      if (!this.refundNoHisOrderNo) {
        Toast.fail('请输入订单号');
        return;
      }
      if (!this.refundNoHisAmount) {
        Toast.fail('请输入金额');
        return;
      }
      
      this.showLoading('退费处理中...');
      
      WxRefundOrder({
        powertranid: this.refundNoHisOrderNo,
        money: this.refundNoHisAmount,
        type: "微信"
      }).then(res => {
        this.hideLoading();
        if (res.code === 200) {
          Toast.success('退费成功');
          this.showRefundNoHis = false;
        } else {
          Toast.fail('退费失败：' + res.message);
        }
      }).catch(error => {
        this.hideLoading();
        Toast.fail('退费失败，请稍后重试');
        console.error('线上退钱不退his失败:', error);
      });
    },
    
    // 显示线上病案退费弹窗
    showRefundBaDialog() {
      this.refundBaPatientId = '';
      this.refundBaHosNum = '';
      this.showRefundBa = true;
    },
    
    // 查询病案信息
    searchBaInfo() {
      if (!this.refundBaPatientId && !this.refundBaHosNum) {
        Toast.fail('请输入患者ID或住院号');
        return;
      }
      
      this.showLoading('查询中...');
      
      apiGetBAList2({
        patientId: this.refundBaPatientId,
        hosNum: this.refundBaHosNum,
        method:"sfs"
      }).then(res => {
        this.hideLoading();
        if (res.code === 200) {
          console.log("病案记录为:", res.data);
          
          // 处理res.data可能是数组或单个对象的情况
          const rawData = res.data;
          const dataArray = Array.isArray(rawData) ? rawData : [rawData];
          
          // 提取需要的字段
          this.baList = dataArray.map(item => ({
            userId: item.userId || '',
            patientId: item.patientId || '',
            patientName: item.patientName || '',
            reName: item.reName || '',
            orderno: item.orderno || '',
            amount: item.amount || '',
            // 保留原始数据中的所有必要字段用于后续退费操作
            ...item
          }));
          
          // 显示病案记录列表
          this.showBaList = true;
        } else {
          Toast.fail('查询失败：' + res.message);
        }
      }).catch(error => {
        this.hideLoading();
        Toast.fail('查询失败，请稍后重试');
        console.error('查询病案信息失败:', error);
      });
    },
    
    // 确认病案退费
    confirmBaRefund(index) {
      if (index < 0 || index >= this.baList.length) {
        Toast.fail('请选择要退费的病案记录');
        return;
      }
      
      const selectedItem = this.baList[index];
      
      this.showLoading('退费处理中...');
      
      // 这里需要调用病案退费接口，假设也是使用WxRefundOrder
      WxRefundOrder({
        powertranid: selectedItem.orderno,
        money: selectedItem.amount,
        type: "全部"
      }).then(res => {
        this.hideLoading();
        if (res.code === 200) {
          Toast.success('退费成功');
          // 可以从列表中移除已退费的记录
          this.baList.splice(index, 1);
          if (this.baList.length === 0) {
            this.showBaList = false;
          }
        } else {
          Toast.fail('退费失败：' + res.message);
        }
      }).catch(error => {
        this.hideLoading();
        Toast.fail('退费失败，请稍后重试');
        console.error('病案退费失败:', error);
      });
    },
    
    // 显示加载提示
    showLoading(message = '加载中...') {
      this.loadingInstance = Toast.loading({
        message: message,
        forbidClick: true,
        duration: 0 // 0表示不自动关闭
      });
    },
    
    // 关闭加载提示
    hideLoading() {
      if (this.loadingInstance) {
        this.loadingInstance.clear();
        this.loadingInstance = null;
      }
    },
    
    // 根据就诊人ID查询挂号信息
    searchRegistrationInfo() {
      if (!this.patientId) {
        Toast.fail('请输入就诊人ID');
        return;
      }
      
      // 显示加载提示
      this.showLoading('查询中...');
      
      selectGuaHaoList({patientId: this.patientId,method:"sfs"}).then(res => {
        // 关闭加载提示
        this.hideLoading();
        
        if (res.code === 200) {
          console.log("此人的挂号记录为:", res.data);
          
          // 处理res.data可能是数组或单个对象的情况
          const rawData = res.data;
          const dataArray = Array.isArray(rawData) ? rawData : [rawData];
          
          // 提取用户需要的特定字段并转换为前端需要的格式
          this.registrationList = dataArray.map(item => ({
            // 保留原始数据中的所有必要字段用于后续退号操作
            id: item.id,
            patientid: item.patientid,
            reptnum: item.reptnum,
            orderno: item.orderno,
            zfamount: item.zfamount,
            hisopernum: item.hisopernum,
            paynature: item.paynature || 1, // 默认支付性质为1
            paytype: item.paytype || '微信', // 默认微信支付
            registerdate: item.registerdate, // 保留原始日期字段用于排序
            
            // 映射到前端显示字段
            patientName: item.name,
            registerTime: `${item.registerdate} ${item.timeinterval}`,
            department: item.ksmc,
            doctor: item.ysmc,
            refundAmount: `¥${item.zfamount.toFixed(2)}`,
            
            // 状态信息（4：已支付，1：已退号）
            status: item.appStatus,
            statusText: item.appStatus === 4 ? '已支付' : item.appStatus === 1 ? '已退号' : '未知状态'
          }))
          .filter(item => item.status === 4) // 只显示可退号的记录（已支付状态）
          .sort((a, b) => this.parseDate(b.registerdate) - this.parseDate(a.registerdate)); // 按照日期降序排序，最新日期在前
          
          // 如果有挂号记录，默认选中第一条
          if (this.registrationList.length > 0) {
            this.selectedIndex = 0;
            this.showRegistrationList = true;
          } else {
            Toast.info('未查询到可退号的挂号记录');
          }
        } else {
          Toast.fail("此人可能不是手机上挂号的，可能是自助机或者门诊处挂号");
        }
      }).catch(error => {
        // 关闭加载提示
        this.hideLoading();
        Toast.fail('查询失败，请稍后重试');
        console.error('查询挂号记录失败:', error);
      });
      
      // 移除模拟数据部分，只使用API返回的真实数据
      // 弹窗切换逻辑已在API回调中处理
    },
    // 日期格式化函数：将YYYYMMDD格式化为YYYY-MM-DD
    formatDate(dateStr) {
      if (!dateStr || dateStr.length !== 8) return '';
      // 将YYYYMMDD转换为YYYY-MM-DD
      return `${dateStr.substring(0, 4)}-${dateStr.substring(4, 6)}-${dateStr.substring(6, 8)}`;
    },
    // 解析日期，兼容iOS
    parseDate(dateStr) {
      if (!dateStr) return new Date();
      
      // 替换掉"-"分隔符为"/"，以兼容iOS
      if (dateStr.indexOf('-') > -1 && dateStr.indexOf('T') === -1) {
        dateStr = dateStr.replace(/-/g, '/');
      }
      
      return new Date(dateStr);
    },
    
    //门诊医保查询退费
    searchRegistrationInfo2(){
      if (!this.patientId) {
        Toast.fail('请输入就诊人ID');
        return;
      }
      this.showLoading('查询医保信息中...');
      selectYbByPatientId({patientId: this.patientId,method:"sfs"}).then(res => {
        this.hideLoading();
        if (res.code === 200) {
          console.log("此人的医保缴费信息为:", res.data);
          
          // 处理res.data可能是数组或单个对象的情况
          const rawData = res.data;
          const dataArray = Array.isArray(rawData) ? rawData : [rawData];
          
          // 转换为表格所需的数据格式
          this.ybPaymentList = dataArray.map(item => {
            // 解析detail字段获取patId
            let patId = '';
            try {
              const detail = JSON.parse(item.detail);
              patId = detail.patid || '';
            } catch (e) {
              console.error('解析detail失败:', e);
            }
            
            // 获取flowNo的前8位作为订单日期
            let orderDate = '';
            if (item.flowNo && item.flowNo.length >= 8) {
              const flowNoDate = item.flowNo.substring(0, 8);
              orderDate = this.formatDate(flowNoDate);
            }
            
            return {
              patId: patId,
              hospOutTradeNo: item.hospOutTradeNo || '',
              orderDate: orderDate,
              feeSumamt: item.feeSumamt || 0,
              ownPayAmt: item.ownPayAmt || 0,
              psnAcctPay: item.psnAcctPay || 0,
              fundPay: item.fundPay || 0,
              // 保留原始数据供退费使用
              originalData: item
            };
          });
          
          // 显示医保缴费信息弹窗
          if (this.ybPaymentList.length > 0) {
            this.showYbPaymentList = true;
          } else {
            Toast.info('未查询到医保缴费信息');
          }
        } else {
          Toast.fail("查询医保信息失败");
        }
      }).catch(error => {
        this.hideLoading();
        Toast.fail('查询医保信息失败，请稍后重试');
        console.error('查询医保信息失败:', error);
      });

    },
    
    // 门诊自费退费查询
    searchRegistrationInfo3() {
      if (!this.patientId) {
        Toast.fail('请输入就诊人ID');
        return;
      }
      // 显示加载提示
      this.showLoading('查询中...');
      selectOrderList({patientId: this.patientId,method:"sfs"}).then(res=>{
        this.hideLoading();
        if (res.code === 200) {
          // 处理查询结果，显示缴费记录列表
          console.log("此人的门诊自费缴费信息为:", res.data);
          
          // 处理res.data可能是数组或单个对象的情况
          const rawData = res.data;
          const dataArray = Array.isArray(rawData) ? rawData : [rawData];
          
          // 转换为表格所需的数据格式
          this.selfPaymentList = dataArray
            .filter(item => item.appStatus === 4) // 只显示已支付状态的记录
            .map(item => {
              // 处理支付时间，只保留日期部分
              let payTime = '';
              if (item.billtime) {
                payTime = item.billtime.split(' ')[0]; // 只取日期部分
              }
              
              return {
                patientId: item.patientid,
                orderNo: item.orderno,
                department: item.setdepartname,
                doctor: item.doctorname,
                amount: item.zfamount,
                payTime: payTime,
                // 保留原始数据供退费使用
                originalData: item
              };
            })
            .sort((a, b) => this.parseDate(b.payTime) - this.parseDate(a.payTime)); // 按支付时间降序排序
          
          // 显示门诊自费退费记录弹窗
          if (this.selfPaymentList.length > 0) {
            this.showSelfPaymentList = true;
          } else {
            Toast.info('未查询到门诊自费缴费记录');
          }
        } else {
          Toast.fail("查询失败");
        }
      }).catch(error => {
        this.hideLoading();
        Toast.fail('查询失败，请稍后重试');
        console.error('查询失败:', error);
      });
 
    },
    
    // 选择挂号记录
    selectRegistration(index) {
      this.selectedIndex = index;
    },
    
    // 确认门诊自费退费
    confirmSelfRefund(index) {
      if (index < 0 || index >= this.selfPaymentList.length) {
        Toast.fail('请选择要退费的缴费记录');
        return;
      }
      
      const selectedItem = this.selfPaymentList[index];
      
      // TODO: 这里添加门诊自费退费逻辑
      // 示例：调用退费API
      // apiopBillsPayedRefund({orderNo: selectedItem.orderNo}).then(res => {
      //   if (res.code === 200) {
      //     Toast.success('退费成功');
      //     this.showSelfPaymentList = false;
      //   } else {
      //     Toast.fail('退费失败：' + res.message);
      //   }
      // }).catch(error => {
      //   Toast.fail('退费失败，请稍后重试');
      //   console.error('门诊自费退费失败:', error);
      // });
      
      // 显示退费提示
      Dialog.confirm({
        title: '确认退费',
        message: `确定要为订单号 ${selectedItem.orderNo} 退费吗？`,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        // 用户点击确定后的操作
        this.showLoading('退费处理中...');
        
        // TODO: 这里添加实际的退费API调用
        WxRefundOrder({
          powertranid: selectedItem.orderNo,
          money: selectedItem.amount,
          type: "全部"
        }).then(res => {
          if (res.code === 200) {
            Toast.success('退费成功');
            this.showSelfPaymentList = false;
          } else {
            Toast.fail('退费失败：' + res.message);
          }
        }).catch(error => {
          Toast.fail('退费失败，请稍后重试');
          console.error('门诊自费退费失败:', error);
        });
        
      }).catch(() => {
        // 用户点击取消后的操作
        Toast.info('已取消退费');
      });
    },
    
    // 确认退号
    confirmRefund(index) {
      // 如果有传入index参数，则使用该参数，否则使用当前选中的索引
      const refundIndex = index !== undefined ? index : this.selectedIndex;
      
      if (refundIndex < 0 || refundIndex >= this.registrationList.length) {
        Toast.fail('请选择要退号的挂号记录');
        return;
      }
      
      const selectedItem = this.registrationList[refundIndex];
      
      // 限制退号时间：8:30 - 23:00
      const now = new Date();
      const hour = now.getHours();
      const minute = now.getMinutes();

      if (hour < 8 || (hour === 8 && minute < 30) || hour >= 23) {
        Toast("当前暂无法退号，请于每日8:30-23:00期间进行退号退费操作\n或到线下缴费处进行退费退号");
        return;
      }

      Dialog.confirm({
        title: '退号确认',
        message: `确定要退${selectedItem.department}${selectedItem.doctor}的号吗？\n注：退号需在挂号当天或次日9点后办理，超过就诊时间无法退费退号。\n退号后将无法恢复。`,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        // 真实退号操作
        this.showLoading('退号处理中...');
        
        // 从选中的挂号记录中获取formData所需的所有参数
        const formData = {
          patientid: selectedItem.patientid,
          billsmsg: selectedItem.reptnum,
          paynature: selectedItem.paynature,
          paytype: selectedItem.paytype,
          powertranid: selectedItem.orderno,
          zfamount: selectedItem.zfamount,
          ybzhamount: '',
          ybtcamount: '',
          yboutmsg: '',
          hisopernum: selectedItem.hisopernum,
          txsend: '退号'
        };
        console.log("formData",formData)
        apiopBillsPayedRefund(formData)
          .then((res) => {
            if (res && (res.code === 200 || res.code === "200")) {
              Toast("退号成功");
              
              // 退号成功后，从列表中移除该记录
              this.registrationList.splice(refundIndex, 1);
              
              // 如果还有记录，保持弹窗打开并重新选择第一条
              if (this.registrationList.length > 0) {
                this.selectedIndex = 0;
              } else {
                // 如果没有记录了，显示提示后关闭弹窗
                setTimeout(() => {
                  this.showRegistrationList = false;
                }, 1500);
              }
            } else {
              Toast({
                message: res.data?.message || res.message || "操作失败",
                duration: 6000,
                type: 'fail'
              });
            }
          })
          .catch((error) => {
            console.error("退号接口异常:", error);
            Toast({
              message: "退号失败: " + (error.message || "网络异常"),
              duration: 6000,
              type: 'fail'
            });
          })
          .finally(() => {
            this.hideLoading();
          });
      }).catch(() => {
        // 用户取消退号
      });
    },
    
    // 确认门诊退费
    confirmRefundOutpatient() {
      if (!this.orderNumber || !/^yb/i.test(this.orderNumber)) {
        Toast.fail('请输入有效的yb开头订单号');
        return;
      }
      
      this.showRefundOutpatient = false;
      Toast('门诊退费操作已确认，订单号已保留');
      console.log('门诊退费确认，订单号:', this.orderNumber);
      // 这里可以将订单号保存到全局状态或本地存储供后续操作使用
    },
    
    // 确认医保退费
    confirmYbRefund(index) {
      if (index < 0 || index >= this.ybPaymentList.length) {
        Toast.fail('请选择有效的医保缴费记录');
        return;
      }
      
      const selectedItem = this.ybPaymentList[index];
      
      // 限制退费时间：8:30 - 23:00
      const now = new Date();
      const hour = now.getHours();
      const minute = now.getMinutes();

      if (hour < 8 || (hour === 8 && minute < 30) || hour >= 23) {
        Toast("当前暂无法退费，请于每日8:30-23:00期间进行退费操作\n或到线下缴费处进行退费");
        return;
      }

      Dialog.confirm({
        title: '退费确认',
        message: `确定要退医保订单${selectedItem.hospOutTradeNo}的费用吗？\n退费金额：¥${selectedItem.feeSumamt}\n退费后将无法恢复。`,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        // 真实退费操作
       console.log("yb订单号是",selectedItem.hospOutTradeNo)
       refundOrderOnline({hosp_out_trade_no:selectedItem.hospOutTradeNo,refdType:"ALL"}).then(res=>{
        if(res.code === 200){
          Toast({
            message: "退费退款成功",
            duration: 5000
          })
          // 退费成功后，从列表中移除该记录
          this.ybPaymentList.splice(index, 1);
          
          // 如果还有记录，保持弹窗打开
          if (this.ybPaymentList.length === 0) {
            setTimeout(() => {
              this.showYbPaymentList = false;
            }, 1500);
          }
        }else{
          Toast({
            message: "授权码超时，请让用户扫码授权退款",
            duration: 5000
          })
        }
       }
       )
      }).catch(() => {
        // 用户取消退费
      });
    }
  },
};
</script>

<style scoped lang="scss">
// 全局变量定义
$primary-color: #1677FF;
$danger-color: #FF4D4F;
$light-gray: #F5F7FA;
$dark-gray: #6B7280;
$text-black: #1F2328;
$border-color: #E5E7EB;
$card-radius: 12px;
$modal-radius: 16px;
$spacing-sm: 8px;
$spacing-md: 16px;
$spacing-lg: 24px;

// 全局样式重置
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
}

// 页面容器
.home-container {
  min-height: 100vh;
  background-color: $light-gray;
  padding: $spacing-md;
}

// 核心内容容器（验证通过后显示）
.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
}

// 余额卡片组
.balance-card-group {
  display: flex;
  flex-direction: column;
  gap: $spacing-md;
  margin-bottom: $spacing-lg;

  @media screen and (min-width: 768px) {
    flex-direction: row;
    justify-content: space-between;
  }
}

// 余额卡片
.balance-card {
  background-color: #FFFFFF;
  border-radius: $card-radius;
  padding: $spacing-lg;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  flex: 1;
  min-width: 0;

  &__label {
    font-size: 14px;
    color: $dark-gray;
    margin-bottom: $spacing-sm;
  }

  &__amount {
    font-size: 24px;
    font-weight: 700;
    color: $primary-color;
  }
}

.refund-amount {
  color: $danger-color !important;
}

// 功能按钮组
.function-button-group {
  display: flex;
  flex-direction: column;
  gap: $spacing-md;
  margin-bottom: $spacing-lg;

  @media screen and (min-width: 768px) {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: $spacing-lg;
  }
}

// 功能按钮
.func-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  background: linear-gradient(135deg, $primary-color 0%, #0F62D9 100%);
  border: none;
  color: #FFFFFF !important;
  font-weight: 500;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(22, 119, 255, 0.3);
  }

  @media screen and (min-width: 768px) {
    height: 56px;
    font-size: 16px;
  }
}

// 登录弹窗
.modal-login {
  background-color: #FFFFFF;
  display: flex;
  flex-direction: column;

  &__header {
    text-align: center;
    margin-bottom: $spacing-lg;

    &__title {
      font-size: 18px;
      font-weight: 700;
      color: $text-black;
      margin-bottom: $spacing-sm;
    }

    &__desc {
      font-size: 14px;
      color: $dark-gray;
    }
  }

  &__form {
    margin-bottom: $spacing-lg;
  }

  &__footer {
    width: 100%;
  }
}

// 通用弹窗
.modal-common {
  background-color: #FFFFFF;
  padding: $spacing-lg;
  display: flex;
  flex-direction: column;

  &__title {
    font-size: 18px;
    font-weight: 700;
    color: $text-black;
    margin-bottom: $spacing-sm;
    text-align: center;
  }

  &__desc {
    font-size: 14px;
    color: $dark-gray;
    margin-bottom: $spacing-lg;
    text-align: center;
  }

  &__form {
    margin-bottom: $spacing-lg;
  }

  &__btns {
    display: flex;
    gap: $spacing-md;
    width: 100%;
  }
}

// 表格弹窗
.modal-table {
  height: 100%;
  background-color: #FFFFFF;
  display: flex;
  flex-direction: column;

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: $spacing-md $spacing-lg;
    border-bottom: 1px solid $border-color;

    &__title {
      font-size: 18px;
      font-weight: 700;
      color: $text-black;
    }
  }

  &__scroll {
    flex: 1;
    overflow: auto;
    padding: $spacing-lg;

    // 优化滚动条（Windows浏览器）
    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: $border-color;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background-color: $light-gray;
    }
  }
}

// 数据表格
.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
  min-width: 600px; // 保证桌面端表格不挤压

  thead {
    tr {
      background-color: $light-gray;

      th {
        padding: $spacing-md;
        text-align: center;
        font-weight: 700;
        color: $text-black;
        border: 1px solid $border-color;
        white-space: nowrap;
      }
    }
  }

  tbody {
    tr {
      &.table-row {
        &:nth-child(even) {
          background-color: rgba(245, 247, 250, 0.5);
        }

        &:hover {
          background-color: rgba(22, 119, 255, 0.05);
        }
      }

      &.table-row--selected {
        background-color: rgba(22, 119, 255, 0.1) !important;
      }

      td {
        padding: $spacing-md;
        text-align: center;
        color: $text-black;
        border: 1px solid $border-color;
        white-space: nowrap;
      }
    }
  }
}

// 表格金额样式
.table-amount {
  color: $primary-color;
  font-weight: 500;
}

// 表单输入框
.form-input {
  margin-bottom: $spacing-md;
  width: 100%;

  .van-field__control {
    font-size: 14px;
    color: $text-black;
    padding: 0 $spacing-sm;
  }

  .van-field__control::placeholder {
    color: $dark-gray;
    opacity: 0.7;
  }

  .van-field__left-icon {
    color: $dark-gray;
  }
}

// 记住密码
.form-remember {
  margin: $spacing-sm 0 $spacing-md 0;
  text-align: left;

  .remember-checkbox {
    font-size: 14px;
    color: $text-black;
  }
}

// 错误提示
.form-error {
  color: $danger-color;
  font-size: 13px;
  text-align: center;
  margin-top: $spacing-sm;
}

// 按钮通用样式
.btn-login {
  width: 100%;
  height: 44px;
  font-size: 16px;
  background-color: $primary-color;
  border: none;
}

.btn-cancel {
  flex: 1;
  height: 44px;
  font-size: 14px;
  color: $text-black;
  border: 1px solid $border-color;
  background-color: #FFFFFF;
}

.btn-confirm {
  flex: 1;
  height: 44px;
  font-size: 14px;
  background-color: $primary-color;
  border: none;
}

.btn-close {
  color: $dark-gray;

  &:hover {
    color: $text-black;
  }
}

.btn-operate {
  background-color: $danger-color;
  border: none;
  padding: 4px 8px;

  &:hover {
    background-color: #E83A3A;
  }
}

// 响应式适配（桌面端）
@media screen and (min-width: 1200px) {
  .home-container {
    padding: $spacing-lg;
  }

  .balance-card {
    padding: $spacing-lg * 1.5;
  }

  .modal-common {
    padding: $spacing-lg * 1.5;
  }
}

// 响应式适配（小屏手机）
@media screen and (max-width: 375px) {
  .balance-card__amount {
    font-size: 20px;
  }

  .func-btn {
    height: 44px;
    font-size: 14px;
  }
}
</style>