<template>
  <div class="home">
    <nav-bar/>
    <p class="usage-note">仅用于线上门诊缴费使用医保缴费时需退款使用，且咨询门诊收费室配合退费。</p>
    <!-- 授权成功信息显示 -->
    <div v-if="showAuthSuccess" class="success-message-container">
      <div class="success-icon">✓</div>
      <div class="success-title">授权完成</div>
      <div class="success-content">请等待收费室操作医保退款</div>
    </div>
    <!-- 授权按钮 -->
    <div v-else class="button-container">
        <Button type="primary" class="auth-button" @click="handleMedicalInsurancePay('tuifei')">授权退款</Button>
    </div>
    
  </div>
</template>

<script>
// 脚本部分与之前一致，省略重复代码
import { Toast } from 'vant';
import { preCheck, getPayAuthCode } from "@/request/api.js";

export default {
  data() {
    return {
      returnUrl: 'https://nxwj.btlsoln.com/nxwj-gzh/#/ybAUTH', // 回调地址
      card: {},
      isPaying: false,
      TuiFei: '',
      showAuthSuccess: false // 授权成功显示标志
    };
  },
  mounted() {
    // 处理授权回调
    this.card = JSON.parse(sessionStorage.getItem("card"));
    console.log("card:", this.card);
       this.TuiFei = this.$route.query.TuiFei || this.$route.params.TuiFei || '';
   
    // 处理授权回调
    let authCode = this.$route.query.authCode;
    let retCode = this.$route.query.retCode;
// alert(`authCode: ${authCode}, retCode: ${retCode}, 地址：${window.location.href}`);
    if (retCode === '0' && authCode) {
    // this.radiovalue1='微信医保支付';
      this.getPayAuth(authCode);
      // 不return，允许后续执行getData()（或在getPayAuth中调用）
    }

    
   
    
  },
  methods: {
    getPayAuth(code) {
      // 显示加载中Toast（回跳后立即显示）
      const loadingToast = Toast.loading({
        message: '加载中...',
        forbidClick: true, // 禁止点击背景
        duration: 0 // 不自动关闭
      });

      let params = {
        qrcode: code
      };
    //   alert(params.qrcode);
      console.log(params);
      getPayAuthCode(params).then((res) => {
        console.log(res);
        if (res.code == 200) {
         
              loadingToast.clear(); // 授权成功时关闭加载
              this.showAuthSuccess = true; // 显示页面上的授权成功信息
              this.isPaying = false;
         
        }
      }).catch(err => {
        console.error("授权流程失败", err);
        Toast.fail("授权失败，请稍后重试");
        loadingToast.clear();
        this.isPaying = false;
      });
    },
 handleMedicalInsurancePay(item) {
      // 显示加载中Toast
      const loadingToast = Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0 // 不自动关闭
      });

      preCheck().then(res => {
        if (res.code === 200) {
          // 生成带参数的returnUrl（关键！）
          const returnUrlWithParams = `${this.returnUrl}${item ? `?TuiFei=${item}` : ''}`;
          const encodedReturnUrl = encodeURIComponent(returnUrlWithParams);

          let authUrl = res.data;
          if (authUrl.includes('?')) {
            authUrl += '&redirectUrl=' + encodedReturnUrl;
          } else {
            authUrl += '?redirectUrl=' + encodedReturnUrl;
          }

          // 关闭Toast后跳转
          loadingToast.clear();
          window.location.href = authUrl; // 跳转授权页
        } else {
          // API返回非成功状态
          loadingToast.clear();
          Toast.fail('请求失败，请稍后重试');
        }
      }).catch(err => {
        // 捕获请求异常
        loadingToast.clear();
        console.error('医保支付检查失败:', err);
        Toast.fail('网络请求失败，请稍后重试');
      });
    },
  }
};
</script>

<style scoped lang="scss">
.home {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.usage-note {
  padding: 15px 20px;
  margin: 0 20px 20px;
  background-color: #fff3cd;
  border: 1px solid #ffeeba;
  border-radius: 8px;
  color: #856404;
  font-size: 0.4rem;
  line-height: 1.5;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.button-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.auth-button {
  width: 80%;
  max-width: 400px;
  height: 3rem;
  font-size: 0.6rem;
  font-weight: 600;
  border-radius: 25px;
  box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
  transition: all 0.3s ease;
}

.auth-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 123, 255, 0.4);
}

.auth-button:active {
  transform: translateY(0);
}

/* 授权成功信息样式 */
.success-message-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  text-align: center;
}

.success-icon {
  width: 100px;
  height: 100px;
  background-color: #07c160;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 50px;
  color: white;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(7, 193, 96, 0.3);
}

.success-title {
  font-size: 1.2rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.success-content {
  font-size: 0.8rem;
  color: #666;
  line-height: 1.5;
}
</style>