/// <reference path="echarts.js" />

const visTabCols = ['时间', '酒店名', '房间号', 'Mac地址', '主机编号', '内网IP', '外网IP', '外网Port', '间隔', '方向', '日志', '帧号', '命令',];
const fields = [
    { name: "IP类型", length: 1, type: "decimal" },
    { name: "机型编号", length: 16, type: "decimal" },
    { name: "IP地址", length: 4, type: "ip" },
    { name: "服务器IP地址", length: 4, type: "ip" },
    { name: "子网掩码", length: 4, type: "ip" },
    { name: "网关", length: 4, type: "ip" },
    { name: "端口", length: 4, type: "decimal" },
    { name: "DNS地址", length: 4, type: "ip" },
    { name: "软件版本号", length: 20, type: "ascii" },
    { name: "主机时间", length: 6, type: "time" },
    { name: "Launcher版本", length: 20, type: "ascii" },
    { name: "MAC地址", length: 6, type: "mac" },
    { name: "项目编号", length: 4, type: "halfdecimal" },
    { name: "房号ID", length: 4, type: "halfdecimal" },
    { name: "房型ID", length: 4, type: "halfdecimal" },
    { name: "配置数据版本号", length: 4, type: "halfdecimal" },
    { name: "房态", length: 4, type: "hex" },
    { name: "季节", length: 4, type: "hex" },
    { name: "锁定状态", length: 4, type: "hex" },
    { name: "授权时间", length: 4, type: "time" },
    { name: "授权天数", length: 4, type: "ascii" },
    { name: "房号备注", length: 16, type: "ascii" },
    { name: "房型备注", length: 16, type: "ascii" },
    { name: "房间备注", length: 96, type: "ascii" },
    { name: "MCU机型名称", length: 64, type: "ascii" },
    { name: "中控机型名称", length: 64, type: "ascii" },
    { name: "配置数据酒店名称", length: 32, type: "ascii" },
    { name: "配置数据房型别名", length: 32, type: "ascii" }
];
const fields2 = [
    { name: "服务器IP地址", length: 4, type: "ip" },
    { name: "子网掩码", length: 4, type: "ip" },
    { name: "网关", length: 4, type: "ip" },
    { name: "端口", length: 2, type: "port" }, // 端口是2字节，需要特殊处理
    { name: "MAC地址", length: 6, type: "mac" },
    { name: "版本号", length: 20, type: "ascii" },
    { name: "配置数据版本号", length: 3, type: "decimal" }, // 3字节需要特殊处理
    { name: "DNS地址", length: 4, type: "ip" },
    { name: "房型备注", length: 16, type: "ascii" },
    { name: "房号备注", length: 16, type: "ascii" },
    { name: "房型ID", length: 4, type: "halfdecimal" },
    { name: "房号ID", length: 4, type: "halfdecimal" }
];
var app = new Vue({
    el: '#app',
    data() {

        return {
            testData: [
                /*{
                    key: 'AA',
                    value: '测试解析'
                },
                {
                    key: 'BB',
                    value: '测试解析'
                },
                {
                    key: 'CC',
                    value: '测试解析'
                },
                {
                    key: '00',
                    value: '测试解析'
                },
                {
                    key: '10',
                    value: '测试解析'
                },*/
            ],
            isReady: false, // 页面加载状态
            tableHeight: '0',
            loading: null, // 加载flash
            openDialog: false, // 打开弹窗
            dialogw: '100%', // 弹窗宽度
            selectHotelRoom: null, // 选择里的房间
            multipleSelection: [], // 选出的房间
            pickerOptions: {
                shortcuts: [{
                    text: '最近1天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        //start.setTime(start.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', [start, end]);
                    }
                },
                {
                    text: '最近3天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
                        picker.$emit('pick', [start, end]);
                    }
                },
                {
                    text: '最近7天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
                        picker.$emit('pick', [start, end]);
                    }
                },
                {
                    text: '最近15天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 14);
                        picker.$emit('pick', [start, end]);
                    }
                },
                {
                    text: '最近30天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 29);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            }, // 日期选择器
            hotelCurrent: null, // 选中的酒店ID
            allHotel: [], // 所有酒店列表
            hotels: [], // 酒店列表
            roomCurrent: null, // 选中的房间ID
            isTheRoomGet: false, // 是否获取了房间列表
            allRoom: [], // 所有房间列表
            rooms: [], // 房间列表
            pickerDate: [new Date(), new Date()], // 选择的日期范围
            logs: null, // 日志列表
            roomDisable: true, // 房间选择框是否可选
            multipleBtn: true, // 批量查询或者批量删除按钮是否可用
            btnIntoDisable: true, // 加入监控按钮是否可选
            CreatDataTable: [
                hotel = [],
                room = [],
            ], // 筛选表
            visTabCol: ['时间', '日志', '方向', '间隔', '帧号', '命令'], // 设置默认表头
            //visTabCol: visTabCols, // 默认表头(全选测试)
            tabCols: visTabCols, // 表头筛选框
            checkAll: true, // 是否全选
            isIndeterminate: true, // 是否半选
            displayCheck: false, // 是否显示筛选框
            pageSize: 50, // 每页条数
            currentPage: 1, // 初始前往页
            allPageNum: 0, // 总条数
            cmdList: [], // 命令列表
            allCmdList: [], // 命令列表
            cmdCurrent: null, // 选中的命令
            mobileSelectedVis: false, // 移动设备搜索框下拉适配
            echartVis: false, // 是否显示图表
            stateVis: false, // 当前是否显示状态表
            states: null, // 状态列表
            logAnalysisList: [], // 日志分析列表
        };
    },
    watch: {
        /*        clipboardValue: {
                    handler: function (newVal, oldVal) {
                        //console.log(newVal);
                        if (newVal) {
        
                        }
                    }
                },*/
        selectHotelRoom: {
            handler: function (newVal, oldVal) {
                //if ((oldVal.length == 0 && newVal.length > 0) || newVal == oldVal && newVal.length == 0 && this.allHotel.length > 0) {
                if (newVal.length >= 0 && this.allHotel.length > 0) {
                    this.isReady = true; // 页面加载完毕，设置isReady为true，显示页面内容
                    this.loading.close();
                }
            }
        },
        roomCurrent: {
            handler: function (newVal, oldVal) {
                if (newVal != null && newVal != undefined) {
                    if (newVal.length > 0) {
                        this.btnIntoDisable = false;
                    } else {
                        this.btnIntoDisable = true;
                    }
                }
            }
        },
        allHotel: {
            handler: function (newVal, oldVal) {
                if (newVal.length > 0 && oldVal.length == 0) { // 首次加载
                    this.getHotelRooms();
                    this.hotels = this.removeDuplicatesById(JSON.parse(localStorage.getItem('hotelCurrent')));
                    //console.log(hotels1);
                }
            }
        },
        multipleSelection: {
            handler: function (newVal, oldVal) {
                if (newVal.length > 0) {
                    this.multipleBtn = false;
                } else {
                    this.multipleBtn = true;
                }
            }
        },
        /*logs: {
            handler: function (newVal, oldVal) {
                if (newVal != null && newVal != undefined && newVal.length > 0) {
                    const appVal = {
                        nowTime: new Date(),
                        pickerDate: this.pickerDate,
                        logs: this.logs,
                        visTabCol: this.visTabCol,
                        pageSize: this.pageSize,
                        currentPage: this.currentPage,
                        cmdCurrent: this.cmdCurrent,
                    };
                    sessionStorage.setItem('appVal', JSON.stringify(appVal));
                }
            }
        },*/
    },
    methods: {
        logHome() {
            window.location.href = "/Home/Index";
        },
        refreshViewValue() { // 刷新页面数据
            if (this.isReady) {
                this.$message({
                    message: '刷新成功，重新加载中…',
                    type: 'success'
                });
            }
            this.selectHotelRoom = [];
            this.getHotelRooms();
            this.getHotels();

        },
        handleDelayed(row) { // 重置监控剩余时间
            let arr = [row];
            this.addOrRemoveSub(JSON.stringify(arr), "add");
        },
        handleRemove(row) { // 移除对象
            let arr = [row];
            this.addOrRemoveSub(JSON.stringify(arr), "remove");
        },
        handleAdd() { // 新增对象
            this.roomCurrent.map(room => {
                room.HotelCode = app.hotelCurrent.code;
                room.MAC = room.mac;
                room.RoomNumber = room.roomno;
                room.Key_HostNumber = room.hostnumber;
                room.HostID = room.id;
            });
            console.log(this.roomCurrent);
            this.addOrRemoveSub(JSON.stringify(this.roomCurrent), "add");
        },
        delSelectedLogs() { // 删除选中监控
            this.addOrRemoveSub(JSON.stringify(this.multipleSelection), "remove");
        },
        addOrRemoveSub(jsonlist, sub) { // 新增或者删除监控点
            var _this = this;
            let getdata = {
                data: jsonlist,
                add_remove: sub,
            }
            //console.log(getdata)
            $.ajax({
                url: '/api/LowerMachineLog/Monitor_Host_Handle',
                type: 'POST',
                contentType: 'application/x-www-form-urlencoded',
                data: getdata,
                success: function (response) {
                    if (response.isok) {
                        _this.getHotelRooms();
                        _this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                    } else {
                        _this.$message.error(response.message + '！');
                    }
                },
                error: function (error) {
                    _this.$message.error('失败，请稍后再试');
                }
            });
        },
        handleSelectionChange(val) { // 表格选择
            //console.log(val)
            this.multipleSelection = val;
        },
        showLog(index, row) { // 显示单行日志
            //console.log(index, row);
            this.multipleSelection = [row]
            //this.multipleSelection.push(row);
            this.showSelectedLogs(1);
        },
        showSelectedLogs(type) { // 显示日志
            if (this.cmdCurrent.length == 0) {
                this.$message.error('请选择日志类型！');
                return;
            }
            if (this.echartVis) {
                this.echartShow();
            }
            if (type == 1) { this.currentPage = 1 }
            this.logs = [];
            //console.log(this.cmdCurrent);
            var _this = this;
            let getdata = {
                Data: this.multipleSelection,
                Start_Time: this.formatDate(this.pickerDate[0], true),
                End_Time: this.formatDate(this.pickerDate[1], false),
                PageSize: this.pageSize,
                PageIndex: this.currentPage,
                CommandType: this.cmdCurrent,
            };
            //console.log(getdata)
            //return;
            this.LoadingPic();

            $.ajax({
                url: '/api/LowerMachineLog/Get_Log',
                type: 'POST',
                contentType: 'application/x-www-form-urlencoded',
                data: { QueryData: JSON.stringify(getdata) },
                success: function (res) {
                    console.log(res);
                    //return;
                    if (res.isok) {
                        //_this.logs = JSON.parse(JSON.stringify(res.response));

                        var mergedData = [];
                        let previousCreateTime = null;
                        _this.allPageNum = res.response.totalCount;
                        res.response.devMonitorLogResults.forEach(item => {
                            // 解构赋值提取devLog和exData
                            const { devLog, exData } = item;

                            // 合并devLog和exData
                            const mergedItem = { ...devLog, ...exData };

                            // 计算时间差
                            if (previousCreateTime) {
                                const createTime = new Date(mergedItem.createTime);
                                const previousCreateTimeDate = new Date(previousCreateTime);
                                mergedItem.timeDifference = Math.abs(createTime - previousCreateTimeDate); // 时间差，单位为毫秒
                            } else {
                                mergedItem.timeDifference = 0; // 第一个对象没有前一个时间，所以时间差为0
                            }

                            // 更新previousCreateTime为当前对象的createTime
                            previousCreateTime = mergedItem.createTime;


                            // 其他对象的添加
                            mergedItem.hotelNameAndCode = _this.findNameByCode(mergedItem.hotelCode);
                            mergedItem.commandTypeVal = _this.getCharsFromString(mergedItem.data, 8, 1);

                            // 添加到结果数组
                            mergedData.push(mergedItem);
                        });
                        _this.logs = mergedData.slice().reverse();

                        _this.loading.close();
                        //_this.logs.reverse();
                        //console.log(_this.logs);
                        _this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        _this.openDialog = false;

                    } else {
                        _this.$message.error(res.message + '！');
                        app.loading.close();
                    }
                },
                error: function (error) {
                    _this.$message.error('失败，请稍后再试');
                    app.loading.close();
                }
            });

        },
        getHotelRooms() { // 获取酒店房间列表
            var _this = this;
            $.ajax({
                url: '/api/LowerMachineLog/GetAll_MonitorHost',
                type: 'POST',
                contentType: 'application/json',
                success: function (res) {
                    //console.log(res);
                    if (res.isok) {
                        connection.invoke("SendMessage", "1", "2").catch(function (err) {
                            return console.error(err);
                        });
                        let cmd = res.response.commandList.reduce((uniqueCmds, currentCmd) => {
                            if (!uniqueCmds.some(item => item.value === currentCmd)) {
                                uniqueCmds.push({ label: currentCmd, value: currentCmd });
                            }
                            return uniqueCmds;
                        }, []);
                        _this.cmdList = JSON.parse(JSON.stringify(cmd));
                        let cmds = res.response.commandList.reduce((unique, cmd) => {
                            if (!unique.includes(cmd)) {
                                unique.push(cmd);
                            }
                            return unique;
                        }, []);
                        _this.allCmdList = JSON.parse(JSON.stringify(cmds));
                        _this.cmdCurrent = JSON.parse(JSON.stringify(cmds));
                        _this.selectHotelRoom = res.response.data.map(function (htro) {
                            // 创建一个新对象，包含你想要的数据结构
                            return {
                                // 保持原有的属性...
                                ...htro,
                                // 以及新的属性，这些属性通过调用相应的方法来获取
                                hotelNameAndCode: _this.findNameByCode(htro.hotelCode),
                                remainingTime: _this.timeDifference(htro.createDateTime),
                            };
                        });
                        _this.creatTable();
                        //console.log(_this.selectHotelRoom);
                    }
                },
                error: function (error) {
                    _this.$message.error('失败，请稍后再试');
                }
            });
        },
        handleCheckAllChange(val) { // 是否全选
            this.visTabCol = val ? visTabCols : [];
            this.isIndeterminate = false;
        },
        handleCheckedTabChange(value) { // 是否半选
            this.LoadingPic();
            this.isReady = false;
            setTimeout(() => {
                app.isReady = true;
                app.loading.close();
            }, 233);
            this.checkAll = value.length == this.visTabCol.length;
            this.isIndeterminate = value.length == this.visTabCol.length;
            if (value.length == 0) {
                this.checkAll = false;
                this.isIndeterminate = false;
            }
        },
        creatTable() { // 创建筛选数据
            var tb = {
                hotel: [],
                room: [],
            };
            this.selectHotelRoom.forEach(log => {
                // 检查hotel是否已初始化为数组
                if (Array.isArray(tb.hotel) && log.hotelNameAndCode && !tb.hotel.some(item => item.value == log.hotelNameAndCode)) {
                    tb.hotel.push({
                        text: log.hotelNameAndCode,
                        value: log.hotelNameAndCode
                    });
                }
                // 检查room是否已初始化为数组
                if (Array.isArray(tb.room) && log.roomNumber && !tb.room.some(item => item.value == log.roomNumber)) {
                    tb.room.push({
                        text: log.roomNumber,
                        value: log.roomNumber
                    });
                }
            });
            this.CreatDataTable = tb;
        },
        getHotels() { // 获取酒店列表
            var _this = this;
            $.ajax({
                url: '/api/LowerMachineLog/GetHotelList',
                type: 'POST',
                contentType: 'application/json',
                success: function (response) {
                    //console.log(response);

                    //, pageNumber, pageSize
                    if (response.isok) {

                        _this.allHotel = JSON.parse(JSON.stringify(response.response));

                    }
                },
                error: function (error) {
                    _this.$message.error('失败，请稍后再试');
                }
            });
        },
        stateTable() { // 获取被监控房间状态
            if (!this.stateVis) {
                this.stateVis = true;
            }
            this.getHotelRooms();
            //this.states = null;
            this.selectHotelRoom.forEach(function (item) {
                connection.invoke("GetTakeCardStatus", item.hostID, item.key_HostNumber).catch(function (err) {
                    return console.error(err);
                });
            });


        },
        isSupply(hostID, lastData) { // 判断是否取电
            let rs = "";
            this.selectHotelRoom.forEach(Item => {
                // 如果数据项的值与对照表的键相等
                if (hostID == Item.hostID) {
                    // 将对照表的值返回
                    if ((new Date() - new Date(lastData)) < 300000) {
                        rs = "True";
                    } else {
                        rs = "False";
                    }
                    return;
                }
            });
            // 如果没有找到对应的键，则返回null或者自定义的错误信息
            return rs;
        },
        remoteHotel(query) { // 搜索hotel
            if (query != "" && (this.hotelCurrent == null || this.hotelCurrent == "")) {
                //this.hotels = [...new Set([...this.hotels, ...this.allHotel])];
                this.hotels = [];
                const nc = this.allHotel.filter(item => item.code.includes(query) || item.name.includes(query));
                // console.log(nc);
                if (nc.length > 0) {
                    this.hotels = nc;
                } else {
                    this.hotels = JSON.parse(JSON.stringify(this.allHotel));
                }

            } else {
                this.hotels = JSON.parse(localStorage.getItem('hotelCurrent'));
                // this.hotels = JSON.parse(JSON.stringify(this.allHotel));
            }

        },
        remoteRoom(query) { // 搜索room
            //console.log(query);
            if (query != "" && (this.roomCurrent == null || this.roomCurrent == "")) {
                this.rooms = [];
                const nc = this.allRoom.filter(item => item.roomno.includes(query));
                //console.log(nc);
                if (nc.length > 0) {
                    this.rooms = nc;
                } else {
                    this.rooms = JSON.parse(JSON.stringify(this.allRoom));
                }

            } else {
                this.rooms = JSON.parse(JSON.stringify(this.allRoom));
            }

        },
        remoteCmd(query) { // 搜索cmdlist
            //console.log(query);
            if (query != "") {
                this.cmdList = [];
                const nc = this.allCmdList.filter(item => item.value.includes(query));
                //console.log(nc);
                if (nc.length > 0) {
                    this.cmdList = nc;
                } else {
                    this.cmdList = JSON.parse(JSON.stringify(this.allCmdList));
                }

            } else {
                this.cmdList = JSON.parse(JSON.stringify(this.allCmdList));
            }

        },
        getRooms(hotel) { // 获取房间列表
            var _this = this;
            const getdate = {
                hotel_code: hotel.code,
                createDate: hotel.createdate,
            };
            if (!this.isTheRoomGet) {
                $.ajax({
                    url: '/api/LowerMachineLog/GetHostList',
                    type: 'POST',
                    contentType: 'application/x-www-form-urlencoded',
                    data: getdate,
                    success: function (response) {
                        //console.log(response);
                        if (response.isok) {
                            this.isTheRoomGet = true;
                            _this.rooms = JSON.parse(JSON.stringify(response.response));
                            _this.allRoom = JSON.parse(JSON.stringify(response.response));
                        }

                    },
                    error: function (error) {
                        _this.$message.error('失败，请稍后再试');
                    }
                });
            }
        },
        allRoomsBtn() { // 全选所有房间
            this.roomCurrent = JSON.parse(JSON.stringify(this.allRoom));
        },
        allCmdBtn() { // 全选所有CMD
            //console.log(this.allCmdList);
            this.cmdCurrent = JSON.parse(JSON.stringify(this.allCmdList));
        },
        filterHandler(value, row, column) { // 筛选
            //console.log(value, row, column);
            const property = column['property'];
            return row[property] === value;
        },
        filterHandlerMobile(value, row, column) { // 筛选(移动端)
            //console.log(value, row, column);
            return row.hotelNameAndCode == value;
        },
        cmdFilterChange(key, value) { // cmd筛选
            //console.log(key, value);

        },
        dateMobile(date) { // 手机端日期选择
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * date);
            this.pickerDate = [start, end];
            //picker.$emit('pick', [start, end]);
        },
        hotelChange(tag) { // 酒店选择变化时触发
            //console.log(tag);
            if (tag == null || tag == "") {
                this.roomDisable = true;
                this.hotels = JSON.parse(localStorage.getItem('hotelCurrent'));
            } else {
                this.saveObjectToLocalStorage('hotelCurrent', tag);
                this.isTheRoomGet = false;
                this.getRooms(tag);
                this.roomDisable = false;
            }
            this.roomCurrent = null;
        },
        saveObjectToLocalStorage(key, object) { // 保存对象到localStorage
            // 从localStorage获取旧的数组
            const oldArrayString = localStorage.getItem(key);
            let oldArray;

            // 检查是否已经有旧的数组存在
            if (oldArrayString) {
                // 如果存在，则解析为对象数组
                oldArray = JSON.parse(oldArrayString);
            } else {
                // 如果不存在，初始化为空数组
                oldArray = [];
            }

            // 添加新对象到数组
            oldArray.push(object);
            const uniqueArray = this.removeDuplicatesById(oldArray);
            // 将更新后的数组转换回字符串并保存到localStorage
            localStorage.setItem(key, JSON.stringify(uniqueArray));
        },
        visibleChangeHotel(e) {
            if (e) {
                this.hotels = JSON.parse(localStorage.getItem('hotels'));
            } else {
                this.hotels = [];
            }
        },
        visibleChangeRoom(e) {
            if (e) {
                let arr = JSON.parse(localStorage.getItem('rooms'));
                if (arr && arr.code == this.hotelCurrent.code) {
                    this.rooms = arr.roomno;
                }
            } else {
                this.rooms = [];
            }
        },
        paginate(data, pageNumber, pageSize) { // 分页函数
            // 计算起始索引
            const startIndex = (pageNumber - 1) * pageSize;
            // 截取当前页的数据
            const paginatedData = data.slice(startIndex, startIndex + pageSize);
            // 返回当前页的数据
            return paginatedData;
        },
        handleSizeChange(val) { // 每页显示条数变化时触发
            this.pageSize = val;
            this.showSelectedLogs(0);
            //console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) { // 当前页变化时触发
            //console.log(`当前页: ${val}`);
            this.currentPage = val;
            this.showSelectedLogs(0);
        },
        formatDate(date, se) { // 格式化日期, se为true时返回开始时间，false时返回结束时间
            const y = date.getFullYear();
            const M = (date.getMonth() + 1).toString().padStart(2, '0');
            const d = date.getDate().toString().padStart(2, '0');
            if (se) {
                return `${y}-${M}-${d} 00:00:00`;
            } else {
                return `${y}-${M}-${d} 23:59:59`;
            }

        },
        findNameByCode(code) { // 根据ID查找酒店名称
            //console.log(code);
            let rs = null;
            this.allHotel.forEach(Item => {
                // 如果数据项的值与对照表的键相等
                if (code == Item.code) {
                    // 将对照表的值返回
                    rs = Item.name + " | " + Item.code;
                    return;
                }
            });
            // 如果没有找到对应的键，则返回null或者自定义的错误信息
            return rs;

        },
        findNameByMac(mac) { // 根据MAC查找酒店名称
            //console.log(code);
            let rs = null;
            this.selectHotelRoom.forEach(Item => {
                // 如果数据项的值与对照表的键相等
                if (mac == Item.mac) {
                    // 将对照表的值返回
                    rs = Item.hotelNameAndCode;
                    return;
                }
            });
            // 如果没有找到对应的键，则返回null或者自定义的错误信息
            return rs;
        },
        findRoomByMac(mac) { // 根据MAC查找房间号
            //console.log(code);
            let rs = null;
            this.selectHotelRoom.forEach(Item => {
                // 如果数据项的值与对照表的键相等
                if (mac == Item.mac) {
                    // 将对照表的值返回
                    rs = Item.roomNumber;
                    return;
                }
            });
            // 如果没有找到对应的键，则返回null或者自定义的错误信息
            return rs;
        },
        copyData(data) { // 复制数据
            /*try {
                navigator.clipboard.writeText(data);
                //console.log('复制成功');
                // 这里可以添加一个提示，告诉用户复制成功
                this.$message({
                    message: '已复制日志原文！',
                    type: 'success'
                });
            } catch (err) {
                //console.error('无法复制', err);
                this.$message.error('复制错误！');
                // 这里可以添加一个提示，告诉用户复制失败
            }*/
        },
        tableRowClassName({ row, rowIndex }) { // 表格行样式
            /*if (rowIndex === 1) {
                return 'warning-row';
            } else if (rowIndex === 3) {
                return 'success-row';
            }*/
            if (row.sendOrReceive == '主机->服务器') {
                return 'up-row';
            } else if (row.sendOrReceive == '服务器->主机') {
                return 'down-row';
            } else {
                return 'error-row';
            }
        },
        LoadingPic() { // 加载时遮罩层
            this.loading = this.$loading({
                lock: true,
                text: '加载中...',
                spinner: 'el-icon-loading',
                background: 'rgba(255, 255, 255, 1)'
            });
        },
        exportExcel() { // 导出Excel

            var wb = XLSX.utils.table_to_book(this.$refs.logsTable.$el, { sheet: "Sheet JS" });
            var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'binary' });

            // 将字符串转换为ArrayBuffer
            function s2ab(s) {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for (var i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
                return buf;
            }

            // 创建一个 Blob 对象
            let blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });

            function timehandle(date) {
                const y = date.getFullYear();
                const M = (date.getMonth() + 1).toString().padStart(2, '0');
                const d = date.getDate().toString().padStart(2, '0');
                return `${y}${M}${d}`;

            }
            // 创建一个链接元素用于下载
            let link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            let Start = timehandle(this.pickerDate[0]);
            let End = timehandle(this.pickerDate[1]);
            link.download = this.logs[0].hotelNameAndCode.replace(/\s+/g, '') + '_logs_' + Start + '-' + End + '.xlsx';

            // 模拟点击事件进行下载
            document.body.appendChild(link);
            link.click();

            // 清理：释放 Blob 对象并移除链接元素
            window.URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
        },
        getCharsFromString(str, x, y) { // 截取data字符串
            x = x * 2;
            y = y * 2;
            // 移除所有空格
            const stringWithoutSpaces = str.replace(/\s+/g, '');
            // 截取指定数量的字符
            const extractedChars = stringWithoutSpaces.substring(x, x + y);
            // 将提取的字符按照原始字符串中的空格重新格式化
            const formattedChars = extractedChars.match(/.{1,2}/g).join(' ');
            return formattedChars;
        },
        removeDuplicatesById(array) { // 根据id去重
            //console.log(array);
            const uniqueArray = array.reduce((acc, current) => {
                // 检查累加器数组中是否已经存在具有相同id的对象
                const exists = acc.some(item => item.id === current.id);
                // 如果不存在，则添加到累加器数组中
                if (!exists) {
                    acc.push(current);
                }
                return acc;
            }, []);
            return uniqueArray.sort((a, b) => a.id - b.id);;
        },
        timeDifference(targetTimeStr) { // 计算时间差
            // 获取当前时间
            const currentTime = new Date();
            // 计算当前时间前推30天的时间
            const time30DaysAgo = new Date(currentTime);
            time30DaysAgo.setDate(currentTime.getDate() - 30);

            // 将目标时间字符串转换为Date对象
            const targetTime = new Date(targetTimeStr);

            // 计算时间差（以毫秒为单位）
            const differenceInMilliseconds = targetTime - time30DaysAgo;

            // 将时间差转换为天数
            const days = Math.floor(differenceInMilliseconds / (1000 * 60 * 60 * 24));
            // 将剩余的毫秒数转换为小时数
            const hours = Math.floor((differenceInMilliseconds % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

            // 返回格式化的字符串
            return `${days}天${hours}小时`;
        },
        echartShow() { // echart图表展示
            if (this.cmdCurrent.length == 0) {
                this.$message.error('请选择日志类型！');
                return;
            }
            //console.log(this.cmdCurrent);
            var _this = this;
            let getdata = {
                Data: this.multipleSelection,
                Start_Time: this.formatDate(this.pickerDate[0], true),
                End_Time: this.formatDate(this.pickerDate[1], false),
                CommandType: this.cmdCurrent,
            };
            this.echartVis = true;
            $.ajax({
                url: '/api/LowerMachineLog/BingTu',
                type: 'POST',
                contentType: 'application/x-www-form-urlencoded',
                data: { QueryData: JSON.stringify(getdata) },
                success: function (res) {
                    //console.log(res);
                    //return;
                    if (res.isok) {

                        optioncircular.series[0].data = res.response.rx;
                        optioncircular2.series[0].data = res.response.tx;
                        optionbar.series[0].data = res.response.rX_EVERY_Hour;
                        optionbar.series[1].data = res.response.tX_EVERY_Hour;
                        optionbar.series[2].data = res.response.rtX_EVERY_Hour;
                        optionbar.xAxis[0].data = generateHourlyIntervals(_this.pickerDate[0], _this.pickerDate[1]);

                        let singleTickValue = processNumber(Math.max(...res.response.rtX_EVERY_Hour));
                        /*let singleTickValueR = Math.max(...res.response.rX_EVERY_Hour);
                        let singleTickValueT = Math.max(...res.response.tX_EVERY_Hour);*/
                        /*if (singleTickValueR > singleTickValueT) {
                            optionbar.yAxis[0].max = processNumber(singleTickValueR);
                            optionbar.yAxis[1].max = processNumber(singleTickValueR);
                        } else {
                            optionbar.yAxis[0].max = processNumber(singleTickValueT);
                            optionbar.yAxis[1].max = processNumber(singleTickValueT);
                        }*/
                        //console.log(optionbar)
                        optionbar.yAxis[0].max = singleTickValue;
                        optionbar.yAxis[1].max = singleTickValue;
                        optionbar.yAxis[2].max = singleTickValue;

                        //console.log(optionbar)
                        if (optioncircular && typeof optioncircular === 'object') {
                            //console.log(optioncircular);
                            myChartcircular.setOption(optioncircular);
                        }
                        if (optioncircular2 && typeof optioncircular2 === 'object') {
                            myChartcircular2.setOption(optioncircular2);
                        }
                        if (optionbar && typeof optionbar === 'object') {
                            myChartbar.setOption(optionbar);
                        }
                        //console.log(option);
                        if (option && typeof option === 'object') {
                            myChart.setOption(option);
                        }

                        _this.$message({
                            message: '图表加载中，请稍候...',
                            type: 'success'
                        });

                    } else {
                        _this.$message.error(res.message + '！');
                    }
                },
                error: function (error) {
                    _this.$message.error('失败，请稍后再试');
                }
            });
        },
        analyzeLogs(row) { // 解析日志
            console.log(row);
            this.logAnalysisList = [];
            const bytes = row.data.split(' ');
            const cmdType = row.commandTypeVal;
            const upload = row.sendOrReceive === "主机->服务器";
            if (cmdType == "0E" && upload) {
                const num = parseInt(bytes[22], 16); // 获取数据块数量
                const startIndex = 23; // 数据起始位置
                for (let i = 0; i < num; i++) {
                    const baseIndex = startIndex + i * 6;
                    const type = bytes[baseIndex];

                    const loopNum16 = bytes[baseIndex + 3].toString() + bytes[baseIndex + 2].toString();
                    const loopNum = parseInt(loopNum16, 16);

                    const state = bytes.slice(baseIndex, baseIndex + 6);

                    let analysis = {
                        key: '',
                        value: '',
                        data: state.join(' '),
                    };
                    // 按设备类型解析
                    switch (type) {
                        case "04": // 服务信息
                            analysis.key = '服务信息'
                            analysis.value = `回路:${loopNum} 状态:${state[4]} - `;
                            if (loopNum == 1) {
                                analysis.value += state[4] == "01" ? "入住开" : "入住关";
                            } else if (loopNum === 2) {
                                analysis.value += state[4] == "01" ? "勿扰开" : "勿扰关";
                            } else if (loopNum === 3) {
                                analysis.value += state[4] == "01" ? "清理开" : "清理关";
                            } else if (loopNum === 4) {
                                analysis.value += state[4] == "01" ? "呼叫开" : "呼叫关";
                            } else if (loopNum === 5) {
                                analysis.value += state[4] == "01" ? "洗衣开" : "洗衣关";
                            } else if (loopNum === 6) {
                                analysis.value += state[4] == "01" ? "退房开" : "退房关";
                            } else if (loopNum === 7) {
                                analysis.value += state[4] == "01" ? "稍后开" : "稍后关";
                            } else if (loopNum === 8) {
                                analysis.value += state[4] == "01" ? "SOS开" : "SOS关";
                            } else if (loopNum === 9) {
                                analysis.value += state[4] == "01" ? "送餐开" : "送餐关";
                            } else if (loopNum === 10) {
                                analysis.value += state[4] == "01" ? "开锁开" : "开锁关";
                            } else if (loopNum === 11) {
                                analysis.value += state[4] == "01" ? "行李开" : "行李关";
                            } else if (loopNum === 12) {
                                analysis.value += state[4] == "01" ? "保险箱开" : "保险箱关";
                            } else if (loopNum === 13) {
                                analysis.value += state[4] == "01" ? "门磁开" : "门磁关";
                            } else {
                                analysis.value = `未知服务:0x${loopNum.toString(16)}状态:${state[4]}`;
                            }
                            break;
                        default:
                            //analysis.value = `未识别类型:${type}`;
                            analysis.key = '回路'
                            analysis.value = '回路编号' + convertHexString(analysis.data);
                    }
                    this.logAnalysisList.push(analysis);
                }

                if ((bytes.length - (num * 6) - 23) > 5) {
                    const startIndex = (num * 6) + 24; // 数据起始位置
                    const num2 = parseInt(bytes[startIndex - 1], 16); // 获取数据块数量
                    /*console.log("bytes", bytes);
                    console.log("startIndex", startIndex);*/

                    for (let i = 0; i < num2; i++) {
                        const baseIndex2 = startIndex + i * 6;

                        const state = bytes.slice(baseIndex2, baseIndex2 + 6);

                        let analysis = {
                            key: '',
                            value: '',
                            data: state.join(' '),
                        };

                        analysis.key = 'Error'
                        analysis.value = '' + analysis.data;

                        this.logAnalysisList.push(analysis);
                    }
                }
            }
            if (cmdType == "B1" && upload) {
                const bytes = row.data.split(' ');
                // 定义协议字段数组，包含字段名、长度和解析类型

                let offset = 15; // 从字节数组的第16个元素开始对应P0

               

                for (let i = 0; i < fields.length; i++) {
                    const field = fields[i];
                    const endIndex = offset + field.length;
                    // 检查是否超出数组范围
                    if (endIndex > bytes.length) {
                        console.error(`解析B1指令时超出数组范围: 需要索引 ${endIndex}, 但数组长度仅为 ${bytes.length}`);
                        break;
                    }
                    const segment = bytes.slice(offset, endIndex);
                    const dataStr = segment.join(' ');

                    let value = '';
                    // 根据字段类型解析值
                    switch (field.type) {
                        case "decimal":
                            value = hexToDecimal(segment);
                            break;
                        case "ip":
                            value = hexToIP(segment);
                            break;
                        case "mac":
                            value = hexToMAC(segment);
                            break;
                        case "ascii":
                            value = hexToASCII(segment);
                            break;
                        case "time":
                            value = hexToTime(segment);
                            break;
                        case "hex":
                            value = keepHex(segment);
                            break;
                        case "halfdecimal":
                            value = hexToHalfDecimal(segment);
                            break;
                        default:
                            value = "未知类型";
                    }

                    const analysis = {
                        key: field.name,
                        value: value,
                        data: dataStr
                    };
                    this.logAnalysisList.push(analysis);
                    offset = endIndex;
                }
            }
            if (cmdType == "01" && upload) {
                const bytes = row.data.split(' ');
                // 定义协议字段数组，包含字段名、长度和解析类型


                let offset = 15; // 从字节数组的第16个元素开始

                for (let i = 0; i < fields2.length; i++) {
                    const field2 = fields2[i];
                    const endIndex = offset + field2.length;
                    // 检查是否超出数组范围
                    if (endIndex > bytes.length) {
                        console.error(`解析01指令时超出数组范围: 需要索引 ${endIndex}, 但数组长度仅为 ${bytes.length}`);
                        break;
                    }
                    const segment = bytes.slice(offset, endIndex);
                    const dataStr = segment.join(' ');

                    let value = '';
                    // 根据字段类型解析值
                    switch (field2.type) {
                        case "decimal":
                            value = hexToDecimal(segment);
                            break;
                        case "ip":
                            value = hexToIP(segment);
                            break;
                        case "mac":
                            value = hexToMAC(segment);
                            break;
                        case "ascii":
                            value = hexToASCII(segment);
                            break;
                        case "port":
                            value = hexToPort(segment);
                            break;
                        case "threeByteDecimal":
                            value = hexToThreeByteDecimal(segment);
                            break;
                        default:
                            value = "未知类型";
                    }

                    const analysis = {
                        key: field2.name,
                        value: value,
                        data: dataStr
                    };
                    this.logAnalysisList.push(analysis);
                    offset = endIndex;
                }
            }
        },

    },
    created: function () { // 页面创建时执行

    },
    mounted: function () {
        this.getHotels();
        this.LoadingPic();



        /*let appval = JSON.parse(sessionStorage.getItem('appVal'));
        if (appval != null && appval != '' && appval != undefined) {
            const date1 = new Date();
            const date2 = new Date(appval.nowTime);
    
            // 计算两个时间之间的差异（以毫秒为单位）
            const diffInMilliseconds = Math.abs(date2 - date1);
            // 将毫秒转换为小时
            const diffInHours = diffInMilliseconds / (1000 * 60 * 60);
            if (diffInHours < 2) {
                this.pickerDate = appval.pickerDate;
                this.logs = appval.logs;
                this.visTabCol = appval.visTabCol;
                this.pageSize = appval.pageSize;
                this.currentPage = appval.currentPage;
                this.cmdCurrent = appval.cmdCurrent;
            }
        }*/
    },
    beforeDestroy: function () {

    },
});

