// pages/order/order.js
let Util = require("../../utils/util");
let log = require('../../utils/log.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderid: null,
    userId: null,
    chargPileId: null,
    order: null,
    startTime: null,
    endTime: null,
    totalTime: null,
    orderFlag:false
  },

  payOrder(e) {
    log.info('[订单支付]', '[用户触发支付订单]');
    wx.showLoading({
      title: '支付中...',
      mask: true
    });
    console.log('去支付');
    console.log(this.order);
    let that = this;
    let {
      order,
      userId
    } = this.data;
    log.info('[订单支付]', '[用户触发支付订单]', '[wx.login请求]');
    wx.login({
      success(res) {
        console.log(res);
        log.info('[订单支付]', '[用户触发支付订单]', '[wx.login响应]',res);
        if (res.code) {
          // 发起网络请求
          log.info('[订单支付]', '[服务端订单支付]', '[请求]', {
            outTradeNo: order.orderid, //订单号
            totalFee: order.chargallmoney, //钱
            code: res.code,
            user_id: userId
          });
          wx.request({
            url: getApp().globalData.postHeadAgreement +'/restapi/wechatpay/chargpayfor',
            data: {
              outTradeNo: order.orderid, //订单号
              totalFee: order.chargallmoney, //钱
              code: res.code,
              user_id: userId
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
            },
            success(res1) {
              let {
                data
              } = res1;
              log.info('[订单支付]', '[服务端订单支付]', '[响应]', data);
              console.log(res1);
              if (data && data.code == 200) {
                if (data.result) {
                  //wx.showModal({
                  //  showCancel: false,
                  //  content: '请微信支付'
                  // });
                  log.info('[订单支付]', '[余额不足微信支付]','[请求]',{
                    timeStamp: data.result.timeStamp,
                    nonceStr: data.result.nonceStr,
                    package: data.result.package,
                    signType: data.result.signType,
                    paySign: data.result.paySign});
                  wx.requestPayment({
                    timeStamp: data.result.timeStamp,
                    nonceStr: data.result.nonceStr,
                    package: data.result.package,
                    signType: data.result.signType,
                    paySign: data.result.paySign,
                    success(res2) {
                      log.info('[订单支付]', '[余额不足微信支付成功]', '[响应]', res2);
                      log.info('[订单支付]', '[微信支付成功回调服务端]', '[请求]', {
                        //chargPileId,
                        //userId,
                        orderid: order.orderid
                      });
                      wx.hideLoading();
                      wx.showModal({
                        showCancel: false,
                        content: '支付订单成功',
                        confirmColor:'#00AADD',
                      });

                      that.setData({
                        orderFlag:true 
                      });
                      // wx.request({
                      //   url: getApp().globalData.postHeadAgreement +'/restapi/pileLog/wechatpayback',
                      //   data: {
                      //     //chargPileId,
                      //     //userId,
                      //     orderid: order.orderid
                      //   },
                      //   method: 'POST',
                      //   success(res3) {
                      //     wx.hideLoading();
                      //     let {
                      //       data
                      //     } = res3;
                      //     log.info('[订单支付]', '[微信支付成功回调服务端]', '[响应]', data);
                      //     if (data && data.code == 200) {
                      //       that.setData({
                      //         orderFlag:true 
                      //       });
                      //       wx.showModal({
                      //         showCancel: false,
                      //         content: '支付订单成功',
                      //         confirmColor:'#00AADD',
                      //       });
                      //       log.info('[订单支付]', '[微信支付成功回调服务端]', '[成功]');
                      //     } else {
                      //       wx.showModal({
                      //         showCancel: false,
                      //         content: '支付订单失败',
                      //         confirmColor:'#00AADD',
                      //       });
                      //       log.info('[订单支付]', '[微信支付成功回调服务端]', '[失败data null||data.code<>200]', data);
                      //     }
                      //   }
                      // });
                    },
                    fail(res3) {
                      wx.hideLoading();
                      log.info('[订单支付]', '[余额不足微信支付]', '[fail]', res3);
                      console.log(res3);
                    }
                  });
                } else {
                  wx.hideLoading();
                  that.setData({
                    orderFlag: true
                  });
                  wx.showModal({
                    showCancel: false,
                    content: data.msg,
                    confirmColor:'#00AADD',
                  });
                }
                log.info('[订单支付]', '[服务端订单支付]', '[余额支付成功]', data);
              } else {
                wx.hideLoading();
                wx.showModal({
                  showCancel: false,
                  content: data.msg,
                  confirmColor:'#00AADD',
                });
                log.info('[订单支付]', '[服务端订单支付]', '[失败data null||data.code<>200]', data);
              }
            }
          });
        } else {
          wx.hideLoading();
          console.log('登录失败！' + res.errMsg);
          log.info('[订单支付]', '[用户触发支付订单]', '[wx.login响应失败code null]', res);
        }
      }
    });

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let i = 0;
    let {
      orderid,
      userId,
      chargPileId
    } = options;
    log.info('[订单支付]', '[加载完成]', '[参数]', {
      orderid,
      userId,
      chargPileId
    });

    console.info("ooooooooooooooooooooooooooooo")
    console.info(orderid)
    console.info(userId)
    console.info(chargPileId)
    console.info("ooooooooooooooooooooooooooooo")


    this.setData({
      orderid,
      userId,
      chargPileId
    });
    var that = this;
    wx.showLoading({
      title: '订单生成中...',
      mask:true
    });
    var timeoutflag = setInterval(function() {
        i++;
        log.info('[订单支付]', '[轮训获取订单]', '[请求]', {
          chargPileId,
          userId,
          orderid
        });
        wx.request({
          url: getApp().globalData.postHeadAgreement +'/restapi/pileLog/wechatsettlement_new',
          data: {
            chargPileId,
            userId,
            orderid
          },
          method: 'POST',
          success(res) {
            let {
              data
            } = res;
            log.info('[订单支付]', '[轮训获取订单]', '[响应]', data);
            let {
              result: order
            } = data;
            if (data && data.code == 200) {
              if (order.transstatus==3){
                //order.paystatus=1;
                //order.chargstarttime='2020-10-19 10:00:00';
                //order.chargendtime = '2020-10-19 10:20:20';
                wx.hideLoading();
                clearInterval(timeoutflag);
                log.info('[订单支付]', '[轮训获取订单]', '[订单transstatus状态3]可手动支付');
              }
              // if (order.chargallmoney && order.chargpower) {
              //   wx.hideLoading();
              //   clearInterval(timeoutflag);
              // }
              //wx.showModal({
              //showCancel: false,
              //content: '获取订单成功'
              //});
              
              var startDate = Util.parseDate(order.chargstarttime);
              var endDate = Util.parseDate(order.chargendtime);
              var totalTime = Math.floor((endDate.getTime() - startDate.getTime()) / 60000);
              var totalTimeHour = Math.floor(totalTime / 60);
              var totalTimeMinute = totalTime % 60;
              var startTime = Util.formatNumber(startDate.getMonth() + 1) + '月' + Util.formatNumber(startDate.getDate()) + '日  ' + Util.formatNumber(startDate.getHours()) + ':' + Util.formatNumber(startDate.getMinutes()) + ':' + Util.formatNumber(startDate.getSeconds());
              var endTime = Util.formatNumber(endDate.getMonth() + 1) + '月' + Util.formatNumber(endDate.getDate()) + '日  ' + Util.formatNumber(endDate.getHours()) + ':' + Util.formatNumber(endDate.getMinutes()) + ':' + Util.formatNumber(endDate.getSeconds());
              totalTime = Util.formatNumber(totalTimeHour) + "时" + Util.formatNumber(totalTimeMinute) + "分";
              that.setData({
                order,
                startTime,
                endTime,
                totalTime
              });

              //console.log(that.data.result);

            } else {
              //wx.hideLoading();
              if (i>=60){
                clearInterval(timeoutflag);
                log.info('[订单支付]', '[轮训获取订单]', '[60S超时]', data);
                wx.showModal({
                  showCancel: false,
                  content: '获取订单失败',
                  confirmColor:'#00AADD',
                });
              }
            }
          },
          fail(err) {
            wx.hideLoading();
            clearInterval(timeoutflag);
            log.info('[订单支付]', '[轮训获取订单]', '[fail]', err);
            wx.showModal({
              showCancel: false,
              content: '获取订单失败',
              confirmColor:'#00AADD',
            });
          }
        });
      },
      1000);

  },
  closeView:function(){
    let url = `/pages/index/index`;
    wx.reLaunch({
      url
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})