const {
  default: api
} = require("../../js/api");
const utils = require('../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    nozzleId: '',
    isLoading: false,
    nozzleInfo: null,
    quantify: '元',
    stationName:'',//油站名
    fastInputs: [10, 20, 50, 100, 200, 500],
    selectIndex:-1,
    type: [{
      name: '金额',
      checked: true
    },
    {
      name: '升数',
      checked: false
    }
    ],
    inputValue: '',
    inputTip: '请输入金额',
    amount: '',
    latitude: 0, //用户当前经度
    longitude: 0, //用户当前纬度
    stationLatitude: 0, //站点经度
    stationLongitude: 0, //站点纬度
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const link = decodeURIComponent(options.q) // 获取到二维码原始链接
    var id = link.split('yuwxapp?id=')[1];
    if (id == undefined) {
      id = options.id;
    }
    this.setData({
      nozzleId: id
    })
  },

  /** 获取站点信息 */
  getStationData() {
    console.log("获取站点")
    api.request_GetSiteInfo().then(res => {
      if (res.data.statusCode == 203) {
        //若为203，证明还未登录，跳转到登录页，这里可能刚从主页跳转过来，频繁的跳转可能会跳转页面超时，故而加上延时
        setTimeout(() => {
          wx.navigateTo({
            url: '../login/login'
          })
        }, 500)
        return
      }
      console.log("站点信息", res)
      const name = res.data.data.site.name;
      this.setData({
        stationName:name,
      })
      const stationLocation = res.data.data.site.gpsCoordinates.split(",");
      if (stationLocation.length == 2) {
        this.setData({
          stationLatitude: stationLocation[0],
          stationLongitude: stationLocation[1]
        })
      }
      this.getLocation();
    })
  },

  /** 获取用户经纬度 */
  getLocation() {
    const that = this;
    wx.getLocation({
      type: 'wgs84',
      isHighAccuracy:true,
      highAccuracyExpireTime:5000,
      success(res) {
        console.log("获取经纬度结果", res)
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
      }
    })

    this.getNozzleInfo();
  },

  /** 获取油枪信息 */
  getNozzleInfo() {
    const that = this;
    api.request_GetNozzleInfo(this.data.nozzleId).then(res => {
      console.log("获取油枪信息", res)
      if (res.data.content.length != 0) {
        var nozzle = res.data.content[0];
        nozzle.productPrice = utils.formatDiNumber(nozzle.productPrice);
        that.setData({
          nozzleInfo: nozzle
        });
      } else {
        console.log('获取油枪信息失败，无内容返回');
      }
    }).catch(err => {
      console.log('获取油枪信息接口请求失败', err);
    });
  },

  /** 输入框监听 */
  onInputChange(event) {
    console.log("输入框变化", event)
    let value = event.detail.value;
    
    // 1. 过滤非法字符（只允许数字和小数点）
    value = value.replace(/[^\d.]/g, "");

    // 2. 限制小数点只能出现一次
    const dotIndex = value.indexOf(".");
    if (dotIndex !== -1) {
      value = value.substring(0, dotIndex + 1) + value.substring(dotIndex).replace(/\./g, "");
    }

    // 3. 限制小数点后最多两位
    if (dotIndex !== -1 && value.length > dotIndex + 3) {
      value = value.substring(0, dotIndex + 3);
    }

    // 4. 更新输入框值
    this.setData({ inputValue: value });
  },

  /**
   * 处理快速输入金额的点击事件
   */
  onFastInputClick(event) {
    console.log("点击", event)
    const value = event.currentTarget.dataset.id;
    const index = event.currentTarget.dataset.index;
    this.setData({
      inputValue: value,
      selectIndex:index
    });
  },

  /** 授权 */
  toAuthorization() {
    if(this.data.inputValue == '') {
      wx.showToast({
        title: '请输入定量值',
        icon:'none'
      })
      return
    }
    wx.showLoading({
      title: '下单中',
    })
  
    console.log('进入 toAuthorization 方法');
    console.log(this.data)
    const distance = utils.haversine(this.data.stationLatitude,this.data.stationLongitude,this.data.latitude,this.data.longitude);
    if(distance > 500) {
      wx.showToast({
        title: '您不在油站范围内，请到油站时进行下单',
      })
      return
    }
    this.createOrder();
  },

  /** 创建订单 */
  createOrder() {
    const nozzle = this.data.nozzleInfo;
    if (!nozzle) {
      wx.hideLoading()
      wx.showToast({
        title: '油枪信息未获取',
        icon: 'error',
      });
      return;
    }
    const value = parseFloat(this.data.inputValue);
    console.log("要授权的油枪信息", nozzle, value);
    if (this.data.quantify == '元' && (value < 2.00 || value > 9900.00)) {
      wx.showToast({
        title: '金额须在2~9900之间',
      });
      return;
    }
    const price = parseFloat(nozzle.productPrice);
    if (this.data.quantify == '升' && (value < 1.00 || (value * price) > 9900.00)) {
      wx.showToast({
        title: '升数不合法',
      });
      return;
    }
    var requestData = null;
    if (this.data.quantify == '元') {
      requestData = {
        externalGunNumber: nozzle.externalGunNumber,
        originalAmount: value,
        product: nozzle.productName,
        price: parseFloat(nozzle.productPrice),
        transactionNumber: ''
      };
    } else {
      requestData = {
        externalGunNumber: nozzle.externalGunNumber,
        qty: value,
        product: nozzle.productName,
        price: nozzle.productPrice,
        transactionNumber: ''
      };
    }

    api.request_createOrder(requestData).then(res => {
      console.log("创建订单", res);
      if (res.data.statusCode == 200) {
        utils.subAndsendMessage(res.data.data.id, "下单").then(response => {
          this.toPayPage(res);
        }).catch(err => {
          this.toPayPage(res);
        });
      } else {
        wx.showToast({
          icon: "none",
          title: '授权失败',
        });
      }
    }).catch(err => {
      console.log("创建订单失败", err);
      wx.showToast({
        icon: "none",
        title: '授权失败',
      });
    });
  },

  toPayPage(res) {
    const that = this;
    const order = res.data.data;
    const time = utils.formatDateNotSecond(order.createTime);
    setTimeout(() => {
      wx.navigateTo({
        url: '../AuthorizationTransactionPage/AuthorizationTransactionPage?nozzleId=' + this.data.nozzleId,
        success: function (res) {
          res.eventChannel.emit('acceptDataFromQuantify', {
            oilName: order.productName,
            nozzle: order.nozzleId,
            volume: order.qty,
            amount: order.originalAmount,
            payAmount: order.actualPaymentAmount,
            discount: order.originalAmount - order.actualPaymentAmount,
            orderId: order.id,
            time: time,
            price:order.price,
            station:that.data.stationName
          })
        }
      })
    }, 500);
    wx.hideLoading()
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log("页面显示")
    this.getStationData();
  },

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

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 当选择定量类型
   */
  onTypeChange(event) {
    var type = event.detail.value;
    if (type == '升数') {
      this.setData({
        quantify: '升',
        inputTip: '请输入升数'
      });
    } else {
      this.setData({
        quantify: '元',
        inputTip: '请输入金额'
      });
    }
  }
});