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

  /**
   * 页面的初始数据
   */
  data: {
    searchIndex:-1,
    reservUserOrderList: [],
    pagesize:10,
    pagenum:1,
    total:-1,
    loadTotal: 0,
    dataLoading: false,
    finishedLoadTap: 0,
    finishedLoadShowTimes: 0,
    chongdianzhuangmingcheng: false,
    chongdianzhuangbianhao: false,
    chongdianshichang: false,
    chongdiankaishijieshu: false,
    customerServiceFlag: false,
    cancleBtnFlag: false,
    servicetel: getApp().globalData.helpPhoneNum,
  },
  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 reservUserOrderList =  []
    let pagesize = 10
    let pagenum = 1
    let total = -1
    let loadTotal =  0
    let dataLoading =  false
    let finishedLoadTap =  0
    let finishedLoadShowTimes =  0
    this.setData({
      reservUserOrderList,
      pagesize,
      pagenum,
      total,
      loadTotal,
      dataLoading,
      finishedLoadTap,
      finishedLoadShowTimes,
    })
  },
  getPage(){
    // console.info(this.data.reservUserOrderList.length + " MMM " + this.data.total)
    
    if(this.data.reservUserOrderList.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: '数据加载中....',
    })

  let that = this;

    wx.request({
      url: getApp().globalData.postHeadAgreement +'/restapi/wechat/ReservUserOrder',
      data: {
        userId: wx.getStorageSync('userInfo').userId,
        searchIndex: that.data.searchIndex<0?null:that.data.searchIndex,
        pagenum: this.data.pagenum++,
        pagesize: 10,
      },
      method: 'POST',
      success(res) {
        console.log(res);
        if (res.data.result.rows) {
          let {
            rows: reservUserOrderList
          } = res.data.result;
          // that.startTimeOrder(charginglogs);
          that.formatCharginglogs(reservUserOrderList);
          wx.hideLoading()
          that.setData({
            reservUserOrderList: that.data.reservUserOrderList.concat(reservUserOrderList),
            total: res.data.result.total,
            dataLoading: false
          });
        }
      }
    });
  },


  formatCharginglogs(formatCharginglogs) {
    formatCharginglogs.forEach((item, index) => {
      try {
          // 时间截取
          item.reservChargeStartTime = item.reservChargeStartTime.substr(0,16)
          item.reservChargeEndTime = item.reservChargeEndTime.substr(0,16)
          // 状态翻译
          if(item.reservStatus==0){
            item.reservStatusCN = '待履约'
          }else if(item.reservStatus==1){
            item.reservStatusCN = '已取消'
          }else if(item.reservStatus==2){
            item.reservStatusCN = '已履约'
          }else if(item.reservStatus==3){
            item.reservStatusCN = '已违约'
          }else if(item.reservStatus==4){
            item.reservStatusCN = '已纠正'
          };
          // 判断标记为  chongdianzhuangmingcheng chongdianzhuangbianhao chongdianshichang chongdiankaishijieshu
          let chongdianzhuangmingcheng =  false
          let chongdianzhuangbianhao =  false
          let chongdianshichang =  false
          let chongdiankaishijieshu =  false
          let chongdianfeiyong =  false
          let customerServiceFlag = false;
          let cancleBtnFlag= false;
          let height= 'h4';

          if(item.reservStatus==2){
            // 已履约
            if(item?.pileLog?.transstatus == 3){
              if(item?.pileLog?.chargPileId == item?.reservPile?.chargPileId){
                chongdianzhuangmingcheng = false
                chongdianzhuangbianhao = false
                chongdianshichang = true
                chongdiankaishijieshu = true
                chongdianfeiyong = true
                height= 'h1';
              }else{
                chongdianzhuangmingcheng = true
                chongdianzhuangbianhao = true
                chongdianshichang = true
                chongdiankaishijieshu = true
                chongdianfeiyong = true
                height= 'h2';
              }

            }else{
              if(item?.pileLog?.chargPileId == item?.reservPile?.chargPileId){
                chongdianzhuangmingcheng = false
                chongdianzhuangbianhao = false
                chongdianshichang = false
                chongdiankaishijieshu = false
                chongdianfeiyong = false
                height= 'h4';
              }else{
                chongdianzhuangmingcheng = true
                chongdianzhuangbianhao = true
                chongdianshichang = false
                chongdiankaishijieshu = false
                chongdianfeiyong = false
                height= 'h3';

              }

            }
          }
          if(item.reservStatus==3){
            customerServiceFlag = true;
          }
          if(item.reservStatus==0){
            cancleBtnFlag = true;
          }
          item.chongdianzhuangmingcheng = chongdianzhuangmingcheng;
          item.chongdianzhuangbianhao = chongdianzhuangbianhao;
          item.chongdianshichang = chongdianshichang;
          item.chongdiankaishijieshu = chongdiankaishijieshu;
          item.chongdianfeiyong = chongdianfeiyong;
          item.customerServiceFlag = customerServiceFlag;
          item.cancleBtnFlag = cancleBtnFlag;
          item.height = height;
        //console.log(item.chargPile);
      } catch (err) {
        //在这里处理错误
      }
      try {
        let chargePile = item.pileLog;
        console.info(chargePile)
        let startDate = Util.parseDate(chargePile.chargstarttime);
        let endDate = Util.parseDate(chargePile.chargendtime)
        let totalTime = Math.round((endDate.getTime() - startDate.getTime()) / 60000);
        let totalTimeHour = Math.floor(totalTime / 60);
        let totalTimeMinute = totalTime % 60;
        let startTime = startDate.getFullYear() + "年" + Util.formatNumber(startDate.getMonth() + 1) + '月' + Util.formatNumber(startDate.getDate()) + '日  ' + Util.formatNumber(startDate.getHours()) + ':' + Util.formatNumber(startDate.getMinutes()) + ':' + Util.formatNumber(startDate.getSeconds());
        let endTime = endDate.getFullYear() + "年" + 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) + "分";
        chargePile.startTime = startTime;
        chargePile.endTime = endTime;
        chargePile.totalTime = totalTime;
        chargePile.chargallmoney = chargePile.chargallmoney.toFixed(2);
        chargePile.chargservice = chargePile.chargservice.toFixed(2);
        chargePile.chargmoney = chargePile.chargmoney.toFixed(2);
        //console.log(chargePile.chargPile);
      } catch (err) {
        //在这里处理错误
      }


    });

  },
  startTimeOrder(charginglogs) {
    if (charginglogs && 0 != charginglogs.length) {
      charginglogs.sort(function(ma, mb) {
        return mb.chargstarttime.localeCompare(ma.chargstarttime);
      });
    }
  },
  customerServiceBtn(){
    wx.makePhoneCall({
      phoneNumber: this.data.servicetel
    })
  },
  cancleBtn(e){
    let  that = this
    let reservId = e.currentTarget.dataset.idx;
    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    wx.showModal({
      title: '提示',
      content: '是否取消预约',
      complete: (res) => {
        if (res.cancel) {
          
        }
    
        if (res.confirm) {
          wx.request({
            url: getApp().globalData.postHeadAgreement +'/restapi/wechat/canelReserv?userName=' + userInfo.loginName + '&reservId=' + reservId,
            data: {
            },
            method: 'POST',
            success(res) {
              console.info(res)
              // TODO 重新加载页面
              that.resetListZero();
              that.getPage();
            }
          });
        }
      }
    })


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

  },

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

  },

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

  },

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

  },

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

  },

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

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

  }
})