// 页面加载时
window.onload = function () {
    AdjustWindow();
};

function AdjustWindow() { /* 调整窗口大小 */
    // 监听窗口大小变化事件
    if (window.innerWidth <= 888) {
        app.dialogw = "100%";
        document.getElementById('appleft').style.width = '100%';
        app.tableHeight = window.innerHeight - 10;
    } else {
        app.dialogw = "70%";
        document.getElementById('appleft').style.width = '47%';
        app.tableHeight = window.innerHeight - 177;
    }

}

function convertHexString(input) {
    // 分割字符串为数组
    const hexArray = input.split(' ');

    // 确保至少有3组十六进制数
    if (hexArray.length < 3) {
        throw new Error('输入字符串至少需要包含3组十六进制数');
    }

    // 取前3组
    const firstThree = hexArray.slice(0, 3);

    // 转换为十进制并格式化为3位数
    const decimalArray = firstThree.map(hex => {
        // 将十六进制转换为十进制
        const decimal = parseInt(hex, 16);
        // 格式化为3位数，前面补零
        return decimal.toString().padStart(3, '0');
    });

    // 拼接结果字符串
    return decimalArray.join(' ');
}

/* 懒加载对象列表 */
var connection = new signalR.HubConnectionBuilder().withUrl("/blw/datapush").build();

