import { diamonds, diamondVirtualPayment, updatesessionkey, updateuserinfo, userInfo } from '../../../utils/request';

interface CoinPackage {
  id: number
  coins: number
  price: number
  ribbon?: string
  ribbonClass?: string
  artClass: string
  chest?: boolean
  selected: boolean
}
Page({
  data: {
    packages: [],
    selectedPackage: null as CoinPackage | null,
    userInfo: { diamond: 0 }
  },

  onLoad() {
    this.setData({ userInfo: wx.getStorageSync('userInfo') })
    diamonds().then((res: any) => {
      if (!res.code) {
        this.setData({ packages: res.data });
      }
    })
  },

  handleBack() {
    wx.navigateBack({
      fail: () => wx.switchTab({ url: '/pages/my/my' }),
    })
  },
  handlePackageTap(e: WechatMiniprogram.TouchEvent) {
    const id = e.currentTarget.dataset.id
    const selectedPackage = this.data.packages.find((item: CoinPackage) => item.id === id) || this.data.selectedPackage

    this.setData({
      selectedPackage,
    })
  },
  handleBuy() {
    const that = this;
    if (that.data.selectedPackage == null) {
      return;
    }
    wx.showLoading({ title: '处理中, 请稍后.', mask: true });
    wx.checkSession({
      success() {
        that.payment();
      },
      fail() {
        wx.login({
          success(login) {
            updatesessionkey(login.code).then((res: any) => {
              if (!res.code) {
                that.payment();
              } else {
                wx.showModal({
                  title: '温馨提示',
                  content: res.message,
                  showCancel: false
                })
              }
            })
          }
        })

        wx.hideLoading();
      }
    })
  },

  payment() {
    let that = this;
    diamondVirtualPayment((that.data.selectedPackage || { id: 0 }).id).then((res: any) => {
      wx.requestVirtualPayment({
        signData: JSON.stringify(res.param.signData),
        paySig: res.param.paySig,
        signature: res.param.signature,
        mode: res.param.mode,
        success(result: any) {
          wx.hideLoading();
          console.log(result)

          userInfo().then((res: any) => {
            if (!res.code) {
              wx.setStorageSync('userInfo', res.data);
              that.setData({ userInfo: res.data });
            }
          })
        },
        fail(error: any) {
          wx.hideLoading();
          console.log(error);
          wx.showModal({
            title: '温馨提示',
            content: '支付失败',
            showCancel: false
          })
        }
      });
    }).catch(() => {
      wx.hideLoading();
      wx.showModal({
        title: '温馨提示',
        content: '系统繁忙, 请稍后再试',
        showCancel: false
      })
    })
  }
})
