// 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: '',
    formPhone: '',
    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],
    sessionId: '',
    visible: false,
    errMsg: false,
    // 价格展示
    vip_price: 0,
    novip_price: 0,
    total_price: 0,

    addressdf: null, // 默认收货地址
    exist_address: false, // 是否存在收货地址
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.id) {
      this.setData({
        id: options.id
      })
    }

    // 获取session id
    let that = this
    this.getSessionKey(function(sid) {
      that.setData({
        sessionId: sid
      })
    })
  },

  /**
   * 快递配送：选择收货地址
   */
  onSelectAddress() {
    wx.navigateTo({
      url: '/pages/address/' + (this.data.exist_address ? 'index?from=flow' : 'create')
    });
  },

  /**
   * 保存手机号
   */
  savePhone() {
    //发送请求保存手机号
    const phone = this.data.formPhone
    api.getPhoneNumber({
      phone: phone
    }).then(res => {
      if (!res.code) {
        // 将刚拿到的手机号码放到全局数据中，否则phone数据只会是当前页面数据
        if (app.globalData.userInfo) {
          app.globalData.userInfo.phone = res.data.phone
        }
        this.setData({
          phone: res.data.phone,
          visible: false
        })

        if (res.is_relation) {
          $Toast({
            content: '温馨提示:手机号授权成功,系统已自动关联您在其他平台购买的美行者VIP会员',
            type: 'success'
          });

        } else {
          $Toast({
            content: '手机号授权成功',
            type: 'success'
          });
        }

        //在拉去一遍用户信息
        this.getUserInfo();
      } else {
        this.setData({
          'errMsg': true,
          'errMessage': '*' + res.msg
        })
      }
    })

  },

  //获取用户信息
  // 获取个人资料
  getUserInfo: function() {
    api.me.info().then(res => {
      if (!res.code) {
        console.log(res.data);
        app.globalData.userInfo = res.data
        // 渲染数据
        this.setData({
          user: res.data,
        })
      }
    })
  },

  /**
   * 关闭手机号填写弹窗
   */
  alertClose() {
    this.setData({
      visible: false
    });
  },

  /**
   * 打开手机号填写弹窗
   */
  openAlert() {
    this.setData({
      visible: true
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  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
      })
    }
    // 获取个人地址
    this.getUserAddress();
  },

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

  // 个人收获地址
  getUserAddress: function() {
    let that = this
    api.address.userdf().then(res => {
      if (!res.code) {
        this.setData({
          exist_address: res.data.exist_address,
          addressdf: res.data.address
        })
      }
    })
  },

  // 获取手机号
  handlePhoneAuth: function(event) {
    // 获取session key
    let encryptedData = event.detail.encryptedData
    let iv = event.detail.iv
    let that = this
    // 检查session key是否过期，如果过期的话，那么就获取新的再请求，否则直接请求
    wx.checkSession({
      success: function(res) {
        //session_key未过期，直接操作
        let sessionId = that.data.sessionId
        api.getPhoneNumber({
          sessionId: sessionId,
          encryptedData: encryptedData,
          iv: encodeURIComponent(iv)
        }).then(res => {
          if (!res.code) {
            $Toast({
              content: '手机号授权成功',
              type: 'success'
            });
            that.setData({
              phone: res.data.phone
            })
            // 将刚拿到的手机号码放到全局数据中，否则phone数据只会是当前页面数据
            if (app.globalData.userInfo) {
              app.globalData.userInfo.phone = res.data.phone
            }
          } else {
            $Toast({
              content: res.msg,
              type: 'error'
            });
          }
        })
      },
      fail: function() {
        console.log('checkSession fail!')
        // session_key 已过期，进行登录操作，提示错误
        // 获取session id
        let that = this
        this.getSessionKey(function(sid) {
          that.setData({
            sessionId: sid
          })
          // 授权手机号
          api.getPhoneNumber({
            sessionId: sid,
            encryptedData: encryptedData,
            iv: encodeURIComponent(iv)
          }).then(res => {
            if (!res.code) {
              $Toast({
                content: '手机号授权成功',
                type: 'success'
              });
              that.setData({
                phone: res.data.phone
              })
              // 将刚拿到的手机号码放到全局数据中，否则phone数据只会是当前页面数据
              if (app.globalData.userInfo) {
                app.globalData.userInfo.phone = res.data.phone
              }
            } else {
              $Toast({
                content: res.msg,
                type: 'error'
              });
            }
          })
        })
      }
    })
  },

  /**
   * 获取服务器端 session key
   */
  getSessionKey(callback) {
    Wx.login().then(res => {
      if (res.errMsg == 'login:ok') {
        api.getSessionKey({
          code: res.code
        }).then(res => {
          if (res.code == 0) {
            typeof callback == "function" && callback(res.data)
          } else {
            $Toast({
              content: res.msg,
              type: 'error'
            });
          }
        })
      } else {
        $Toast({
          content: 'wx.login失败',
          type: 'error'
        });
      }
    })
  },

  /**
   * 解密手机号数据
   */
  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) {
    let familyNum = parseInt(event.detail.value)
    this.setData({
      familyNum: familyNum
    })
    this.projectOrderPrice()
  },

  // 计算价格 - 服务器端获取
  projectOrderPrice: function() {
    api.project.orderPrice({
      pid: this.data.id,
      sign_limits: (this.data.familyNum + 1)
    }).then(res => {
      if (!res.code) {
        this.setData({
          vip_price: res.data.vip_price,
          novip_price: res.data.novip_price,
          total_price: res.data.total_price
        })
      }
    })
  },

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

  handlePhone: function(event) {
    this.setData({
      formPhone: event.detail.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 (!that.data.exist_address) {
      $Toast({
        content: '请添加收货地址',
        type: 'error'
      });
      return
    }

    // if (!this.data.nickname || !this.data.phone) {
    //   $Toast({
    //     content: '请完善必要信息',
    //     type: 'error'
    //   });
    //   return
    // }
    // if (this.data.phone.length == 0) {
    //   $Toast({
    //     content: '请授权手机号',
    //     type: 'error'
    //   });
    //   return
    // }

    wx.showNavigationBarLoading()
    wx.showLoading({
      title: '加载中...',
    })

    api.project.order({
      pid: this.data.id,
      sign_limits: this.data.familyNum + 1,
      address_id: this.data.addressdf.address_id
      // 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 => {
      wx.hideNavigationBarLoading()
      wx.hideLoading()
      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.redirectTo({
                    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)
    })
  }

})