<template>
  <div class="home">
    <nav-bar title="我的申请单" />

    <div class="application-list-container">
      <div class="list-header">
        <h2 class="title">我的病案申请</h2>
        <p class="count">{{ applications.length }} 条申请记录</p>
      </div>

      <div class="applications-list">
        <div v-if="applications.length === 0" class="empty-state">
          <div class="empty-icon">
            <i class="fa fa-file-text-o" aria-hidden="true"></i>
          </div>
          <p class="empty-text">暂无申请记录</p>
        </div>

        <div v-for="(item, index) in applications" :key="index" class="application-item">
          <div v-if="getWatermarkType(item)" class="watermark-container">
            <div class="watermark" :class="getWatermarkClass(item)">
              {{ getWatermarkText(item) }}
            </div>
          </div>

          <div class="application-info">
            <div class="info-row">
              <span class="label">就诊人：</span>
              <span class="value">{{ item.patientName }}</span>
            </div>

            <div class="info-row">
              <span class="label">住院号：</span>
              <span class="value">{{ item.hosNumber }}</span>
            </div>

            <div class="info-row">
              <span class="label">住院时间：</span>
              <span class="value">{{ formatDate(item.inhosDate) }} - {{ formatDate(item.outhosDate) }}</span>
            </div>

            <div class="info-row">
              <span class="label">病案页数：</span>
              <span class="value">{{ item.pages || '等待病案室医生审核填写' }}</span>
            </div>

            <div class="info-row">
              <span class="label">办理人：</span>
              <span class="value">{{ item.handleType === '1' ? '本人办理' : '他人代办' }}</span>
            </div>

            <div class="info-row" v-if="item.handleType === '2' && item.reName">
              <span class="label">代办人：</span>
              <span class="value">{{ item.reName }}</span>
            </div>

            <div class="info-row">
              <span class="label">取件方式：</span>
              <span class="value">{{ item.deliveryType === '1' ? '自取' : '邮寄' }}</span>
            </div>

            <div class="info-row" v-if="item.amount !== null && item.status === 1 && item.send === 0">
              <span class="label">待支付金额：</span>
              <span class="value pay-amount">{{ item.amount }} 元</span>
            </div>

            <div class="info-row pickup-code" v-if="item.status === 2 && item.code">
              <span class="label">取件码：</span>
              <span class="value">{{ item.code }}</span>
            </div>
          </div>

          <div class="action-buttons">
            <button class="cancel-btn" v-if="canCancelApplication(item)" @click="showCancelConfirm(item)">
              取消申请
            </button>

            <button class="pay-btn" v-if="item.amount !== null && item.status === 1 && item.send === 0"
              @click="goToPayment(item)">
              去缴费
            </button>

            <button class="ship-btn" v-if="item.status === 2 && item.send === 0 && item.deliveryType === '2'"
              @click="goToShipping(item)">
              通知快递取件
            </button>
            <button class="ship-btn" v-if="item.status === 2 && item.send === 0 && item.deliveryType === '1'"
              @click="goToShipping(item)">
              到院自取
            </button>
          </div>
        </div>
      </div>
    </div>

    <div v-if="showCancelDialog" class="dialog-overlay">
      <div class="dialog">
        <div class="dialog-header">
          <h3>确认取消申请？</h3>
        </div>
        <div class="dialog-content">
          <p>您确定要取消该病案申请吗？取消后将无法恢复。</p>
        </div>
        <div class="dialog-footer">
          <button class="dialog-btn cancel" @click="showCancelDialog = false">
            取消
          </button>
          <button class="dialog-btn confirm" @click="confirmCancel()">
            确认取消
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { apiGetBAList, apiDeleteApplication, apiBAPay, apiOpWxQuery } from "@/request/api.js";
import { Toast } from "vant";

