import * as echarts from '../../ec-canvas/echarts';
import * as liquidFill from '../../ec-canvas/echarts-liquidfill.min';
const util = require('../../utils/util.js')
const api = require('../../api/index.js');
const moment = require('moment');
Page({

  /**
   * 页面的初始数据
   */
  data: {
 // 状态栏高度
 statusBarHeight: wx.getStorageSync('statusBarHeight'),
 // 导航栏高度
 navBarHeight: wx.getStorageSync('navBarHeight'),
 // 导航栏和状态栏高度
 navStatusBarHeight: wx.getStorageSync('navStatusBarHeight'),
 // 胶囊
 menu:wx.getStorageSync('menu'),
 mode: '',
 datetimeVisible: false,
 datetime: new Date('2021-12-23').getTime(),
 datetimeText: '',
 img_path:'',
tapindex:0,
labelindex:1,
visible: false,
ec: {
  lazyLoad: true
},
ech: {
  lazyLoad: true
},
value:[],
valueitem:'',
minDate: new Date(2022, 1, 1).getTime(),
maxDate: new Date(util.getdataTime('当日')).getTime(),
format(day) {
  const { date } = day;
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const curDate = date.getDate();
if (year== moment().format('YYYY')) {
  if(month== moment().format('MM')){
    if(curDate== moment().format('DD')){
      day.suffix = '今日';
    }
  }
}
  return day;
},
Electricitylevel:[],
chargeTotal:[],
dischargeTotal:[],
ymdlist:[],
echartstype:'bar',
unm:0,
current:0,
rangetype:''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
 
    // let base64imgages =util.Background_base64('https://esos-iot.bjdexn.cn/wx_images/bj.png')
    this.setData({
     img_path:'https://esos-iot.bjdexn.cn/wx_images/bj.png',
     value:[new Date(util.getdataTime('当日')).getTime(),new Date(util.getdataTime('当日')).getTime()],
   valueitem:`${util.getdataTime('当日')} - ${util.getdataTime('当日')}`,

    })
    this.ecComponent = this.selectComponent('#mychart_line1');
    this.ecline = this.selectComponent('#mychart_line2');
    this.getlineMonth()
  },
 
  // 返回上一级
  onIconTap(){
    wx.navigateBack({
      delta: 1
    });
  },
  // 切换标签
  ontop(e){
    // console.log(e);
    this.setData({
      tapindex:e.detail.current
    })
    console.log(this.data.tapindex);

    if (this.data.tapindex==0) {
      this.ecComponent = this.selectComponent('#mychart_line1');
      this.ecline = this.selectComponent('#mychart_line2');
      this.setData({
        labelindex:1,
        value:[new Date(util.getdataTime('当日')).getTime(),new Date(util.getdataTime('当日')).getTime()],
                valueitem:`${util.getdataTime('当日')} - ${util.getdataTime('当日')}`,
        echartstype:'bar'
      })
  this.getlineMonth();
    }else if(this.data.tapindex==1){
      this.ecline = this.selectComponent('#mychart_line2');
      this.setData({
        valueitem:util.getdataTime('当日'),
        value:new Date(util.getdataTime('当日')).getTime(),
        echartstype:'line'
      })
      this.Powertrend();
    }else if(this.data.tapindex==2){
      this.ecline = this.selectComponent('#mychart_line2');
      this.setData({
        labelindex:1,
        value:[new Date(util.getdataTime('当日')).getTime(),new Date(util.getdataTime('当日')).getTime()],
                valueitem:`${util.getdataTime('当日')} - ${util.getdataTime('当日')}`,
        echartstype:'bar'
      })
      this.electrictime()
    }

  },
  onlabel(e){
    this.setData({
      labelindex:e.target.dataset.index
    })
    if (this.data.tapindex==0) {
         if (this.data.labelindex==1) {
      this.setData({
        echartstype:'bar',
        value:[new Date(util.getdataTime('当日')).getTime(),new Date(util.getdataTime('当日')).getTime()],
        valueitem:`${util.getdataTime('当日')} - ${util.getdataTime('当日')}`,

      })
     }else if(this.data.labelindex==2){
     
      this.setData({
        echartstype:'line',
        value:[new Date(util.getdataTime(31)).getTime(),new Date(util.getdataTime('当日')).getTime()],
        valueitem:`${util.getdataTime(31)} - ${util.getdataTime('当日')}`,
      })
     }else{
    
      this.setData({
        echartstype:'line',
        value:[new Date(util.getdataTime(365)).getTime(),new Date(util.getdataTime('当日')).getTime()],
        valueitem:`${util.getdataTime(365)} - ${util.getdataTime('当日')}`,

      })
     }
    this.getlineMonth();
    }else if(this.data.tapindex==1){
      this.ecline = this.selectComponent('#mychart_line2');
      this.setData({
        valueitem:util.getdataTime('当日'),
        echartstype:'line'
      })
      this.Powertrend();
    }else if(this.data.tapindex==2){
      if (this.data.labelindex==1) {
        this.setData({
          echartstype:'bar',
          value:[new Date(util.getdataTime('当日')).getTime(),new Date(util.getdataTime('当日')).getTime()],
        valueitem:`${util.getdataTime('当日')} - ${util.getdataTime('当日')}`,
        })
       }else if(this.data.labelindex==2){
       
        this.setData({
          echartstype:'line',
          value:[new Date(util.getdataTime(31)).getTime(),new Date(util.getdataTime('当日')).getTime()],
        valueitem:`${util.getdataTime(31)} - ${util.getdataTime('当日')}`,
        })
       }else{
     
        this.setData({
          echartstype:'line',
          value:[new Date(util.getdataTime(365)).getTime(),new Date(util.getdataTime('当日')).getTime()],
        valueitem:`${util.getdataTime(365)} - ${util.getdataTime('当日')}`,
        })
       }
      this.electrictime();

    }
  
  },
  // 上一天
  Lastday(){
    this.data.unm++
    this.setData({
      unm:this.data.unm
    })
    this.ecline = this.selectComponent('#mychart_line2');
    this.setData({
      valueitem:util.CumulativeTime(this.data.unm),
      echartstype:'line'
    })
    this.Powertrend();
  },
  handleCalendar() {
    if (this.data.tapindex==1) {
      this.setData({
        visible: true,
        rangetype:'single'
      })
    }else{
      this.setData({
        visible: true,
        rangetype:'range'
      })
    }
  
  },
  // 下一天
  dayfollowing(){
    if (this.data.unm==0) {
      return wx.showToast({
        title: '不可超出当前时间',
        icon: 'none',
      });
    }
    this.data.unm--
    this.setData({
      unm:this.data.unm
    })
    this.ecline = this.selectComponent('#mychart_line2');
    this.setData({
      valueitem:util.CumulativeTime(this.data.unm),
      echartstype:'line'
    })
    this.Powertrend();
  },
  // 时间区间范围
  bindclose(){
    this.setData({
      visible: false
    })
  },
  handleConfirm(e) {
    console.log(e);
    let formattedTime =[]
    if (this.data.tapindex==1) {
        formattedTime.push(moment(e.detail.value).format('YYYY-MM-DD'));
       this.setData({
        visible: false,
       valueitem:`${formattedTime[0]}`,
       value:e.detail.value
      });  
      this.Powertrend();
    }else{
      if (e.detail.value.length==0) {
        e.detail.value.forEach(ts => {
          formattedTime.push(moment(ts).format('YYYY-MM-DD'));
         });
         this.setData({
          visible: false,
         valueitem:`${formattedTime[0]} - ${util.getdataTime('当日')}`,
         value:e.detail.value
        }); 
       }else{
        e.detail.value.forEach(ts => {
          formattedTime.push(moment(ts).format('YYYY-MM-DD'));
         });
        this.setData({
          visible: false,
         valueitem:`${formattedTime[0]} - ${formattedTime[1]}`,
         value:e.detail.value
        }); 
       }
       if (this.data.tapindex==1) {
        this.getlineMonth()
       }else{
        this.electrictime()

       }
    }
  },
    // 电量
  getlineMonth(){
    let data={
      startDate:moment(this.data.value[0]).format('YYYY-MM-DD'),
      endDate:moment(this.data.value[1]).format('YYYY-MM-DD')
    }
    api.request(`/stats/singleStation/${wx.getStorageSync('station').id}/betweenhe`, 'POST',data )
    .then((res) => {
     
        let { list } = res.data;
        let chargeTotal = list.map(item => item.chargeTotal);
        let dischargeTotal = list.map(item => item.dischargeTotal);
        let ymdlist = list.map(item => item.ymd.slice(5, 11));
        this.setData({
          Electricitylevel: res.data,
          chargeTotal: chargeTotal,
          dischargeTotal: dischargeTotal,
          ymdlist: ymdlist,
        });
      this.initChartright()
      this.initChart_right()
    })
    .catch((err) => {
      console.error('请求失败：', err);
      // 在这里处理请求失败的情况
    });
  },
  Powertrend(){
  // 充放电功率
 api.request(`/station/${wx.getStorageSync('station').id}/system/power/trend`, 'POST',{data:this.data.valueitem} )
 .then((res) => {
   let list = res.data;
   console.log(list);
  let chargeTotal = list.gridPower.map(item => item.totalActivePower);
  let dischargeTotal = list.storedPower.map(item => item.totalActivePower);
  let ymdlist = list.gridPower.map(item => item.ts.slice(12, 16));
  this.setData({
    Electricitylevel: res.data,
    chargeTotal: chargeTotal,
    dischargeTotal: dischargeTotal,
    ymdlist: ymdlist,
  });
 
  this.initChart_right()
 })
 .catch((err) => {
   console.error('请求失败：', err);
   // 在这里处理请求失败的情况
 
   
 });
  },
  // 充放电时间
  electrictime(){
    let data={
      startDate:moment(this.data.value[0]).format('YYYY-MM-DD'),
      endDate:moment(this.data.value[1]).format('YYYY-MM-DD')
    }
    
  // 充放电时间
 api.request(`/stats/singleStation/${wx.getStorageSync('station').id}/between/time`, 'POST',data )
 .then((res) => {
   let { list } = res.data;
   console.log(list);
  let chargeTotal = list.map(item => item.chargetime);
  let dischargeTotal = list.map(item => item.dischargetime);
  let ymdlist = list.map(item => item.ym.slice(5, 11));
  this.setData({
    Electricitylevel: res.data,
    chargeTotal: chargeTotal,
    dischargeTotal: dischargeTotal,
    ymdlist: ymdlist,
  });
  this.initChart_right()
 })
 .catch((err) => {
   console.error('请求失败：', err);
   // 在这里处理请求失败的情况
 
   
 });
  },
  onTabsChange(event) {
    this.setData({
      tapindex:event.detail.value
    })
  },


  onStickyScroll(event) {
    console.log(event.detail);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },
  initChartright: function(){
    let _this = this
    this.ecComponent.init((canvas, width, height, dpr)=> {
      
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      canvas.setChart(chart);
  
    var option = {
      legend:[ {
        right: '0',  // 图例水平居中
        bottom: '35%',
        itemHeight:8,
        itemWidth:8,
        icon:"circle",
        formatter: function (name) {
          return name + _this.data.Electricitylevel.total.sumdischargeTotal+' kwh';  // 在名称和单位之间添加空格间距
      },
        data:[
          {name: '累计充电'},
        ]
      },{
        right: '0',  // 图例水平居中
        bottom: '50%',
        itemHeight:8,
        itemWidth:8,
        icon:"circle",
        formatter: function (name) {
          return name + _this.data.Electricitylevel.total.sumchargeTotal + ' kwh';  // 在名称和单位之间添加空格间距
      },
        data:[
          {name: '累计放电'},
        ]
      }],
      tooltip: {
        trigger: 'item'
      },
      series: [{
        type: 'pie',
        radius: ['40%', '60%'],
        center: ['20%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 0,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [{
          value: _this.data.Electricitylevel.total.sumchargeTotal,
          name: '累计充电',
          itemStyle: { color: '#4DF096' }
        }, {
          value: _this.data.Electricitylevel.total.sumdischargeTotal,
          name: '累计放电',
          itemStyle: { color: '#3C9EFA' }
        }  
      ]
      }]
    };
  
    chart.setOption(option);
    return chart;
  })},
  initChart_right: function () {
    var unitName = 'kWh'; 
    var viewname = ['充电量','放电量']; 
    if (this.data.tapindex==0) {
      unitName = 'kWh';
      viewname = ['充电量','放电量'];
    }else if(this.data.tapindex==1){
      unitName = 'kW';
      viewname = ['峰值充电功率','峰值放电功率'];

    }else if(this.data.tapindex==2){
      unitName = 'h';
      viewname = ['充电时长','放电时长'];

    }
    let _this = this
    this.ecline.init((canvas, width, height, dpr)=> {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
    canvas.setChart(chart);
    var option = {
      legend: { bottom: '0%'},
      grid: {
        left:'1%',
        top:'20%',
        right:'1%',
        bottom:'20%',
        containLabel: true
      },
      tooltip: {
        show: true,
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data:_this.data.ymdlist,
        // show: false,
        axisTick: {
          show: false // 这里设置x轴的刻度线不显示
      },
      
        barWidth: 10 // 设置柱状图的宽度
      },
      yAxis: {
        name:'单位：'+unitName,                   
        x: 'center',                  
        type: 'value',
        axisTick: {
          show: false // 这里设置x轴的刻度线不显示
      },
       
        splitLine: {
          show: false // 这里设置x轴的刻度线不显示
        },
      
        // show: false
      },
      series: [{
        name: viewname[0],
        type: _this.data.echartstype,
        barMaxWidth: 20,// 设置柱状图的宽度
        smooth: true,
        showSymbol: false, 
        data:_this.data.chargeTotal,
        itemStyle: {
          color: 'rgba(60, 158, 250, 0.5)' // 设置数据点颜色为蓝色（使用十六进制表示法）
      },
        areaStyle: {
          color: 'rgba(60, 158, 250, 0.3)'   // 设置区域填充颜色
      }
      },{
        name: viewname[1],
        type: _this.data.echartstype,
        smooth: true,
        showSymbol: false, 
        barMaxWidth: 20,// 设置柱状图的宽度
        data: _this.data.dischargeTotal,
        itemStyle: {
          color: 'rgba(77, 240, 150, 0.5)'  // 设置数据点颜色为绿色（使用十六进制表示法）
      },
      areaStyle: {
          color: 'rgba(77, 240, 150, 0.3)'  // 设置区域填充颜色为半透明的绿色
      }
      } ]
    };
  
    chart.setOption(option);
    return chart;
  })}
})
