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

// pages/historyOrderAfter/historyOrderAfter.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orders: [],
    date: '',
    latitude: 0, //用户当前经度
    longitude: 0, //用户当前纬度
    stationName:'',//油站名
    stationLatitude: 0, //站点经度
    stationLongitude: 0, //站点纬度
    startDate: '',
    endDate: '',
    pageNum: 1,//查询页码
    pageSize: 5,//页数
    isHaveOrder: true,//是否还有订单
    paymentMode: -1,
    /** 后支付订单状态  订单状态（0：未支付； 1：已支付； 2：订单全额退款；3：订单部分退款；5：已完成）*/
    payStatusValue: [{
      orderStatus: 0,
      status: '未支付',
      statusColor: '#ff8d1a'
    },
    {
      orderStatus: 1,
      status: '已完成',
      statusColor: '#a6a6a6'
    },
    {
      orderStatus: 5,
      status: '已完成',
      statusColor: '#a6a6a6'
    }
    ],
    /** 预支付订单状态 授权状态（未授权：0；已授权：1）
     * + 订单状态（0：未支付； 1：已支付； 2：订单全额退款；3：订单部分退款；5：已完成） */
    prepayStatuValue: [
      {
        authorizationStatus: 0,
        orderStatus: 0,
        status: '支付失败',
        statusColor: '#f1912f'
      },
      {
        authorizationStatus: 0,
        orderStatus: 1,
        status: '授权失败',
        statusColor: '#f0d02e'
      },
      {
        authorizationStatus: 1,
        orderStatus: 1,
        status: '授权成功',
        statusColor: '#a2cd4a'
      },
      {
        authorizationStatus: 0,
        orderStatus: 2,
        status: '已完成',
        statusColor: '#a6a6a6'
      },
      {
        authorizationStatus: 0,
        orderStatus: 3,
        status: '已完成',
        statusColor: '#a6a6a6'
      },
      {
        authorizationStatus: 0,
        orderStatus: 5,
        status: '已完成',
        statusColor: '#a6a6a6'
      },
    ],

  },



  /** 获取当前日期 */
  getNowDate() {
    const date = new Date(); // 获取当前日期
    const year = date.getFullYear(); // 获取年份
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份，补零
    const day = String(date.getDate()).padStart(2, '0'); // 获取日期，补零

    return `${year}-${month}-${day}`; // 拼接成 yyyy-MM-dd 格式
  },
  /** 获取上个月日期 */
  getLastMouthDate() {
    const currentDate = new Date(); // 获取当前日期
    const year = currentDate.getFullYear(); // 当前年份
    const month = currentDate.getMonth(); // 当前月份（0-11）
    const day = currentDate.getDate(); // 当前日期

    // 计算一个月前的日期
    const oneMonthAgoDate = new Date(year, month - 1, day);

    // 处理跨年问题（如果当前月份是 1 月，month - 1 会是 0，即上一年的 12 月）
    // 无需额外处理，Date 对象会自动处理

    // 格式化日期为 YYYY-MM-DD
    const formattedDate = `${oneMonthAgoDate.getFullYear()}-${String(oneMonthAgoDate.getMonth() + 1).padStart(2, '0')}-${String(oneMonthAgoDate.getDate()).padStart(2, '0')}`;

    return formattedDate;
  },

  /** 计算倒计时，倒计时结束后发起取消授权 */
  startCountdow() {
    this.timer = setInterval(() => {
      const countDownZeroOrders = []
      const orders = this.data.orders.map(order => {
        if (order.countdown && order.countdown != '0') {
          const currentCountDown = (Number(order.countdown) - 1);
          order.countdown = currentCountDown.toString();
          if (currentCountDown <= 0) countDownZeroOrders.push(order)
        }
        return order
      })

      this.setData({
        orders: orders
      })
      this.toUnAnthorization(countDownZeroOrders)
    }, 1000);
  },

  /** 结束倒计时 */
  endCountDown() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  },
  /** 发送取消授权 */
  toUnAnthorization(orders) {
    console.log(orders)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const today = this.getNowDate();
    const lastMouthDay = this.getLastMouthDate();
    this.setData({
      // date: today,
      paymentMode: options.paymentMode,
      startDate: today,
      endDate: lastMouthDay
    });
    console.log("历史页当前data", this.data)
    this.getStationInfo();
    // this.startCountdow();
  },

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

      this.getLocation();
    })
  },

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

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getOrder();
  },

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

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

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.endCountDown()
  },

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (!this.data.isHaveOrder) return;
    var page = this.data.pageNum + 1;
    this.setData({
      pageNum: page
    })
    this.getOrder()
  },

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

  },

  /** 日期选择器选择时间 */
  bindDateChange(date) {
    console.log("日期选择",date)
    this.setData({
      date: date.detail.value,
      pageNum:1,
      pageSize:5,
      orders: []
    });
    console.log(date)
    this.getOrder()
  },

  /** 组件按钮一点击事件 */
  onOrderButtonClick1(event) {
    console.log(event)
    const order = event.detail.order;
    const message = event.detail.event;
    if (message == "退款") {
      wx.showLoading({
        title: '正在退款',
      })
      api.request_RefundTrx({ "trxId": order.orderId }).then(res => {
        console.log("退款", res)
        wx.hideLoading()
        if (res.data.statusCode == 200) {
          return util.subAndsendMessage(order.orderId, "退款")
        } else {
          wx.showToast({
            title: res.data.message,
          })
        }
      }).then(res => {
        this.refreshOrder();
      })
        .catch(err => {
          console.log("退款失败", err)
          wx.hideLoading()
        })
    }
  },

  /** 组件按钮二点击事件 */
  onOrderButtonClick2(event) {
    console.log(event)
    if (event.detail.event == "重新授权") {
      this.toAuthorization(event.detail.order.orderId)
    }
    if(event.detail.event == "继续支付") {
      this.toPay(event.detail.order.orderId)
    }
  },

  /** 支付按钮点击事件 */
  toPay(orderId) {
    wx.showLoading({
      title: '支付中',
    })
    this.subMessage(orderId)
  },
  /** 订阅消息模板 */
  subMessage(orderId) {
    const that = this;
    wx.requestSubscribeMessage({
      tmplIds: ['V0tl-4n-5hwNZc4SrEttvrmawAyM-SB0pQWZNwp54Ks'], // 最多支持3条
      success(res) {
        that.pay(orderId)
        // 'accept'表示用户同意订阅该条id对应的模板消息
        if (res['V0tl-4n-5hwNZc4SrEttvrmawAyM-SB0pQWZNwp54Ks'] === 'accept') {
          
        }
      },
      fail(err) {
        that.pay(orderId)
      }
    })


  },
  /** 实际支付 */
  pay(orderId) {
    const that = this;
    api.request_wechatPay(orderId)
      .then(res => {
        wx.requestPayment({
          timeStamp: res.data.data.unifiedOrderResult.timeStamp,
          nonceStr: res.data.data.unifiedOrderResult.nonceStr,
          package: res.data.data.unifiedOrderResult.package,
          signType: res.data.data.unifiedOrderResult.signType,
          paySign: res.data.data.unifiedOrderResult.paySign,
          success: res => {
            wx.hideLoading()
            that.sendMessage(orderId)
            that.refreshOrder()
          },
          fail: res => {
            wx.hideLoading()
          }
        })
      });
  },
  /** 发送消息模板 */
  sendMessage(orderId) {
    const message = {
      trxid: orderId,
      orderType: '支付'
    }
    api.request_sendMessage(message).then(res => {
      console.log("发送消息模板结果", res)
    }).catch(err => {
      console.log("发送消息模板失败", err)
    })
  },

  /** 授权 */
  toAuthorization(orderId) {
    const that = this;
    wx.showLoading({
      title: '授权中',
    })
    const distance = util.haversine(this.data.stationLatitude,this.data.stationLongitude,this.data.latitude,this.data.longitude);
    if(distance > 500) {
      wx.showToast({
        title: '您不在油站范围内，请到油站时进行下单',
      })
      return
    }
    api.request_NozzleAuthorization(orderId).then(res => {
      console.log("授权", res)
      wx.hideLoading()
      if (res.data.statusCode == 200) {
        that.refreshOrder()
      } else {
        wx.showToast({
          title: '授权失败',
        })
      }
    }).catch(err => {
      console.log("授权报错", err)
      wx.showToast({
        title: '授权失败',
      })
    })
  },

  /** 获取订单 */
  getOrder() {
    wx.showLoading({
      title: '获取订单中',
    })
    const that = this;
    const findTime = this.data.date != '' ? this.data.date + "T23:59:59" : this.data.date;
    api.request_WXFindOrders(findTime, this.data.pageNum, this.data.pageSize).then(res => {
      wx.hideLoading()
      wx.stopPullDownRefresh()
      // api.request_WXFindOrders(this.data.date, 3, 5).then(res => {
      console.log("获取历史订单", res)
      let datas = res.data.data;
      if (datas.length <= 0) {
        that.data.isHaveOrder = false;
        return
      }
      var getOrders = that.turnOnOrder(datas)

      var orderList = [...this.data.orders, ...getOrders]
      this.setData({
        orders: orderList
      })

      console.log("转换后的订单", this.data.orders)
    }).catch(err => {
      wx.hideLoading()
      console.log("获取历史订单失败", err)
      wx.showModal({
        title: '提示',
        content: '获取订单失败',
      })
    })
  },

  /** 打包订单信息 */
  turnOnOrder(orders) {
    const that = this;
    var getOrders = orders.map(order => {
      //获取订单时间
      var times = [order.authorizationTime, order.createTime, order.fuelItemTransactionEndTime, order.transactionTime];
      var timeFormate = times.find(t => t != undefined && t != null && t != '');
      var time = util.formatDateNotSecond(timeFormate);

      //获取订单升数
      var volume = (order.originalQty != null && order.originalQty != undefined) ? order.originalQty : order.qty

      //获取订单状态
      var status = undefined;
      //根据不同的模式获取订单状态值
      if (order.orderType == 0) {
        status = that.data.payStatusValue.find(state => state.orderStatus == order.orderStatus)
      } else {
        status = that.data.prepayStatuValue.find(state =>
          state.authorizationStatus == order.authorizationStatus &&
          state.orderStatus == order.orderStatus
        )
      }

      var stute = '';
      var stateColor = '';
      var bt1 = ''
      var bt2 = ''
      if (status != undefined) {
        stute = status.status
        stateColor = status.statusColor
      }
      if (order.orderType == 0) {
        if (stute == '未支付') bt2 = '重新支付';
        return {
          order: {
            status: stute,
            statusColor: stateColor,
            oilName: order.productName,
            nozzle: order.nozzleId,
            volume: volume,
            amount: order.originalAmount,
            payAmount: order.actualPaymentAmount,
            discount: order.originalAmount - order.actualPaymentAmount,
            orderId: order.id,
            time: time,
            price: order.price,
            station:that.data.stationName
          },
          bottonText2: bt2,
          orderType:order.orderType
        }
      } else {
        if (stute == "授权成功") bt2 = "请尽快提枪"
        if (stute == "支付失败") {
          bt1 = "取消"
          bt2 = "继续支付"
        }
        if (stute == "授权失败") {
          bt1 = "退款"
          bt2 = "重新授权"
        }
        return {
          order: {
            status: stute,
            statusColor: stateColor,
            oilName: order.productName,
            nozzle: order.nozzleId,
            volume: volume,
            amount: order.originalAmount,
            payAmount: order.actualPaymentAmount,
            discount: order.originalAmount - order.actualPaymentAmount,
            refund: order.refundAmount,
            orderId: order.id,
            time: time,
            station:that.data.stationName
          },
          bottonText1: bt1,
          bottonText2: bt2,
          orderType:order.orderType
        }
      }
    })

    return getOrders;
  },

  /** 刷新订单 */
  refreshOrder() {
    this.setData({
      date: '',
      pageNum:1,
      pageSize:5,
      orders: []
    });
    console.log(this.data.date)
    this.getOrder()
  }
})