export default {
  data() {
    return {
      applications: [],
      showCancelDialog: false,
      currentItem: null,  // 存储当前要删除的item
      isPaying: false, // 新增：标记是否正在支付中
      fetchTimer: null, // 定时器ID
    };
  },

  mounted() {
    this.fetchApplications();
    // 设置每20秒查询一次
    this.fetchTimer = setInterval(() => {
      this.fetchApplications();
    }, 20000);
  },

  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.fetchTimer) {
      clearInterval(this.fetchTimer);
      this.fetchTimer = null;
    }
  },

  methods: {
    formatDate(dateStr) {
      if (!dateStr) return '';
      return dateStr.replace(/-/g, '/');
    },

    fetchApplications() {
      apiGetBAList().then(res => {
        if (res.code === 200) {
          console.log(res.data);
          this.applications = res.data;
        } else {
          console.error('获取申请列表失败:', res.message);
        }
      }).catch(err => {
        console.error('请求出错:', err);
      });
    },

    canCancelApplication(item) {
      return [3, 1].includes(item.status);
    },

    showCancelConfirm(item) {
      this.currentItem = item;  // 存储当前item
      this.showCancelDialog = true;
    },

    /**
     * 确认取消申请
     * 从列表中移除当前申请项，关闭弹窗并重置索引
     */
    confirmCancel() {
      if (!this.currentItem) return;

      // 调用后端删除接口，传递当前item作为参数
      // console.log(this.currentItem);
      let params = {
        "id": this.currentItem.id
      }
      apiDeleteApplication(params)
        .then(res => {
          if (res.code === 200) {
            Toast('申请已成功取消');
            this.fetchApplications(); // 重新获取列表数据
          } else {
            Toast(`取消失败：${res.message || '服务器异常'}`);
          }
        })
        .catch(err => {
          console.error('取消申请接口调用失败:', err);
          Toast('网络异常，取消失败，请稍后重试');
        })
        .finally(() => {
          // 无论成功失败，都关闭弹窗并重置当前item
          this.showCancelDialog = false;
          this.currentItem = null;
        });
    },

    goToPayment(item) {
     // 防止重复点击：如果正在支付中，直接返回
    if (this.isPaying) return;
    
    console.log("去支付", item);
    this.isPaying = true; // 标记为支付中
    // 显示加载中Toast
    Toast.loading({
      forbidClick: true, // 禁止背景点击
      message: '处理中...',
      duration: 0 // 不自动关闭
    });
    this.handleWechatPay(item);
    },
    handleWechatPay(item) {
      let params = {
        id: item.id,
        amount: item.amount,
        pages: item.pages,
        selectAmount: item.selectAmount,
        userId: item.userId
      }
      console.log("this.params", params);
      apiBAPay(params).then((ref) => {
        if (ref.code === 200) {
          //调用微信支付
          try {

            const data = ref.data;

            // 兼容不同字段名
            let payParams = {
              appId: data.appid || data.appId,
              timeStamp: data.timeStamp || data.timestamp,
              nonceStr: data.nonce_str || data.nonceStr,
              package: data.package || `prepay_id=${data.prepay_id || data.prepayId}`,
              signType: 'MD5',
              paySign: data.paySign
            };

            console.log('支付参数:', payParams);

            // 查询参数
            let queryParams = {
              outTradeNo: data.outTradeNo
            };
            console.log('订单号:', queryParams.outTradeNo);

            // 验证必要参数
            const requiredParams = ['appId', 'timeStamp', 'nonceStr', 'package', 'paySign'];
            for (let param of requiredParams) {
              if (!payParams[param]) {
                Toast(`缺少支付参数: ${param}`);
                return;
              }
            }

            if (typeof WeixinJSBridge == "undefined") {
              Toast("请在微信中打开页面进行支付");
              return;
            }
         
            // 调起微信支付
            WeixinJSBridge.invoke('getBrandWCPayRequest', payParams, (res) => {
              console.log('微信支付返回:', res);
              console.log("订单号：", queryParams.outTradeNo);
              // 关闭加载中Toast（无论支付结果如何）
              Toast.clear();
              this.isPaying = false; // 重置状态
              if (res.err_msg && res.err_msg.indexOf('ok') > -1) {
                // ✅ 支付成功，启动轮询
                this.startPaymentPolling(queryParams); // 调用组件方法
              } else if (res.err_msg && res.err_msg.indexOf('cancel') > -1) {
                Toast("用户取消支付");
              } else {
                Toast("支付失败: " + (res.err_msg || '未知错误'));
              }
            });

          } catch (error) {
            console.error('支付调用异常:', error);
            Toast("支付调用失败");
           this.isPaying = false; // 重置状态
          }
        }
      }).catch((err) => {
       console.error('支付接口调用失败:', err);
        Toast("通讯异常，请稍后重试");
        this.isPaying = false; // 重置状态
        Toast.clear(); // 关闭加载中
      });
    },
    // 独立方法：启动轮询查询支付结果
   startPaymentPolling(queryParams) {
  // 防止重复启动
  if (this.pollTimer) {
    clearInterval(this.pollTimer);
    this.pollTimer = null;
  }

  const toast = Toast.loading({
    forbidClick: true,
    message: '正在查询支付结果...',
    loadingType: 'circular',
    duration: 0
  });

  let pollCount = 0;
  const maxPollCount = 15; // 最多 30 秒（15次 × 2秒）

  this.pollTimer = setInterval(() => {
    pollCount++;
    console.log(`第 ${pollCount} 次轮询查询支付状态...`);

    apiOpWxQuery(queryParams)
      .then((res) => {
        console.log('查询响应:', res);

        if (res.code === 200) {
          const data = res.data;
          const state = data.trade_state;

          if (state === 'SUCCESS') {
            // 支付成功
            clearInterval(this.pollTimer);
            this.pollTimer = null;
            toast.clear();
            Toast.success("支付成功");
            this.isPaying = false; // 额外保险：重置状态
            this.fetchApplications();
          } else if (state === 'NOTPAY') {
            // 继续等待
            console.log('用户尚未支付');
          } else {
            // 其他失败状态
            clearInterval(this.pollTimer);
            this.pollTimer = null;
            toast.clear();
            Toast.fail("支付失败：" + (data.trade_state_desc || state));
            this.isPaying = false; // 重置状态
          }
        } else {
          console.warn('查询接口异常:', res);
        }
      })
      .catch((error) => {
        console.error('查询请求失败:', error);
      })
      .finally(() => {
        if (pollCount >= maxPollCount) {
          if (this.pollTimer) {
            clearInterval(this.pollTimer);
            this.pollTimer = null;
          }
          toast.clear();
          Toast.fail("支付超时，请稍后查看订单状态");
          this.isPaying = false; // 重置状态
        }
      });
  }, 2000);

  // 总超时兜底（30秒）
  setTimeout(() => {
    if (this.pollTimer) {
      clearInterval(this.pollTimer);
      this.pollTimer = null;
    }
    if (toast) {
      toast.clear();
    }
    this.isPaying = false; // 重置状态
  }, maxPollCount * 2000);
},

    goToShipping(item) {
      if (item.deliveryType === '1') {
        alert(`请从门诊楼进入,到7号窗口病案室,凭借取件码【${item.code}】取病案。`);
        return;
      }
      const message = `姓名: 武警宁夏总队医院病案室
手机号码: 0951-4078114
所在地区: 宁夏回族自治区银川市兴庆区清和南街895号
详细地址: 宁夏武警医院门诊楼7号窗口病案室`
      this.copyToClipboard(message);
    },

    copyToClipboard(text) {
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text).then(() => {
          alert('医院地址信息已复制到剪贴板，请联系顺丰或者邮政上门取件，发件人地址请使用医院地址。');
        }).catch(err => {
          console.error('复制失败:', err);
          this.fallbackCopyTextToClipboard(text);
        });
      } else {
        this.fallbackCopyTextToClipboard(text);
      }
    },

    fallbackCopyTextToClipboard(text) {
      const textArea = document.createElement("textarea");
      textArea.value = text;
      textArea.style.position = "fixed";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();

      try {
        const successful = document.execCommand('copy');
        if (successful) {
          alert('医院地址信息已复制到剪贴板，请联系顺丰或者邮政上门取件，发件人地址请使用医院地址');
        } else {
          alert('复制失败，请重新尝试');
        }
      } finally {
        document.body.removeChild(textArea);
      }
    },

    getWatermarkType(item) {
      if (item.send === 1) return 'picked';
      if (item.send === 2) return 'shipped';
      if (item.status === 2) return 'paid';
      if (item.amount !== null && item.status === 1) return 'unpaid';
      if (item.amount === null && item.status === 3) return 'pending';
      return null;
    },

    getWatermarkText(item) {
      const type = this.getWatermarkType(item);
      const texts = {
        pending: '待审核',
        unpaid: '待支付',
        paid: '已支付',
        picked: '已自取',
        shipped: '已邮寄'
      };
      return texts[type] || '';
    },

    getWatermarkClass(item) {
      return this.getWatermarkType(item);
    }
  }
};
</script>

