// pages/order/confirm.js
import Toast from '@vant/weapp/toast/toast';
import {
  confirmOrder,
  getJhPayInfo,
  getCustomerGradeInfo
} from "../../api/home"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    images: [
      'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2684369054,623698254&fm=26&gp=0.jpg',
      'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2684369054,623698254&fm=26&gp=0.jpg',
      'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2684369054,623698254&fm=26&gp=0.jpg',
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let orderAmt = getApp().orderAmount;
    let oilPrice = getApp().oilPrice;
    // console.log("oilGunName:"+oilGunName);
    let oilLitre = null; //加油升数
    let totalMoney = null;
    let youHuiAmount = null;
    let discountPrice = null; //优惠价格
    let gasoilDiscountAmount = null; //优惠金额-满减，立减，直降
    let discountAmount = null; //优惠起点金额
    var mobileValue = wx.getStorageSync('mobilePhone')
    if (mobileValue) {
      if (getApp().gunType === '1') {
        getCustomerGradeInfo({
          "stationId": getApp().stationId,
          "userType": "2",
          "oilName": getApp().oilGunName,
          "openId": getApp().mpOpenId,
          "mobilePhone": mobileValue
        }).then(res => { // handle success
          if (res.retCode == 0) { //获取优惠信息成功
            if (res.data.length > 0) {
              if ((res.data[0].discountWay === '直降')) { //优惠方式为等级直降
                discountPrice = res.data[0].gasoilDiscountLitre; //直降方案，按会员等级、按油品单价直降
                totalMoney = (orderAmt / oilPrice) * (oilPrice - discountPrice);
                // console.log("totalMonry1:"+totalMoney);
                totalMoney = totalMoney.toFixed(2);
                // console.log("totalMonry2:"+totalMoney);
                youHuiAmount = (orderAmt / oilPrice) * discountPrice;
                youHuiAmount = youHuiAmount.toFixed(2);
              } else if (res.data[0].discountWay === '1') { //优惠方式为满减
                gasoilDiscountAmount = Number(res.data[0].gasoilDiscountAmt); //满减方案，价格不变，总额满足条件优惠满减
                discountAmount = Number(res.data[0].discountAmt);
                discountPrice = Number(res.data[0].gasoilDiscountAmt);
                if (orderAmt >= discountAmount) {
                  let discountTimes = Math.floor(orderAmt / discountAmount);
                  totalMoney = Number(orderAmt - (gasoilDiscountAmount * discountTimes));
                  totalMoney = totalMoney.toFixed(2);
                  youHuiAmount = Number(gasoilDiscountAmount * discountTimes);
                  youHuiAmount = youHuiAmount.toFixed(2);
                } else {
                  totalMoney = orderAmt;
                  youHuiAmount = 0;
                }
              } else if (res.data[0].discountWay === '2') { //优惠方式为立减
                gasoilDiscountAmount = res.data[0].gasoilDiscountAmt; //立减方案，价格不变，总额满足条件优惠立减
                discountAmount = res.data[0].discountAmt;
                discountPrice = Number(res.data[0].gasoilDiscountAmt);
                if (orderAmt >= discountAmount) {
                  totalMoney = Number(orderAmt - gasoilDiscountAmount);
                  totalMoney = totalMoney.toFixed(2);
                  youHuiAmount = Number(gasoilDiscountAmount);
                  youHuiAmount = youHuiAmount.toFixed(2);
                } else {
                  totalMoney = orderAmt;
                  youHuiAmount = 0;
                }
              } else if ((res.data[0].discountWay === '3')) { //优惠方式为独立直降
                discountPrice = Number(res.data[0].gasoilDiscountAmt);
                if (res.data[0].discountTerm === '1') { //按总金额直降
                  if (orderAmt >= res.data[0].discountAmt) {
                    discountPrice = Number(res.data[0].gasoilDiscountAmt); //独立直降方案，按油品升数或者总价直降
                    totalMoney = (orderAmt / oilPrice) * (oilPrice - discountPrice);
                    // console.log("totalMonry1:"+totalMoney);
                    totalMoney = totalMoney.toFixed(2);
                    // console.log("totalMonry2:"+totalMoney);
                    youHuiAmount = (orderAmt / oilPrice) * discountPrice;
                    youHuiAmount = youHuiAmount.toFixed(2);
                  } else {
                    totalMoney = orderAmt;
                    youHuiAmount = 0;
                  }
                } else if (res.data[0].discountTerm === '2') { //按升数直降
                  discountPrice = Number(res.data[0].gasoilDiscountAmt);
                  //取条件升数
                  let dislQty = Number(res.data[0].discountAmt);
                  //计算升数
                  let lQty = orderAmt / oilPrice;
                  lQty = lQty.toFixed(2);
                  if (lQty >= dislQty) {
                    totalMoney = (orderAmt / oilPrice) * (oilPrice - discountPrice);
                    // console.log("totalMonry1:"+totalMoney);
                    totalMoney = totalMoney.toFixed(2);
                    // console.log("totalMonry2:"+totalMoney);
                    youHuiAmount = (orderAmt / oilPrice) * discountPrice;
                    youHuiAmount = youHuiAmount.toFixed(2);
                  } else {
                    totalMoney = orderAmt;
                    youHuiAmount = 0;
                  }
                } else {
                  totalMoney = orderAmt;
                  youHuiAmount = 0;
                }
              } else { //没有以上三种优惠方式
                totalMoney = orderAmt;
                youHuiAmount = 0;
              }
            } else { //没有查询到优惠信息，新用户没有优惠
              totalMoney = orderAmt;
              youHuiAmount = 0;
            }
            oilLitre = Number(orderAmt / oilPrice);
            oilLitre = oilLitre.toFixed(2);


            this.setData({
              stationName: getApp().stationName,
              imageURL: getApp().picUrl,
              gunNo: getApp().oilGunNum,
              oilName: getApp().oilGunName,
              oilPrice: getApp().oilPrice,
              orderMoney: getApp().orderAmount,
              discountPrice: discountPrice,
              oilLitre: oilLitre,
              manJian: 0,
              liJian: 0,
              youHuiAmount: youHuiAmount,
              youHui: 0,
              vipMoney: 0,
              apayMoney: totalMoney
            })

          } else {
            Toast.fail(res.message);
          }
        }).catch(error => { // handle error
          Toast.fail(error);
        })
      } else {
        totalMoney = orderAmt;
        youHuiAmount = 0;
        oilLitre = 0;
        this.setData({
          stationName: getApp().stationName,
          imageURL: getApp().picUrl,
          gunNo: getApp().oilGunNum,
          oilName: getApp().oilGunName,
          oilPrice: getApp().oilPrice,
          orderMoney: getApp().orderAmount,
          discountPrice: discountPrice,
          oilLitre: oilLitre,
          manJian: 0,
          liJian: 0,
          youHuiAmount: youHuiAmount,
          youHui: 0,
          vipMoney: 0,
          apayMoney: totalMoney
        })
      }
    } else {
      wx.showToast({
        title: '手机号未授权',
      })
    }
  },

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

  },

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

  },

  /**
   * 立即支付方法
   */
  pay: function () {
    //支付前，先进行订单确认，确认无误后，获取到订单id，作为入参，调用支付平台的下单接口
    var app = getApp()
    //请求后台创建订单接口，获取订单号
    confirmOrder({
      "orderNo": app.orderNo,
      "openId": app.mpOpenId,
      "userType": 2
    }).then(res => { // handle success 
      // console.log("data:" + res.data);
      if (res.retCode == 0 && res.data.length == 1) {
        // console.log("orderNo:" + res.data[0].orderNo)
        //确认订单存在，获取到订单id，请求聚合支付下单接口
        var orderId = res.data[0].orderId;
        // console.log("orderId="+orderId);
        getJhPayInfo({
          "orderId": orderId,
          "openId": app.mpOpenId,
          "stationId": app.stationId,
          "subject": app.stationName + "_" + app.oilGunName + "油品支付订单",
          "userType": "2"
        }).then(res => { // handle success
          //判断封装接口请求成功
          if (res.retCode == 0) {
            //判断随行付支付网关是否请求成功
            if (res.data.code == '0000') {
              let timeStamp = res.data.respData.payTimeStamp;
              let nonceStr = res.data.respData.paynonceStr;
              let payPackage = res.data.respData.payPackage;
              let signType = res.data.signType;
              let paySign = res.data.respData.paySign;

              wx.requestPayment({
                'timeStamp': timeStamp,
                'nonceStr': nonceStr,
                'package': payPackage,
                'signType': signType,
                'paySign': paySign,
                'success': function (res) {
                  wx.navigateTo({
                    url: '/pages/order/success',
                  })
                },
                'fail': function (res) {

                },
                'complete': function (res) {

                }
              })
            } else {
              Toast.fail(res.data.msg);
            }
          } else { //请求失败，提示失败信息
            Toast.fail(res.message);
          }
        }).catch(error => { // handle error
          // console.log(error);
          Toast.fail(error);
        })
      } else {
        Toast.fail(res.message);
      }
    }).catch(error => { // handle error
      // console.log(error);
      Toast.fail(error);
    })
  }

})