// pages/confirmOrder/confirmOrder.js
var http = require('../../utils/http.js');
var config = require("../../utils/config.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderPath: '',
    fullItemObj: {},
    totalPrice: 0,
    goodsPrice: 0,
    transfee: 0,
    orderParam: {},
    userAddr: null,
    remarks: ""
  },

  onRemarksInput: function(e) {
    this.setData({
      remarks: e.detail.value
    });
  },

  // 获取orderPath
  getSeckill() {
    var _this = this
    http.request({
      url: '/p/seckill/orderPath',
      method: 'GET',
      callBack: (res) => {
        _this.setData({
          orderPath: res
        })
        _this.confirmOrder()
      }
    })
  },

  // 确认订单
  confirmOrder() {
    var secKillObj = wx.getStorageSync("secKillObj")
    if (this.data.userAddr) {
      secKillObj.addrId = this.data.userAddr.addrId
    }
    var orderPath = this.data.orderPath
    var _this = this
    http.request({
      url: `/p/seckill/${orderPath}/confirm`,
      method: 'POST',
      data: secKillObj,
      callBack: (res) => {
        _this.setData({
          fullItemObj: res,
          goodsPrice: res.shopCartItem.prodCount * res.shopCartItem.seckillPrice,
          transfee: res.transfee,
          totalPrice: res.transfee + res.shopCartItem.prodCount * res.shopCartItem.seckillPrice,
          userAddr: res.userAddr
        })
      }
    })
  },
  // 提交订单
  commitOrder() {
    this.createSocket()
  },
  // ws
  createSocket() {
    var _this = this
    wx.closeSocket()
    var st = wx.connectSocket({
      url: `${config.wsDomain}/seckill/websocket/${this.data.orderPath}`,
      method: 'get',
      fail: function(err) {
        wx.showToast({
          title: 'ws连接失败',
        })
        console.log(err)
      },
      success: function(res) {
        console.log("connect")
        console.log(res)

      }
    })

    st.onOpen(function(res) {
      console.log("open")
      console.log(res)
      wx.showLoading({
        title: '正在拼命抢购',
        mask: true
      })
      setTimeout(() => {
        var orderShopParam = {
          remarks: _this.data.remarks,
          shopId: _this.data.fullItemObj.shopCartItem.shopId

        }
        http.request({
          url: `/p/seckill/${_this.data.orderPath}/submit`,
          method: 'POST',
          data: orderShopParam
        })
      }, 1000)

    })

    st.onError(function(res) {
      console.log("error")
      console.log(res)
    })
    st.onClose(function(res) {
      console.log("close")
      console.log(res)
    })
    st.onMessage(function(res1) {
      console.log("mesg")
      console.log(res1)
      var orderParam = JSON.parse(res1.data)
      if (!orderParam.success) {
        wx.showToast({
          title: orderParam.msg,
          icon: "none"
        })
        return
      }
      if (orderParam.obj) {
        _this.calWeixinPay(orderParam.obj);
      }
      wx.closeSocket()
    })
  },

  /**
   * 唤起微信支付
   */
  calWeixinPay: function(orderNumbers) {
    wx.showLoading({
      mask: true
    });
    var params = {
      url: "/p/order/pay",
      method: "POST",
      data: {
        payType: 1,
        orderNumbers: orderNumbers
      },
      callBack: function(res) {
        wx.hideLoading();
        wx.requestPayment({
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          package: res.package,
          signType: res.signType,
          paySign: res.paySign,
          success: e => {
            wx.navigateTo({
              url: '/pages/pay-result/pay-result?sts=1&orderNumbers=' + orderNumbers + "&orderType=" + this.data.orderType,
            })
          },
          fail: err => {
            wx.navigateTo({
              url: '/pages/pay-result/pay-result?sts=0&orderNumbers=' + orderNumbers + "&orderType=" + this.data.orderType,
            })
          }
        })

      }
    };
    http.request(params);
  },

  /**
   * 选择地址
   */
  toAddrListPage: function() {
    wx.navigateTo({
      url: '/pages/delivery-address/delivery-address?order=0',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    if (currPage.data.selAddress == "yes") {
      this.setData({ //将携带的参数赋值
        userAddr: currPage.data.item
      });
    }
    this.getSeckill()
  },

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

  },

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

  },

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

  },

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

  },

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

  }
})