// pages/submit-order/submit-order.js
var http = require("../../utils/http.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    popupShow: false,
    // 订单入口 0购物车 1立即购买
    orderEntry: "0",
    userAddr: null,
    orderItems: [],
    shopCartOrders: [], //所有店铺的数据
    couponSts: 1,
    platformCoupons: {}, // 平台优惠券数据
    showCoupons: {
      canUseCoupons: [],
      unCanUseCoupons: []
    },

    actualTotal: 0,
    total: 0,
    totalCount: 0,
    transfee: 0,
    reduceAmount: 0, //减免金额
    couponIds: [],
    orderReduce: 0,
    userChangeCoupon: 0, // 用户有没有对优惠券进行改变
    orderReduce: 0,
    choose: true,
    totalScoreAmount: 0, //积分抵扣金额
    maxUsableScore: 0, //整个订单可以使用的积分数
    isScorePay: 0, //用户是否选择积分抵现(0不使用 1使用 默认不使用)
    isChecked: false, //是否选择会员积分抵现
    totalLevelAmount: 0, //等级抵扣金额
    freeTransfee: 0, //用户等级免运费金额

    userUseScore: '', // 用于抵扣的金额数量
    scorePopPlaceholder: '', // 积分弹窗输入框占位符

    isPurePoints: false,
    address_id: 0,
    shop_id: 0,
    deliveryAmount_num: 0,
    shop_weight: 0,
    is_distance:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      orderEntry: options.orderEntry,
    });
    // 请求用户可用积分
    this.getUserScore()
  },
  /**
   * 获取用户可用积分
   */
  getUserScore() {
    var params = {
      url: '/p/user/userInfo',
      method: 'GET',
      callBack: res => {
        this.setData({
          accountScore: res.score
        })
      }
    }
    http.request(params)
  },

  // 会员积分抵现选择
  useMemberPoints: function () {
    this.data.isChecked = !this.data.isChecked
    if (this.data.maxUsableScore > 0) { // maxUsableScore 整个订单可以使用的积分数
      this.setData({
        isScorePay: this.data.isChecked ? 1 : 0,
        userUseScore: this.data.isChecked ? this.data.userUseScore : ''
      })
      this.loadOrderData()
    }
  },
  /**
   * 积分抵扣输入框
   */
  handleScoreInput(e) {
    var maxScore = 0
    if (this.data.maxUsableScore > this.data.accountScore) {
      maxScore = this.data.accountScore
    } else {
      maxScore = this.data.maxUsableScore
    }
    this.setData({
      userUseScore: e.detail.value > 0 ? e.detail.value > maxScore ? maxScore : e.detail.value : ''
    })
  },
  /**
   * 修改积分确定弹窗
   */
  confirmScore() {
    this.loadOrderData()
    this.closePopup()
  },
  //加载订单数据
  loadOrderData: function () {
    var addrId = 0;
    if (this.data.userAddr != null) {
      addrId = this.data.userAddr.addrId;
    }
    wx.showLoading({
      mask: true
    });
    // 重置地址  避免超出配送 使用之前地址
    this.setData({userAddr:null})
    var params = {
      url: "/p/order/confirm",
      method: "POST",
      data: {
        addrId: addrId,
        orderItem: this.data.orderEntry === "1" ? JSON.parse(wx.getStorageSync("orderItem")) : undefined,
        basketIds: this.data.orderEntry === "0" ? JSON.parse(wx.getStorageSync("basketIds")) : undefined,
        couponIds: this.data.couponIds,
        userChangeCoupon: this.data.userChangeCoupon,
        isScorePay: this.data.isScorePay,
        userUseScore: this.data.userUseScore ? this.data.userUseScore : 0,
      },
      callBack: res => {
        this.setData({
          address_id: res.userAddr.addrId,
          shop_weight: res.weight
        })
        wx.hideLoading();
        var shopCartOrders = res.shopCartOrders; //购物车店铺商品信息列表
        var couponIds = []
        let img=''
        shopCartOrders.forEach(shopCart => {
          shopCart.shopCartItemDiscounts.forEach(e=>{
            e.shopCartItems.forEach(item=>{
              img=item.pic.split(',')
              item.pic=img[0]
            })
          })
          this.setData({
            shop_id: shopCart.shopId
          })
          shopCart.remarks = '';
          shopCart.shopCoupons = this.splitCouponAndPushCouponIds(shopCart.coupons, couponIds)
        })
        // 平台优惠券
        var platformCoupons = this.splitCouponAndPushCouponIds(res.coupons, couponIds) //平台优惠券
        // 平台优惠券end
        this.setData({
          platformCoupons: platformCoupons, //整个订单可以使用的优惠券列表
          shopCartOrders: shopCartOrders, //所有的店铺的购物车信息
          actualTotal: res.actualTotal, //实际总值
          total: res.total, //商品总值
          totalCount: res.totalCount, //商品总数
          userAddr: res.userAddr, //地址Dto
          transfee: res.totalTransfee, //总运费
          orderReduce: res.orderReduce, //订单优惠金额(所有店铺优惠金额和使用积分抵现相加)
          totalScoreAmount: res.totalScoreAmount, //积分抵扣金额
          totalUsableScore: res.totalUsableScore, //用于抵扣的积分数量
          isScorePay: res.isScorePay, //用户是否选择积分抵现(0不使用 1使用 默认不使用)
          totalLevelAmount: res.totalLevelAmount, //等级抵扣金额
          freeTransfee: res.freeTransfee, //用户等级免运费金额
          couponIds: couponIds,
          maxUsableScore: res.maxUsableScore, //整个订单可以使用的积分数
          scorePopPlaceholder: `剩余积分${this.data.accountScore}，此订单最多可用${res.maxUsableScore}`,
          scorePlaceholder: `使用${res.totalUsableScore}积分抵扣${res.totalScoreAmount}元`,
          shopUseScore: res.shopUseScore, // 店铺积分抵扣比例; 
          isPurePoints: res.actualTotal == 0 ? true : false,
        });
        this.getDeliveryAmount()
      },
      errCallBack: res => {
        setTimeout(()=>{
          wx.showToast({
            title:res.data,
            icon: "none"
          })
        },1)
        wx.hideLoading();
      }
    };
    http.request(params);

  },
  /**
   * 分割优惠券成
   * 1. canUseCoupons 可使用优惠券列表
   * 2. unCanUseCoupons 不可使用优惠券列表
   * 3. couponAmount 选中的优惠券可优惠金额
   * 4. 将选中的优惠券ids保存起来
   * @param {*} coupons 优惠券列表
   * @param {*} couponIds 选中的优惠券id
   */
  splitCouponAndPushCouponIds(coupons, couponIds) {
    if (!coupons || !coupons.length) {
      return
    }
    let canUseCoupons = []
    let unCanUseCoupons = []
    let couponAmount = 0;
    coupons.forEach(coupon => {
      if (coupon.canUse) {
        canUseCoupons.push(coupon)
      } else {
        unCanUseCoupons.push(coupon)
      }
      if (coupon.choose) {
        couponIds.push(coupon.couponId)
        couponAmount = coupon.reduceAmount;
      }
    })
    return {
      canUseLength: canUseCoupons.length,
      couponAmount: couponAmount,
      canUseCoupons: canUseCoupons,
      unCanUseCoupons: unCanUseCoupons,
    }
  },
  /**
   * 提交订单校验
   */
  toPay: function () {
    if (this.data.actualTotal < this.data.deliveryAmount_num) {
      wx.showToast({
        title: '商品总额需大于起送价~',
        icon: "none"
      })
      return;
    }
    if (!this.data.userAddr) {
      wx.showToast({
        title: '请选择地址',
        icon: "none"
      })
      return;
    }
    if (this.data.shop_weight > 20000) {
      wx.showToast({
        title: '已超过单次配送限制20kg，请减少商品数',
        icon: "none"
      })
    return
    }
    if(this.data.is_distance==false){
      wx.showToast({
        title: '超出配送范围',
        icon: "none"
      })
      return
    }
    this.submitOrder();
  },
  /**
   * 获取起送价
   */
  getDeliveryAmount: function () {
    var params = {
      url: "/p/address/deliveryAmount/" + this.data.shop_id + '/' + this.data.address_id,
      method: "GET",
      callBack: res => {
        this.setData({
          deliveryAmount_num: res.deliveryAmount,
          is_distance:true
        })
      },
      errCallBack:(err)=>{
        this.setData({
          is_distance:false
        })
      }
    }
    http.request(params);
  },
