import * as echarts from '../../component/ec-canvas/echarts';
let util = require('../../../../utils/util')
const apiArr = require('../../../../api/water_filter')
const app = getApp({allowDefault:true})
const __staticUrl = require('../../../../config/env.js').static_url
Page({

  /**
   * 页面的初始数据
   */
  data: {
    s: app.system.statusBarHeight, // 状态栏高度
    n: (app.menu.top - app.system.statusBarHeight) * 2 + app.menu.height, // 导航栏高度
    t: app.menu.top, // 胶囊局顶部距离
    h: app.menu.height, // 胶囊高度
    // 功能列表
    functional_List: [{
        "image": (__staticUrl + '/water_filter/Group_407.png'),
        "name": "一键报修",
        // "url": "packages/WaterPurifier/pages/repair/repair",
        "url": `../../../WaterPurifier/pages/repair/repair`,
        "type": "h5"
      },
      {
        "image": (__staticUrl + '/water_filter/Group_408.png'),
        "name": "购买套餐",
        "url": "../Recharge/Recharge",
        "type": "h5"
      },
      {
        "image": (__staticUrl + '/water_filter/Group_409.png'),
        "name": "滤芯购买记录",
        "url": "../RechargeRecord/RechargeRecord",
        "type": "h5"
      },
      {
        "image": (__staticUrl + '/water_filter/Group_410.png'),
        "name": "滤芯详情",
        "url": "../filter/filter",
        "type": "h5"
      },
      {
        "image": (__staticUrl + '/water_filter/Group_411.png'),
        "name": "设备分享",
        // "url":"../shareDerive/shareDerive",
        "type": "h5"
      },
      {
        "image": (__staticUrl + '/water_filter/Group_412.png'),
        "name": "客服中心",
        "url": "../Addfriend/Addfriend",
        "type": "h5"
      },
      {
        "image": (__staticUrl + '/water_filter/Group_413.png'),
        "name": "维修工单",
        "url": "../upKeep/upKeep",
        "type": "h5"
      },
      {
        "image": (__staticUrl + '/water_filter/Group_414.png'),
        "name": "滤芯更换",
        // "url": "https://zhsq.hshuishang.com/user/exchange/index",
        "url":"/packages/WaterPurifier/pages/water_change/water_change",
        "type": "h5"
      }
    ],
    // 滤芯寿命
    progress_List: [{
        "name": "HXTH滤芯",
        "progress": 97.41
      },
      {
        "name": "RO膜滤芯",
        "progress": 87.41
      },
      {
        "name": "PP+CB滤芯",
        "progress": 40.41
      },
      {
        "name": "PP棉滤芯",
        "progress": 90.41
      }
    ],
    imagePath: '',
    ec: {
        onInit: initChart
    },
    imagePath: '',
    page_num:1,
    page_size:10,
    currentDevice:[],
    is_deal:false
  },
  partner(){
      wx.navigateTo({
        url: '../../../partner/pages/partner',
      })
  },
  device(){
      wx.navigateTo({
        url: '../device/myDevice/myDevice',
      })
  },
  handleNavigateBack(){
      wx.navigateBack({delta:1})
  },
  convertCanvasToImage(){
    wx.canvasToTempFilePath({
        canvasId: 'myChart',
        success: (res) => {
        console.log(res.tempFilePath);
          this.setData({
            imagePath: res.tempFilePath
          });
        },
        fail: (err) => {
          console.error('Canvas to image failed:', err);
        }
    });
  },
  maintenanceList(){
    wx.navigateTo({
      url: '../Maintenance/Maintenance',
    })
  },

  buyFilter(){
    wx.navigateTo({
      url: '../Buyfilter/Buyfilter',
    })
  },

  NotOpen(){
    wx.showModal({
      title: '提示',
      content: '此功能暂未开通！',
      showCancel:false,
      complete: (res) => {
        if (res.cancel) {
          
        }
      }
    })
},
  jump(e){
      if(!e.target.dataset.url){
          this.NotOpen()
      }
    wx.navigateTo({
      url: e.target.dataset.url,
    })
  },

  base64({ url, type }) {
    return new Promise((resolve, reject) => {
        wx.getFileSystemManager().readFile({
            filePath: url, //选择图片返回的相对路径
            encoding: 'base64', //编码格式
            success: res => {
                resolve('data:image/' + type.toLocaleLowerCase() + ';base64,' + res.data)
            },
            fail: res => reject(res.errMsg)
        })
    })
},

getDaysBetweenDates(inputDate) {
    const currentDate = new Date();
    // 将传入的日期字符串转换为日期对象
    const targetDate = new Date(inputDate);
    // 计算两个日期之间的时间差（以毫秒为单位）
    const timeDifference = currentDate - targetDate;
    // 将时间差转换为天数
    const daysDifference = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
    // 返回天数
    return daysDifference;
},

//获取用户设备
getDeviceList(){
    wx.showLoading({
      title: '加载中...',
      mask:true
    })
    let that = this
    util.postUrl(apiArr.getUserList,{
        page_num:that.data.page_num,
        page_size:that.data.page_size,
        user_id:Number(wx.getStorageSync('userId'))
    },res=>{
        wx.hideLoading()
        let currentDevice = {}
        res.rows.forEach(item=>{
            if(item.is_first == 1){
                currentDevice = item
                item.install_time = item.install_time.slice(0,10)
                item.difDay = that.getDaysBetweenDates(item.install_time)
                wx.setStorageSync('device_id', item.device_id),
                wx.setStorageSync('dealerId', item.dealer_id)
                // wx.setStorageSync('device_code', item.)
                wx.setStorageSync('currentDevice', item)
            }
        })

       
        
        that.setData({
            currentDevice
        })
    })
},




  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    let that = this
    setTimeout(()=>{
        const ecComponent = that.selectComponent("#mychart-dom-bar")
        // 将 canvas 内容转换为临时图片文件
        ecComponent.canvasToTempFilePath({
        // canvasId: 'mychart-dom-bar',
        success: (result) => {
            this.base64({
                url:result.tempFilePath,
                type:'png',
            }).then((res)=>{
                that.setData({
                    imagePath:res
                })
            })
            
            // console.log('转换成功，图片路径：', result.tempFilePath);
        },
        fail: (err) => {
            console.error('转换失败:', err);
        }
        });
    },2000)

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    setTimeout(()=>{
        this.convertCanvasToImage()
    },5000)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this
    that.getDeviceList()
    that.setData({
        is_deal:wx.getStorageSync('is_deal')
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },
})

function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // 将此选项设置为 2，可以在高分辨率屏幕上绘制更清晰的图表
  });
  canvas.setChart(chart);
  const option = {
    xAxis: {
      type: 'category',
      data: ['16:41', '22:41', '04:41', '10:41', '16:41']
    },
    yAxis: {
      type: 'value',
      data: ['0ml','560ml']
    },
    series: [{
      data: [150, 230, 224, 218, 135, 147, 260],
      type: 'bar',
      barWidth: 15,
      itemStyle: {    //柱状颜色和圆角
            color: {
                x:0,
                y:1,
                colorStops:[{
                    offset: 0,
                    color: '#FFBBAC',
                },{
                    offset: 1,
                    color: '#2583FF'
                }]
            },
            barBorderRadius: [5, 5, 0, 0], // （顺时针左上，右上，右下，左下）
    },
    }]
  };
  chart.setOption(option);
    wx.canvasToTempFilePath({
    canvasId: 'mychart-bar',
    success: (res) => {
        this.setData({
        imagePath: res.tempFilePath
        });
    },
    fail: (err) => {
        console.error('Canvas to image failed:', err);
    },
    },this);

  return chart;
}


