import {
  getProducts,
  getTasks,
  submitTask,
} from '~/api/global'
import {
  buyVip,
  buyNum,
  getMyInfo,
  getVipInfo,
  exchangePhone,
  bindPhone
} from '~/api/user'
import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
  store
} from '~/store/index'
const app = getApp()
Page({
  data: {
    userInfo: {},
    vipTime: '',
    tasks: [],
    isIos: app.globalData.isIOS,
    productNum: {},
    productVip: {}
  },
  onLoad() {
    this.getProducts()
    // 手工绑定 
    this.storeBindings = createStoreBindings(this, {
      store,
      actions: {
        setUser: 'setUser'
      }
    })
  },
  async onShow() {
    if (typeof this.getTabBar === 'function') {
      this.getTabBar().setData({
        selected: 4
      })
    }
    let uid = wx.getStorageSync('uid') || ''
    if (!uid) {
      getApp().callBack = (res) => {
        this.setUserInfo()
      }
    } else {
      this.setUserInfo()
    }
  },
  // 设置用户信息及vip状态和任务完成情况
  async setUserInfo() {
    let userInfo = await getMyInfo()
    let vipTime = await getVipInfo()
    this.setUser(userInfo.user)
    this.getTasks()
    this.setData({
      userInfo,
      vipTime,
    })
  },
  async getTasks() {
    let tasks = await getTasks()
    this.setData({
      tasks
    })
  },
  async getProducts() {
    let products = await getProducts()
    let productVip = products.find(item => {
      return item.type == 1
    })
    let productNum = products.find(item => {
      return item.type == 2
    })
    this.setData({
      productNum,
      productVip
    })
  },
  //购买vip和购买次数不是一个接口 type 1001是vip,1010是次数
  async toBuy({
    currentTarget
  }) {
    let productId = currentTarget.dataset.type
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    let res = ''
    if (productId == '1001') {
      res = await buyVip({
        productId
      }).finally(() => {
        wx.hideLoading()
      })
    } else if (productId == '1010') {
      res = await buyNum({
        productId
      }).finally(() => {
        wx.hideLoading()
      })
    } else {
      wx.hideLoading()
      wx.showToast({
        title: "支付失败,请重试",
        icon: "none",
        duration: 3000
      })
    }
    let {
      timeStamp,
      nonceStr,
      signType,
      paySign
    } = res
    // package保留字
    wx.requestPayment({
      timeStamp,
      nonceStr,
      package: res.package,
      signType,
      paySign,
      success(res) {
        wx.showToast({
          title: "支付成功",
          duration: 2500
        })
        setTimeout(() => {
          this.setUserInfo()
        }, 1500)
      },
      fail(res) {
        wx.showToast({
          title: "支付失败",
          icon: "none",
          duration: 3000
        })
      }
    })
  },
  // 提交任务
  async submitTask({
    currentTarget
  }) {
    let id = currentTarget.dataset.type
    await submitTask({
      id
    })
    wx.showToast({
      title: id == '1' ? '签到成功!' : id == 3 ? "观看成功!" : "",
      icon: "none",
      duration: 2000
    })
    this.setUserInfo()
  },
  async getPhoneNumber({
    detail
  }) {
    if (detail.code) {
      let mobile = await exchangePhone({
        code: detail.code
      })
      await bindPhone({
        mobile
      })
      this.setUserInfo()
      wx.showToast({
        title: '绑定成功!已获得7天VIP',
        icon: "none",
        duration: 4000
      })
    }
  },
  jump({
    currentTarget
  }) {
    let url = currentTarget.dataset.url
    wx.navigateTo({
      url: url
    });
  },
  // 调起广告
  rewardedVideo() {
    if (this.data.tasks.length != 3 || this.data.tasks[2].completed) {
      return
    }
    this.selectComponent('#advert').rewardedVideo();
  },
  clipboar() {
    wx.setClipboardData({
      data: this.data.userInfo.user.eid,
      success: function (res) { //成功回调函数
        wx.showToast({
          title: '已复制',
          icon: "none"
        })
      }
    })
  },
  // 分享配置
  onShareAppMessage: function (res) {
    const user = wx.getStorageSync('uid');
    return {
      title: '自从用了它,家里朗朗书声,美妙极了!你家孩子也快来试试!',
      path: `/pages/index/index?uid=${user}`,
      imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/375-300-1.jpg'
    }
  },
  onShareTimeline: function () {
    return {
      title: '终于找到适合孩子的朗读神器了!动画配音,边玩边学!',
      query: `uid=${wx.getStorageSync('uid')}`,
      imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/yuwen.jpg'
    }
  },
})