
let util = require('../../../utils/util')
let apiArr = require('../../../api/water_filter')
import * as echarts from '../../../component/ec-canvas/echarts';

// packages/master/deviceInfo/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: "",
        currentDevice: "",
        imagePath: "",
        ec: {
            onInit: initChart
        },

        appointment_time:"",
        show:false,
        minDate: new Date().getTime(),
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            }
            if (type === 'month') {
                return `${value}月`;
            }
            if (type === 'day') {
                return `${value}日`;
            }
            return value;
        },
    },
    onInput(event) {
        let that = this
        const date = new Date(event.detail); // 获取选中的 Date 对象
        const year = date.getFullYear(); // 获取年份
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0'); // 小时补零
        const minutes = String(date.getMinutes()).padStart(2, '0'); // 分钟补零
        const time = `${year}-${month}-${day} ${hours}:${minutes}`;
        that.setData({
            appointment_time:time,
            show: false
        })

        that.cancelActivation()
    },
    onClose(){
        let that =this
        that.setData({
            show:false
        })
    },
    formatPercentage(value) {
        return Math.max(0, Number((value || 0).toFixed(0)));
    },
    getInfo() {
        let that = this
        console.log(that, 'ssss');
        util.postUrl(apiArr.masterDeviceInfo, {
            device_id: that.data.id
        }, res => {
            res.remainDay = Math.max(0, that.getDaysBetweenDates2(res.expiration_duration)) //剩余天数
            if (res.expiration_duration) {
                res.difDay = Math.max(0, that.getDaysBetweenDates(res.install_time)) //服务天数，确保不小于0
            } else {
                const installDate = new Date(res.install_time)
                const expireDate = new Date(res.expiration_duration)
                res.difDay = Math.max(0, Math.floor((expireDate - installDate) / (1000 * 60 * 60 * 24))) //确保不小于0
            }

            if (res.parts) {
                res.parts.forEach(item => {
                    item.difDay = that.getDaysBetweenDates(item.start_time)
                    const remainingDays = Math.max(0, (item.available_days || 0) - (item.difDay || 0));

                    item.percentageDay = that.formatPercentage(
                        (remainingDays / (item.available_days || 1)) * 100
                    );
                    item.percentageCapacity = that.formatPercentage(
                        (1 - (item.threshold_volume || 0) / (item.available_volume || 1)) * 100
                    );
                })
            }
            res.today = Number(res.today).toFixed(2)
            res.yesterday = Number(res.yesterday).toFixed(2)
            
            that.setData({
                currentDevice: res
            })
            let Xarr = [];
            let Yarr = [];
            res.device_net.forEach(item => {
                Xarr.push(item.create_time.slice(11, 16))
                Yarr.push((item.cumulative_filtration_flow).toFixed(1))
            })
            that.updateChart({
                xAxis: Xarr,
                series: Yarr
            })
            that.getDeriveInfo()
            setTimeout(() => {
                const ecComponent = that.selectComponent("#mychart-dom-bar")
                // 将 canvas 内容转换为临时图片文件
                ecComponent.canvasToTempFilePath({
                    // canvasId: 'mychart-dom-bar',
                    success: (result) => {
                        that.base64({
                            url: result.tempFilePath,
                            type: 'png',
                        }).then((res) => {
                            that.setData({
                                imagePath: res
                            })
                        })
                    },
                    fail: (err) => {
                        console.error('转换失败:', err);
                    }
                });
            }, 2000)

        })
    },
    replay(e){
        const that = this
        wx.showLoading({
            title: '重置中...',
          })
          // part_id 必须是 device_parts 行 id，不是滤芯品类 parts_id
          util.postUrl(apiArr.resetFilter,{
              part_id:e.currentTarget.dataset.item.id,
              device_id:e.currentTarget.dataset.item.device_id,
          },res=>{
              wx.hideLoading()
              console.log(res);
              if(res.msg == '操作成功'){
                  wx.showToast({
                    title: '重置成功！',
                    icon:"none"
                  })
                  that.getInfo()
              }else{
                  wx.showToast({
                    title: res.msg || '重置失败',
                    icon:"none"
                  })
              }
          })
    },
    //拆机
    deleteDevice(){
        let that = this
        wx.showModal({
          title: '提示',
          content: '请确保设备通电开机状态，该操作将取消设备激活状态',
          complete: (res) => {
            if (res.cancel) {
              
            }
        
            if (res.confirm) {
                that.setData({
                    show:true
                })
            }
          }
        })
    },

    cancelActivation(){
        let that = this
        util.postUrl(apiArr.cancelActivation,{
            device_id:that.data.currentDevice.device_id
        },res=>{
            that.createUninstall()
        })
    },
    createUninstall(){
        let that= this
        util.postUrl(apiArr.createUninstallOrder,{
            device_id:that.data.currentDevice.device_id,
            info_id:wx.getStorageSync('info_id'),
            appointment_time:that.data.appointment_time,
            remark: ''
        },res=>{
            console.log(res);
            wx.navigateTo({
              url: `/packages/master/orderDesc/index?id=${res.uninstall_id}&type=3`,
            })
        })
    },

    //查询设备实时信息
    getDeriveInfo() {
        let that = this
        util.postUrl(apiArr.boardInfo, {
            device_id: that.data.currentDevice.device_id
        }, res => {
            console.log(res);
        })
    },
    //开关机
    openOff() {
        let that = this
        let onOff = ''
        if(that.data.currentDevice.sevice_status == 1){
            onOff = 2
        }else if(that.data.currentDevice.sevice_status == 2){
            onOff = 1
        }
        util.postUrl(apiArr.openOff, {
            deviceId: that.data.currentDevice.device_id,
            onOff
        }, res => {
            if (res.msg == '操作成功') {
                if (res.data.params.sevice_status.value == '00') {
                    wx.showToast({
                        title: '关机成功！',
                        icon: "none"
                    })
                    that.setData({
                        "currentDevice.sevice_status": 0
                    })
                } else if (res.data.params.sevice_status.value == '10') {
                    wx.showToast({
                        title: '开机成功！',
                        icon: "none"
                    })
                    that.setData({
                        "currentDevice.sevice_status": 1
                    })
                    console.log('开机');
                }
            }
        })
    },

    updateChart(data) {
        const ecComponent = this.selectComponent("#mychart-dom-bar");
        if (!ecComponent) return;

        this.setData({
            chartData: data
        });

        ecComponent.init((canvas, width, height, dpr) => {
            const chart = initChart(canvas, width, height, dpr);
            chart.setOption({
                grid: {
                    left: '3%',    // 左边距
                    right: '4%',   // 右边距
                    bottom: '3%',  // 底部边距
                    containLabel: true // 确保标签包含在内
                },
                xAxis: {
                    data: data.xAxis
                },
                series: [{
                    data: data.series,
                    label: {  // 添加这个label配置
                        show: true,          // 开启显示
                        position: 'top',     // 位置在柱子上方
                        color: '#333',       // 文字颜色
                        // fontSize: 8         // 文字大小
                    }
                }]
            });
            return chart;
        });
    },

    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)
            })
        })
    },
    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);
            }
        });
    },
    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;
    },
    getDaysBetweenDates2(targetDate) {
        // 获取当前日期（不含时间）
        const today = new Date();
        today.setHours(0, 0, 0, 0); // 时间归零，避免时间差影响
        // 解析目标日期（格式：YYYY-MM-DD）
        const target = new Date(targetDate);
        target.setHours(0, 0, 0, 0);
        // 计算毫秒差并转换为天数
        const timeDiff = target - today;
        const daysRemaining = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
        return daysRemaining;
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        that.setData({
            id: options.id
        })
        
        that.getInfo()
    },

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

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

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    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'],
            data: []
        },
        yAxis: {
            type: 'value',
            // data: ['0ml', '560ml']
            min: 0,
            axisLabel: {
                formatter: '{value}ml'
            }
        },
        series: [{
            // data: [150, 230, 224, 218, 135, 147, 345],
            data: [],
            type: 'bar',
            barWidth: 15,
            itemStyle: {    //柱状颜色和圆角
                color: {
                    x: 0,
                    y: 1,
                    colorStops: [{
                        offset: 0,
                        color: '#FFBBAC',
                    }, {
                        offset: 1,
                        color: '#338BFF'
                    }]
                },
                barBorderRadius: [5, 5, 0, 0], // （顺时针左上，右上，右下，左下）
            },
        }]
    };
    chart.setOption(option);
    return chart;
}