import * as echarts from '../../ec-canvas/echarts';
import * as liquidFill from '../../ec-canvas/echarts-liquidfill.min';
const util = require('../../utils/util.js')
const app = getApp()
const api = require('../../api/index.js');
Page({
  data: {
 // 状态栏高度
 statusBarHeight: wx.getStorageSync('statusBarHeight'),
 // 导航栏高度
 navBarHeight: wx.getStorageSync('navBarHeight'),
 // 导航栏和状态栏高度
 navStatusBarHeight: wx.getStorageSync('navStatusBarHeight'),
 // 胶囊
 menu:wx.getStorageSync('menu'),
 mode: '',
    ec_dispace_charts: {
      lazyLoad: true
    },
    ec:{
      lazyLoad: true
    },
    img_path:'',
    ectricdata:[],
    between:{},
    currentDate:'',
    fitnessdata:[],
    rotation:0,
    objectArray: [],
    stationindex:0,
    stationName:wx.getStorageSync('station').stationName,
    timer1:'',
    timer2:'',
    timer3:'',
    chartInstance1:'',
    chartInstance2:'',
    chartInstance3:''
  },
  onLoad: function () {
    let _this =this
    const updateManager = wx.getUpdateManager();
   // 获取手机系统信息
 
updateManager.onCheckForUpdate(function (res) {
  if (res.hasUpdate) {
    // 提示用户更新
    wx.showModal({
      title: '更新提示',
      content: '发现新版本，是否下载新版本并重启应用？',
      success: function (res) {
        if (res.confirm) {
          // 用户确认下载新版本
          downloadAndUpdate();
        } else if (res.cancel) {
          // 用户取消，可以选择后续操作
        }
      }
    });
  }
});

    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const date = now.getDate();

    const dateString = `${year}-${month}-${date}`;

    this.setData({
      currentDate: dateString // 假设在小程序页面中使用了data属性绑定了currentDate
    });
    // 获取组件
    this.ecComponent = this.selectComponent('#dispace_charts');
    this.ecline = this.selectComponent('#mychart_line');
    // this.initChart()
  //  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'
   })
     
  //  this.rotateImage()
 
  },
 downloadAndUpdate() {
    wx.downloadFile({
      url: 'https://example.com/path/to/new/version.zip', // 新版本小程序包的下载链接
      success: function (res) {
        if (res.statusCode === 200) {
          // 下载成功，保存临时文件路径
          const tempFilePath = res.tempFilePath;
          // 应用新版本
          applyUpdate(tempFilePath);
        } else {
          // 下载失败，处理异常
        }
      }
    });
  },
  applyUpdate(tempFilePath) {
    let _this = this
    wx.applyUpdate({
      filePath: tempFilePath,
      success: function () {
        // 新版本应用成功
        _this.getlist()  

      }
    });
  },
  // 图片旋转
  rotateImage() {
    const currentRotation = this.data.rotation + 180; // 每次增加180度
    const animation = wx.createAnimation({
      duration: 300, // 动画时长
      timingFunction: 'ease', // 动画效果
    });
    animation.rotate(currentRotation).step();
    this.setData({
      animationData: animation.export(),
      rotation: currentRotation
    });
  },
  // 电站列表
  bindPickerChange (e) {
    console.log('选中项改变，携带值为', e.detail.value);
    let _this = this
    const station = this.data.objectArray[e.detail.value];
    
    wx.setStorage({
      key: 'station', // 本地缓存中指定的 key
      data: station,
      success: function () {
        _this.setData({
          stationName:wx.getStorageSync('station').stationName
        })
        clearInterval(_this.timer1);
        clearInterval(_this.timer2);
        clearInterval(_this.timer3);
        _this.getlist()  
      }
    });
  },
  getlist(){
   //  电站信息
api.request(`/station/ectric/${wx.getStorageSync('station').id}`, 'POST')
  .then((res) => {
    this.setData({
      stationName:wx.getStorageSync('station').stationName,
      ectricdata:res.data
    })
    
    // console.log('请求成功：', res);
  // 先卸载旧图表

  this.beforeDestroy();

  // 重新初始化图表
  this.initCharts(res.data.quantity/100);
    // 在这里处理返回的数据
  })
  .catch((err) => {
    console.error('请求失败：', err);
    // 在这里处理请求失败的情况
  });
// 电量信息
api.request(`/stats/singleStation/${wx.getStorageSync('station').id}/between/time`, 'POST',{startDate:this.data.currentDate,endDate:this.data.currentDate})
  .then((res) => {
    if (res.data.length>0) {
      this.setData({
        between:res.data,
      })
    }else{
      this.setData({
        between:{
          list:[{chargetime: 0,
            dischargetime: 0,
            ym: "2024-07-08"},
          ],
          total:{accumulatedchargetime: "0",
          accumulateddischargetime: "0"} ,
          zonghe:{
            accumulatedchargetime: "0",
accumulateddischargetime: "0"
          }
        },
      }) 
    }
    this.beforeDestroys();
    this.initChartright()
  })
  .catch((err) => {
    console.error('请求失败：', err);
    // 在这里处理请求失败的情况
  });
  //设备监测
  this.getfitness()
    this.timer1=setInterval(() => {
      this.getfitness()
          }, 10000)
  },
  // 获取首页数据
  getfitness(){
    api.request(`/station/fitness/${wx.getStorageSync('station').id}`, 'POST')
    .then((res) => {
      this.setData({
        fitnessdata:res.data,
      })
      // console.log('请求成功：', res);
     
      // 在这里处理返回的数据
    })
    .catch((err) => {
      console.error('请求失败：', err);
      // 在这里处理请求失败的情况
    });
  },
  // 卸载图表，清理资源
