import { APPID, USERCODE, USE_PRIVATEKEY, MYpublicKey } from '../../config_sand.js';
import util from '../../utils_sand/util.js';

Page({
  data: {
    wechatData: null,
    orderNo: '',
    msg: '',
    sandpay: '',
    backing: true,
  },

  onLoad(options) {
    const { orderNo, back } = options;
    this.setData({ orderNo: orderNo || '' });
    if (back) this.setData({ backing: false });

    // Try cached order
    const cacheKey = `order_${orderNo}`;
    const cached = wx.getStorageSync(cacheKey);
    if (cached) {
      console.log('[Cache] Found cached payment data for', orderNo, cached);
      this.setData({ wechatData: cached });
      this.composeAndPay();
    } else if (orderNo) {
      this.initiateLogin(orderNo);
    } else {
      util.Tips({ title: '无效的订单号' });
    }
  },

  initiateLogin(orderNo) {
    wx.login({
      success: ({ code }) => this.fetchOpenId(code, orderNo),
      fail: () => util.Tips({ title: '微信登录失败' }),
    });
  },

  fetchOpenId(code, orderNo) {
    if (!orderNo) return util.Tips({ title: '订单号缺失' });
    wx.request({
      url: `https://mylive91.com/api/efps/wechat/miniapp/?code=${code}`,
      method: 'POST',
      success: res => {
        const { statusCode, data } = res;
        if (statusCode === 200 && data.success) {
          this.createOrder(orderNo, data.openid);
        } else {
          console.log(res)
          util.Tips({ title: `获取OpenID失败：${data.msg || statusCode}` });
        }
      },
      fail: err => {
        util.Tips({ title: `获取OpenID错误：${err?.statusCode ? err?.statusCode : ''} ${err?.data?.error ? err?.data?.error : ''} ${err?.errMsg  ? err?.errMsg : ''}` })
      },
    });
  },

  createOrder(orderNo, openId) {
    wx.request({
      url: `https://mylive91.com/api/web/wechatMiniAppPay?orderNo=${orderNo}&openId=${openId}`,
      method: 'POST',
      success: res => {
        const { statusCode, data } = res;
        if (statusCode === 200 && data.code === 200) {
          let outputJSON;
          try {
            outputJSON = JSON.parse(data.data.outputJSON);
          } catch (e) {
            return util.Tips({ title: `解析响应失败：${data.msg}` });
          }

          const { returnCode, returnMsg } = outputJSON;
          if (returnCode === '0000') {
            this.cacheOrder(this.data.orderNo, outputJSON);
            this.setData({ wechatData: outputJSON });
            this.composeAndPay();
          } else {
            util.Tips({ title: `创建订单失败：${returnMsg}` });
          }
        } else {
          util.Tips({ title: `下单失败：${data.msg}` });
        }
      },
      fail: err => util.Tips({ title: `下单错误：${err}` }),
    });
  },

  cacheOrder(orderNo, data) {
    try {
      const key = `order_${orderNo}`;
      wx.setStorageSync(key, data);
      console.log('[Cache] 保存订单', key, data);
    } catch (e) {
      console.warn('缓存订单失败', e);
    }
  },

  clearOrderCache(orderNo) {
    try {
      const key = `order_${orderNo}`;
      wx.removeStorageSync(key);
      console.log('[Cache] 清除订单缓存', key);
    } catch (e) {
      console.warn('清除订单缓存失败', e);
    }
  },

  launchAppError(e) {
    wx.showToast({ title: '跳回 App 失败', icon: 'none' });
  },

  composeAndPay() {
    const payData = this.data.wechatData.wxJsapiParam;
    if (!payData) return util.Tips({ title: '支付参数缺失' });

    wx.showLoading({ title: '加载中' });
    wx.hideLoading();
    try {
      wx.requestPayment({
        timeStamp: payData.timeStamp,
        nonceStr: payData.nonceStr,
        package: payData.package,
        signType: payData.signType,
        paySign: payData.paySign,
        success: () => {
          this.setData({ msg: '0000', back: true, sandpay: 'success' });
          this.clearOrderCache(this.data.orderNo);
        },
        fail: err => {
          console.error('支付失败', err);
          this.setData({ msg: '9999', back: true, sandpay: 'fail' });
        },
        complete: () => {},
      });
    } catch {
      this.setData({ msg: redirectUrl, sandpay: 'fail' });
    }
  },
});