/**
 * 获取配送距离
 */
// getaddress_transports: function () {
//   let _this = this
//   var params = {
//     url: "/p/address/transport2",
//     method: "GET",
//     data: {
//       shopId: this.data.shop_id,
//       addrId:this.data.address_id
//     },
//     callBack: function (res) {
//       wx.setStorageSync('DISTANCE', res.distance)
//       _this.setData({
//       })
//     }
//   };
//   http.request(params);
// },
  // 提交订单
  submitOrder: function () {
    wx.showLoading({
      mask: true
    });
    var shopCartOrders = this.data.shopCartOrders;
    var orderShopParam = [];
    shopCartOrders.forEach(shopCart => {
      orderShopParam.push({
        remarks: shopCart.remarks,
        shopId: shopCart.shopId
      });
    })
    var params = {
      url: "/p/order/submit",
      method: "POST",
      data: {
        orderShopParam: orderShopParam,
        // coupons: this.data.platformCoupons,
        coupons: this.data.coupons,
        isScorePay: this.data.isScorePay,
      },
      callBack: res => {
        wx.hideLoading();
        this.calWeixinPay(res.orderNumbers);
      },
      errCallBack: res => {
        wx.showModal({
          showCancel: false,
          title: '提示',
          content: res.data
        })
      }
    };
    http.request(params);
  },

  /**
   * 唤起微信支付
   */
  calWeixinPay: function (orderNumbers) {
    wx.showLoading({
      mask: true
    });
    var params = {
      url: "/p/order/pay",
      method: "POST",
      data: {
        payType: 1, //支付方式 (1:微信小程序支付 2:支付宝 3微信扫码支付 4 微信h5支付)
        orderNumbers: orderNumbers
      },
      callBack: (res) => {
        wx.hideLoading();
        if (this.data.isPurePoints) {
          wx.redirectTo({
            url: `/pages/pay-result/pay-result?sts=1&orderNumbers=${orderNumbers}&orderType=${this.data.orderType}`,
          })
          return
        }
        wx.requestPayment({
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          package: res.packageValue,
          signType: res.signType,
          paySign: res.paySign,
          success: e => {
            wx.redirectTo({
              url: `/pages/pay-result/pay-result?sts=1&orderNumbers=${orderNumbers}&orderType=${this.data.orderType}`,
            })
          },
          fail: err => {
            wx.redirectTo({
              url: `/pages/pay-result/pay-result?sts=0&orderNumbers=${orderNumbers}&orderType=${this.data.orderType}`,
            })
          }
        })

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

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  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.loadOrderData();
    setTimeout(() => {
      this.getDeliveryAmount()
    }, 500)
  },

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

  },

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

  },

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

  },

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

  },

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

  },

  // 店铺切换可用/不可用优惠券列表
  changeCouponSts: function (e) {
    this.setData({
      couponSts: e.currentTarget.dataset.sts
    });
  },

  // 店铺优惠券弹框
  showCouponPopup: function (e) {
    var index = e.currentTarget.dataset.index;
    var shopCartOrders = this.data.shopCartOrders;
    this.setData({
      showCoupons: index + '' === '-1' ? this.data.platformCoupons : shopCartOrders[index].shopCoupons,
      popupShow: true,
    });
  },


  closePopup: function () {
    this.setData({
      popupShow: false,
      // platPopupShow: false
      showScorePop: false
    });
  },

  /**
   * 去地址页面
   */
  toAddrListPage: function () {
    wx.navigateTo({
      url: '/pages/delivery-address/delivery-address?order=0',
    })
  },
  /**
   * 确定选择好的优惠券
   */
  choosedCoupon: function () {
    var couponIds = this.data.couponIds
    if (!this.data.showCoupons) {
      this.setData({
        popupShow: false
      })
      return
    }
    // 店铺优惠券单选操作
    var canUseCoupons = this.data.showCoupons.canUseCoupons;
    var checkedCouponId = ''
    for (var canUseCouponIndex in canUseCoupons) {
      var coupon = canUseCoupons[canUseCouponIndex];
      if (!coupon.choose && couponIds.indexOf(coupon.couponId) !== -1) {
        couponIds.splice(couponIds.indexOf(coupon.couponId), 1)
      }
      if (coupon.choose) {
        checkedCouponId = coupon.couponId
      }
    }
    couponIds.push(checkedCouponId)
    this.setData({
      couponIds: couponIds,
      popupShow: false
    });
    this.loadOrderData();
  },

  /**-
   * 优惠券子组件发过来
   */
  checkCoupon: function (e) {
    var showCoupons = this.data.showCoupons;
    // 店铺优惠券单选操作
    var canUseCoupons = showCoupons.canUseCoupons;
    for (var canUseCouponIndex in canUseCoupons) {
      if (e.detail.couponId === canUseCoupons[canUseCouponIndex].couponId && canUseCouponIndex == e.detail.index) {
        canUseCoupons[canUseCouponIndex].choose = !canUseCoupons[canUseCouponIndex].choose
      } else {
        canUseCoupons[canUseCouponIndex].choose = false
      }
    }
    this.setData({
      showCoupons: showCoupons,
      userChangeCoupon: 1
    });
  },

  /**
   * 输入备注
   */
  onRemarkIpt: function (e) {
    var index = e.currentTarget.dataset.index;
    var shopCartOrders = this.data.shopCartOrders;
    shopCartOrders[index].remarks = e.detail.value;
    this.setData({
      shopCartOrders: shopCartOrders
    });
  },

  /**
   * 积分输入弹窗显示
   */
  handleScorePop() {
    this.setData({
      showScorePop: true
    })
  },
})