connection.on("ReceiveMessage", function (message) {
    // 处理收到的消息
    let rs = JSON.parse(message);
    let rowIndex = app.selectHotelRoom.findIndex(row => row.mac == rs.MAC);
    //console.log(rowIndex);
    if (rowIndex != -1) {
        // 更新这一行的TX值
        app.$set(app.selectHotelRoom[rowIndex], 'tx', rs.TX);
        app.$set(app.selectHotelRoom[rowIndex], 'rx', rs.RX);
        app.$set(app.selectHotelRoom[rowIndex], 'lastData', rs.LastData);
    } else {
        console.error('没有找到对应的mac地址:' + rs.MAC);
    }

});

connection.on("TakeCardReceiveMessage", function (message) {
    // 处理收到的消息
    //console.log(message);
    let rs = JSON.parse(message);
    let rowIndex = app.selectHotelRoom.findIndex(row => row.hostID == rs.HostID);
    //console.log(rowIndex);
    if (rowIndex != -1) {
        // 更新这一行的TX值
        let tcs = (rs.TakeCard_Status != 'True' && rs.TakeCard_Status != 'False') ? '' : rs.TakeCard_Status;
        app.$set(app.selectHotelRoom[rowIndex], 'TakeCard_Status', tcs);
        let iss = app.isSupply(rs.HostID, rs.LastDateTime);
        //console.log(iss);
        app.$set(app.selectHotelRoom[rowIndex], 'isSupply', iss);
    } else {
        console.error('没有找到对应的HostID:' + rs.HostID);
    }

});

