// subPackagesB/pages/GroupConfirm/GroupConfirm.js
import {
  get,
  post
} from '../../../utils/http'
var timer;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    store_name: '', //店铺名称
    goodsDetailsList: '', //美妆产品详情
    cardDetailList: '', //次卡产品详情
    source: '', //产品类型
    store_id: '', //店铺ID
    goods_id: '', //美妆产品ID
    payNow: false, //控制提交订单弹出框
    inserllAmount: '', // 我的储值
    pay_methon: 1, //支付方式 1微信2储值
    orderId: '', //订单ID
    groupPrice: '', //拼团价格
    isGrouping: '', //是否是拼团购买
    original_price: '', //原价
    groupID: '', //拼团活动ID
    isSuccess: '', //是否是去拼团进入
    grouping_id: '', //拼团记录ID
    isCheckOrder: true, //判断支付后是否成功
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
        // 禁用分享
        wx.hideShareMenu()
    // 获取美妆产品Id&&产品类型&&店铺ID
    console.log(options);
    let isSuccess = false
    if (options.isSuccess) {
      isSuccess = true
    }
    this.setData({
      goods_id: options.productId,
      source: options.source,
      store_id: options.store_id || wx.getStorageSync('store_id'),
      groupPrice: options.groupPrice,
      isGrouping: JSON.parse(options.isGrouping),
      original_price: options.original_price,
      groupID: options.groupID,
      isSuccess,
      grouping_id: options.grouping_id
    })
    if (options.source == 'goods') {
      // 获取美妆产品详情
      this.getGoodsDetail()
    } else {
      // 获取次卡详情
      this.getCardDetail()
    }
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearTimeout(timer)
  },

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

  },

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

  },

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

  },

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

  },
  // 获取美妆产品详情
  getGoodsDetail() {
    let params = {
      goods_ids: this.data.goods_id,
      store_id: this.data.store_id,
      type: 2
    }
    post('v2/api/goods_order/confirm', params, (res) => {
      if (res.code == 200) {
        console.log(res);
        this.setData({
          store_name: res.data.store_name,
          goodsDetailsList: res.data.list
        })
      }
    })
  },
  // 获取次卡详情
  getCardDetail() {
    get('v2/api/card/info', {
      id: this.data.goods_id,
      store_id: this.data.store_id || wx.getStorageSync('store_id')
    }, (res) => {
      this.setData({
        cardDetailList: res.data
      })
    })
  },
  // 单独购买提交订单
  onCardgoodsPay() {
    // 判断是美妆还是次卡下单
    let url = this.data.source == 'goods' ? 'v2/api/car/closing' : 'v2/api/order/card/add'
    let params = this.data.source == 'goods' ? {
      goods_ids: this.data.goods_id,
      store_id: this.data.store_id || wx.getStorageSync('store_id'),
      type: 2,
    } : {
      store_id: this.data.store_id || wx.getStorageSync('store_id'),
      id: this.data.goods_id,
      group_type: 1,
      group: '',
    }
    post(url, params, res => {
      if (res.code == 200) {
        if (res.data.pay_status == 1) {
          wx.showToast({
            title: '支付成功',
            icon: 'success'
          })
          // 只有项目购买，需要订阅消息
          wx.reLaunch({
            url: `/pages/paySuccess/paySuccess?current=1&source=goods&order_id=${res.data.order_id}`
          })
        } else {
          this.setData({
            payNow: true,
            orderId: res.data.order_id
          })
          this.getAmount()
        }
      }
    })
  },
  // 拼团购买提交订单
  onNewPay() {
    post('v2/api/grouping/buy', {
      id: this.data.groupID,
      store_id: this.data.store_id,
      grouping_id: this.data.grouping_id || ''
    }, res => {
      this.setData({
        payNow: true,
        orderId: res.data.order_id
      })
      this.getAmount()
    })
  },
  // 获取拼团记录ID
  getGroupRecordID(order_id, goods_type) {
    get('v2/api/grouping/get_grouping_id', {
      order_id,
      goods_type
    }, (res) => {
      if (res.data.grouping_id != '') {
        this.setData({
          isCheckOrder: false
        })
      }
      // 判断是否是去拼团  进入购买 是就跳转到拼团成功页面
      if (this.data.isCheckOrder) {
        return
      }
        if (this.data.isSuccess) {
          // 拼团成功返回首页
          wx.reLaunch({
            url: `/subPackagesB/pages/groupOrder/groupOrder?groupStatus=1&&userGroupId=${this.data.grouping_id}`
          })
        } else {
          wx.reLaunch({
            url: `/subPackagesB/pages/successOrder/successOrder?goods_id=${this.data.goods_id}&&original_price=${this.data.original_price}&&source=${this.data.source}&&grouping_id=${res.data.grouping_id}&&groupID=${this.data.groupID}`
          })
        }

    })
  },
  /**
   * 订单支付
   */
  payOrder() {
    let that = this
    let url = this.data.source == 'goods' ? 'v2/api/order/goods/pay' : 'v2/api/order/card/pay'
    post(
      url, {
        pay_way: this.data.pay_methon == 1 ? 'weixin' : 'amount',
        order_id: this.data.orderId
      },
      (res) => {
        that.setData({
          payNow: false
        })
        if (that.data.pay_methon == 2) {
          that.goToOrder('支付成功')
          return
        }
        wx.requestPayment({
          timeStamp: res.data.pay_data.timeStamp,
          nonceStr: res.data.pay_data.nonceStr,
          package: res.data.pay_data.package,
          signType: res.data.pay_data.signType,
          paySign: res.data.pay_data.paySign,
          success(res) {
            if (res.errMsg == 'requestPayment:ok') {
              that.goToOrder('支付成功')
            }
          },
          fail(res) {
            that.goToOrder('支付失败')
          }
        })
      }
    )
  },
  // 判断是否完成订单支付
  checkOrder() {
    timer = setTimeout(res => {
      if (!this.data.isCheckOrder) {
        clearTimeout(timer)
        return
      }
      this.getGroupRecordID(this.data.orderId, this.data.source == 'goods' ? 1 : 2)
      this.checkOrder()
    }, 1000)
  },
  /**
   * 跳转订单列表
   */
  goToOrder(text) {
    let that = this
    wx.showToast({
      title: text,
      icon: text == '支付成功' ? 'success' : 'error'
    })
    if (text == '支付成功') {
      // 只有项目购买，需要订阅消息
      if (this.data.isGrouping) {
        this.checkOrder()
      } else {
        wx.reLaunch({
          url: `/pages/paySuccess/paySuccess?current=1&source=${this.data.source}&order_id=${that.data.orderId}`
        })
      }
      return
    } else if(this.data.isGrouping){
      setTimeout(() => {
        wx.reLaunch({
          url: '/subPackagesB/pages/joinGroup/joinGroup'
        })
      }, 1000)
    }else if(!this.data.isGrouping&&this.data.source=='secondaryCard'){
      setTimeout(() => {
        wx.reLaunch({
          url: '/subPackagesB/pages/joinGroup/joinGroup'
        })
      }, 1000)
    }else{
      let failUrl = `/pages/goods/orderList/orderList?current=0`
      setTimeout(() => {
        wx.reLaunch({
          url: failUrl
        })
      }, 1000)
    }
  },
  // 关闭提交订单框
  onClosePay() {
    this.setData({
      payNow: false
    })
  },
  // 选择微信支付
  pay_methonw() {
    this.setData({
      pay_methon: 1
    })
  },
  // 选择储值支付
  pay_methonc() {
    this.setData({
      pay_methon: 2
    })
  },
  /**
   * 获取我的储值
   * api/user
   */
  getAmount() {
    get('api/user/amount', {}, (res) => {
      if (res.data) {
        this.setData({
          inserllAmount: res.data.amount
        })
      }
    })
  },
})