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


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

Page({

  /**
   * 页面的初始数据
   */
  data: {
    brandName:'',
    name:'',
    address:'', 
    offlineServicecall:'',
    stationTagList:[],
    chargprice: '', 
    serviceprice: '', 
    chargid: '',
    sumprice: '',
    fastFree:0,
    slowFree:0,
    fastSum:0,
    slowSum:0,
    pagesize:10,
    pagenum:1,
    ele_pagenum:1,
    total:-1,
    ele_total:-1,
    loadTotal: 0,
    dataLoading: false,
    ele_dataLoading: false,
    finishedLoadTap: 0,
    ele_finishedLoadTap: 0,
    finishedLoadShowTimes: 0,
    ele_finishedLoadShowTimes: 0,
    chargList: [],
    ele_chargList: [],
    seeInfoChargPile:{},
    userInfo:{},
    chargfeatureList:[],
    isLogin: false,
    resultTable: [],
    // 是否减免停车费
    carParkingRate: false,
    // 停车时间
    parkTime: 0,
    activeTab: '0',
    scrollTop:0,
    occupyFee:{},
    showOccupyFee:false
  },
  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 =  (seeInfoChargPile.chargprice==null || seeInfoChargPile.serviceprice==null || seeInfoChargPile.chargprice=='暂无费用' || seeInfoChargPile.serviceprice=='暂无费用')? null:parseFloat((seeInfoChargPile.chargprice + seeInfoChargPile.serviceprice)).toFixed(8);

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



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

    name =  name=='null'?null:name;
    brandName = (brandName == 'null' || brandName == 'undefined') ? null : brandName;
    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({
      brandName,
      name,
      address,
    //   stationTagList,
      chargprice,
      serviceprice,
      chargid,
      sumprice
    });
    this.fastAndSlow()
    this.ori_getPage();
    this.ele_getPage();
    this.getOccupyFee();
  },
  fastAndSlow(e){
    let that = this;
    wx.request({
      url: getApp().globalData.postHeadAgreement +'/restapi/wechat/fastAndSlow',
      data: {
        id: that.data.chargid,
        ivType: 3,//统计桩和电池
      },
      method: 'POST',
      success(res) {
        that.setData({
          fastFree : res.data.fastFree,
          slowFree : res.data.slowFree,
          fastSum : res.data.fastSum,
          slowSum : res.data.slowSum
        });
      }
    });
  },
  previewImage(e){
    var that = this,
    //获取当前图片的下表
      index = e.currentTarget.dataset.index,
      //数据源
      pictures = this.data.chargfeatureList;
    wx.previewImage({
    //当前显示下表
     current: pictures[index],
     //数据源
     urls: pictures
    })
  },
  getPage(){
    let that = this;
    if(that.__data__.activeTab=='0'){
        that.ori_getPage();
    }else{
        that.ele_getPage();
    }
  },
  getOccupyFee(){
    // test对象对接后端服务传递过来的数据
    var test = {
      cost_cycle:2,
      max_fee_time:120,
      cost_time_period:'00:00-08:00,12:00-14:00,18:00-21:00,22:00-23:00,22:00-23:00',
      free_time:10
    }
    if (Object.keys(test).length > 0) { // 判断对象数据是否为空
      this.setData({
        occupyFee:test,
        showOccupyFee:true
      })
    }  
    console.log("occupyFee",Object.keys(this.data.occupyFee).length > 0);
  },

  ori_getPage(){
    // ivType
    // 是否为无人车充电站（0否；1是）
    // 0:桩
    // 1:电池
    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++,
          ivType: 0,
          pagesize: 10,
        },
        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.total,
            dataLoading: false,
            fastFree : res.data.fastFree,
            slowFree : res.data.slowFree,
            fastSum : res.data.fastSum,
            slowSum : res.data.slowSum
          });
          console.log("that.data：",that.data);
        }
      });
  },

  ele_getPage(){
    // ivType
    // 是否为无人车充电站（0否；1是）
    // 0:桩
    // 1:电池
    if(this.data.ele_chargList.length == this.data.ele_total){
      this.setData({
        ele_finishedLoadTap:this.data.ele_finishedLoadTap+1
      })
      if(this.data.ele_finishedLoadTap>0 && this.data.ele_finishedLoadShowTimes==0){
        this.setData({
          ele_finishedLoadShowTimes:this.data.ele_finishedLoadShowTimes+1
        })
        wx.showToast({
          title: '全部加载完毕',
          icon: 'success',
          duration: 2000
        })
      }
      return
    }

    if(this.data.ele_dataLoading){
      return
    }
    this.setData({
      ele_dataLoading: true
    })
    wx.showLoading({
      title: '数据加载中....',
    })
    let that = this;
    // that.setData({
    //   pagenum:1
    // });
    // 充电桩
    wx.request({
      url: getApp().globalData.postHeadAgreement +'/restapi/wechat/chargInfo',
      data: {
        id: that.data.chargid,
        pagenum: this.data.ele_pagenum++,
        ivType: 1,
        pagesize: 10,
      },
      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({
          ele_chargList: that.data.ele_chargList.concat(chargList),
          ele_total: res.data.chargList.total,
          ele_dataLoading: false,
          ele_fastFree : res.data.fastFree,
          ele_slowFree : res.data.slowFree,
          ele_fastSum : res.data.fastSum,
          ele_slowSum : res.data.slowSum
        });
        console.log("that.setData:",that.data);
      }
    });

  },
  refreshPage: function(e) {
    wx.showLoading({
      title: '数据加载中....',
    })
    let that = this;
    that.setData({
      pagenum:1,
    });
  // 清空数据 重新进行刷新
    this.data.ele_chargList = []
    this.data.ele_total = -1
    this.data.chargList=[]
    this.data.total = -1
    this.ori_getPage();
    this.ele_getPage();
    that.fastAndSlow()
    that.setData({
      scrollTop: 0
    });
    wx.hideLoading()
  },

  goEleCarMap(e){
    console.info("呼叫充电车");
    let that = this;
    wx.setStorageSync('eleCarMapPage', {
    chargid: that.data.chargid
    })
    let url = '/pages/charginfo/eleCarMap';
    wx.navigateTo({
        url
    });
  },
  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 brandName = that.data.brandName
    let userId = userInfo.userId;
    let url = `/pages/reservation/reservation?chargStationId=` + chargStationId + `&chargPileName=` + chargPileName + `&chargPileId=` + chargPileId + `&chargPileIdId=` + id + "&chargStationName=" + chargStationName + "&userId=" + userId+ "&brandName=" + brandName;
    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();
    console.log("触发滚动");
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

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

  },

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

  }
})