import * as echarts from '../../ec-canvas/echarts';
import * as lf from '../../ec-canvas/echarts-liquidfill';


let log = require('../../utils/log.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    name:'',
    address:'', 
    offlineServicecall:'',
    stationTagList:[],
    chargprice: '', 
    serviceprice: '', 
    chargid: '',
    sumprice: '',
    fastFree:0,
    slowFree:0,
    fastSum:0,
    slowSum:0,
    pagesize:30,
    pagenum:1,
    total:-1,
    loadTotal: 0,
    dataLoading: false,
    finishedLoadTap: 0,
    finishedLoadShowTimes: 0,
    chargList: [],
    seeInfoChargPile:{},
    userInfo:{},
    chargfeatureList:[],
    isLogin: false,
    resultTable: [],
    // 是否减免停车费
    carParkingRate: false,
    // 停车时间
    parkTime: 0,
    activeTab: '0',
  },
  execParking(that,stationId){
    wx.request({
      url: getApp().globalData.postHeadAgreement + '/restapi/wechat/carParkingRate?stationId=' + stationId,
      // data: {
      // loginName: userInfo.loginName
      // },
      method: 'POST',
      success: function (res) {
        // 是否减免停车费
        // carParkingRate: false,
        // parkTime: 0,
        console.info(res)
        let reduceTime = res.data?.reduceTime;
        if(!reduceTime){
          that.setData({
            carParkingRate:false
          })
          return;
        }
        that.setData({
          carParkingRate:true
        })
        try{
          that.setData({
            parkTime: parseFloat((reduceTime/ 3600).toFixed(2))
          })
        }catch(e){
          that.setData({
            carParkingRate:false
          })
        }

      },
      fail(e) {
      console.log("用户数据同步失败");
      log.info('[扫码]', '[同步用户数据]', '[fail]', e);
      }
    });

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(e) {
    let that = this;
    let stationTagList = [];
    let offlineServicecall ="";
    wx.getStorage({
      key: 'index_seeInfo_chargpile',
      success: function (res) {
        console.info(res)
        var seeInfoChargPile = res.data;
        stationTagList = seeInfoChargPile.stationTagList
        offlineServicecall = seeInfoChargPile.offlineServicecall
        that.setData({
            stationTagList,
            offlineServicecall,
        })
        console.info(stationTagList)
        // 异步更新
        console.info(seeInfoChargPile.chargStationId)
        that.execParking(that,seeInfoChargPile.chargStationId)
        let resultTable = seeInfoChargPile.resultList
        that.setData({
          resultTable
        })
        that.setData({
          resultTable
        })
        let chargfeatureList;

        if(seeInfoChargPile.chargfeatures){
          chargfeatureList = seeInfoChargPile.chargfeatures.split(',')
        }else{
          chargfeatureList = [];
        }

        seeInfoChargPile.sharpTotalPrice = parseFloat((seeInfoChargPile.sharpChargPrice==null || seeInfoChargPile.sharpServicePrice==null || seeInfoChargPile.sharpChargPrice=='暂无费用' || seeInfoChargPile.sharpServicePrice=='暂无费用')? null:(seeInfoChargPile.sharpChargPrice + seeInfoChargPile.sharpServicePrice).toFixed(6));
        seeInfoChargPile.peakTotalPrice = parseFloat((seeInfoChargPile.peakChargPrice==null || seeInfoChargPile.peakServicePrice==null || seeInfoChargPile.peakChargPrice=='暂无费用' || seeInfoChargPile.peakServicePrice=='暂无费用' )? null:(seeInfoChargPile.peakChargPrice + seeInfoChargPile.peakServicePrice).toFixed(6));
        seeInfoChargPile.flatTotalPrice = parseFloat((seeInfoChargPile.flatChargPrice==null || seeInfoChargPile.flatServicePrice==null || seeInfoChargPile.flatChargPrice=='暂无费用' || seeInfoChargPile.flatServicePrice=='暂无费用' )? null:(seeInfoChargPile.flatChargPrice + seeInfoChargPile.flatServicePrice).toFixed(6));
        seeInfoChargPile.valleyTotalPrice = parseFloat((seeInfoChargPile.valleyChargPrice==null || seeInfoChargPile.valleyServicePrice==null || seeInfoChargPile.valleyChargPrice=='暂无费用' || seeInfoChargPile.valleyServicePrice=='暂无费用' )? null:(seeInfoChargPile.valleyChargPrice + seeInfoChargPile.valleyServicePrice).toFixed(6));
        seeInfoChargPile.totalprice =  parseFloat((seeInfoChargPile.chargprice==null || seeInfoChargPile.serviceprice==null || seeInfoChargPile.chargprice=='暂无费用' || seeInfoChargPile.serviceprice=='暂无费用')? null:(seeInfoChargPile.chargprice + seeInfoChargPile.serviceprice).toFixed(6));

        that.setData({
          seeInfoChargPile,
          chargfeatureList
        });
        console.info(seeInfoChargPile)
        console.info(chargfeatureList)
        wx.removeStorage({
          key: 'index_seeInfo_chargpile',
          success(res) {
          }
        });
      }
    });



    let { name, address, chargprice, serviceprice, chargid } = e;

    name =  name=='null'?null:name;
    address =  address=='null'?null:address;
    // stationTagList = !stationTagList?null:stationTagList;
    chargprice =  chargprice=='null'?null:chargprice;
    serviceprice =  serviceprice=='null'?null:serviceprice;
    chargid =  chargid=='null'?null:chargid;
    // let sumprice = (chargprice==null || serviceprice==null)? null:chargprice+serviceprice;
    let sumprice = (chargprice==null || serviceprice==null)? null:chargprice+serviceprice;

    this.setData({
      name,
      address,
    //   stationTagList,
      chargprice,
      serviceprice,
      chargid,
      sumprice
    });
 
    this.getPage();
  },
  previewImage(e){
    var that = this,
    //获取当前图片的下表
      index = e.currentTarget.dataset.index,
      //数据源
      pictures = this.data.chargfeatureList;
    wx.previewImage({
    //当前显示下表
     current: pictures[index],
     //数据源
     urls: pictures
    })
  },
  getPage(){

    if(this.data.chargList.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/chargInfo',
      data: {
        id: that.data.chargid,
        pagenum: this.data.pagenum++,
        pagesize: 30,
      },
      method: 'POST',
      success(res) {
        console.log(res);
        let chargList = res.data.chargList.rows;

        chargList.forEach(key => {
          let chargstatusname = '';
          let chargstatusclass = '';
          if(key.chargstatus == 2){
            chargstatusname='空闲中'
            chargstatusclass = 'chargstatus_kxz'
          }else if(key.chargstatus == 11){
            chargstatusname='已插枪'
            chargstatusclass = 'chargstatus_ycq'
          }else if(key.chargstatus == 3 || key.chargstatus == 10){
            chargstatusname='充电中'
            chargstatusclass = 'chargstatus_cdz'
          }else if(key.chargstatus == 0){
            chargstatusname='离线'
            chargstatusclass = 'chargstatus_lx'
          }else{
            chargstatusname='故障'
            chargstatusclass = 'chargstatus_gz'
          }
          key.chargstatusname = chargstatusname;
          key.chargstatusclass = chargstatusclass;
      })

        console.log(chargList);
        // that.rechargeTimeOrder(chargemoneylogs);
        wx.hideLoading()
        that.setData({
          chargList: that.data.chargList.concat(chargList),
          total: res.data.chargList.total,
          dataLoading: false,
          fastFree : res.data.fastFree,
          slowFree : res.data.slowFree,
          fastSum : res.data.fastSum,
          slowSum : res.data.slowSum
        });
      }
    });

  },
  goScanResult(e){
    // scan_result

  console.info('xxxxxxxxxxxxxx')
    let {
      keywords
    } = e.currentTarget.dataset;
    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    let chargid = keywords.chargPileId;
    let that = this;

    if(isLogin && userInfo.bindingPhone==0){
      console.info('xxxxxxxxxxxxxx1')
      wx.showModal({
        title: '提示',
        content: '当前账户未绑定手机号,请您进行手机号绑定操作',
        showCancel:false,
        confirmText: '去绑定',
        confirmColor:'#00AADD',
        success: function (res1) {
            let url = `/pages/bindPhone/bindPhone`;
            wx.navigateTo({
              url
            });
        }
      });
      return;
    }
    wx.showLoading({
      title: '努力加载中...',
    })

    if (!isLogin) {
      console.info('xxxxxxxxxxxxxx2')
      log.info('[首页]', '[未登陆跳转登录界面]');
      let url = `/pages/login/phone_login/phone_login`;
      wx.hideLoading();
      wx.navigateTo({
        url
      });
      // return;
    } else {
      log.info('[首页]', '[获取用户是否有未支付订单]', '[请求]', { userId: userInfo.userId });
      wx.request({
        url: getApp().globalData.postHeadAgreement + '/restapi/pileLog/wechatsettlement',
        data: {
          userId: userInfo.userId
        },
        method: 'POST',
        success(res) {
          let {
            data
          } = res;
          let {
            result: order
          } = data;
          log.info('[首页]', '[获取用户是否有未支付订单]', '[响应]', data);
          if (data && order && data.code == 200) {
            wx.hideLoading();
            log.info('[首页]', '[用户有未支付订单跳转订单支付界面]');
            wx.showModal({
              showCancel: false,
              content: '你有未支付的订单,请先支付',
              confirmColor:'#00AADD',
              success: function (res) {
                //console.log(res);
                if (!res.cancel) {
                  //点击确定
                  let url = `/pages/order/order?orderid=${order.orderid}&userId=${order.userId}&chargPileId=${order.chargPileId}`;
                  wx.navigateTo({
                    url
                  });
                }
              }
            });
            //console.log(that.data.result);
          } else {
            //console.log('无订单');
            log.info('[首页]', '[用户无未支付订单]');

            wx.request({
              url: getApp().globalData.postHeadAgreement + '/restapi/wechat/chargPile',
              // data: scanResult,
              data: {
                chargPileId: chargid,
                userId: userInfo.userId
              },
              method: 'POST',
              success(res) {
                console.log(chargid);
                log.info('[首页]', '[获取扫一扫充电桩]', '[响应]', res.data);
                if (!res.data || res.data.code == 500) {
                  that.scanFlag = false;
                  wx.hideLoading();
                  //没有该充电桩信息
                  wx.showModal({
                    showCancel: false,
                    confirmColor:'#00AADD',
                    content: res && res.data && res.data.msg ? res.data.msg :'无效的终端编号'
                  });
                } else {
                  res.data = res.data.result
                  //充电状态0:离线、1:故障、2:空闲中、3:充电中、4:欠压故障、5:过压故障、6:过电流故障、8:预约、9:在线升级、10:操作中、11:已插枪等
                  if (!res.data.chargstatus || res.data.chargstatus == 0 || res.data.chargstatus == 1 || res.data.chargstatus == 4 || res.data.chargstatus == 5 || res.data.chargstatus == 6 || res.data.chargstatus == 9) {
                    //充电桩故障    
                    wx.showModal({
                      showCancel: false,
                      content: '终端故障,维修中',
                      confirmColor:'#00AADD',
                    });
                  } else if (res.data.chargstatus == 3 || res.data.chargstatus == 8 || res.data.chargstatus == 10) {
                    wx.showModal({
                      showCancel: false,
                      content: '正在充电中',
                      confirmColor:'#00AADD',
                    });
                  } else if (res.data.chargstatus == 2 || res.data.chargstatus == 11) {
                    wx.setStorage({
                      key: "scan_chargpile",
                      data: res.data
                    });
                    log.info('[首页]', '[扫一扫充电桩空闲跳转去充电界面]');
                    let url = `/pages/scan_result/scan_result`;
                    wx.hideLoading();
                    wx.navigateTo({
                      url
                    });
                  }
                  wx.hideLoading();
                }
              },
              fail(e) {
                getApp().showNetworkError();
              }
            });

          }
        },
        fail(e) {
          that.scanFlag = false;
          wx.hideLoading();
          getApp().showNetworkError();
        }
      });
    }
  },

  seeReservation: function(e){

    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    let that = this;

    if(isLogin && userInfo.bindingPhone==0){
      console.info('xxxxxxxxxxxxxx1')
      wx.showModal({
        title: '提示',
        content: '当前账户未绑定手机号,请您进行手机号绑定操作',
        showCancel:false,
        confirmText: '去绑定',
        confirmColor:'#00AADD',
        success: function (res1) {
            let url = `/pages/bindPhone/bindPhone`;
            wx.navigateTo({
              url
            });
        }
      });
      return;
    }

    if (!isLogin) {
      console.info('xxxxxxxxxxxxxx2')
      log.info('[首页]', '[未登陆跳转登录界面]');
      let url = `/pages/login/phone_login/phone_login`;
      wx.hideLoading();
      wx.navigateTo({
        url
      });
      return;
    }


    let idx = e.currentTarget.dataset.idx;
    console.info(idx)
    let {
      chargStationId,
      chargPileName,
      chargPileId,
      chargStationName,
      id
    } = idx;
    let userId = userInfo.userId;
    let url = `/pages/reservation/reservation?chargStationId=` + chargStationId + `&chargPileName=` + chargPileName + `&chargPileId=` + chargPileId + `&chargPileIdId=` + id + "&chargStationName=" + chargStationName + "&userId=" + userId;
    wx.navigateTo({
      url
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(e) {
    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    //console.log(userInfo);
    // 页面显示
    if (userInfo && isLogin) {
      //userInfo.flag = true;
      this.setData({
        userInfo: userInfo,
        isLogin: isLogin
      });
    } else {
      //未登录信息
      this.setData({
        userInfo: {}
      });
    }
  },
  chargingLog(e){
    
    let idx = e.currentTarget.dataset.idx;
    let chargPileId = idx.chargPileId;
    console.info(chargPileId);
    let url = '/pages/ucenter/charginglog/opsCharginglog?chargPileId=' + chargPileId
    wx.navigateTo({
      url
    });
    return;
  },
  callphone(){
    let that = this
    let phonenum =  that.data.offlineServicecall;
    wx.makePhoneCall({
        phoneNumber: that.data.offlineServicecall, //此号码并非真实电话号码,仅用于测试
        success:function(){
          console.log("拨打电话成功!" + phonenum)
        },
        fail:function(){
          console.log("拨打电话失败!" + phonenum)
        }
      })
  
  },
  toggleTabs(e){
    let idx = e.currentTarget.dataset.idx;
    this.setData({
        activeTab: idx
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
  
  },

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

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

  },

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

  },

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

  }
})