connection.start().then(function () {
    //console.log("连接成功");
    // 连接成功
}).catch(function (error) {
    console.log("连接失败");
    // 连接失败
});


window.addEventListener('resize', function () { AdjustWindow() });

function generateHourlyIntervals(startDateStr, endDateStr) { /* 生成小时区间 */
    // 将日期字符串转换为Date对象
    const d1 = new Date(startDateStr);
    const d2 = new Date(endDateStr);

    // 计算两个日期的毫秒差
    const diffInMilliseconds = Math.abs(d2 - d1);
    let intervals = [];
    // 将毫秒差转换为天数
    const diffInDays = Math.round(diffInMilliseconds / (1000 * 60 * 60 * 24));


    for (let i = 0; i <= diffInDays; i++) {
        const resultDate = new Date(d1);
        resultDate.setDate(d1.getDate() + i);
        const d11 = formatDate(resultDate);
        for (let j = 1; j <= 24; j++) {
            intervals.push(`${d11}${j}时`);
        }
        /*if (i == 0) {
            const d11 = formatDate(d1);
            intervals = [`${d11}1时`, `${d11}2时`, '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24'];
        } else {
            const resultDate = new Date(d1);
            resultDate.setDate(d1.getDate() + i);
            const d11 = formatDate(resultDate);
            for (let j = 1; j <= 24; j++) {
                intervals.push(`${d11}${j}时`);
            }
            *//*intervals.push(`${d11}1时`, `${d11}2时`, `${d11}2时`, '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24');*//*
}*/
    }
    return intervals;
}
function formatDate(date) { // 格式化日期为mm月DD日
    const mm = (date.getMonth() + 1).toString(); // 获取月份
    const dd = date.getDate().toString(); // 获取日期
    return `${mm}月${dd}日`;
}


