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

  /**
   * 页面的初始数据
   */
  data: {
    searchIndex:-1,
    occupyFeeOrderList: [],
    pagesize:10,
    pagenum:1,
    total:-1,
    loadTotal: 0,
    dataLoading: false,
    finishedLoadTap: 0,
    finishedLoadShowTimes: 0,
    customerServiceFlag: false,
    cancleBtnFlag: false,
    servicetel: getApp().globalData.helpPhoneNum,
    orderid: null,
    userId: null,
    order: {},
  },
  switchBar(e){
    let searchIndex = e.currentTarget.dataset.idx;
    this.setData({
      searchIndex
    })
    this.resetListZero();
    this.getPage();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    let that = this;
    // 页面显示
    if (userInfo && isLogin) {
      this.resetListZero();
      this.getPage();
    }
    
  },
  resetListZero(){
    let occupyFeeOrderList =  []
    let pagesize = 10
    let pagenum = 1
    let total = -1
    let loadTotal =  0
    let dataLoading =  false
    let finishedLoadTap =  0
    let finishedLoadShowTimes =  0
    this.setData({
      occupyFeeOrderList,
      pagesize,
      pagenum,
      total,
      loadTotal,
      dataLoading,
      finishedLoadTap,
      finishedLoadShowTimes,
    })
  },
  getPage(){
    // console.info(this.data.occupyFeeOrderList.length + " MMM " + this.data.total)
    
    if(this.data.occupyFeeOrderList.length == this.data.total){
      this.setData({
        finishedLoadTap:this.data.finishedLoadTap+1
      })
      if(this.data.finishedLoadTap>0 && this.data.finishedLoadShowTimes==0){
        this.setData({
          finishedLoadShowTimes:this.data.finishedLoadShowTimes+1
        })
        wx.showToast({
          title: '全部加载完毕',
          icon: 'success',
          duration: 2000
        })
      }
      return
    }

    if(this.data.dataLoading){
      return
    }
    this.setData({
      dataLoading: true
    })
    wx.showLoading({
      title: '数据加载中....',
    })
    this.queryOccupyFeeOrder();
  },

  queryOccupyFeeOrder(){
    let that = this;
    wx.request({
      url: getApp().globalData.postHeadAgreement +'/restapi/wechat/queryOccupyFeeOrder',
      data: {
        userId: wx.getStorageSync('userInfo').userId,
        searchIndex: that.data.searchIndex<0?-1:that.data.searchIndex,
        pagenum: this.data.pagenum++,
        pagesize: 10,
      },
      method: 'POST',
      success(res) {
        console.log("占位费",res);
        if (res.data.code == 200) {
          let {
            rows: occupyFeeOrderList
          } = res.data.result;
          // that.startTimeOrder(charginglogs);
          that.formatCharginglogs(occupyFeeOrderList);
          wx.hideLoading()
          that.setData({
            occupyFeeOrderList: that.data.occupyFeeOrderList.concat(occupyFeeOrderList),
            total: res.data.result.total,
            dataLoading: false
          });
        }else{
          wx.hideLoading()
        }
      }
    });
  },
  formatCharginglogs(formatCharginglogs) {
    formatCharginglogs.forEach((item, index) => {
      try {
        console.log("item",item);
          // 时间截取
          item.occupyBeginTime = item.occupyBeginTime.substr(0,19)
          item.occupyEndTime = item.occupyEndTime.substr(0,19)
          // 状态翻译
          if(item.status==3){
            item.occupyStatusCN = '未支付'
          }else if(item.status==4){
            item.occupyStatusCN = '已支付'
          }else if(item.status==6){
            item.occupyStatusCN = '已取消'
          }else if(item.status==7){
            item.occupyStatusCN = '已退款'
          };
          let customerServiceFlag = false;
          let cancleBtnFlag= false;
          let height= 'h3';

          if(item.status==3){
            customerServiceFlag = true;
          }
          if(item.status==3 || item.status == 4){
            cancleBtnFlag = true;
          }
          item.customerServiceFlag = customerServiceFlag;
          item.cancleBtnFlag = cancleBtnFlag;
          item.height = height;
        //console.log(item.chargPile);
      } catch (err) {
        //在这里处理错误
      }
    });

  },
  startTimeOrder(charginglogs) {
    if (charginglogs && 0 != charginglogs.length) {
      charginglogs.sort(function(ma, mb) {
        return mb.chargstarttime.localeCompare(ma.chargstarttime);
      });
    }
  },
  customerServiceBtn(e){
    let parkId = e.currentTarget.dataset.idx;
    wx.makePhoneCall({
      phoneNumber: this.data.servicetel
    })
  },
  payOrder(e) {
    log.info('[订单支付]', '[用户触发支付订单]');
    wx.showLoading({
      title: '支付中...',
      mask: true
    });
    let parkId = e.currentTarget.dataset.idx;
    let that = this;
    let userId = wx.getStorageSync('userInfo').userId
    this.queryOccupyById(userId,parkId).then(res=> {
      wx.hideLoading();
      let {
        order,
      } = that.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.occupyFee, //钱
            code: res.code,
            user_id: userId
          });
          wx.request({
            url: getApp().globalData.postHeadAgreement +'/restapi/wechatpay/occupyFeeOrderPayfor',
            data: {
              outTradeNo: order.orderId, //订单号
              totalFee: order.occupyFee, //钱
              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',
                        success(res) {
                          if (res.confirm) {
                            that.resetListZero(); 
                            that.getPage();
                          }
                        }
                      });
                     
                    },
                    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);
        }
      }
    });
    })
  },
  queryOccupyById(userId,parkId) {
    return new Promise((resolve, reject) => {
      let that = this;
      wx.request({
        url: getApp().globalData.postHeadAgreement +'/restapi/wechat/queryOccupyById',
        data: {
          userId: userId,
          id:parkId,
          searchIndex: 3 // 未支付
        },
        method: 'POST',
        success(res) {
          if (res.data.code == 200) {
            console.log("更具订单号插叙",res.data.result);
            that.setData({
            order:res.data.result
          })
          resolve(res.data.result);
          }else{
            resolve(res.data);
          }
        },
        fail(err) {
          console.error('请求失败', err);
          reject(err);
        }   
      });
    });
  },
  cancleBtn(e){
    let  that = this
    let reservId = e.currentTarget.dataset.idx;
    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    wx.showModal({
      title: '提示',
      confirmColor: '#00AADD',
      content: '若对当前占位费订单有疑问，请拨打客服电话4009608068，工作时间：08:00-18:00',
      complete: (res) => {
        // 可以在这里添加回调逻辑
        if (res.confirm) {
          console.log('用户点击了确认按钮');
        }else{
          console.log('用户点击了取消按钮');
        }
      }
    });


  },
  cancelM:function(e){
    this.setData({
       hiddenmodalput: true,
    })
 },


 iName: function (e) {
    this.setData({
       name:e.detail.value
    })
 },
 iPhoneNum: function (e) {
    this.setData({
       phoneNum: e.detail.value
    })
 },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },
  bindScrollTolowerEvent: function(){
    this.getPage();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})