import * as echarts from '../../component/ec-canvas/echarts';
let util = require('../../utils/util')
import { setupTimedTask, clearTimedTask } from '../../utils/timedCall';

const apiArr = require('../../api/water_filter')
const app = getApp({ allowDefault: true })

const TASK_NAME = 'dataRefreshTask';

const __staticUrl = require('../../config/env.js').static_url
Page({

    /**
     * 页面的初始数据
     */
    data: {

        newOrderDesc: {},
        s: app.system.statusBarHeight, // 状态栏高度
        n: (app.menu.top - app.system.statusBarHeight) * 2 + app.menu.height, // 导航栏高度
        t: app.menu.top, // 胶囊局顶部距离
        h: app.menu.height, // 胶囊高度
        // isLogin: false,
        is_dev: '',
        // 功能列表
        functional_List: [{
            "image": (__staticUrl + '/water_filter/Group_407.png?v1'),
            "name": "一键报修",
            // "url": "packages/WaterPurifier/pages/repair/repair",
            "url": `/packages/WaterPurifier/pages/repair/repair`,
            "type": "h5"
        },
        {
            "image": (__staticUrl + '/water_filter/Group_408.png?v1'),
            "name": "续费充值",
            "url": "/packages/WaterPurifier/pages/Recharge/Recharge",
            "type": "h5"
        },
        {
            "image": (__staticUrl + '/water_filter/Group_409.png?v1'),
            // "name": "滤芯购买记录",
            "name": "套餐购买记录",
            "url": "/packages/WaterPurifier/pages/RechargeRecord/RechargeRecord",
            "type": "h5"
        },
        {
            "image": (__staticUrl + '/water_filter/Group_410.png?v1'),
            "name": "滤芯详情",
            "url": "/packages/WaterPurifier/pages/filter/filter",
            "type": "h5"
        },
        {
            "image": (__staticUrl + '/water_filter/Group_411.png?v1'),
            "name": "设备分享",
            "type": "h5",
            "url": "/pages/share/share"
        },
        {
            "image": (__staticUrl + '/water_filter/Group_412.png?v1'),
            "name": "客服中心",
            "url": "/packages/WaterPurifier/pages/Addfriend/Addfriend",
            "type": "h5"
        },
        {
            "image": (__staticUrl + '/water_filter/Group_413.png?v1'),
            "name": "维修工单",
            // "url": "/packages/WaterPurifier/pages/upKeep/upKeep",
            "url": "/packages/WaterPurifier/pages/Maintenance/Maintenance",
            "type": "h5"
        },
        {
            "image": (__staticUrl + '/water_filter/Group_414.png?v1'),
            "name": "滤芯更换记录",
            // "url": "https://zhsq.hshuishang.com/user/exchange/index",
            // "url": "/pages/filterChange/filterChange",
            "url": "/packages/WaterPurifier/pages/filterChangeList/filterChangeList",
        }
        ],
        // 滤芯寿命
        progress_List: [],
        imagePath: '',
        ec: {
            onInit: initChart
        },
        imagePath: '',
        page_num: 1,
        page_size: 10,
        currentDevice: [],
        is_deal: false,
        login: false,
        chartData: {
            xAxis: [],
            series: []
        },

        nav_list: [
            {
                url: "/pages/water_filter/water_filter",
                nav_name: "设备",
                photo: (__staticUrl + '/water_filter/deviceIcon.png')
            },
            {
                url: "/pages/info/info",
                nav_name: "我的",
                photo: (__staticUrl + '/person/Group_309.png')
            },
        ],
        foot_width: '50%',

        newOrderList: [],
        newOrderInfo: "",
    },
    back() {
        wx.redirectTo({
            url: '/pages/newLogin/newLogin',
        })
    },
    scanOrder() {
        let that = this
        // 未登录时不打转账确认（需 Authorization），避免 401 误弹「请登录」
        if (!wx.getStorageSync('ctoken')) {
            return
        }
        let openId = wx.getStorageSync('openId')
        if (!openId) {
            const info = wx.getStorageSync('userInfo') || {}
            openId = info.open_id || ''
            if (openId) {
                wx.setStorageSync('openId', openId)
            }
        }
        if (!openId) {
            // login-info 尚未回写时跳过，避免 openId 空触发业务错误
            return
        }
        util.postUrl(apiArr.scanOrder, { open_id: openId }, res => {
            console.log(res, '数据返回');
            if (res.unauthorized || !res) {
                return
            }
            if (res.id) {
                if (wx.canIUse('requestMerchantTransfer')) {
                    wx.requestMerchantTransfer({
                        mchId: res.mch_id,
                        appId: res.app_id,
                        package: res.package_info,
                        success: (ress) => {
                            console.log(res, '成功');
                            that.queryOrder(res.id)
                            wx.showToast({
                                title: '支付成功！',
                                icon: "none"
                            })
                        },
                        fail: (res) => {
                            console.log(res, '失败');
                            wx.showToast({
                                title: '支付失败',
                                icon: "none"
                            })
                        },
                    });
                    return

                } else {
                    wx.showModal({
                        content: '你的微信版本过低，请更新至最新版本。',
                        showCancel: false,
                    });
                }
            }
        }, null, { skipAuthRedirect: true })
    },

    getPermission() {
        let that = this
        wx.requestSubscribeMessage({
            tmplIds: ["5yPg-WOoP9-9ZU1fHjC4zg1KNaPWb76K87JzzKb58f0", "2BX7Zh5ccLzmHvvbCHuPWiaoZQyDCGfziCruxUct_EU", "eEetEKoNpqXk_EY0xqMt22_Xd7NFEyiODY6j0t3_A24"],
            success(res) {
                console.log(res, 'sucs');
            },
            fail(err) {
                console.log(err, 'err');
            }
        })

        wx.requestSubscribeMessage({
            tmplIds: ["re34uubgvrwJLaiM3LhQEmvxrRxoNcJbo7b8gcbxx44", "_s7GcsGNqapbnlLAJ5lUFexCEAx-dl4RD-DwwL9QqC4", "CWtF10H3syth9rdUaGr-4XojSa8TJMflb2z7zStw384"],
            success(res) {
                console.log(res, 'sucs');
            },
            fail(err) {
                console.log(err, 'err');
            }
        })
        wx.requestSubscribeMessage({
            tmplIds: ["qLYGETdlX5pR8WvTs8v4g4zlBOhA04z46KS_Q_yesr4", "T87KsBIrVrjgO4VETEOpIn4c4-bsxOTpzM6lR0ghduo", "q3Aa07wgYPgB23mu4JOuSzgFoiYhouUcw-NhV5CNuSA"],
            success(res) {
                console.log(res, 'sucs');
            },
            fail(err) {
                console.log(err, 'err');
            }
        })
        wx.requestSubscribeMessage({
            tmplIds: ["pUkdPwh7jWLjCWWv2zyz7I086xNO_GoaJQ6A-cYuGVg", "VXRbeTG6gPPOrxTSwF_da8jzqH0UVHxQykYAH0XH51s"],
            success(res) {
                console.log(res, 'sucs');
            },
            fail(err) {
                console.log(err, 'err');
            }
        })

    },

    queryOrder(data) {
        let that = this
        util.postUrl(api.queryOrder, { id: data }, res => {
            console.log(res);
        })
    },

    replay(e) {
        const that = this
        wx.showLoading({
            title: '重置中...',
            mask: true
        })
        util.postUrl(apiArr.resetFilterUser, {
            device_id: e.currentTarget.dataset.item.device_id,
            part_id: e.currentTarget.dataset.item.id,
        }, res => {
            wx.hideLoading()
            console.log(res);
            if (res.msg == '操作成功') {
                wx.showToast({
                    title: '重置成功！',
                    icon: "none"
                })
                that.getInfo(wx.getStorageSync('device_id'))
            } else {
                wx.showToast({
                    title: res.msg || '重置失败',
                    icon: "none"
                })
            }
        })
    },
    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
        }

        wx.showLoading({
            title: '操作中...',
            mask: true
        })

        util.postUrl(apiArr.openOff, {
            deviceId: that.data.currentDevice.device_id,
            onOff
        }, res => {
            wx.hideLoading()
            if (res.msg == '操作成功') {
                if (res.data.params.sevice_status.value == '00') {
                    wx.showToast({
                        title: '关机成功！',
                        icon: "none"
                    })
                    that.setData({
                        "currentDevice.sevice_status": 2
                    })
                    console.log('关机');
                } else if (res.data.params.sevice_status.value == '10') {
                    wx.showToast({
                        title: '开机成功！',
                        icon: "none"
                    })
                    that.setData({
                        "currentDevice.sevice_status": 1
                    })
                    console.log('开机');
                }
            }
        })
    },

    getNewOrderList() {
        let that = this
        wx.showLoading({
            title: '加载中...',
            mask: true,
        })
        //设置加载状态
        util.postUrl(apiArr.userNewOrderList, {
            page_size: that.data.page_size,
            page_num: that.data.page_num,
        }, res => {
            wx.hideLoading()
            if (res.rows) {
                let flag = false
                that.setData({
                    newOrderList: that.data.newOrderList.concat(res.rows || []),
                })
                if (res.rows.length) {
                    that.getNewOrderInfo(res.rows[0].install_id)
                }
            }
        })
    },

    call() {
        let that = this
        wx.makePhoneCall({
            phoneNumber: that.data.newOrderDesc.cus_service_phone,
        })
    },

    getNewOrderInfo(e) {
        let that = this
        util.postUrl(apiArr.newOrderDesc, { install_id: Number(e) }, res => {
            res.product_icon2 = util.img_url + res.product_icon
            res.qrcode2 = util.img_url + res.qrcode
            that.setData({
                newOrderDesc: res,
            })
            if (res.status == 3) {
                let imgList2 = res.install_imgs.split(',')
                let imgList = []
                imgList2.forEach((item, index) => {
                    imgList.push(util.img_url + item)
                })
                that.setData({
                    msg: res.install_desc,
                    imgList2,
                    imgList,
                    dis1: true
                })
            }
        })
    },

    getUserInfo() {
        wx.showLoading({
            title: '加载中...',
        })
        let that = this
        util.postUrl(apiArr.loginInfo, {}, ress => {
            wx.hideLoading()
            if (ress.error) return;
            // console.log(ress,'asd');
            // ress.is_dev = 0
            wx.setStorageSync('userId', ress.user_id);
            wx.setStorageSync('openId', ress.open_id);
            wx.setStorageSync('shopId', ress.wshop_id);
            wx.setStorageSync('mshopId', ress.mshop_id);
            wx.setStorageSync('is_dev', ress.is_dev);
            that.setData({
                is_dev: wx.getStorageSync('is_dev')
            })

            if (ress.is_dev == 2) {
                that.getNewOrderList()
            }

        })
    },

    partner() {
        if (!wx.getStorageSync('ctoken')) {
            return wx.showModal({
                title: '提示',
                content: '请登录后查看',
                confirmText: "去登录",
                complete: (res) => {
                    if (res.cancel) {

                    }

                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/newLogin/newLogin',
                        })
                    }
                }
            })
        }

        // if (!wx.getStorageSync('is_deal')) {
        //     return wx.showToast({
        //         title: '暂未权限',
        //         icon: "none"
        //     })
        // }
        wx.navigateTo({
            url: '/packages/partner/pages/partner',
        })

    },
    device() {
        if (!wx.getStorageSync('ctoken')) {
            return wx.showModal({
                title: '提示',
                content: '请登录后查看',
                confirmText: "去登录",
                complete: (res) => {
                    if (res.cancel) {

                    }

                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/newLogin/newLogin',
                        })
                    }
                }
            })
        }
        wx.navigateTo({
            url: '/packages/WaterPurifier/pages/device/myDevice/myDevice',
        })
    },
    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() {
        if (!wx.getStorageSync('ctoken')) {
            return wx.showModal({
                title: '提示',
                content: '请登录后查看',
                confirmText: "去登录",
                complete: (res) => {
                    if (res.cancel) {

                    }

                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/newLogin/newLogin',
                        })
                    }
                }
            })
        }
        wx.navigateTo({
            url: '/packages/WaterPurifier/pages/Maintenance/Maintenance',
        })
    },

    buyFilter() {
        if (!wx.getStorageSync('ctoken')) {
            return wx.showModal({
                title: '提示',
                content: '请登录后查看',
                confirmText: "去登录",
                complete: (res) => {
                    if (res.cancel) {

                    }

                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/newLogin/newLogin',
                        })
                    }
                }
            })
        }
        wx.navigateTo({
            url: '/packages/WaterPurifier/pages/Buyfilter/Buyfilter',
        })
    },

    NotOpen() {
        wx.showModal({
            title: '提示',
            content: '此功能暂未开通！',
            showCancel: false,
            complete: (res) => {
                if (res.cancel) {

                }
            }
        })
    },
    jump(e) {
        let that = this
        if (!e.target.dataset.url) {
            this.NotOpen()
        }
        if (!wx.getStorageSync('ctoken')) {
            return wx.showModal({
                title: '提示',
                content: '请登录后查看',
                confirmText: "去登录",
                complete: (res) => {
                    if (res.cancel) {

                    }

                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/newLogin/newLogin',
                        })
                    }
                }
            })
        }
        if(e.target.dataset.url == '/packages/WaterPurifier/pages/Recharge/Recharge'){
            if(that.data.currentDevice.network_status != 1){
                return wx.showModal({
                  title: '设备已离线！',
                  content: '请将设备断电后重新上电，确保设备在线，再进行续费充值!',
                  showCancel:false,
                  complete: (res) => {
                    if (res.cancel) {
                      
                    }
                
                    if (res.confirm) {
                      
                    }
                  }
                })
            }
        }
        wx.navigateTo({
            url: e.target.dataset.url,
        })
    },

    jumps(e) {
        console.log(e);
        if (e.currentTarget.dataset.idx == '1') {
            wx.redirectTo({
                url: e.currentTarget.dataset.url,
            })
            return
            wx.getSetting({
                withSubscriptions: true,
                success: (res) => {
                    if (res.subscriptionsSetting && res.subscriptionsSetting.mainSwitch) {
                        const itemSettings = res.subscriptionsSetting.itemSettings || {};
                        const tmplMap = {
                            '5yPg-WOoP9-9ZU1fHjC4zg1KNaPWb76K87JzzKb58f0': '工单完成通知',
                            'qLYGETdlX5pR8WvTs8v4g4zlBOhA04z46KS_Q_yesr4': '工单派工通知',
                            '5yPg-WOoP9-9ZU1fHjC4zg1KNaPWb76K87JzzKb58f0': '订单付款通知'
                        };

                        const unsubscribedTmplIds = [];
                        Object.keys(tmplMap).forEach(tmplId => {
                            if (itemSettings[tmplId] !== 'accept') {
                                unsubscribedTmplIds.push(tmplId);
                            }
                        });

                        if (unsubscribedTmplIds.length > 0) {
                            wx.requestSubscribeMessage({
                                tmplIds: unsubscribedTmplIds,
                                success: (res) => {
                                    console.log('订阅成功', res);
                                    wx.redirectTo({
                                        url: e.currentTarget.dataset.url,
                                    })
                                },
                                fail: (err) => {
                                    console.error('订阅失败', err);
                                    wx.redirectTo({
                                        url: e.currentTarget.dataset.url,
                                    })
                                }
                            });
                        } else {
                            wx.redirectTo({
                                url: e.currentTarget.dataset.url,
                            })
                        }
                    }
                },
                fail: () => {
                    wx.redirectTo({
                        url: e.currentTarget.dataset.url,
                    })
                }
            });
        } else {
            wx.redirectTo({
                url: e.currentTarget.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;
    },
    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;
    },

    //获取用户设备
    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 login = false
            if (res.rows && res.rows.length > 0) {
                login = true
            }
            let currentDevice = {}
            let currentDeviceId = ''

            if (res.rows) {
                if (res.rows.length == 1) {
                    res.rows[0].is_first = 1
                }
                res.rows.forEach(item => {
                    if (item.is_first == 1) {
                        currentDevice = item
                        currentDeviceId = item.device_id
                        wx.setStorageSync('device_id', item.device_id)

                    }
                })



                that.getInfo(wx.getStorageSync('device_id'))

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

    masterList() {
        if (!wx.getStorageSync('ctoken')) {
            return wx.showModal({
                title: '提示',
                content: '请登录后查看',
                confirmText: "去登录",
                complete: (res) => {
                    if (res.cancel) {

                    }
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/newLogin/newLogin',
                        })
                    }
                }
            })
        }
        // if (!wx.getStorageSync('is_deal')) {
        //     return wx.showToast({
        //         title: '暂未权限',
        //         icon: "none"
        //     })
        // }

        wx.navigateTo({
            url: '/packages/master/order/index',
        })
    },
    formatPercentage(value) {
        return Math.max(0, Number((value || 0).toFixed(0)));
    },
    getInfo(e) {
        wx.showLoading({
            title: '加载中...',
            mask: true
        })
        let that = this
        util.postUrl(apiArr.deviceInfo, { device_id: e }, res => {
            wx.hideLoading()
            // res.expiration_duration = '2025-06-01 08:06:42'
            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.device_part) {
                res.device_part.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
                    );
                })

                const first = res.device_part.findIndex(item =>
                    item.parts_name.indexOf("PP棉滤芯") !== -1
                );
                if (first !== -1) {
                    const [removed] = res.device_part.splice(first, 1); // 移除该对象
                    res.device_part.unshift(removed); // 插入到首位
                }
                const Second = res.device_part.findIndex(item =>
                    item.parts_name.indexOf("PP+CB") !== -1
                );
                if (Second !== -1) {
                    const [removed] = res.device_part.splice(Second, 1); // 移除该对象
                    res.device_part.splice(1, 0, removed);   // 插入到第二位
                }
                const Third = res.device_part.findIndex(item =>
                    item.parts_name.indexOf("RO") !== -1
                );
                if (Third !== -1) {
                    const [removed] = res.device_part.splice(Third, 1); // 移除该对象
                    res.device_part.splice(2, 0, removed);   // 插入到第二位
                }
                const Fourth = res.device_part.findIndex(item =>
                    item.parts_name.indexOf("后置活性炭") !== -1
                );
                if (Fourth !== -1) {
                    const [removed] = res.device_part.splice(Fourth, 1); // 移除该对象
                    res.device_part.splice(3, 0, removed);   // 插入到第二位
                }
            }

            res.today = Number(res.today).toFixed(2)
            res.yesterday = Number(res.yesterday).toFixed(2)

            that.setData({
                currentDevice: res
            })
            that.getDeriveInfo()

            wx.setStorageSync('device_id', res.device_id),
            wx.setStorageSync('currentDevice', res)
            wx.setStorageSync('billing_method', res.billing_method)
            wx.setStorageSync('dealer_id', res.dealer_id);
            if (!res.device_net) {

            } else {
                if (res.device_net.length == 0) {
                } else {
                    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
                    })

                }
            }


            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
                            })
                        })
                    },
                    fail: (err) => {
                        console.error('转换失败:', err);
                    }
                });
            }, 2000)

        })
    },
    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;
        });
    },

    getVersion() {
        let that = this
        let version = ''
        const accountInfo = wx.getAccountInfoSync();
        if (accountInfo.miniProgram.version) {
            version = accountInfo.miniProgram.version
        } else {
            version = '1.0.14'
        }
        wx.setStorageSync('version', version)
        util.postUrl3(apiArr.getVersion, {}, version, res => {
            if (res.versions) {
                let LoginType = res.versions.includes(version)
                wx.setStorageSync('LoginType', LoginType)
            } else {
                wx.setStorageSync('LoginType', false)
            }
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function () {
        let that = this
        that.getVersion()
        that.scanOrder()
        // login-info 若晚于首屏，补一次转账确认扫描
        setTimeout(() => {
            that.scanOrder()
        }, 1500)
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })

    },


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

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

    addDevice() {
        let that = this
        if (!wx.getStorageSync('ctoken')) {
            return wx.showModal({
                title: '提示',
                content: '请登录后查看',
                confirmText: "去登录",
                complete: (res) => {
                    if (res.cancel) {

                    }

                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/newLogin/newLogin',
                        })
                    }
                }
            })
        }

        wx.navigateTo({
            url: '/pages/deposit/deposit',
        })
    },

    // newOrder() {
    //     wx.navigateTo({
    //         url: '/pages/newOrderList/newOrderList',
    //     })
    // },

    //查询设备实时信息
    getDeriveInfo() {
        let that = this
        util.postUrl(apiArr.boardInfo, {
            device_id: that.data.currentDevice.device_id
        }, res => {
            console.log(res);
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        clearTimedTask(TASK_NAME);
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        clearTimedTask(TASK_NAME);
    },

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

    },

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

    },

    /**
     * 用户点击右上角分享
     */
    onShareTimeline() {
        return {
            title: '人人爱净水', // 自定义标题
            query: '', // 自定义页面路径中的参数
            imageUrl: (__staticUrl + '/share.png') // 自定义分享图片路径
        }
    },
    onShareAppMessage() {
        return {
            title: '人人爱净水',  // 分享卡片标题（必填）
            path: '/packages/water_filter/water_filter',  // 用户点击后跳转的路径（可选，默认当前页）
            imageUrl: (__staticUrl + '/share.png')  // 自定义图片（可选，比例建议 5:4）
        }
    },
})

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;
}