function processNumber(num) { // 处理数字，使其为整数
    // 将数字转换为字符串
    const numStr = num.toString();
    // 检查是否已经是除首位外其余所有位都为0的数
    if (/^\d0*$/.test(numStr)) {
        return num;
    }
    // 获取最高位
    const firstDigit = numStr[0];
    // 将最高位转换为数字并加1
    const newFirstDigit = parseInt(firstDigit, 10) + 1;
    // 获取最高位之后的数字长度
    const restLength = numStr.length - 1;
    // 构造新的数字字符串
    const newNumStr = newFirstDigit.toString() + '0'.repeat(restLength);
    // 将新的数字字符串转换回数字并返回
    return parseInt(newNumStr, 10);
}
// 辅助函数：按照小端序规则反转字节顺序（每两个字节为一组进行反转）
function littleEndianConvert(byteArray) {
    let result = [];
    for (let i = 0; i < byteArray.length; i += 2) {
        if (i + 1 < byteArray.length) {
            // 交换每对字节的顺序
            result.push(byteArray[i + 1]);
            result.push(byteArray[i]);
        } else {
            // 如果字节数为奇数，最后一个字节保持不变
            result.push(byteArray[i]);
        }
    }
    return result;
}

// 辅助函数：将十六进制字节数组转换为十进制字符串
function hexToDecimal(byteArray) {
    const converted = littleEndianConvert(byteArray);
    return converted.map(byte => parseInt(byte, 16).toString(10)).join('.');
}
// 辅助函数：将十六进制字节数组转换为十进制字符串
function hexToHalfDecimal(byteArray) {
    const converted = littleEndianConvert(byteArray.slice(0, 2));
    return parseInt(converted.map(byte => parseInt(byte, 16)).join(''), 16);
}

