const visTabCols = ['时间', '酒店名', '房间号', 'Mac地址', '主机编号', 'IP', 'Port', '间隔', '方向', '日志', '帧号', '命令',];
var app = new Vue({
    el: '#app',
    data() {

        return {
            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); // 减去1小时
                        picker.$emit('pick', [start, end]);
                    }
                },
                {
                    text: '3小时内',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 3); // 减去3小时
                        picker.$emit('pick', [start, end]);
                    }
                },
                {
                    text: '12小时内',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 12); // 减去12小时
                        picker.$emit('pick', [start, end]);
                    }
                },
                {
                    text: '24小时内',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24); // 减去24小时
                        picker.$emit('pick', [start, end]);
                    }
                },
                {
                    text: '72小时内',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 72); // 减去72小时
                        picker.$emit('pick', [start, end]);
                    }
                }]
            }, // 日期选择器
            hotelCurrent: null, // 选中的酒店ID
            allHotel: [], // 所有酒店列表
            hotels: [], // 酒店列表
            roomCurrent: null, // 选中的房间ID
            isTheRoomGet: false, // 是否获取了房间列表
            allRoom: [], // 所有房间列表
            rooms: [], // 房间列表
            pickerDate: [(new Date().getTime() - 3600 * 1000), 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, // 状态列表
            activeName: 1, // 当前激活的tab
            logData: null, // 日志数据
            errLogs: null, // 错误日志
            onlyCorrect: false, // 是否只显示正确的日志
            onlyCorrectErr: 0, // 错误日志数量
            onlyCorrectAll: 0, // 总日志数量
            activeTxt: '异常', // 有数据提示
            inactiveTxt: '全部', // 无数据提示
            elcarddialogVisible: false, // 是否显示弹窗
            selectedItem: {}, // 当前选中项
            nowMethodName: '', // 当前方法名
            nowMethodValue: '', // 当前方法内容
            openRowDialog: false, // 是否打开行弹窗
            selectedTime: null, // 当前打开页面的分时段数据
        };
    },
    watch: {
        onlyCorrect: {
            handler: function (newVal, oldVal) {
                //console.log(newVal);
                if (newVal) {
                    this.logs = JSON.parse(JSON.stringify(this.errLogs));
                } else {
                    this.logs = JSON.parse(JSON.stringify(this.logData));
                }
            }
        },
        logs: {
            handler: function (newVal, oldVal) {
                if (newVal.length > 0) {
                    this.multipleBtn = false;
                } else {
                    this.multipleBtn = true;
                }
                /* if (newVal.length >= 0 && this.allHotel.length > 0) {
                     this.isReady = true; // 页面加载完毕，设置isReady为true，显示页面内容
                     this.loading.close();
                 }*/
            }
        },
        allHotel: {
            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.showSelectedLogs();
                    this.isReady = true; // 页面加载完毕，设置isReady为true，显示页面内容
                    this.loading.close();
                }
            }
        },
        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.showSelectedLogs();
        },
        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.RoomNumber = room.roomno;
                room.hotelID = app.hotelCurrent.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_IOT_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 = {
                Start_Time: this.dateStr(this.pickerDate[0]),
                End_Time: this.dateStr(this.pickerDate[1]),
            };
            //console.log(getdata)
            //return;
            this.LoadingPic();

            $.ajax({
                url: '/api/LowerMachineLog/Get_WebAPILog',
                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)).map(method => ({
                            ...method,
                            codeInvokeData: method.codeInvokeData.map(codeItem => ({
                                ...codeItem,
                                hotelNameAndCode: _this.findNameByCode(codeItem.hotelCode)
                            }))
                        }));;

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

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

        },
        showRowLogs(type, row) { // 显示详细日志

            var _this = this;

            if (type == 'hotelcode') {
                getdata = {
                    Start_Time: this.dateStr(this.pickerDate[0]),
                    End_Time: this.dateStr(this.pickerDate[1]),
                    Data: [{
                        MethodName: this.selectedItem.methodName,
                        HotelCode: row.hotelCode,
                    }],
                };
            } else if (type == 'ip') {
                getdata = {
                    Start_Time: this.dateStr(this.pickerDate[0]),
                    End_Time: this.dateStr(this.pickerDate[1]),
                    Data: [{
                        MethodName: this.selectedItem.methodName,
                        IP: row.ip,
                    }],
                };
            }

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

                        _this.nowMethodValue = JSON.parse(JSON.stringify(res.response)).map(codeItem => ({
                            ...codeItem,
                            hotelNameAndCode: _this.findNameByCode(codeItem.hotelCode)
                        }));

                        _this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        _this.openRowDialog = true;

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

        },
        getHotelRooms() { // 获取酒店房间列表
            var _this = this;
            $.ajax({
                url: '/api/LowerMachineLog/GetAll_MonitorIOT',
                type: 'POST',
                contentType: 'application/json',
                success: function (res) {
                    //console.log(res);
                    /*app.isReady = true;
                    app.loading.close();
                    return;*/
                    if (res.isok) {
                        /*let cmd = res.response.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.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.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 * 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`;
            }

        },
        dateStr(date) { // 时间戳转换
            date = new Date(date);
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            const seconds = date.getSeconds().toString().padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

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

        },
        findNamesByCode(code) { // 根据ID查找酒店名称
            //console.log(code);
            let rs = null;
            this.allHotel.forEach(Item => {
                // 如果数据项的值与对照表的键相等
                if (code == Item.code) {
                    // 将对照表的值返回
                    rs = Item.name;
                    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 = this.dateStr(this.pickerDate[0]);
            let End = this.dateStr(this.pickerDate[1]);
            link.download = this.nowMethodValue[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}小时`;
        },
        calculateTimeDifference(startTime, endTime) { // 计算时间差
            const start = new Date(startTime);
            const end = new Date(endTime);
            return Math.abs(end - start);
        },
        cardOpenDialog(item) { // 打开弹窗
            //console.log(item);
            //this.nowMethodName = item.methodName
            this.selectedItem = item;
            this.selectedTime = [];
            this.LoadingPic();
            var _this = this;
            let getdata = {
                Start_Time: this.dateStr(this.pickerDate[0]),
                End_Time: this.dateStr(this.pickerDate[1]),
                Data: [{
                    MethodName: this.selectedItem.methodName,
                }],
            };
            $.ajax({
                url: '/api/LowerMachineLog/Get_WebAPISliceLog',
                type: 'POST',
                contentType: 'application/x-www-form-urlencoded',
                data: { QueryData: JSON.stringify(getdata) },
                success: function (res) {
                    /*console.log(res);
                    return;*/
                    if (res.isok) {
                        _this.selectedTime = res.response;
                        console.log(_this.selectedTime);
                        _this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        _this.loading.close();
                        
                        _this.elcarddialogVisible = true;
                    } else {
                        _this.$message.error(res.message + '！');
                        app.loading.close();
                    }
                },
                error: function (error) {
                    _this.$message.error('失败，请稍后再试');
                    app.loading.close();
                }
            });
            
        },
        viewCodeRowData(row) { // 查看酒店编码行的具体数据
            //console.log(row);
            this.showRowLogs("hotelcode", row);
        },
        viewIPRowData(row) { // 查看IP行的具体数据
            //console.log(row);
            this.showRowLogs("ip", row);
        },

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

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

    },
    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 = "50%";
        //document.getElementById('appleft').style.width = '47%';
        app.tableHeight = window.innerHeight - 177;
    }

}





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


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



