var api = require('../../utils/api')

Page({
  data: {
    statusBarHeight: 44,
    plans: [],
    selected: 'yearly',
    purchasing: false,
    subscription: null,
    subRemaining: 0,
    loadingPlans: true
  },

  onBack: function () {
    wx.navigateBack({
      fail: function () {
        wx.reLaunch({ url: '/pages/index/index' })
      }
    })
  },

  onLoad: function () {
    var app = getApp()
    this.setData({ statusBarHeight: app.globalData.statusBarHeight })
  },

  onShow: function () {
    this.loadPlans()
    this.loadSubscription()
  },

  loadPlans: function () {
    var self = this
    self.setData({ loadingPlans: true })
    api.getPlans().then(function (data) {
      var serverPlans = data.plans || []
      var monthlyPrice = 99
      for (var i = 0; i < serverPlans.length; i++) {
        if (serverPlans[i].key === 'monthly') monthlyPrice = serverPlans[i].price
      }
      var plans = serverPlans.map(function (p) {
        var daily = p.days > 0 ? (p.price / p.days).toFixed(1) : 0
        var desc = ''
        if (p.key === 'trial') desc = p.days + '天免费体验'
        else if (p.key === 'yearly') desc = '省¥' + Math.round(monthlyPrice * 12 - p.price)
        else desc = '约' + daily + '元/天'
        return {
          key: p.key,
          name: p.name,
          price: p.price,
          priceLabel: p.key === 'trial' ? '免费' : '¥' + p.price,
          desc: desc,
          tag: p.key === 'yearly' ? '推荐' : '',
          disabled: false
        }
      })
      if (plans.length > 0) self.setData({ plans: plans })
      self.setData({ loadingPlans: false })
      self.checkTrialUsed()
    }).catch(function () {
      self.setData({
        loadingPlans: false,
        plans: [
          { key: 'trial', name: '试用', price: 0, priceLabel: '免费', desc: '7天免费体验', disabled: false },
          { key: 'monthly', name: '月卡', price: 99, priceLabel: '¥99', desc: '约3.3元/天' },
          { key: 'yearly', name: '年卡', price: 899, priceLabel: '¥899', desc: '省¥289', tag: '推荐' }
        ]
      })
      self.checkTrialUsed()
    })
  },

  checkTrialUsed: function () {
    var self = this
    var sub = self.data.subscription
    if (sub && sub.trial_used) {
      var plans = self.data.plans.map(function (p) {
        if (p.key === 'trial') return Object.assign({}, p, { disabled: true, tag: '已使用' })
        return p
      })
      self.setData({ plans: plans })
      if (self.data.selected === 'trial') self.setData({ selected: 'yearly' })
    }
  },

  loadSubscription: function () {
    var self = this
    api.getSubscription().then(function (sub) {
      self.setData({
        subscription: sub,
        subRemaining: sub.remaining_days || 0
      })
      self.checkTrialUsed()
    }).catch(function () {})
  },

  onAgreement: function () {
    wx.showModal({ title: '提示', content: '订阅协议内容建设中', showCancel: false })
  },

  onSelect: function (e) {
    this.setData({ selected: e.currentTarget.dataset.plan })
  },

  onPurchase: function () {
    var self = this
    var selected = this.data.selected
    var plan = null
    for (var i = 0; i < this.data.plans.length; i++) {
      if (this.data.plans[i].key === selected) {
        plan = this.data.plans[i]
        break
      }
    }
    if (!plan || plan.disabled) return

    if (plan.key === 'trial') {
      wx.showModal({
        title: '激活试用',
        content: '免费试用 ' + plan.desc + '？',
        success: function (res) {
          if (res.confirm) self.doActivateTrial()
        }
      })
      return
    }

    var isRenew = self.data.subscription && self.data.subscription.status === 'active' && self.data.subRemaining > 0
    var planDays = plan.key === 'yearly' ? 365 : 30
    var title = isRenew ? '确认续费' : '确认支付'
    var content = isRenew
      ? '在现有订阅基础上延长' + planDays + '天，支付 ¥' + plan.price
      : '支付 ¥' + plan.price

    wx.showModal({
      title: title,
      content: content,
      success: function (res) {
        if (res.confirm) {
          self.doPurchase(plan)
        }
      }
    })
  },

  doActivateTrial: function () {
    var self = this
    self.setData({ purchasing: true })
    api.activateTrial().then(function () {
      self.setData({ purchasing: false })
      wx.showToast({ title: '试用已激活', icon: 'success' })
      setTimeout(function () {
        wx.redirectTo({ url: '/pages/subscribe-success/subscribe-success?plan=trial' })
      }, 1000)
    }).catch(function (err) {
      self.setData({ purchasing: false })
      wx.showToast({ title: err.message || '激活失败', icon: 'none' })
    })
  },

  doPurchase: function (plan) {
    var self = this
    self.setData({ purchasing: true })
    api.purchase(plan.key).then(function (data) {
      if (!data.payment_params) {
        self.setData({ purchasing: false })
        wx.showToast({ title: '支付服务暂不可用', icon: 'none' })
        return
      }

      var params = data.payment_params
      self._currentOrderId = data.order_id
      wx.requestPayment({
        timeStamp: params.timeStamp,
        nonceStr: params.nonceStr,
        package: params.package,
        signType: params.signType,
        paySign: params.paySign,
        success: function () {
          // Payment dialog succeeded, sync order to confirm
          self.syncAndRedirect(data.order_id, plan.key)
        },
        fail: function (err) {
          self.setData({ purchasing: false })
          var msg = (err.errMsg || '').indexOf('cancel') > -1 ? '已取消支付' : '支付失败'
          wx.showToast({ title: msg, icon: 'none' })
        }
      })
    }).catch(function (err) {
      self.setData({ purchasing: false })
      wx.showToast({ title: err.message || '创建订单失败', icon: 'none' })
    })
  },

  syncAndRedirect: function (orderId, planKey) {
    var self = this
    var retryCount = 0
    var maxRetries = 3

    function pollSync() {
      api.syncPaymentOrder(orderId).then(function (result) {
        if (result.status === 'paid') {
          self.setData({ purchasing: false })
          wx.showToast({ title: '支付成功', icon: 'success' })
          setTimeout(function () {
            wx.redirectTo({ url: '/pages/subscribe-success/subscribe-success?plan=' + planKey })
          }, 1000)
        } else if (retryCount < maxRetries) {
          retryCount++
          setTimeout(pollSync, 2000)
        } else {
          self.setData({ purchasing: false })
          wx.showToast({ title: '支付处理中，请稍后在订阅页查看', icon: 'none' })
        }
      }).catch(function () {
        if (retryCount < maxRetries) {
          retryCount++
          setTimeout(pollSync, 2000)
        } else {
          self.setData({ purchasing: false })
          wx.showToast({ title: '支付处理中，请稍后在订阅页查看', icon: 'none' })
        }
      })
    }
    pollSync()
  }
})