// 辅助函数：将十六进制字节数组转换为IP地址字符串
function hexToIP(byteArray) {
    const converted = byteArray;
    return converted.map(byte => parseInt(byte, 16).toString(10)).join('.');
}

// 辅助函数：将十六进制字节数组转换为MAC地址字符串
function hexToMAC(byteArray) {
    const converted = byteArray;
    return converted.map(byte => byte.toUpperCase()).join(':');
}

// 辅助函数：将十六进制字节数组转换为ASCII字符串
function hexToASCII(byteArray) {
    // 先进行小端序转换
    const converted = byteArray;
    // 转换为ASCII字符
    let result = '';
    for (let i = 0; i < converted.length; i++) {
        const charCode = parseInt(converted[i], 16);
        // 只处理可打印字符（32-126）和换行符（10）、回车符（13）
        if (charCode === 0) break; // 遇到空字符停止转换
        if (charCode >= 32 && charCode <= 126 || charCode === 10 || charCode === 13) {
            result += String.fromCharCode(charCode);
        } else {
            result += '.'; // 不可打印字符用点代替
        }
    }
    return result;
}
// 辅助函数：处理3字节的配置数据版本号
function hexToThreeByteDecimal(byteArray) {
    // 3字节需要特殊处理
    const converted = byteArray;
    // 将三个字节转换为十进制数，用点连接
    if (converted.length >= 3) {
        return converted.map(byte => parseInt(byte, 16).toString(10)).join('.');
    }
    return "无效版本号";
}

