<template>
    <div id="index" ref="appRef" :class="{ pageisScale: true }" class="index_ssjc index_bbgl"
        style="background-image: url('../../assets/bigScreen/img/bg.png')">
        <div class="bg">
            <dv-loading v-if="loading">Loading...</dv-loading>
            <div v-else class="host-body">
                <!-- 头部 s -->
                <div class="d-flex jc-center title_wrap">
                    <div class="zuojuxing"></div>
                    <div class="youjuxing"></div>
                    <div class="guang"></div>
                    <div class="d-flex jc-center">
                        <div class="title">
                            <span class="title-text">
                                <img :src="logo" class="logo"
                                    style="vertical-align: middle; width: 50px; margin-top: -5px; margin-left: 100px"
                                    alt="" />
                                {{ gongsi }}云平台
                            </span>
                            <div style="float: right">
                                <div style="position: relative; color: #fff; display: flex; align-items: center">
                                    <el-badge style="height: 40px; width: 40px" :value="unreadCount">
                                        <img @click="toggleTooltip" src="../../assets/bigScreen/img/通知.png" alt="用户"
                                            class="user-icon" />
                                    </el-badge>

                                    <div v-if="showTooltip" class="tooltip" @click.stop>
                                        <div class="gjcontainer">
                                            <div class="gjitem">
                                                <h2
                                                    style="color: #00ff6f; font-weight: 700; font-size: 28px; padding-top: 15px">
                                                    {{ alarmCountData[0].count }}
                                                </h2>
                                                <span>{{ alarmCountData[0].name }}</span>
                                            </div>
                                            <div class="gjitem">
                                                <h2
                                                    style="color: #ffcb2f; font-weight: 700; font-size: 28px; padding-top: 15px">
                                                    {{ alarmCountData[1].count }}
                                                </h2>
                                                <span>{{ alarmCountData[1].name }}</span>
                                            </div>
                                            <div class="gjitem">
                                                <h2 style="color: #ff504d; font-weight: 700; font-size: 28px">
                                                    {{ alarmCountData[2].count }}
                                                </h2>
                                                <span>{{ alarmCountData[2].name }}</span>
                                            </div>
                                        </div>

                                        <button
                                            style="width: 159px; height: 39px; background-color: #0076b0; color: #fff; border: none"
                                            v-if="userRole === 'admin'" @click="handleButtonClick">告警详情</button>
                                    </div>

                                    <div style="float: right; margin-left: 10px; display: flex; align-items: center">
                                        <img src="../../assets/bigScreen/img/头像@2x.png" alt="设置"
                                            style="width: 20px; height: 20px; margin-right: 5px" class="setting-icon" />
                                        <span>{{ userName }}</span>

                                        <el-dropdown>
                                            <span class="el-dropdown-link">
                                                <img src="../../assets/bigScreen/img/arrow-down-s-fill@2x.png" alt="设置"
                                                    style="width: 20px; height: 20px; margin-right: 5px; vertical-align: middle" />
                                            </span>
                                            <el-dropdown-menu
                                                style="background-color: #113160; color: #fff; border-color: #113160"
                                                slot="dropdown">
                                                <router-link to="/index">
                                                    <el-dropdown-item
                                                        style="background-color: #113160; color: #fff; border-color: #113160">
                                                        返回后台
                                                    </el-dropdown-item>
                                                </router-link>
                                                <el-dropdown-item @click.native="logout"
                                                    style="background-color: #113160; color: #fff">
                                                    退出系统
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </el-dropdown>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="timers">
                        {{ dateYear }} {{ dateWeek }} {{ dateDay }}
                        <i class="blq-icon-shezhi02" style="margin-left: 10px" @click="showSetting"></i>
                    </div>
                </div>

                <!-- 内容  s-->

                <div class="nr">

                    <div class="cebianlan card-ssjc">
                        <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small"
                            prefix-icon="el-icon-search" style="margin-bottom: 20px;" />
                        <div>
                            <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
                                :filter-node-method="filterNode" ref="tree" node-key="id" :default-expand-all="false"
                                highlight-current @node-click="handleNodeClick" />
                        </div>
                    </div>

                    <div class="bbgl-right" style="width: 100%">
                        <el-card class="top-bbgl bbgl-form" body-style="padding:0">
                            <el-form ref="queryForm" :inline="true" :model="searchData" label-width="96px">
                                <el-form-item label="设备名称" prop="classifyId">
                                    <el-select popper-class="bbgl-select" v-model="searchData.deviceName" clearable
                                        placeholder="请选择设备" style="width: 200px" @change="handleDevDeviceChange">
                                        <el-option v-for="(item, index) in classifyList" :key="index"
                                            :label="item.deviceName" :value="item.deviceName" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="时间区间" prop="date">
                                    <!-- :picker-options="pickerOptions" -->
                                    <el-date-picker v-model="searchData.date" end-placeholder="结束日期" format="yyyy-MM-dd"
                                        range-separator="至" start-placeholder="开始日期" style="width: 225px"
                                        type="daterange" value-format="yyyy-MM-dd"></el-date-picker>
                                </el-form-item>
                                <el-form-item label="设备产品" prop="selectedProduct">
                                    <el-select popper-class="bbgl-select" v-model="searchData.selectedProduct"
                                        placeholder="请选择关联产品" clearable style="width: 200px">
                                        <el-option v-for="item in productList" :key="item.value"
                                            :label="item.productName" :value="item.productName" />
                                    </el-select>
                                </el-form-item>

                                <el-form-item>
                                    <el-button style="margin-left: 30px; background-color: #153768; border: 0"
                                        :loading="buttonLoading" icon="el-icon-search" size="mini" type="primary"
                                        @click="search">{{ $t('search') }}</el-button>
                                    <el-button style="background-color: #053352; border: 0; color: #fff"
                                        :loading="buttonLoading" icon="el-icon-refresh" size="mini"
                                        @click="resetData">{{ $t('reset') }}</el-button>
                                </el-form-item>

                                <el-button
                                    style="background-color: #153768; margin-left: 10px; margin-top: 5px; border: none"
                                    width="150px" size="mini" type="primary" @click="exportToExcel">导出为Excel</el-button>

                            </el-form>
                        </el-card>

                        <el-card class="bottom-bbgl">
                            <div style="height: 100%">
                                <el-table class="bbgl-table" :data="tempDataList" style="width: 100%;"
                                    :header-cell-style="{ fontSize: '16px', backgroundColor: '#153768', color: '#fff', fontWeight: 'bold', textAlign: 'center' }"
                                    title="所有告警数据">
                                    <el-table-column label="告警名称" align="center" prop="alertName" />
                                    <el-table-column label="设备编号" align="center" prop="serialNumber" />
                                    <el-table-column label="设备名称" align="center" prop="deviceName" />
                                    <el-table-column label="告警级别" align="center" prop="alertLevel" width="120">
                                        <template slot-scope="scope">
                                            <dict-tag :options="dict.type.iot_alert_level"
                                                :value="scope.row.alertLevel" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="告警时间" align="center" prop="createTime" width="170">
                                        <template slot-scope="scope">
                                            <span>{{
                                                parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}')
                                                }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="数据" align="left" header-align="center" prop="detail">
                                        <template slot-scope="scope">
                                            <div v-html="formatDetail(scope.row.detail)"></div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="处理状态" align="center" prop="status">
                                        <template slot-scope="scope">
                                            <dict-tag :options="dict.type.iot_process_status"
                                                :value="scope.row.status" />
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </el-card>
                    </div>
                </div>
                <!-- 内容 e -->
                <div class="button-container">
                    <button class="button" @mouseover="hover = true" @mouseleave="hover = false"
                        @click="changePage('home')">数据大屏</button>

                    <button class="button" @mouseover="hover = true" @mouseleave="hover = false"
                        @click="changePage('gjzx')">实时监控</button>

                    <button class="button" @mouseover="hover = true" @mouseleave="hover = false"
                        @click="changePage('ssjc')">告警中心</button>

                    <button class="button" @mouseover="hover = true" @mouseleave="hover = false"
                        @click="changePage('bbgl')">报表管理</button>
                </div>
            </div>
        </div>
        <Setting ref="setting" />
    </div>
