import { baseUrl, globalImgUrl } from "../../../request";

Page({
  data: {
    countdown: '',
    orderId: 0,
    orderObj: {},  // 订单详情对象
    _secondsRemaining: 0,   // 内部倒计时秒数
    _hasShownTimeout: false, // 是否已弹过“超时未支付”弹窗
    globalImgUrl,
    isMaskVisible: false
  },

  onLoad(options) {
    console.log('options---->',options);
    this.setData({ orderId: options.id });
    this.getOrderDetail();
  },
  showIsPayModal() {
    const {orderId} = this.data
    wx.showModal({
      title: '下单成功',
      content: '您确定要支付吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: (res) => {
        if (res.confirm) {
          this.payOrder(orderId);
        } else if (res.cancel) {
          this.setData({ isMaskVisible: false });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，下单失败',
          icon: 'none'
        });
      }
    });
  },
  payOrder(orderId) {
    // 同样先显示遮罩
 this.setData({ isMaskVisible: true });
   wx.showLoading({ title: '支付中...'});
   wx.request({
     url: baseUrl + '/courseOrder/payment',
     method: 'POST',
     header: { Authorization: wx.getStorageSync('token') },
     data: { id: orderId},
     success: res => {
       wx.hideLoading();
       if (res.data.code === 1) {
         // 支付成功，跳转详情页
         wx.redirectTo({
           url: `/pages/course/orderDetail/orderDetail?id=${orderId}`,
           success: res => {
               // 先把遮罩关掉
               this.setData({ isMaskVisible: false });
           }
         });
       } else {
         this.setData({ isMaskVisible: false });
         wx.showToast({ title: res.data.message || '支付失败', icon: 'none' });
       }
     },
     fail: () => {
       wx.hideLoading();
       this.setData({ isMaskVisible: false });
       wx.showToast({ title: '网络错误，支付失败', icon: 'none' });
     }
   });
 },
  onUnload() {
    clearInterval(this._timer);
  },

  // 拉取订单详情并初始化倒计时
  getOrderDetail() {
    wx.request({
      url: baseUrl + '/courseOrder/query/detail',
      method: 'POST',
      data: { id: this.data.orderId },
      header: { Authorization: wx.getStorageSync('token') },
      success: res => {
        console.log('订单详情--->',res.data.data);
        if (res.data.code !== 1) return wx.showToast({ title: res.data.message, icon: 'none' });
        
        const order = res.data.data;
        this.setData({ orderObj: order });

        // 仅“待支付”需要倒计时
        if (order.orderStatus === '待支付') {
          this._initFromCreateTime(order.createTime);
        }
      },
      fail: () => wx.showToast({ title: '网络错误', icon: 'none' })
    });
  },

  // 计算剩余秒数并启动定时器
  _initFromCreateTime(createTime) {
    // 将 "2025-07-13 12:38:17" → 时间戳
    const createMs = new Date(createTime.replace(/-/g, '/')).getTime();
    const now = Date.now();
    let diff = Math.floor((createMs + 15 * 60 * 1000 - now) / 1000);

    if (diff <= 0) {
      // 已超时
      this._handleTimeout();
    } else {
      // 未超时，初始化秒数并启动倒计时
      this.setData({
        _secondsRemaining: diff,
        countdown: this._format(diff)
      });
      this._startTimer();
    }
  },

  // 每秒递减
  _startTimer() {
    this._timer = setInterval(() => {
      let sec = this.data._secondsRemaining - 1;
      if (sec <= 0) {
        clearInterval(this._timer);
        this._handleTimeout();
      } else {
        this.setData({
          _secondsRemaining: sec,
          countdown: this._format(sec)
        });
      }
    }, 1000);
  },

  // 超时处理：弹窗 + 改状态
  _handleTimeout() {
    if (!this.data._hasShownTimeout) {
      wx.showModal({
        title: '提示',
        content: '订单超时未支付，已取消',
        showCancel: false
      });
      this.setData({ _hasShownTimeout: true });
    }
    // 更新状态并隐藏倒计时
    const o = this.data.orderObj;
    o.orderStatus = '交易取消';
    this.setData({
      orderObj: o,
      countdown: '00分00秒'
    });
  },

  // 秒数 → "MM分SS秒"
  _format(sec) {
    const m = Math.floor(sec / 60);
    const s = sec % 60;
    const mm = m < 10 ? '0' + m : m;
    const ss = s < 10 ? '0' + s : s;
    return `${mm}分${ss}秒`;
  },

  // 取消订单
  cancelOrder() {
    wx.showModal({
      title: '取消订单',
      content: '是否要取消订单？',
      success: res => {
        if (res.confirm) {
          wx.request({
            url: baseUrl + "/courseOrder/cancel",
            method: 'POST',
            data: { courseId: this.data.orderId },
            header: { Authorization: wx.getStorageSync('token') },
            success: () => this.getOrderDetail()
          });
        }
      }
    });
  },

  // 去支付（示例跳转）
  goPay() {
    // wx.navigateTo({ url: `/pages/pay/pay?orderId=${this.data.orderId}` });
    wx.showToast({ title: '支付功能稍后开放', icon: 'none' });
  },

  // 退款（示例弹窗）
  refundOrder() {
    wx.showToast({ title: '退款功能稍后开放', icon: 'none' });
  }
});