// 辅助函数：将十六进制字节数组转换为时间字符串
function hexToTime(byteArray) {
    // 先进行小端序转换
    const converted = byteArray;
    // 时间格式通常为年月日时分秒
    // 这里假设是6字节时间格式：年(2字节)、月、日、时、分、秒
    if (converted.length === 6) {
        const year = parseInt(converted[0] + converted[1], 16);
        const month = parseInt(converted[2], 16);
        const day = parseInt(converted[3], 16);
        const hour = parseInt(converted[4], 16);
        const minute = parseInt(converted[5], 16);
        return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
    }
    // 4字节时间格式可能只是年月日
    else if (converted.length === 4) {
        const year = parseInt(converted[0] + converted[1], 16);
        const month = parseInt(converted[2], 16);
        const day = parseInt(converted[3], 16);
        return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
    }
    // 其他长度直接返回十六进制字符串
    return converted.map(byte => byte.toUpperCase()).join('');
}

// 辅助函数：保留十六进制格式
function keepHex(byteArray) {
    const converted = byteArray;
    return converted.map(byte => byte.toUpperCase()).join('');
}

/* echarts */
/* 饼图js */
var domcircular = document.getElementById('circular-echart');
var myChartcircular = echarts.init(domcircular, null, {
    renderer: 'canvas',
    useDirtyRect: false
});

