// pages/order/index.js
import Toast from '@vant/weapp/toast/toast';
import {
  getOilGunList,
  postOrderInfo,
  saveAppUserInfo,
  getMpOpenId,
  decryptEncryptedData,
  getCustomerGradeInfo
} from "../../api/home"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showPopup: false,
    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',
    ],
    gasarr: [],
    gasallarr: [],
    money: [100, 200, 300, 400],
    gas: 0,
    account: '',
    showModal: false, //是否弹出登录弹窗
    showModalPhone: false, //是否弹出手机号绑定弹窗
    isShowUserInfoLayer: false, //是否手弹出获取用户信息弹窗
    userInfo: {},
    phoneNumber: null,
    hasUserInfo: false,
    hasPhoneNumber: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    iconSize: [20, 30, 40, 50, 60, 70],
    iconColor: [
      'red', 'orange', 'yellow', 'green', 'rgb(0,255,255)', 'blue', 'purple'
    ],
    iconType: [
      'success', 'success_no_circle', 'info', 'warn', 'waiting', 'cancel', 'download', 'search', 'clear'
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var app = getApp();
    var userInfoValue = wx.getStorageSync('userInfo')
    try {
      if (userInfoValue) {
        // Do something with return value
        // console.log("本地缓存中的userInfo：" + userInfoValue);
        try {
          var mobileValue = wx.getStorageSync('mobilePhone')
          if (mobileValue) {
            // Do something with return value
            // console.log("本地缓存中的phoneNumber：" + mobileValue);
          } else {
            this.showDialogPhone(); //调用手机号登录弹窗
          }
        } catch (e) {
          // Do something when catch error
        }
      } else {
        // console.log("app.globalData中的userInfo：" + app.globalData.userInfo);
        this.showDialogLogin(); //调用登录弹窗
      }
    } catch (e) {
      // Do something when catch error
    }
    if (options.q) {
      let scan_url = decodeURIComponent(options.q);
      app.stationId = this.gup('stationId', scan_url);
      // wx.showToast({
      //   title: 'id1:' +app.stationId
      // })
    } else {
      // var stationId = app.stationId;
      // wx.showToast({
      //   title: 'id2:' + stationId
      // })
    }

    getOilGunList({
      stationId: app.stationId
    }).then(res => { // handle success 
      // console.log(res.data);
      // res.data.length
      if (res.retCode == 0) {
        var gasArr = [];
        for (let i = 0; i < res.data.length; i++) {
          gasArr.push(res.data[i]);
        }
        this.setData({
          gasallarr: res.data,
          gasarr: gasArr
        })
        app.stationName = res.data[0].stationName;
      }
      // console.log("gasArr lengh:"+gasArr.length);
    }).catch(error => { // handle error
      console.log(error);
    })
  },
  gup: function (name, url) {
    if (!url) url = location.href;
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(url);
    return results == null ? null : results[1];
  },

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

  onClose() {
    this.setData({
      showPopup: false
    });
  },
  clickMore: function () {
    this.setData({
      showPopup: true
    });
  },
  selectGas: function (event) {
    var app = getApp()
    let gunNo = event.target.dataset.index;
    let gunName = event.target.dataset.oilname;
    let oilPrice = event.target.dataset.oilprice;
    let gunType = event.target.dataset.guntype;
    app.oilGunNum = gunNo;
    app.oilGunName = gunName;
    app.oilPrice = oilPrice;
    app.gunType = gunType;
    // console.log("gunType="+event.target.dataset.guntype);
    this.setData({
      gas: event.target.dataset.index,
      showPopup: false
    });
    // console.log("gas is :" + event.target.dataset.index);
  },
  selectGasAll: function (event) {
    var app = getApp()
    var gasarr = [];
    var arrLength = this.data.gasallarr.length;
    if (event.target.dataset.index > 5) {
      for (let index = event.target.dataset.index - 5; index <= event.target.dataset.index; index++) {
        gasarr.push(this.data.gasallarr[index]);
      }
    } else {
      for (let index = 0; index < arrLength; index++) {
        gasarr.push(this.data.gasallarr[index]);
      }
    }
    let gunNo = event.target.dataset.index;
    let gunName = event.target.dataset.oilname;
    let oilPrice = event.target.dataset.oilprice;
    let gunType = event.target.dataset.guntype;
    app.oilGunNum = gunNo;
    app.oilGunName = gunName;
    app.oilPrice = oilPrice;
    app.gunType = gunType;
    // console.log("选定的油枪号：" + event.target.dataset.num);
    // console.log("gasarr size：" + gasarr.length);
    this.setData({
      gasarr: gasarr,
      gas: event.target.dataset.num,
      showPopup: false
    });
  },
  clickAccount: function (event) {
    var app = getApp()
    app.orderAmount = event.target.dataset.money;
    this.setData({
      account: event.target.dataset.money
    });
    // console.log("account is :" + event.target.dataset.money);
  },
  toastMsg: function () {
    if (this.data.gas <= 0) {
      Toast.fail('请选择油枪');
    } else if (this.data.account <= 0) {
      Toast.fail('请输入金额');
    }
  },
  toConfirm: function () {
    var app = getApp();
    var userInfoValue = wx.getStorageSync('userInfo')
    try {
      if (userInfoValue) {
        // Do something with return value
        // console.log("本地缓存中的userInfo：" + userInfoValue);
        try {
          var mobileValue = wx.getStorageSync('mobilePhone')
          if (mobileValue) {
            // Do something with return value
            // console.log("本地缓存中的phoneNumber：" + mobileValue);
            let orderAmt = app.orderAmount;
            let oilPrice = app.oilPrice;
            let discountPrice = null; //优惠价格
            let gasoilDiscountAmount = null; //优惠金额-满减，立减，直降
            let discountAmount = null; //优惠起点金额
            let totalMoney = null;
            let youHuiAmount = null;
            let gunType = app.gunType;
            if (gunType === '1') { //油品订单
              console.log("**************计算优惠单开始****************");
              /**************计算优惠单开始****************/
              getCustomerGradeInfo({
                "stationId": app.stationId,
                "userType": "2",
                "oilName": app.oilGunName,
                "openId": app.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 = Number(res.data[0].gasoilDiscountAmt); //立减方案，价格不变，总额满足条件优惠立减
                      discountAmount = Number(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;
                  }
                  /**************计算优惠结束****************/
                  //请求后台创建订单接口，获取订单号
                  postOrderInfo({
                    "stationId": app.stationId,
                    "oilGun": app.oilGunNum,
                    "oilName": app.oilGunName,
                    "oilPrice": app.oilPrice,
                    "receivableAmt": app.orderAmount, //应收金额
                    "discountAmt": youHuiAmount, //优惠金额
                    "amt": totalMoney, //实收金额
                    "token": app.mpOpenId,
                    "userType": 2,
                    "orderType": "1"
                  }).then(res => { // handle success 
                    // console.log(res.data);
                    if (res.retCode == 0) {
                      app.orderNo = res.data;
                      wx.navigateTo({
                        url: "/pages/order/confirm"
                      });
                    } else {
                      Toast.fail(res.message);
                    }
                  }).catch(error => { // handle error
                    // console.log(error);
                    Toast.fail(error);
                  })
                } else {
                  Toast.fail(res.message);
                }
              }).catch(error => { // handle error
                Toast.fail(error);
              })
            } else { //非油品订单
              totalMoney = orderAmt;
              youHuiAmount = 0;
              //请求后台创建订单接口，获取订单号
              postOrderInfo({
                "stationId": app.stationId,
                "oilGun": app.oilGunNum,
                "oilName": app.oilGunName,
                "oilPrice": app.oilPrice,
                "receivableAmt": app.orderAmount, //应收金额
                "discountAmt": youHuiAmount, //优惠金额
                "amt": totalMoney, //实收金额
                "token": app.mpOpenId,
                "userType": 2,
                "orderType": "2"
              }).then(res => { // handle success 
                // console.log(res.data);
                if (res.retCode == 0) {
                  app.orderNo = res.data;
                  wx.navigateTo({
                    url: "/pages/order/confirm"
                  });
                } else {
                  Toast.fail(res.message);
                }
              }).catch(error => { // handle error
                // console.log(error);
                Toast.fail(error);
              })
            }
          } else {
            this.showDialogPhone(); //调用手机号登录弹窗
          }
        } catch (e) {
          // Do something when catch error
          Toast.fail(e);
        }
      } else {
        // console.log("app.globalData中的userInfo：" + app.globalData.userInfo);
        this.showDialogLogin(); //调用登录弹窗
      }
    } catch (e) {
      // Do something when catch error
      Toast.fail(e);
    }
  },
  //金额输入框获取实时输入的值
  bindKeyInput: function (e) {
    var app = getApp()
    const reg = /^[1-9]{1,}(\.)?([0-9]{0,2})?/ // 最小数额1   
    // /^[0-9]{1,}(\.)?([0-9]{0,2})?/        // 不设置最小数额
    const res = e.detail.value.match(reg, "");
    if(res !== null){
      app.orderAmount = res[0]
      this.setData({
        account: res[0]
      })
    }else{
      app.orderAmount = ""
      this.setData({
        account: ""
      })
    }
  },
  // 显示登录弹窗
  showDialogLogin: function () {
    this.setData({
      showModal: true //修改弹窗状态为true，即显示
    })
  },
  // 隐藏登录弹窗
  hideDialogLogin: function () {
    this.setData({
      showModal: false //修改弹窗状态为false,即隐藏
    });
  },

  getUserInfo: function (e) {
    var app = getApp()
    let that = this;
    // console.log(e)
    // 获取用户信息
    wx.getSetting({
      success(res) {
        // console.log("res", res)
        if (res.authSetting['scope.userInfo']) {
          // console.log("已授权=====")
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success(res) {
              // console.log("获取用户信息成功", res.userInfo);
              app.globalData.userInfo = res.userInfo;
              wx.setStorage({
                data: res.userInfo,
                key: 'userInfo',
              })
              // console.log("minaOpenid:"+app.mpOpenId);
              // console.log("blogNickName:"+res.userInfo.nickName);
              // console.log("sexFlag:"+res.userInfo.gender === 1?'M':'F');
              // console.log("blogProfilePhoto:"+res.userInfo.avatarUrl);
              that.showDialogPhone(); //调用一键获取手机号弹窗
              that.setData({
                userInfo: res.userInfo,
                hasUserInfo: true
              })
            },
            fail(res) {
              Toast.fail(res);
              console.log("获取用户信息失败", res)
            }
          })
        } else {
          that.setData({
            showModal: false
          });
          wx.showToast({
            title: '拒绝授权！',
            icon: 'error',
            duration: 2000
          })
        }
      }
    })
  },
  //授权用户信息按钮
  bindAuthUserInfo: function (e) {
    var that = this;
    //获取授权结果查看是否已授权用户信息
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo'] == undefined && !res.authSetting['scope.userInfo']) //未授权获取用户信息（首次进来页面）
          that.getLocationInfo(); //获取当前用户信息
        else if (res.authSetting['scope.userInfo'] === false) //未授权获取用户信息(点击官方授权弹框取消按钮后)
          that.setData({
            isShowUserInfoLayer: true
          }) //显示自定义授权框
        else //已授权
          that.getUserInfo(); //获取当前用户信息
      }
    })
  },
  // 显示一键获取手机号弹窗
  showDialogPhone: function () {
    this.setData({
      showModalPhone: true //修改弹窗状态为true，即显示
    })
  },
  // 隐藏一键获取手机号弹窗
  hideDialogPhone: function () {
    this.setData({
      showModalPhone: false //修改弹窗状态为false,即隐藏
    });
  },
  getPhoneNumber: function (e) {
    let that = this;
    let app = getApp();
    // console.log(e.detail.errMsg)
    // console.log("iv:" + e.detail.iv)
    // console.log("encryptedData:" + e.detail.encryptedData)
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      that.setData({
        showModalPhone: false,
        showModal: false
      });
      wx.showToast({
        title: '拒绝授权！',
        icon: 'error',
        duration: 2000
      })
    } else {
      let iv = e.detail.iv;
      let encryptedData = e.detail.encryptedData;
      let mobilePhone = null;
      wx.login({
        success: function (res) {
          that.setData({
            hasPhoneNumber: true
          });
          if (res.code) {
            let code = res.code;
            //发起网络请求  
            getMpOpenId({
              code: code,
              stationId: app.stationId
            }).then(res => { // handle success 
              // console.log("sessionKey:" + res.session_key);
              decryptEncryptedData({
                sessionKey: res.session_key,
                encryptedData: encryptedData,
                iv: iv
              }).then(res => { // handle success
                mobilePhone = res.phoneNumber;
                //保存appUserInfo信息
                saveAppUserInfo({
                  "userType": "2",
                  "minaOpenid": app.mpOpenId,
                  "blogNickName": app.globalData.userInfo.nickName,
                  "sexFlag": app.globalData.userInfo.gender === 1 ? 'M' : 'F',
                  "blogProfilePhoto": app.globalData.userInfo.avatarUrl,
                  "mobilePhone": mobilePhone,
                  "stationId": app.stationId,        //油站Id
                  "stationName": app.stationName,        //油站名称
                  "unionId":app.unionId

                }).then(res => { // handle success 
                  // console.log(res.data);
                  if (res.retCode == 0 || res.retCode == -1) {
                    // console.log("保存app用户信息成功："+app.globalData.userInfo);
                    // console.log("保存app用户信息成功。。。");
                    app.globalData.phoneNumber = mobilePhone;
                    wx.setStorage({
                      data: mobilePhone,
                      key: 'mobilePhone',
                    });
                    // console.log("mobilePhone:" + mobilePhone);
                    ///////////////////////
                    that.setData({
                      showModalPhone: false,
                      showModal: false,
                      phoneNumber: mobilePhone
                    });
                    wx.showToast({
                      title: '登录成功',
                      icon: 'success',
                      duration: 2000
                    })
                  }
                }).catch(error => { // handle error
                  wx.showToast({
                    title: error,
                  })
                  console.log(error);
                })
              }).catch(error => { // handle error
                wx.showToast({
                  title: error,
                })
                console.log(error);
              })
            }).catch(error => { // handle error
              wx.showToast({
                title: error,
              })
              console.log(error);
            })
          } else {
            wx.showToast({
              title: res.errMsg,
            })
            console.log('获取用户登录态失败！' + res.errMsg)
          }
        }
      })
    }
  }
})