unloadCharts: function () {
  if (this.charts) {
    this.charts.dispose(); // 销毁图表实例
    this.charts = null; // 置空图表实例
  }
},

  // 电容量
  initChartright: function () {
    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);
      
      // 初始数据
      let initialData = {
        accumulatedchargetime: _this.data.between.total.accumulatedchargetime,
        accumulateddischargetime: _this.data.between.total.accumulateddischargetime
      };
      
      // 设置初始选项
      let option = _this.getChartOption(initialData);
      chart.setOption(option);
    _this.chartInstance2 = chart;
  

    _this.startDataUpdates();
     
      return chart;
    });
  },
    // 定义更新数据函数
    updateChartData(newData) {
      let updatedOption = this.getChartOption(newData);
      this.chartInstance2.setOption(updatedOption);
    },
// 更新图表数据函数
startDataUpdates() {
  this.timer2 = setInterval(() => {
    api.request(`/stats/singleStation/${wx.getStorageSync('station').id}/between/time`, 'POST',{startDate:this.data.currentDate,endDate:this.data.currentDate})
    .then((res) => {
      if (res.data.length>0) {
        this.setData({
          between:res.data,
        })
      }else{
        this.setData({
          between:{
            list:[{chargetime: 0,
              dischargetime: 0,
              ym: "2024-07-08"},
            ],
            total:{accumulatedchargetime: "0",
            accumulateddischargetime: "0"} ,
            zonghe:{
              accumulatedchargetime: "0",
  accumulateddischargetime: "0"
            }
          },
        }) 
      }
      let initialData = {
        accumulatedchargetime: this.data.between.total.accumulatedchargetime,
        accumulateddischargetime: this.data.between.total.accumulateddischargetime
      };
      this.updateChartData(initialData)
    })
    .catch((err) => {
      console.error('请求失败：', err);
      // 在这里处理请求失败的情况
    });
  }, 10000);
},
  // 辅助函数，用于生成图表选项
  getChartOption: function (data) {
    let _this = this;
    return {
      backgroundColor: "#ffffff",
      legend: [{
        left: '0',
        bottom: 20,
        itemHeight: 8,
        itemWidth: 8,
        icon: "circle",
        formatter: function (name) {
          return name + `   ${data.accumulatedchargetime} kWh`;
        },
        data: [{ name: '今日充电' }]
      }, {
        left: '0',
        bottom: 0,
        itemHeight: 8,
        itemWidth: 8,
        icon: "circle",
        formatter: function (name) {
          return name + `   ${data.accumulateddischargetime} kWh`;
        },
        data: [{ name: '今日放电' }]
      }],
      tooltip: {
        trigger: 'item'
      },
      series: [{
        type: 'pie',
        radius: ['40%', '60%'],
        center: ['50%', '40%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 0,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [{
          value: data.accumulatedchargetime,
          name: '今日充电',
          itemStyle: { color: '#4DF096' }
        }, {
          value: data.accumulateddischargetime,
          name: '今日放电',
          itemStyle: { color: '#3C9EFA' }
        }]
      }]
    };
  },
  
 