var optioncircular = {
    title: {
        text: 'RX',
        subtext: '',
        left: 'center'
    },
    tooltip: {
        trigger: 'item'
    },
    legend: {
        orient: 'vertical',
        left: 'left'
    },
    series: [
        {
            name: 'RX',
            type: 'pie',
            radius: '50%',
            data: [],
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
    ]
};

/*if (optioncircular && typeof optioncircular === 'object') {
    myChartcircular.setOption(optioncircular);
}
*/

/* 饼图js */
var domcircular2 = document.getElementById('circular-echart2');
var myChartcircular2 = echarts.init(domcircular2, null, {
    renderer: 'canvas',
    useDirtyRect: false
});

var optioncircular2 = {
    title: {
        text: 'TX',
        subtext: '',
        left: 'center'
    },
    tooltip: {
        trigger: 'item'
    },
    legend: {
        orient: 'vertical',
        left: 'left'
    },
    series: [
        {
            name: 'TX',
            type: 'pie',
            radius: '50%',
            data: [],
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
    ]
};

/*if (optioncircular2 && typeof optioncircular2 === 'object') {
    myChartcircular2.setOption(optioncircular2);
}*/


window.addEventListener('resize', myChartcircular.resize);
window.addEventListener('resize', myChartcircular2.resize);


/* 柱状图js */
var dombar = document.getElementById('bar-echart');
var myChartbar = echarts.init(dombar, null, {
    renderer: 'canvas',
    useDirtyRect: false
});

const colorsbar = ['#5470C6', '#91CC75', '#EE6666'];

var optionbar = {
    color: colorsbar,
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross'
        }
    },
    grid: {
        right: '20%'
    },
    toolbox: {
        feature: {
            dataView: { show: true, readOnly: false },
            saveAsImage: { show: true }
        }
    },
    legend: {
        data: ['RX', 'TX', 'ALL']
    },
    xAxis: [
        {
            type: 'category',
            axisTick: {
                alignWithLabel: true
            },
            // prettier-ignore
            data: []
        }
    ],
    yAxis: [
        {
            type: 'value',
            name: 'RX',
            position: 'right',
            alignTicks: true,
            axisLine: {
                show: true,
                lineStyle: {
                    color: colorsbar[0]
                }
            },
            axisLabel: {
                formatter: '{value}'
            },
            min: 0,
        },
        {
            type: 'value',
            name: 'TX',
            position: 'right',
            alignTicks: true,
            offset: 80,
            axisLine: {
                show: true,
                lineStyle: {
                    color: colorsbar[1]
                }
            },
            axisLabel: {
                formatter: '{value}'
            },
            min: 0,
        },
        {
            type: 'value',
            name: 'ALL',
            position: 'left',
            alignTicks: true,
            axisLine: {
                show: true,
                lineStyle: {
                    color: colorsbar[2]
                }
            },
            axisLabel: {
                formatter: '{value}'
            },
            min: 0,
        }
    ],
    series: [
        {
            name: 'RX',
            type: 'bar',
            data: []
        },
        {
            name: 'TX',
            type: 'bar',
            yAxisIndex: 1,
            data: []
        },
        {
            name: 'ALL',
            type: 'line',
            yAxisIndex: 2,
            data: []
        }
    ]
};

/*if (optionbar && typeof optionbar === 'object') {
    myChartbar.setOption(optionbar);
}
*/
window.addEventListener('resize', myChartbar.resize);



/* 横置条形图 */
var dom = document.getElementById('profile-echart');
var myChart = echarts.init(dom, null, {
    renderer: 'canvas',
    useDirtyRect: false
});
var data = [];
var dataCount = 50;
var startTime = +new Date();
var categories = ['testA', 'testB'];
var types = [
    { name: 'JS Heap', color: '#7b9ce1' },
    { name: 'Documents', color: '#bd6d6c' },
    { name: 'Nodes', color: '#75d874' },
    { name: 'Listeners', color: '#e0bc78' },
    { name: 'GPU Memory', color: '#dc77dc' },
    { name: 'GPU', color: '#72b362' }
];

// Generate mock data 造数据
categories.forEach(function (category, index) {
    var baseTime = startTime;
    for (var i = 0; i < dataCount; i++) {
        var typeItem = types[Math.round(Math.random() * (types.length - 1))];
        var duration = Math.round(Math.random() * 100);
        data.push({
            name: typeItem.name,
            value: [index, baseTime, (baseTime += duration), duration],
            itemStyle: {
                normal: {
                    color: typeItem.color
                }
            }
        });
        baseTime += Math.round(Math.random() * 20);
    }
});
function renderItem(params, api) {
    var categoryIndex = api.value(0);
    var start = api.coord([api.value(1), categoryIndex]);
    var end = api.coord([api.value(2), categoryIndex]);
    var height = api.size([0, 1])[1] * 0.6;
    var rectShape = echarts.graphic.clipRectByRect(
        {
            x: start[0],
            y: start[1] - height / 2,
            width: end[0] - start[0],
            height: height
        },
        {
            x: params.coordSys.x,
            y: params.coordSys.y,
            width: params.coordSys.width,
            height: params.coordSys.height
        }
    );
    return (
        rectShape && {
            type: 'rect',
            transition: ['shape'],
            shape: rectShape,
            style: api.style()
        }
    );
}

var option = {
    tooltip: {
        formatter: function (params) {
            return params.marker + params.name + ': ' + params.value[3] + ' ms';
        }
    },
    title: {
        text: 'Profile',
        left: 'center'
    },
    dataZoom: [
        {
            type: 'slider',
            filterMode: 'weakFilter',
            showDataShadow: false,
            top: 400,
            labelFormatter: ''
        },
        {
            type: 'inside',
            filterMode: 'weakFilter'
        }
    ],
    grid: {
        height: 300
    },
    xAxis: {
        min: startTime,
        scale: true,
        axisLabel: {
            formatter: function (val) {
                return Math.max(0, val - startTime) + ' ms';
            }
        }
    },
    yAxis: {
        data: categories
    },
    series: [
        {
            type: 'custom',
            renderItem: renderItem,
            itemStyle: {
                opacity: 0.8
            },
            encode: {
                x: [1, 2],
                y: 0
            },
            data: data
        }
    ]
};

/*
if (option && typeof option === 'object') {
    myChart.setOption(option);
}*/

window.addEventListener('resize', myChart.resize);