// pages/confirmVOrder.js
const getReq = require('../../config.js').getReq
import recordSource from '../../utils/recordSource';
import Bundle from '../../utils/Bundle'

let app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goods_id: '',
    ifcart: '0',
    num: '1',
    datas: {},
    goods_list: [],
    firstLoad: true,
    cart_id: '',
    n_goods_list: [],
    fromSource: '',
    available_pred: 0,
    room_bonus: 0,
    full_discount: 0,
    opgoods_discount: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // let goods_id = options.goods_id || ''
    // let iscart = options.iscart || ''
    // let num = options.num || ''
    // let cart_id = options.cart_id || ''
    let goods_id = '6217'
    let iscart = '0'
    let num = '1'
    let cart_id = ''
    
    this.setData({
      goods_id,
      ifcart: iscart,
      num,
      cart_id
    })
    this.getDatas(goods_id, iscart, num, cart_id)
  },
  getDatas(goods_id, ifcart, num, cart_id) {
    wx.showLoading({
      title: '加载中',
    })
    var self = this
    let goods_datas = '';
    if (ifcart == 0) {
      goods_datas = goods_id + '|' + num;
    }
    else {
      goods_datas = cart_id;
    }
    let fromSource = recordSource(app, `act=member_buy&op=step_first&curpage=1&cart_id=${goods_datas}&ifcart=${ifcart}&client_type=mini`)
    let params = {
      act: 'member_buy',
      op: 'step_first',
      curpage: 1,
      cart_id: goods_datas,
      ifcart,
      from: fromSource
    }    
    // this.setData({
    //   fromSource: app.globalData.fromSource
    // }),
    getReq(app,params, function (res) {
      wx.hideLoading()
      if (res.code == 200) {
        let datas = res.datas
        console.log(res.datas.toString())
        let { goods_list, summary, bundling, vpayinfo } = res.datas
        let { goods_amount,consignee } = vpayinfo
        let totalPrice = parseFloat(goods_amount + '0.0').toFixed(2)
        let n_goods_list = self.getNewGoodsList(goods_list, summary, bundling)
        self.setData({
          datas,
          n_goods_list,
          totalPrice,
          firstLoad: false,
        })
      }
      else {
        wx.showToast({
          icon: 'none',
          title: res.message,
          duration: 2000
        })
        app.globalData.fcodeErr = res.message
        wx.navigateBack()
      }
    })
  },
  toPay() {
    let goods_id = this.data.goods_id
    let goods_num = this.data.num
    let iscart = this.data.ifcart
    let cart_id = this.data.cart_id

    let ifcart = cart_id ? 1 : 0
    let cartids = cart_id ? cart_id : (goods_id + '|' + goods_num)
    let params = {
      act: 'member_buy',
      op: 'step_vsecond',
      payment: 'minipay',
      usebonus: 1,
      ifcart,
      cart_id: cartids,
      invoice_id: 0
    }
    params = Object.assign({}, params);
    getReq(app,params, function (res) {
      wx.hideLoading()
      if (res.code == 200) {
        let param = res.datas.param.data
        let pay_sn = res.datas.pay_sn
        wx.requestPayment({
          timeStamp: param.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: param.nonceStr,   //随机串
          package: param.package,
          signType: param.signType, //微信签名方式：
          paySign: param.paySign,   //微信签名
          success: function (res) {
            wx.reLaunch({
              url: "/pages/index/index"
            })
          },
          fail: function (res) {
            wx.redirectTo({
              url: `/pages/orderPaySn/orderPaySn?pay_sn=${pay_sn}`
            })
          }
        });
      }
      else {
        wx.showToast({
          icon: 'none',
          title: res.message,
          duration: 2000
        })
        app.globalData.fcodeErr = res.message
        setTimeout(() => {
          wx.navigateBack()
        }, 2000);
      }
    })
  },
  getNewGoodsList(goods_list, summary, bundling) {
    let summaryMap = new Map()
    let bundlingMap = new Map()
    summary.map(item => {
      summaryMap.set(item['goods_id'], item)
    })
    if (bundling.length) {
      bundling.map(item => {
        bundlingMap.set(item['bl_id'], item)
      })
    }
    let n_goods_list = new Bundle(goods_list, summaryMap, bundlingMap).createOrders()
    return n_goods_list
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // if (!this.data.firstLoad) {
    //   app.setFromSource(this.data.fromSource)
    //   let self = this
    //   let defaultAddress = app.globalData.defaultAddress
    //   if (!defaultAddress) return
    //   let { city_id, area_id } = defaultAddress
    //   let { freight_hash } = self.data
    //   let params = {
    //     act: 'member_buy',
    //     op: 'change_addrex',
    //     city_id,
    //     area_id,
    //     freight_hash
    //   }
    //   getReq(params, function(res) {
    //     if (res.code == 200) {
    //        let { freight } = res.datas
    //        let prev_freight = self.data.freight
    //        let totalPrice = parseFloat((self.data.totalPrice - prev_freight + freight).toFixed(2))
    //        self.setData({
    //         totalPrice
    //       })
    //     }
    //   })    
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})