// pages/me/collection/index.js
import api from '../../../utils/Api.js'
import Schedule from '../../../utils/Schedule.js'
import Wx from '../../../utils/Wx.js'
const {
  $Toast
} = require('../../../iview/base/index');
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: {},
    user: {},
    loading: false,

    familyNum: 0,
    phone: '',
    nickname: '',
    adultNum: 0,
    childrenNum: 0,
    childrenAge: 0,
    address: '',
    remark: '',
    // 订单
    order: {},
    nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.id) {
      this.setData({
        id: options.id
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    let that = this
    wx.showNavigationBarLoading()
    wx.showLoading({
      title: '加载中...',
    })
    new Schedule().task(this.getDetailData).delay(1200).task(() => {
      wx.hideNavigationBarLoading()
      wx.hideLoading()
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      user: app.globalData.userInfo
    })
    this.setData({
      nickname: app.globalData.userInfo.nickname
    })
    if (app.globalData.userInfo.phone && app.globalData.userInfo.phone.length > 0) {
      this.setData({
        phone: app.globalData.userInfo.phone
      })
    }
  },

  getDetailData: function() {
    api.project.detail({
      id: this.data.id
    }).then(res => {
      if (!res.code) {
        this.setData({
          detail: res.data
        })
      }
    })
  },

  handlePhoneAuth: function(event) {
    Wx.login().then(res => {
      console.log('wx.login', res, ' event:', event)
      let encryptedData = event.detail.encryptedData
      let iv = event.detail.iv
      this.decodePhoneData(res.code, encryptedData, iv)
    })
  },

  /**
   * 解密手机号数据
   */
  decodePhoneData: function(code, encryptedData, iv) {
    let that = this
    api.getPhoneNumber({
      code: code,
      encryptedData: encryptedData,
      iv: encodeURIComponent(iv),
      version: 1.1
    }).then(res => {
      console.log('iv: ', iv, ' res.code: ', res.code)
      if (!res.code) {
        $Toast({
          content: '手机号授权成功',
          type: 'success'
        });
        this.setData({
          phone: res.data.phone
        })
        // 将刚拿到的手机号码放到全局数据中，否则phone数据只会是当前页面数据
        if (app.globalData.userInfo) {
          app.globalData.userInfo.phone = res.data.phone
        }
      } else {
        $Toast({
          content: res.msg,
          type: 'error'
        });
      }
    })
  },

  // 家庭组数
  bindPickerChange: function(event) {
    this.setData({
      familyNum: parseInt(event.detail.value)
    })
  },

  handleNickname: function(event) {
    this.setData({
      nickname: event.detail.value
    })
  },

  handleAdultNum: function(event) {
    this.setData({
      adultNum: parseInt(event.detail.value)
    })
  },

  handleChildrenNum: function(event) {
    this.setData({
      childrenNum: parseInt(event.detail.value)
    })
  },

  handleChildrenAge: function(event) {
    this.setData({
      childrenAge: event.detail.value
    })
  },

  handleRemark: function(event) {
    this.setData({
      remark: event.detail.value
    })
  },
  handleAddress: function(event) {
    this.setData({
      address: event.detail.value
    })
  },

  handleSubmit: function() {
    let that = this
    if (!this.data.nickname || !this.data.phone) {
      $Toast({
        content: '请完善必要信息',
        type: 'error'
      });
      return
    }
    if (this.data.phone.length == 0) {
      $Toast({
        content: '请授权手机号',
        type: 'error'
      });
      return
    }
    api.project.order({
      pid: this.data.id,
      sign_limits: this.data.familyNum + 1,
      nickname: this.data.nickname,
      phone: this.data.phone,
      adult_number: this.data.adultNum + 1,
      children_number: this.data.childrenNum + 1,
      children_age: this.data.childrenAge,
      remark: this.data.remark,
      address: this.data.address
    }).then(res => {
      if (res.code) {
        $Toast({
          content: res.msg,
          type: 'error'
        });
      } else {
        console.log("获取支付参数", res)
        that.setData({
          order: res.data
        })
        // 发起微信支付
        wx.requestPayment({
          timeStamp: '' + res.result.timeStamp,
          nonceStr: '' + res.result.nonceStr,
          package: '' + res.result.package,
          signType: '' + res.result.signType,
          paySign: '' + res.result.paySign,
          success: function(ret) {
            console.log(ret)
            if (ret.errMsg === 'requestPayment:ok') {
              that.setOrderPaid(that.data.order.order_id, function(res) {
                // 支付同步回调结果
                console.log("发送模版消息", res)
                // 跳转到订单页面
                wx.showToast({
                  title: '支付成功',
                })
                setTimeout(() => {
                  wx.navigateTo({
                    url: '/pages/me/order/index?order=1',
                  })
                }, 800)
              })
            } else {
              wx.showToast({
                title: ret.errMsg,
              })
            }
          }
        })
      }
    })
  },

  /**
   * 同步支付结果回调：发送模版消息
   */
  setOrderPaid(id, callback) {
    let params = {
      order_id: id
    }
    api.me.vipOrderSendTemplate(params).then(res => {
      typeof callback == "function" && callback(res)
    })
  }

})