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:'',
uuid:'',
chargeTotaldatas:[],
ymdlistdatas:[],
filed:'month',
format:'YYYY-MM'
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  console.log(options);
   this.setData({
    uuid:options.uuid
   })
    // 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('7')).getTime(),new Date(util.getdataTime('当日')).getTime()],
     valueitem:util.getdataTime('7'),
    })
    console.log(util.getdataTime('365'));
    // this.ecComponent = this.selectComponent('#mychart_line1');
    this.ecline = this.selectComponent('#mychart_line2');
    this.getlineMonth()
  },
 
  // 返回上一级
  onIconTap(){
    wx.navigateBack({
      delta: 1
    });
  },
  
  onlabel(e){
    this.setData({
      labelindex:e.target.dataset.index
    })
         if (this.data.labelindex==1) {
      this.setData({
        echartstype:'bar',
        valueitem:util.getdataTime('7'),
        value:util.getdataTime('7'),
        format:'YYYY-MM',
        filed:'month',

      })
      if (this.data.tapindex==0) {
      this.getlineMonth();
      }else{
        this.Powertrend();
      }

     }else if(this.data.labelindex==2){
     
      this.setData({
        echartstype:'bar',
        valueitem:util.getdataTime('365'),
        value:util.getdataTime('365'),
        filed:'year',

        format:'YYYY'

      })
      if (this.data.tapindex==0) {
        this.getlineMonth();
          
        }else{
          this.Powertrend();
        }
     } else if(this.data.labelindex==3){
     
      this.setData({
        echartstype:'bar',
        filed:''

      })
      if (this.data.tapindex==0) {
        this.getlineMonth();
          
        }else{
          this.Powertrend();
        }
     } 
  
  
  },
 
  handleCalendar() {
    this.setData({
      visible: true,
      rangetype:'range' 
    })
  
  },
  // 选择时间
  bindclose(){
    this.setData({
      visible: false
    })
  },
  handleConfirm(e) {
    console.log(e.detail.value);
    this.setData({
      valueitem:e.detail.value,
    })
    if (this.data.tapindex==0) {
      this.getlineMonth();
      }else{
        this.Powertrend();
      }
  },
    // 电量
  getlineMonth(){
    let filed = ''
    if (this.data.labelindex==1) {
      filed = 'day'
    }else if(this.data.labelindex==2){
      filed ='Month'
    }else{
      filed ='year'
      this.setData({
        valueitem:''
      })
    }
    let data={
      page:1,
      rows:10000,
      starttime:this.data.valueitem,
    
      filed:filed,
      filter:'5c465aaa-b65e-463f-a9ae-a338a630a4c1_delta,469dc1cc-e5ad-492f-a350-f7bc473d55ee_delta',
      uuid:wx.getStorageSync('station').id
    }
 
    api.request(`/api/va/hisdata/hour/datas`, 'get',data )
    .then((res) => {
        let list = res.data.list;
        let chargeTotal ='';
        let dischargeTotal ='';
        chargeTotal = list.map(item => parseFloat(item["5c465aaa-b65e-463f-a9ae-a338a630a4c1_delta"]/1000).toFixed(2));
        dischargeTotal = list.map(item => parseFloat(item["469dc1cc-e5ad-492f-a350-f7bc473d55ee_delta"]/1000).toFixed(2));
        let ymdlist = ''
        if(this.data.labelindex==1){
          ymdlist = list.map(item => item.recordtime.slice(-2));
        }else{
          ymdlist = list.map(item => item.recordtime);
      
        }
        this.setData({
          // Electricitylevel: res.data,
          chargeTotal: chargeTotal,
          dischargeTotal: dischargeTotal,
          ymdlist: ymdlist,
        });
    
      this.initChart_right()
    })
    .catch((err) => {
      console.error('请求失败：', err);
      // 在这里处理请求失败的情况
    });
  },
  
  Powertrend(){
    let filed = ''
    if (this.data.labelindex==1) {
      filed = 'day'
    }else if(this.data.labelindex==2){
      filed ='Month'
    }else{
      filed ='year'
      this.setData({
        valueitem:''
      })
    }
    let data={
      page:1,
      rows:10000,
      starttime:this.data.valueitem,
      filed:filed,
      filter:'a0acf8cf-7d12-49af-97d9-1a2e630c4bfe_delta',
      uuid:wx.getStorageSync('station').id
    }
   
 api.request(`/api/va/hisdata/hour/datas`, 'get',data)
 .then((res) => {
   let list = res.data.list;
   console.log(list);
  let chargeTotal = ''
  chargeTotal = list.map(item => 
    parseFloat(item["a0acf8cf-7d12-49af-97d9-1a2e630c4bfe_delta"]/1000).toFixed(2)
    );
  // let dischargeTotal = list.storedPower.map(item => item.totalActivePower);
  let ymdlist = ''
  if(this.data.labelindex==1){
    ymdlist = list.map(item => item.recordtime.slice(-2));
  }else{
    ymdlist = list.map(item => item.recordtime);

  }
  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,
      // labelindex:1,
      // filed:'month',
      // format:'YYYY-MM',
      // valueitem:util.getdataTime('7'),
        // value:util.getdataTime('7'),
    })
    if (this.data.tapindex==0) {
      this.getlineMonth();
      }else{
        this.Powertrend();
      }
   
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },
   
  initChart_right: function () {
    var unitName = ''; 
    
    if (this.data.tapindex==0) {

      if (this.data.labelindex==1) {
        unitName = '电量（MWh/日）'
      } else if(this.data.labelindex==2) {
        unitName = '电量（MWh/月）'
      }else{
        unitName = '电量（MWh/年）'

      }
      
    }else if(this.data.tapindex==1){
      if (this.data.labelindex==1) {
      unitName = '收益（千元/日）';
      }else if(this.data.labelindex==2){
      unitName = '收益（千元/月）';
      }else{
      unitName = '收益（千元/年）';

      }

    } 
    let _this = this;
    this.ecline.init((canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr
        });
        canvas.setChart(chart);
        var option = {
          title: {
            subtext: unitName,
            textStyle: {
              color: 'rgba(0, 0, 0, 0)',
          }
          },
            grid: {
                left: '1%',
                top: '14%',
                right: '1%',
                bottom: '20%',
                containLabel: true
            },
         
            xAxis: {
                type: 'category',
                data: _this.data.ymdlist,
                axisTick: {
                    show: false
                },
                barWidth: 20,
                axisLabel: {
                  interval: 0 // 设置为0以显示所有坐标点  

              },
            
                
            },
            yAxis: {
                // name: unitName,                   
                x: 'center',                  
                type: 'value',
                axisTick: {
                    show: false
                },
                splitLine: {
                    show: false
                }
            },
            dataZoom: {
                type: 'inside',
                start: 0,
                end: 50
              },
              // dataZoom: { 
              //   type: 'slider',
              //   start: 0,
              //   end: 50,
              //   handleSize:0,
              //   show:false

              // },
            series: [{
                type:"bar",
                barMaxWidth: 20,
                smooth: true,
                label: {
                  show: true,
                  position: 'top',
                  color:'#222'
                },
                showSymbol: false, 
                data: _this.data.chargeTotal,
                itemStyle: {
                    color: 'rgba(60, 158, 250, 1)',
                     barBorderRadius: [4, 4, 0, 0] // 设置柱状图的圆角半径为5
                },
                areaStyle: {
                    color: 'rgba(60, 158, 250, 1)',
                }
            }
            // ,{
            //     name: viewname[1],
            //     type: _this.data.echartstype,
            //     smooth: true,
            //     showSymbol: false, 
            //     barMaxWidth: 20,
            //     data: _this.data.dischargeTotal,
            //     itemStyle: {
            //         color: 'rgba(77, 240, 150, 1)',
            //          barBorderRadius: [5, 5, 0, 0]
            //     },
            //     areaStyle: {
            //         color: 'rgba(77, 240, 150, 1)',
            //     }
            // }
          ]
        };

        chart.setOption(option);
        return chart;
    })
},
 
})