// 设备详情
onIconTap(){
 wx.navigateTo({
   url: '/pages/details/index',
 })
},
// 设备健康
onhealthy(){
  wx.navigateTo({
    url: '/pages/healthy/index',
  })
 },
// 设备信息
ondetails(){
  wx.navigateTo({
    url: '/pages/monitor/index',
  })
},
 // 水波图

 initCharts(value) {
  let _this = this;
  this.ecComponent.init((canvas, width, height, dpr) => {
    const charts = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr
    });

    // 将初始的数值转换为数据
    let data = [value, value, value];

    // 初始化图表选项
    let option = _this.getChartOption1(value, data);
    charts.setOption(option);

    // 存储图表实例
    _this.chartInstance3 = charts;

    // 启动定时器更新数据
    _this.startDataUpdate();

    // 返回图表实例
    return charts;
  });
},

// 更新图表数据函数
updateChartData1(value, data) {
  let updatedOption = this.getChartOption1(value, data);
  this.chartInstance3.setOption(updatedOption);
},

// 启动定时器更新数据
startDataUpdate() {
  let _this =this
  _this.timer3 = setInterval(() => {
    // 获取新数据
    api.request(`/station/ectric/${wx.getStorageSync('station').id}`, 'POST')
      .then((res) => {
        // 更新数据
        let data = [res.data.quantity / 100, res.data.quantity / 100, res.data.quantity / 100];
        _this.updateChartData1(res.data.quantity / 100, data);

        // console.log('请求成功：', res);
      })
      .catch((err) => {
        console.error('请求失败：', err);
        // 处理请求失败情况
      });
  }, 10000);
},

// Vue.js 生命周期钩子
beforeDestroy() {

// 清除定时器
if (this.timer3) {
  clearInterval(this.timer3);
}
// 销毁图表实例
if (this.chartInstance3) {
  this.chartInstance3.dispose(); // 销毁图表
  this.chartInstance3 = null;
}
},
beforeDestroys() {

  // 清除定时器
  if (this.timer2) {
    clearInterval(this.timer2);
  }
  // 销毁图表实例
  if (this.chartInstance2) {
    this.chartInstance2.dispose(); // 销毁图表
    this.chartInstance2 = null;
  }
  },
// 辅助函数，用于生成图表选项
getChartOption1: function (value, data) {
  let color = (value * 100).toFixed(0) < 70 ? '#004403' : '#fff';

  return {
    title: {
      text: (value * 100).toFixed(0) + '%',
      textStyle: {
        fontFamily: 'Microsoft Yahei',
        fontWeight: 'normal',
        color: color,
        rich: {
          a: {
            fontSize: 18,
          }
        }
      },
      x: 'center',
      y: '40%'
    },
    series: [
      {
      type: 'liquidFill',
      radius: '80%',
      center: ['50%', '50%'],
      //  shape: 'roundRect',
      data: data,
      color: {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [{
          offset: 1,
          color: 'rgba(0, 117, 68,1)'
        },  {
          offset: 0,
          color: 'rgba(0, 117, 68,0)'
        }],
        globalCoord: false
      },
        // 边框
        outline: {
          borderDistance: 1,
          itemStyle: {
            borderWidth: 2,
            borderColor:'rgba(0, 117, 68, .1)',
           
          }
        },
        backgroundStyle: {
          borderWidth: 1,
          color: '#fff',
        },
      label: {
        normal: {
          formatter: '',
        }
      }
    }]
  };
},
 /**
   * 生命周期函数--监听页面卸载
   */
  onShow(){
    let _this =this
   // 电站列表stationindex
   api.request('/station/list/stationName', 'POST')
   .then((res) => {
     _this.setData({
       objectArray:res.data
     })
     if (wx.getStorageSync('station').id) {
       for (let index = 0; index < _this.data.objectArray.length; index++) {
          if (_this.data.objectArray[index].id==wx.getStorageSync('station').id) {
             _this.setData({
              stationindex:index
             })
          }
         
       }
       _this.getlist()
   
     }else{
      wx.setStorage({
        key: 'station', // 本地缓存中指定的 key
        data: res.data[0],
        success: function () {
               _this.getlist()
       
        }
      });
     }
  
   })
   .catch((err) => {
     console.error('请求失败：', err);
     // 在这里处理请求失败的情况
   });

  },
  onHide() {
    clearInterval(this.timer1);
    // clearInterval(_this.timer3);
    this.beforeDestroy()
    this.beforeDestroys()
  },
});