</template>

<script>
import drawMixin from '../../utils/bigScreen/drawMixin';
import { formatTime } from '../../utils/bigScreen/index.js';
import Setting from './setting.vue';
import index from './indexs/index.vue';
import { getDeptByuserId, getInfo } from '../../api/login';
import { listAlertLog, listAlertLogEchartsByType } from '../../api/iot/alertLog';
import { deptTreeSelect, listUser } from '../energy/api/energy/deviceAreaBinding';
import { getDeviceStatistic, getProductList } from '../../api/iot/device';
import { getDeviceRunningStatus, listThingsModel } from '@/api/iot/device';
import { listHistory, } from '@/api/iot/deviceLog';
import { cacheJsonThingsModel } from '@/api/iot/model';
import sysTable from './components/SysTable';
import * as XLSX from 'xlsx';


export default {
    dicts: ['iot_process_status', 'iot_alert_level'],
    mixins: [drawMixin],
    components: {
        Setting,
        index,
        sysTable,
    },
    data() {
        return {
            searchData: {
                deviceName: '',
                date: [],
                selectedProduct: '',
            },
            alarmCountData: [
                { name: '提醒', count: 0 },
                { name: '轻微', count: 0 },
                { name: '严重', count: 0 },
            ],
            productList: [],
            setTableData: [],
            classifyList: [],
            devIdentifierList: [],
            setTableColumns: [
                {
                    label: '设备名称',
                    prop: 'deviceName',
                    minWidth: '180',
                    align: 'center',
                    fixed: 'left',
                    showOverflowTooltip: true,
                },
                {
                    label: '采集时间',
                    prop: 'equipmentConPrice',
                    minWidth: '180',
                    align: 'center',
                    showOverflowTooltip: true,
                },
            ],
            setTableColumnsCopy: [
                {
                    label: '设备名称',
                    prop: 'deviceName',
                    minWidth: '180',
                    align: 'center',
                    fixed: 'left',
                    showOverflowTooltip: true,
                },
                {
                    label: '采集时间',
                    prop: 'equipmentConPrice',
                    minWidth: '180',
                    align: 'center',
                    showOverflowTooltip: true,
                },
            ],
            datalist: [],
            showTooltip: false, // 控制弹出框显示状态
            userRole: '',
            userName: '',
            unreadCount: 0,
            gongsi: '物联网',
            logo: '',
            timing: null,
            loading: true,
            dateDay: null,
            dateYear: null,
            dateWeek: null,
            weekday: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
            httpStr: '',
            //头部命名数据
            deviceStatistic: {},
            Qyynsb_date: null,
            //内容命名
            activeName: 'first',
            filterText: '',
            // 归属机构
            deptName: undefined,
            deptOptions: undefined,
            defaultProps: {
                children: 'children',
                label: 'name',
            },
            //传递数据对象
            queryParams: {
                deviceName: undefined,
                type: undefined,
                id: undefined,
                typeName: undefined,
                deviceNum: undefined,
                status: undefined,
                pageNum: 1,
                pageSize: 99999,
                deptId: undefined,
            }, //地区名称
            qb_name: '计量设备清单',
            //仪表类型数组
            sourceEnergy: [],
            //巡行状态数组
            sourceStatus: [
                { value: '1', label: '未激活' },
                { value: '2', label: '禁用' },
                { value: '3', label: '在线', },
                { value: '4', label: '离线' },
            ],
            // 总条数
            total: 0,
            //数据接收数组
            dataList: [],
            tempDataList: [],
            //from对象
            ruleForm: [
                {
                    deviceNum: undefined,
                    deviceName: undefined,
                    energyTypeName: undefined,
                    location: undefined,
                    district: undefined,
                    azwz: undefined,
                    status: undefined,
                    fkzt: undefined,
                },
            ],
            rules: {},
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            //组态还是数据
            zuandsj: true,
            open: false,
            radio1: '活动警告',
            buttonLoading: false,
            pageTotal: 0,
            staticList: [],
            allDataList: [],
            maxTotal: 0,
            maxTotalName: '',
            dataLists: []
        };
    },
    filters: {
        numsFilter(msg) {
            return msg || 0;
        },
    },
    computed: {},
    created() {
        this.getDeptTree();
        getInfo().then((res) => {
            this.userRole = res.roles[0];
            let deptId = res.user.deptId;
            let userId = res.user.userId;
            this.userName = res.user.userName;
            getDeptByuserId(userId, deptId).then((res) => {
                this.gongsi = res.data.deptName;
                this.logo = process.env.VUE_APP_BASE_API + res.data.logo;
            });
        });
        let data = {
            StartDate: '',
            endDate: '',
        };
        data.StartDate = new Date().toISOString().split('T')[0];

        data.endDate = data.StartDate; // 如果需要，可以设置相同的结束日期
        listAlertLogEchartsByType(data).then((rp) => {
            this.switper();
            this.getlist();
        });

        getProductList().then((res) => {
            this.productList = res.rows;
        })

        // 获取告警列表
        listAlertLog(this.queryParams).then((rp) => {
            this.alarmList = rp.rows;
            this.alarmList.forEach((item) => {
                this.unreadCount += 1;
                if (item.alertLevel === 1 && item.status === 2) {
                    this.alarmCountData[0].count += 1;
                } else if (item.alertLevel === 2 && item.status === 2) {
                    this.alarmCountData[1].count += 1;
                } else if (item.alertLevel === 3 && item.status === 2) {
                    this.alarmCountData[2].count += 1;
                } else {
                    this.unreadCount -= 1;
                }
            });
        });
    },
    mounted() {
        this.timeFn();
        this.cancelLoading();
        document.addEventListener('click', this.handleClickOutside); // 添加全局点击事件监听
        this.getAllDevice();
    },
    beforeDestroy() {
        document.removeEventListener('click', this.handleClickOutside); // 移除事件监听
    },
    watch: {
        // 根据名称筛选机构树
        deptName(val) {
            this.$refs.tree.filter(val);
        },
    },
    methods: {
        /**查询所有设备 */
        // 选择设备后
        handleDevDeviceChange(val) {
            this.searchData.deviceName = val;
        },
        getDevIdentifierList(deviceId) {
            const params = {
                deviceId: deviceId,
                pageNum: 1,
                pageSize: 9999,
            };
            listThingsModel(params).then((res) => {
                if (res.code === 200) {
                    this.devIdentifierList = res.rows;
                }
            });
        },
        resetData() {
            this.tempDataList = this.dataList;
            this.searchData = {
                classifyId: '',
                date: [],
            };
        },
        getDetailData() {
            // if (!this.searchData.classifyId) {
            //     this.$message({ message: '请选择查询的设备', type: 'warning' });
            //     this.buttonLoading = false;
            //     return false;
            // }
            // if (this.searchData.date.length === 0) {
            //     this.$message({ message: '请选择查询的日期', type: 'warning' });
            //     this.buttonLoading = false;
            //     return false;
            // }
            // getDevice(this.searchData.classifyId).then((response) => {
            //     this.getDeviceStatusWitchThingsModel(response);
            // });
        },
        /** 获取设备状态和物模型 **/
        async getDeviceStatusWitchThingsModel(response) {
            // 获取缓存物模型
            response.data.cacheThingsModel = await this.getCacheThingsModdel(response.data.productId);
            // 获取设备运行状态
            response.data.thingsModels = await this.getDeviceStatus(response.data);
            //分享设备过滤没有权限的物模型
            if (response.data.isOwner == 0) {
                for (let i = 0; i < response.data.thingsModels.length; i++) {
                    if (response.data.userPerms.indexOf(response.data.thingsModels[i].id) == -1) {
                        response.data.thingsModels.splice(i--, 1);
                    }
                }
            }
            // 格式化物模型，拆分出监测值,数组添加前缀
            this.formatThingsModel(response.data);
            this.form = response.data;
            this.isSubDev = this.form.subDeviceList && this.form.subDeviceList.length > 0;
            this.queryParams.slaveId = this.form.slaveId;
            this.queryParams.serialNumber = this.form.serialNumber;
            // 监测数据
            if (this.isSubDev) {
                this.staticList = this.form.cacheThingsModel['properties'].filter((item) => {
                    return item.tempSlaveId == this.queryParams.slaveId;
                });
            } else {
                this.staticList = this.form.staticList;
            }
            this.getListHistory();
            // // 解析设备摘要
            // if (this.form.summary != null && this.form.summary != '') {
            //   this.summary = JSON.parse(this.form.summary);
            // }
            // this.isSubDev = this.form.subDeviceList && this.form.subDeviceList.length > 0;
            // this.oldDeviceStatus = this.form.status;
            // this.loadMap();
            // //Mqtt订阅
            // this.connectMqtt();
            // this.mqttSubscribe(this.form);
        },
        /** 获取缓存物模型*/
        getCacheThingsModdel(productId) {
            return new Promise((resolve, reject) => {
                cacheJsonThingsModel(productId)
                    .then((response) => {
                        resolve(JSON.parse(response.data));
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
        /* 获取监测历史数据*/
        getListHistory() {
            this.loading = true;
            /*this.queryParams.serialNumber = this.queryParams.slaveId ? this.form.serialNumber + '_' + this.queryParams.slaveId : this.form.serialNumber;
            this.queryParams.beginTime = this.searchData.date[0] + ' 00:00:00';
            this.queryParams.endTime = this.searchData.date[1] + ' 23:59:59';
            this.queryParams.identifiers = this.searchData.identifiers;*/
            const data = {
                serialNumber: this.queryParams.slaveId ? this.form.serialNumber + '_' + this.queryParams.slaveId : this.form.serialNumber,
                beginTime: this.searchData.date[0] + ' 00:00:00',
                endTime: this.searchData.date[1] + ' 23:59:59',
                identifiers: this.searchData.identifiers,
            };

            listHistory(data).then((res) => {
                if (Object.keys(res.data).length === 0) {
                    this.setTableData = [];
                    this.buttonLoading = false;
                    return false;
                }
                for (let key in res.data) {
                    for (let i = 0; i < this.staticList.length; i++) {
                        if (key == this.staticList[i].id) {
                            this.setTableColumns.push({
                                label: this.staticList[i].name,
                                prop: this.staticList[i].id,
                                minWidth: '180',
                                align: 'center',
                                showOverflowTooltip: true,
                            });
                            this.dialogRadioList.push({
                                value: this.staticList[i].id,
                                text: this.staticList[i].name,
                            });
                            // 对象转数组
                            let dataList = [];
                            for (let j = 0; j < res.data[key].length; j++) {
                                let item = [];
                                item[0] = res.data[key][j].time;
                                item[1] = res.data[key][j].value;
                                item[2] = res.data[key][j].datetime;
                                item[3] = res.data[key][j].isMonitor;
                                item[4] = res.data[key][j].logType;
                                item[5] = res.data[key][j].mode;
                                item[6] = res.data[key][j].remark;
                                item[7] = res.data[key][j].identity;
                                dataList.push(item);
                            }
                            if (dataList.length > this.maxTotal) {
                                this.maxTotal = dataList.length;
                                this.maxTotalName = this.staticList[i].id;
                            }

                            this.allDataList[this.staticList[i].id] = dataList;
                        }
                    }
                }
                this.allDataList[this.maxTotalName].map((item, index) => {
                    const obj = {};
                    obj.deviceName = this.form.deviceName;
                    obj.deviceName = this.form.serialNumber;
                    obj.equipmentConPrice = item[0];
                    obj.equipmentConPrices = item[2];
                    obj.isMonitor = item[3];
                    obj.logType = item[4];
                    obj.mode = item[5];
                    obj.remark = item[6];
                    obj.identity = item[7];
                    obj.timeObj = {};
                    for (let keys in this.allDataList) {
                        const filterData = this.allDataList[keys].filter((items) => items[0] == item[0]);
                        if (filterData.length > 0) {
                            obj.timeObj[keys] = filterData[0][2];
                            obj[keys] = filterData[0][1];
                        } else {
                            obj[keys] = null;
                        }
                    }
                    this.setTableData.push(obj);
                });
                this.buttonLoading = false;
                this.loading = false;
            });
        },
        /**获取设备运行状态*/
        getDeviceStatus(data) {
            const params = {
                deviceId: data.deviceId,
                slaveId: data.slaveId,
            };
            return new Promise((resolve, reject) => {
                getDeviceRunningStatus(params)
                    .then((response) => {
                        resolve(response.data.thingsModels);
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
        formatDetail(json) {
            if (json == null || json == '') {
                return;
            }
            let item = JSON.parse(json);
            let result = 'id：<span style="color:#F56C6C">' + item.id + '</span><br />';
            result = result + 'value：<span style="color:#F56C6C">' + item.value + '</span><br />';
            return result;
        },
        formatThingsModel(data) {
            data.chartList = [];
            data.monitorList = [];
            data.staticList = [];
            // 物模型格式化
            for (let i = 0; i < data.thingsModels.length; i++) {
                // 数字类型设置默认值并转换未数值
                if (data.thingsModels[i].datatype.type == 'integer' || data.thingsModels[i].datatype.type == 'decimal') {
                    if (data.thingsModels[i].shadow == '') {
                        data.thingsModels[i].shadow = Number(data.thingsModels[i].datatype.min);
                    } else {
                        data.thingsModels[i].shadow = Number(data.thingsModels[i].shadow);
                    }
                }

                // 物模型分类放置
                if (data.thingsModels[i].datatype.type == 'array') {
                    if (data.thingsModels[i].datatype.arrayType == 'object') {
                        for (let k = 0; k < data.thingsModels[i].datatype.arrayParams.length; k++) {
                            for (let j = 0; j < data.thingsModels[i].datatype.arrayParams[k].length; j++) {
                                // 数组元素中参数ID添加前缀，例如：array_00_
                                let index = k > 9 ? String(k) : '0' + k;
                                let prefix = 'array_' + index + '_';
                                data.thingsModels[i].datatype.arrayParams[k][j].id = prefix + data.thingsModels[i].datatype.arrayParams[k][j].id;
                                // 图表、实时监测、监测统计分类放置
                                if (data.thingsModels[i].datatype.arrayParams[k][j].isChart == 1) {
                                    // 图表
                                    data.thingsModels[i].datatype.arrayParams[k][j].name = '[' + data.thingsModels[i].name + (k + 1) + '] ' + data.thingsModels[i].datatype.arrayParams[k][j].name;
                                    data.thingsModels[i].datatype.arrayParams[k][j].datatype.arrayType = 'object';
                                    data.chartList.push(data.thingsModels[i].datatype.arrayParams[k][j]);
                                    if (data.thingsModels[i].datatype.arrayParams[k][j].isHistory == 1) {
                                        // 监测统计
                                        data.staticList.push(data.thingsModels[i].datatype.arrayParams[k][j]);
                                    }
                                    if (data.thingsModels[i].datatype.arrayParams[k][j].isMonitor == 1) {
                                        // 实时监测
                                        data.monitorList.push(data.thingsModels[i].datatype.arrayParams[k][j]);
                                    }
                                    data.thingsModels[i].datatype.arrayParams[k].splice(j--, 1);
                                }
                            }
                        }
                    } else {
                        // 字符串拆分为物模型数组 model=id/name/type/isReadonly/value/shadow
                        let values = data.thingsModels[i].value != '' ? data.thingsModels[i].value.split(',') : [];
                        let shadows = data.thingsModels[i].shadow != '' ? data.thingsModels[i].shadow.split(',') : [];
                        for (let j = 0; j < data.thingsModels[i].datatype.arrayCount; j++) {
                            if (!data.thingsModels[i].datatype.arrayModel) {
                                data.thingsModels[i].datatype.arrayModel = [];
                            }
                            // 数组里面的ID需要添加前缀和索引，例如：array_00_temperature
                            let index = j > 9 ? String(j) : '0' + j;
                            let prefix = 'array_' + index + '_';
                            data.thingsModels[i].datatype.arrayModel[j] = {
                                id: prefix + data.thingsModels[i].id,
                                name: data.thingsModels[i].name,
                                type: data.thingsModels[i].type,
                                isReadonly: data.thingsModels[i].isReadonly,
                                value: values[j] ? values[j] : '',
                                shadow: shadows[j] ? shadows[j] : '',
                            };
                        }
                    }
                } else if (data.thingsModels[i].datatype.type == 'object') {
                    for (let j = 0; j < data.thingsModels[i].datatype.params.length; j++) {
                        // 图表、实时监测、监测统计分类放置
                        if (data.thingsModels[i].datatype.params[j].isChart == 1) {
                            // 图表
                            data.thingsModels[i].datatype.params[j].name = '[' + data.thingsModels[i].name + '] ' + data.thingsModels[i].datatype.params[j].name;
                            data.chartList.push(data.thingsModels[i].datatype.params[j]);
                            if (data.thingsModels[i].datatype.params[j].isHistory == 1) {
                                // 监测统计
                                data.staticList.push(data.thingsModels[i].datatype.params[j]);
                            }
                            if (data.thingsModels[i].datatype.params[j].isMonitor == 1) {
                                // 实时监测
                                data.monitorList.push(data.thingsModels[i].datatype.params[j]);
                            }
                            data.thingsModels[i].datatype.params.splice(j--, 1);
                        }
                    }
                } else if (data.thingsModels[i].isChart == 1) {
                    // // 图表、实时监测、监测统计分类放置
                    data.chartList.push(data.thingsModels[i]);
                    if (data.thingsModels[i].isHistory == 1) {
                        // 监测统计
                        data.staticList.push(data.thingsModels[i]);
                    }
                    if (data.thingsModels[i].isMonitor == 1) {
                        // 实时监测
                        data.monitorList.push(data.thingsModels[i]);
                    }
                    // 使用i--解决索引变更问题
                    data.thingsModels.splice(i--, 1);
                }
            }
        },
        getlist() {
            listAlertLog(this.queryParams).then((rp) => {
                this.dataList = rp.rows;
                this.total = rp.total;

                // 初始化tempDataList为dataList的副本
                this.tempDataList = [...this.dataList];

                // 从dataList中提取唯一的设备名称构建classifyList
                this.classifyList = this.dataList.map(item => item.deviceName);
                const uniqueDeviceNames = [...new Set(this.classifyList)]; // 去重
                this.classifyList = uniqueDeviceNames.map(name => ({ deviceName: name }));

                // 过滤classifyList
                this.filterDataByClassifyList();
            });
        },
        sizeChange(val) {
            this.searchData.pageSize = val;
            this.getPageList();
        },
        currentChange(val) {
            this.searchData.pageNum = val;
            this.getPageList();
        },
        changePage(pageName) {
            this.$router.push({
                path: '/systemS/bigScreen/' + pageName,
            });
        },
        toggleTooltip() {
            this.showTooltip = !this.showTooltip; // 切换弹出框显示状态
        },
        handleClickOutside(event) {
            const tooltipElement = this.$el.querySelector('.tooltip');
            const badgeElement = this.$el.querySelector('.user-icon');
            if (tooltipElement && !tooltipElement.contains(event.target) && !badgeElement.contains(event.target)) {
                this.showTooltip = false; // 点击其他地方，关闭弹出框
            }
        },
        handleButtonClick() {
            this.$router.push({
                path: '/systemS/bigScreen/ssjc',
            });
        },
        async logout() {
            this.$confirm(this.$t('login.989807-31'), this.$t('login.989807-32'), {
                confirmButtonText: this.$t('confirm'),
                cancelButtonText: this.$t('cancel'),
                type: 'warning',
            })
                .then(() => {
                    this.$store.dispatch('LogOut').then(() => {
                        location.href = '/index';
                    });
                })
                .catch(() => { });
        },

        showSetting() {
            this.$refs.setting.init();
        },
        timeFn() {
            this.timing = setInterval(() => {
                this.dateDay = formatTime(new Date(), 'HH: mm: ss');
                this.dateYear = formatTime(new Date(), 'yyyy-MM-dd');
                this.dateWeek = this.weekday[new Date().getDay()];
            }, 1000);
        },
        cancelLoading() {
            setTimeout(() => {
                this.loading = false;
            }, 500);
        },
        clearData() {
            if (this.timer) {
                clearInterval(this.timer);
                this.timer = null;
            }
        },
        //轮询
        switper() {
            // if (this.timer) {
            //     return;
            // }
            // let looper = (a) => {
            //     this.getMqttStats();
            // };
            // this.timer = setInterval(looper, 60000);
        },
        selectList() {
            listsByDeviceComboBox().then((res) => {
                this.equipmentList = res.data;
            });
            findPurchasing().then((res) => {
                this.sourceEnergy = res.data || [];
            });
        },
        // //标签点击事件
        // handleClick(tab) {
        //     this.getList();
        // },
        // 节点单击事件
        handleNodeClick(data, v, n) {
            this.queryParams.workshopid = data.id;
            // this.id1 = data.id;
            this.type = v.level;
            if (v.level == 1) {
                this.address = data.name;
                this.region = data.name;
            } else if (v.level == 2) {
                this.address = `${v.parent.data.name}-${data.name}`;
                this.region = `${v.parent.data.name}-${data.name}`;
            } else if (v.level == 3) {
                this.address = `${v.parent.parent.data.name}-${v.parent.data.name}-${data.name}`;
                this.region = `${v.parent.data.name}-${data.name}`;
            } else if (v.level == 4) {
                this.address = `${v.parent.parent.parent.data.name}-${v.parent.parent.data.name}-${v.parent.data.name}-${data.name}`;
                this.region = `${v.parent.data.name}-${data.name}`;
            }
            this.level = v.level;
            if (v.level == 4) {
                this.getlist();
            }
        },

        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.ybbh);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        getZuandsj(bool) {
            if (this.queryParams.id === undefined) {
                Message.warning('请选择分组');
                return;
            } else {
                this.zuandsj = bool;
            }

            this.zuandsj = bool;
        },
        /** 查询设备统计信息 */
        getDeviceStatistic() {
            getDeviceStatistic().then((response) => {
                this.deviceStatistic = response.data;
            });
        },
        /** 查询机构下拉树结构 */
        /** 查询部门下拉树结构 */
        getDeptTree() {
            let _this = this;
            deptTreeSelect().then((response) => {
                _this.deptOptions = response.data || [];
            });
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        },
        //刷新
        getShuanXin() {
            this.handleClick(this.activeName);
            this.getDeviceStatistic();
            this.getDeptTree();
            this.selectList();
            let now = new Date();
            let year = now.getFullYear();
            let month = now.getMonth() + 1;
            let day = now.getDate();
            let hh = new Date().getHours();
            let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
            let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
            this.Qyynsb_date = year + '-' + month + '-' + day + ' ' + hh + ':' + mf + ':' + ss;
        },
        getOpne(data) {
            this.ruleForm = {};
            this.open = true;
            this.ruleForm = { ...data };
        },
        getList() {
            this.loading = true;
            listUser(this.queryParams).then((response) => {
                this.dataList = response.data.list;
                this.total = response.data.total;
                this.loading = false;
            });
        },
        search() {
            this.buttonLoading = true;
            this.tempDataList = []; // 清空之前的结果
            const { deviceName, date, selectedProduct } = this.searchData;

            if (deviceName === undefined || deviceName === '' || date.length === 0 || selectedProduct === undefined || selectedProduct === '') {
                this.$message({ message: '请选择设备名称、日期范围、产品名称', type: 'warning' });
                this.tempDataList = this.dataList;
                this.buttonLoading = false;
                return;
            }

            // 过滤数据
            this.tempDataList = this.dataList.filter(item => {
                // 检查设备名称是否匹配
                const isDeviceMatch = item.deviceName === deviceName;
                // 检查日期范围是否匹配
                const isDateMatch = date.length === 2 ?
                    (new Date(item.createTime) >= new Date(date[0]) && new Date(item.createTime) <= new Date(date[1] + ' 23:59:59')) : true;
                return isDeviceMatch && isDateMatch;
            });
            // 产品名称过滤
            this.tempDataList = this.tempDataList.filter(item =>
                this.selectedProduct ? item.productName === this.selectedProduct : true
            );

            this.buttonLoading = false;
        },
        // 根据设备名称列表过滤数据
        filterDataByClassifyList() {
            // 这里可以进行一些初始化操作，比如清空tempDataList或者设置初始状态
            this.tempDataList = this.dataList;
        },
        exportToExcel() {
            if (this.tempDataList.length === 0) {
                this.$message({ message: '没有可导出的数据', type: 'warning' });
                return;
            }

            // 准备导出的数据
            const exportData = this.tempDataList.map(item => ({
                '告警名称': item.alertName,
                '设备编号': item.serialNumber,
                '设备名称': item.deviceName,
                '告警级别': item.alertLevel,
                '告警时间': item.createTime,
                '处理状态': item.status,
            }));

            // 创建工作簿
            const worksheet = XLSX.utils.json_to_sheet(exportData);
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, '告警数据');

            // 设置表头加粗
            const headerCell = worksheet['A1'];
            if (headerCell) {
                headerCell.s = {
                    font: {
                        bold: true,
                    },
                };
            }

            // 导出Excel
            XLSX.writeFile(workbook, `告警数据_${new Date().toISOString().split('T')[0]}.xlsx`);
        },
    },
};
</script>
<style lang="scss">
@import './home.scss';
</style>
<style lang="scss" scoped>
@import '../../assets/bigScreen/css/theme/index.css';
@import '../../assets/bigScreen/css/index.scss';

.cebianlan .el-input__inner {
    background-color: #113160 !important;
    color: white !important;
}

.user-icon {
    width: 20px;
    height: 20px;
    margin-right: 10px;
}

.el-badge__content.is-fixed {
    top: 10px !important;
    right: 20px !important;
}

.notification-badge {
    height: 15px;
    width: 15px;
    position: absolute;
    top: 10px;
    right: 110px;
    bgcolor: red;
    background: red;
    color: white;
    border-radius: 50%;
    font-size: 7px;
}

.backdrop {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    /* 背景颜色 */
    z-index: 9;
    /* 确保在弹窗下方 */
}

.dropdown-menu {
    position: absolute;
    border: 1px solid #ccc;
    padding: 10px;
    z-index: 10;
    /* 确保弹窗在其他元素之上 */
    width: 297px;
    height: 272px;
    flex-shrink: 0;
    border-radius: 12px;
    background: #113160;
    box-shadow: 0 4px 39.1px 0 #00000040;
    top: 40px;
    right: 10px;
}

.popper__arrow::after {
    border-top-color: #113160 !important;
    border-bottom-color: #113160 !important;
}

.el-badge__content {
    background-color: red;
    border: none;
}

.tooltip {
    height: 250px;
    width: 270px;
    position: absolute;
    /* 绝对定位 */
    top: 50px;
    /* 调整弹出框的垂直位置，需根据实际情况调整 */
    right: 10px;
    /* 左对齐 */
    background-color: #113160;
    /* 背景颜色 */
    color: white;
    /* 字体颜色 */
    padding: 5px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    z-index: 1;
    /* 确保弹出框在其他元素之上 */
}

.gjcontainer {
    //height: 120px;
    display: grid;
    /* 启用 Grid 布局 */
    grid-template-columns: repeat(2, 1fr);
    /* 两列 */
    gap: 0px;
    /* 列间距 */
}

.gjitem {
    //margin: 10px;
    text-align: center;
    /* 内容居中显示 */
}

.contetn_center_top {
    width: 100%;
}

// 中间
.contetn_center {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    width: 100%;
    height: 60%;
}

.contetn_center-bottom {
    height: 255px;
}

//左边 右边 结构一样
.contetn_left,
.contetn_right {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    position: relative;
}

.button-container {
    //margin-top: 200px;
    width: 800px;
    position: absolute;
    //left: 30%;
    bottom: 35px;
    left: 558px;
    display: flex;
    justify-content: space-between;
    /* 水平对齐 */
}

.button {
    width: 57px;
    height: 60px;
    background-color: transparent;
    background-image: url('../../assets/bigScreen/img/底部tab未选择.png');
    background-position: 50% 25%;
    background-size: 100%, 100%;
    /* 使背景图片完全覆盖按钮，保持比例 */
    background-repeat: no-repeat;
    /* 背景图片不重复 */

    -ms-flex-negative: 0;
    flex-shrink: 0;
    border: none;
    /* 去掉边框 */
    color: #76f1ff;
    /* 默认字体颜色为蓝色 */
    padding: 10px 20px;
    /* 按钮内边距 */
    cursor: pointer;
    /* 鼠标悬停时显示为手型 */
    transition: color 0.3s;
    /* 颜色变化过渡效果 */
}

.button:hover {
    background-image: url('../../assets/bigScreen/img/按钮未选中.png');
    height: 50px;
    color: white;
    /* 鼠标悬停时字体颜色为白色 */
}

.cebianlan {
    padding-left: 10px;
    margin: 30px 30px;
    border-radius: 10px;
    background-color: #113160;
    color: white;
    height: 800px;
    width: 300px;
}

.nr {
    display: flex;
}

.bbgl-right {
    height: 850px;
    width: calc(100% - 300px);
}

.top-bbgl {
    margin-top: 30px;
    height: 86px;
    flex-shrink: 0;
    background: linear-gradient(90deg, #1742837d 0%, #0e284f00 100%);
    display: flex;
    align-items: center;
    text-align: center;
}

.bottom-bbgl {
    margin-top: 30px;
    flex-shrink: 0;
    border-radius: 20px;
    background: linear-gradient(180deg, #092650 0%, #09265000 100%);
    height: 600px;
    /* 设置一个固定的高度 */
    overflow-y: auto !important;
    /* 启用垂直滚动条 */
    position: relative !important
        /* 相对定位，用于表头的sticky定位 */
}

/* 滚动条总体样式 */
.bottom-bbgl::-webkit-scrollbar {
    width: 10px !important
        /* 滚动条宽度 */
}

/* 滚动条滑块样式 */
.bottom-bbgl::-webkit-scrollbar-thumb {
    background-color: #1856b0 !important;
    /* 滑块背景色 */
    border-radius: 5px !important;
    /* 滑块边角 */
}

/* 滚动条轨道样式 */
.bottom-bbgl::-webkit-scrollbar-track {
    background-color: #092650FF !important;
    /* 轨道背景色 */
}

.bbgl-table th {
    position: sticky;
    top: 0;
    background-color: #153768;
    /* 表头背景颜色 */
    color: #fff;
    /* 表头文字颜色 */
    z-index: 10;
    /* 确保表头在滚动时始终在顶部 */
}

.table-header {
    width: 100%;
    background-color: #153768;
    border-radius: 8px;
}

.table-title {
    font-size: 20px;
    color: #fff;
    padding: 10px;
    text-align: center;
    margin-left: 80vh;
}

/* 表格 */
.bbgl-table {
    width: 100%;
    border-collapse: collapse;
    /* 去除表格边框间距 */
}

/* 表头 */
.bbgl-table th {
    position: sticky;
    top: 0;
    background-color: #153768;
    color: #fff;
    z-index: 10;
    white-space: nowrap;
    /* 防止内容换行 */
}

/* 表格单元格 */
.bbgl-table td,
.bbgl-table th {
    min-width: 100px;
    /* 设置最小宽度，根据实际内容调整 */
    white-space: nowrap;
    /* 防止内容换行 */
}
</style>