<style scoped lang="scss">
/* 样式保持不变 */
.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 0.35rem;
  padding-top: 0.25rem;
  border-top: 1px solid #f0f0f0;
  gap: 0.2rem;
}

.cancel-btn {
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 0.08rem;
  padding: 0.15rem 0.35rem;
  font-size: 0.35rem;
  cursor: pointer;
  transition: background-color 0.2s;

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

.pay-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 0.08rem;
  padding: 0.15rem 0.35rem;
  font-size: 0.35rem;
  cursor: pointer;
  transition: background-color 0.2s;

  &:hover {
    background-color: #096dd9;
  }
}

.ship-btn {
  background-color: #52c41a;
  color: white;
  border: none;
  border-radius: 0.08rem;
  padding: 0.15rem 0.35rem;
  font-size: 0.35rem;
  cursor: pointer;
  transition: background-color 0.2s;

  &:hover {
    background-color: #43a047;
  }
}

.home {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.application-list-container {
  flex: 1;
  width: 100%;
  padding: 0.4rem;
  box-sizing: border-box;
}

.list-header {
  margin-bottom: 0.4rem;
}

.title {
  font-size: 0.42rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 0.15rem;
}

.count {
  font-size: 0.35rem;
  color: #666;
  margin: 0;
}

.applications-list {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
}

.application-item {
  background-color: #fff;
  border-radius: 0.18rem;
  padding: 0.35rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease;
  position: relative;

  &:hover {
    transform: translateY(-0.05rem);
  }
}

.watermark-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.watermark {
  width: 3.5rem;
  height: 1.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.6rem;
  font-weight: bold;
  transform: rotate(-30deg);
  border-width: 0.06rem;
  border-style: solid;
  border-radius: 0.1rem;
  margin-right: -4rem;
}

.watermark.pending {
  color: #faad14;
  border-color: #faad14;
  background-color: rgba(250, 173, 20, 0.05);
}

.watermark.unpaid {
  color: #1890ff;
  border-color: #1890ff;
  background-color: rgba(24, 144, 255, 0.05);
}

.watermark.paid {
  color: #52c41a;
  border-color: #52c41a;
  background-color: rgba(82, 196, 26, 0.05);
}

.watermark.picked {
  color: #8c8c8c;
  border-color: #8c8c8c;
  background-color: rgba(140, 140, 140, 0.05);
}

.watermark.shipped {
  color: #8c8c8c;
  border-color: #8c8c8c;
  background-color: rgba(140, 140, 140, 0.05);
}

.info-row {
  display: flex;
  margin-bottom: 0.25rem;
  align-items: flex-start;

  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  font-size: 0.35rem;
  color: #666;
  width: 2.1rem;
  margin-right: 0.15rem;
  flex-shrink: 0;
}

.value {
  font-size: 0.35rem;
  color: #333;
  flex: 1;
  word-break: break-word;
  line-height: 1.6;
}

.pickup-code {
  margin-top: 0.3rem;
  padding-top: 0.2rem;
  border-top: 1px dashed #eee;
}

.pickup-code .label {
  font-size: 0.4rem;
  color: #555;
  align-self: center;
}

.pickup-code .value {
  font-size: 0.7rem;
  color: #1890ff;
  font-weight: 700;
  letter-spacing: 0.05rem;
  line-height: 1.2;
}

.pay-amount {
  color: #ff4d4f;
  font-weight: 600;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 1.5rem 0.4rem;
  color: #999;
  text-align: center;
}

.empty-icon {
  font-size: 1rem;
  margin-bottom: 0.4rem;
  color: #ccc;
}

.empty-text {
  font-size: 0.38rem;
  margin: 0;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s;
}

.dialog {
  background-color: white;
  border-radius: 0.18rem;
  width: 85%;
  max-width: 6rem;
  animation: scaleIn 0.3s;
}

.dialog-header {
  padding: 0.35rem;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  font-size: 0.4rem;
  color: #333;
  text-align: center;
}

.dialog-content {
  padding: 0.4rem;
}

.dialog-content p {
  margin: 0;
  font-size: 0.35rem;
  color: #666;
  text-align: center;
  line-height: 1.8;
}

.dialog-footer {
  display: flex;
  padding: 0.25rem 0.35rem;
  border-top: 1px solid #eee;
}

.dialog-btn {
  flex: 1;
  padding: 0.18rem 0;
  border-radius: 0.08rem;
  font-size: 0.38rem;
  cursor: pointer;
  transition: background-color 0.2s;
  border: none;
  margin: 0 0.15rem;
}

.dialog-btn.cancel {
  background-color: #f5f5f5;
  color: #333;

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

.dialog-btn.confirm {
  background-color: #ff4d4f;
  color: white;

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

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes scaleIn {
  from {
    transform: scale(0.9);
    opacity: 0;
  }

  to {
    transform: scale(1);
    opacity: 1;
  }
}
</style>