<template>
    <div id="index" ref="appRef" :class="{ pageisScale: true }" class="index_ssjc index-gjzx"
         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"
                                              :hidden="unreadCount === 0">
                                        <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="ssjc-right">
                        <div class="flex-between" style="height: 105px">
                            <el-card class="top-ssjc" style="min-width: 1000px; margin: 0; height: 65px"
                                     body-style="padding:9px 20px">
                                <div class="card-form flex-between">
                                    <div class="form-point"></div>
                                    <div class="form-label">设备信息</div>
                                    <div class="form-label">设备数：{{ this.total }}</div>
                                    <div class="form-label">项目告警数：{{ this.alarmCount }}</div>
                                    <div class="form-input">
                                        <el-input type="text"
                                                  v-model="searchDeviceName"
                                                  :placeholder="showPlaceholder ? '请输入设备名称-回车搜索' : ''"
                                                  clearable
                                                  @keyup.enter.native="changeDeviceName"
                                                  enterkeyhint="enter"
                                                  @focus="showPlaceholder = false"
                                                  @blur="showPlaceholder = true"
                                                  style="font-size: 14px; color: #FFFFFF"
                                        ></el-input>
                                    </div>
                                    <el-select class="form-select" style="width: 200px" v-model="selectedProduct"
                                               placeholder="请选择关联产品"
                                               @change="changeProduct" clearable>
                                        <el-option
                                            v-for="item in productList"
                                            :key="item.value"
                                            :label="item.productName"
                                            :value="item.productName"
                                        />
                                    </el-select>

                                    <!-- 3-在线，4-离线 -->
                                    <div class="form-radio-group" style="text-align: center; margin-left: 20px">
                                        <div
                                            class="form-radio f"
                                            :style="{ 'background-color': deviceStatus === 3 ? '#1f6ad7' : '', cursor: 'pointer' }"
                                            @click="changeOnlineStatus(3)"> 在线
                                        </div>
                                        <div
                                            class="form-radio f"
                                            :style="{ 'background-color': deviceStatus === 4 ? '#1f6ad7' : '', 'margin-left': '10px',cursor: 'pointer' }"
                                            @click="changeOnlineStatus(4)"> 离线
                                        </div>
                                    </div>
                                </div>
                            </el-card>
                        </div>
                        <div class="device-list"
                             style="margin-bottom: 60px; margin-right: 30px; overflow-y: auto; height: calc(100% - 110px); padding-right: 30px">
                            <div class="device-option" v-for="(item,index) in tempDataList" :key="index">
                                <div class="option-top flex-between">
                                    <div class="device-name">{{ item.deviceName }}</div>
                                    <div class="flex-center">
                                        <div class="device-icon">
                                            <!--  3-在线，4-离线 -->
                                            <img class="img-inner" v-if="item.status !== 3"
                                                 src="../../assets/bigScreen/img/device-off.png" alt=""/>
                                            <img class="img-inner" v-else
                                                 src="../../assets/bigScreen/img/device-online.png" alt=""/>
                                        </div>
                                        <div class="device-control flex-center">
                                            <i class="el-icon-more control-icon" @click="getdianwei(item)"></i>
                                        </div>
                                    </div>
                                </div>
                                <div class="option-content flex-between">
                                    <div class="device-img">
                                        <img
                                            v-if="item.imgUrl === undefined || item.imgUrl === null || item.imgUrl === ''"
                                            class="img-inner" src="../../assets/bigScreen/img/device-img.png" alt=""/>
                                        <img v-else class="img-inner" :src="baseApi + item.imgUrl"/>
                                    </div>
                                    <div class="device-info">
                                        <div class="info-row flex-between"
                                             v-for="(items, index) in item.thingsModels.slice(0, 3)" :key="index">
                                            <div class="info-name">
                                                {{ items.name_zh_CN != null ? items.name_zh_CN : '点位名' }}
                                            </div>
                                            <div class="info-value">
                                                {{ items.value != null && items.value !== '' ? items.value : 0 }}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </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"/>

        <el-dialog :visible.sync="dialogVisible" width="1520px" center close-on-click-modal append-to-body
                   custom-class="point-dialog-outer">
            <div class="point-dialog">
                <div class="close-button" @click="dialogVisible = false"></div>
                <div class="dialog-inner">
                    <el-table
                        class="point-table"
                        :data="pointList"
                        style="width: 100%"
                        :header-cell-style="{ fontSize: '16px', backgroundColor: '#0D2141', color: '#fff', fontWeight: 'bold', textAlign: 'center', border: 0 }"
                        :row-style="{ fontSize: '14px', backgroundColor: '#091639', color: '#fff', textAlign: 'center', lineHeight: '60px' }"
                    >
                        <el-table-column label="点位名称" align="center" prop="name"/>
                        <el-table-column label="点位标识" align="center" prop="id"/>
                        <el-table-column label="数值" align="center" prop="shadow"/>
                        <el-table-column label="趋势图" align="center" prop="type">
                            <template slot-scope="scope">
                                <i class="el-icon-view" style="color: #007aff" @click="getview(scope.row.id)"></i>
                            </template>
                        </el-table-column>
                        <!--                         根据设备模型 -->
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <!-- 如果该点位 -->
                                <span style="cursor: pointer"
                                      v-if="scope.row.canSetThreshold">
                                                            <i class="el-icon-edit" style="color: #007aff"></i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                                            <i class="" style="color: #ffffff; font-size: 14px"
                                                               @click="setThreshold(scope.row)"> 设置阈值
                                                            </i>
                                                        </span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div v-if="selectId" ref="statisticMap" style="height: 100%; width: 100%;"></div>
                </div>
            </div>
        </el-dialog>

        <!-- 点位数据统计弹窗 -->
        <el-dialog :visible.sync="dialogVisibles" width="1520px" center close-on-click-modal append-to-body
                   custom-class="point-dialog-outer">
            <div class="close-button" @click="dialogVisibles = false"
                 style="margin-right: 100px; top: 2px; z-index: 10000"></div>

            <div style="display: flex; justify-content: flex-end; margin-top: 220px; margin-right: 80%;">
                <el-button
                    :style="{ backgroundColor: isDataTJ ? '#11289a' : 'rgba(21,55,104,0.35)' , marginBottom: '5px', border: 'none', zIndex: 10001 }"
                    width="150px" size="mini" type="primary"
                    @click="historyHandle">历史数据
                </el-button>
                <el-button
                    :style="{ backgroundColor: !isDataTJ ? '#11289a' : 'rgba(21,55,104,0.35)', marginBottom: '5px', border: 'none', zIndex: 10001 }"
                    width="150px" size="mini" type="primary"
                    @click="dataTJHande">数据统计
                </el-button>
            </div>

            <div class="point-dialog-inner point-dialog" style="width: 70%; height: 65%;">
                <!-- Echarts数据统计 -->
                <div v-if="isDataTJ">
                    <el-button style="background-color: #0e284f; border: none" type="primary" size="mini"
                               @click="changeTime(1)">1小时
                    </el-button>
                    <el-button style="background-color: #0e284f; border: none" type="primary" size="mini"
                               @click="changeTime(12)">12小时
                    </el-button>
                    <el-button style="background-color: #0e284f; border: none; margin-right: 30px" type="primary"
                               size="mini" @click="changeTime(24)">24小时
                    </el-button>
                </div>
                <div v-if="isDataTJ" ref="sceneLineChart"
                     style="width: 100%; height: 460px; background: #fff; margin-top: 10px;">
                </div>
                <!-- 历史数据统计 -->
                <div v-else>
                    <!-- 数据统计内容 -->
                    <div class="time-header" style="display: flex; justify-content: start;">
                        <el-date-picker
                            style="background-color: #0e284f; height: 22px; width: 200px; border: none; color: #c9c4c4"
                            v-model="pickerValue"
                            @change="handleDateRangeChange"
                            end-placeholder="结束日期"
                            format="yyyy-MM-dd"
                            range-separator="至"
                            start-placeholder="开始日期"
                            type="daterange"
                            value-format="yyyy-MM-dd"
                        ></el-date-picker>
                        <el-button style="background-color: rgba(21,55,104,0.35); margin-left: 80%; border: none"
                                   width="150px" size="mini" type="primary" @click="exportToExcel">导出为Excel
                        </el-button>
                    </div>
                    <!-- 表格数据 -->
                    <div style="overflow: auto; height: 400px; background-color: #153768; margin-top: 20px;">
                        <el-table
                            class="history-data-table"
                            :data="tempDeviceHistoryList"
                            :header-cell-style="{fontSize: '12px', backgroundColor: '#153768', color: '#fff', textAlign: 'center' }"
                            title="历史数据"
                        >
                            <el-table-column label="时间" align="center" prop="time"
                                             style="background-color: #153768; color: #fff;"/>
                            <el-table-column label="点位名" align="center" prop="pointName"/>
                            <el-table-column label="点位值" align="center" prop="pointValue"/>
                        </el-table>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 智能调度弹窗 -->
        <el-dialog :visible.sync="monitorDialogVisible" width="1520px" center close-on-click-modal append-to-body
                   custom-class="point-dialog-outer">
            <div class="close-button" @click="monitorDialogVisible = false"
                 style="position: relative; margin-left: 88%; margin-top: 14%; z-index: 10000"></div>
            <div class="point-dialog-inner point-dialog" style="width: 65%; height: 70%; ">
                <div v-if="videoUrl === ''" style="display: flex;justify-content: center; align-items: center;">
                    <span
                        style="font-size: 18px; color: #ffffff; margin-bottom: 20px;"> 暂无视频 </span>
                </div>
                <div v-else style="display: flex; align-items: center;">
                    <video controls style="width: 100%; height: 30%; background: #000; margin-bottom: 20px">
                        <source :src="videoUrl" type="video/mp4">
                        您的浏览器不支持视频标签。
                    </video>
                </div>
            </div>
        </el-dialog>

        <!-- 设置阈值 -->
        <el-dialog :visible.sync="thresholdDialogVisible" width="1520px" center close-on-click-modal append-to-body
                   custom-class="point-dialog-outer" style="text-align: center; align-items: center;">
            <div class="point-dialog-inner point-dialog"
                 style="width: 35%; height: 36%; align-items: center; text-align: center; justify-content: center;">
                <div>
                    <span
                        style="color: #ffffff; font-size: 18px; text-align: center; display: block; margin-bottom: 20px">
                        设置场景联动阈值
                    </span>
                    <span class="close-button" @click="thresholdDialogVisible = false"
                          style="right: 20px; top: 30px"></span>
                </div>
                <div style="margin-left: 100px;">
                    <div>
                        <div style="display: flex; align-items: center; margin-bottom: 20px;">
                            <span style="color: #ffffff; font-size: 14px; margin-right: 10px">最大值：</span>
                            <el-input v-model="alertThreshold.maxvalue"
                                      style="background-color: #0e284f; border: none; color: #ffffff; width: 200px;"
                            ></el-input>
                        </div>
                        <div style="display: flex; align-items: center;">
                            <span style="color: #ffffff; font-size: 14px; margin-right: 10px">最小值：</span>
                            <el-input v-model="alertThreshold.minvalue"
                                      style="background-color: #0e284f; border: none; color: #ffffff; width: 200px;"
                            ></el-input>
                        </div>
                    </div>
                </div>

                <el-button
                    style="background-color: #0e284f; border: none; color: #ffffff; margin-top: 20px; margin-left: 90%"
                    type="primary" @click="handleThresholdSubmit">确定
                </el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import drawMixin from '../../utils/bigScreen/drawMixin';
import {formatTime} from '@/utils/bigScreen';
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 {
    getDeviceRunningStatus,
    getDeviceStatistic,
    listDeviceShort,
    listThingsModel,
    getProductList, getSceneServiceList, updateSceneService
} from '@/api/iot/device';
import {getDataCenterDeviceHistory} from '@/api/data/center';
import {getProduct} from '@/api/iot/product';
import * as echarts from 'echarts';
import * as XLSX from "xlsx";
import {serviceInvoke} from "@/api/iot/runstatus";
import {addScene} from "@/api/iot/scene";
import {deptsTreeSelect} from "@/api/system/user";
import {delSceneByName} from "../../api/iot/scene";

export default {
    name: 'gjzx',
    dicts: ['iot_process_status', 'iot_alert_level'],
    mixins: [drawMixin],
    components: {
        Setting,
        index,
    },
    data() {
        return {
            baseApi: process.env.VUE_APP_BASE_API,
            selectId: 'false',
            pointList: [],
            alarmCountData: [
                { name: '提醒', count: 0},
                { name: '轻微', count: 0},
                { name: '严重', count: 0},
            ],
            alarmCount: 0,
            alarmList: [],
            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,
                deviceId: undefined,
                typeName: undefined,
                deviceNum: undefined,
                status: undefined,
                pageNum: 1,
                pageSize: 999999, // 全部查上来
                showChild: true,
                deptId: undefined,
            },
            Params: {
                beginTime: null,
                deviceId: null,
                endTime: null,
                serialNumber: null,
                identifierList: [{
                    identifier: null,
                    type: 1,
                }]
            },
            //地区名称
            qb_name: '计量设备清单',
            //仪表类型数组
            sourceEnergy: [],
            //巡行状态数组
            sourceStatus: [
                {value: '1', label: '未激活'},
                {value: '2', label: '禁用'},
                {value: '3', label: '在线'},
                {value: '4', label: '离线'},
            ],
            // 总条数
            total: 0,
            pagesTotal: 0,
            //数据接收数组
            dataList: [],
            // 临时设备数据，用来回显在页面的初始值 -> 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: '活动警告',
            dialogVisible: false,
            dialogVisibles: false,
            thresholdDialogVisible: false,
            monitorDialogVisible: false, // 监控设备对话框
            isDataTJ: true, // 数据统计 || 历史数据
            devIdentifierList: [],
            searchDeviceName: '', // 搜索的设备名称,
            deviceStatus: -1, // 控制当前选中状态 3-在线，4-离线
            onlines: [],
            offlines: [],
            disableds: [],
            unactivateds: [],
            selectedProduct: '',
            productList: [],
            activeDevice: {}, // 当前设备
            videoUrl: '', // 监控视频地址
            currentProductId: -1, // 当前选中的产品id
            sceneServiceList: [], // 场景服务列表
            currentRow: {},
            deviceHistoryList: [],
            tempDeviceHistoryList: [],
            pickerValue: [],
            filteredDevDatas: [],
            showPlaceholder: true,
            deviceSceneScripts: [], // 场景脚本
            currentPoint: {}, // 当前点位
            alertThreshold: {
                maxvalue: '',
                minvalue: '',
            },
            invokeReqDto: {
                serialNumber: '',
                identifier: '',
                remoteCommand: {},
                isShadow: true,
                type: 1,
                modelName: '',
                productId: 0,
            }
        };
    },
    filters: {
        numsFilter(msg) {
            return msg || 0;
        },
    },
    computed: {},
    created() {
        // 查询所有数据
        this.getLists();
        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) => {
            //统计所有报警信息
            let count1 = 0;
            rp.data.forEach((item) => {
                count1 += item.count1;
            });
            this.unreadCount = count1;
            this.switper();
        });

        // 获取告警列表
        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;
                }
            });
        });
        getSceneServiceList().then((res) => {
            this.sceneServiceList = res.data;
        });
    },
    mounted() {
        this.timeFn();
        this.cancelLoading();
        document.addEventListener('click', this.handleClickOutside); // 添加全局点击事件监听
    },
    beforeDestroy() {
        document.removeEventListener('click', this.handleClickOutside); // 移除事件监听
    },
    watch: {
        // 根据名称筛选机构树
        deptName(val) {
            this.$refs.tree.filter(val);
        },
    },
    methods: {
        getDevIdentifierList(deviceId) {
            const params = {
                deviceId: deviceId,
                pageNum: 1,
                pageSize: 999999,
            };
            listThingsModel(params).then((res) => {
                if (res.code === 200) {
                    this.devIdentifierList = res.rows;
                }
            });
        },
        getview(row) {
            this.currentRow = row;
            const date = this.getFormattedDate();
            this.Params.beginTime = date + " 00:00:00";
            this.Params.endTime = date + " 23:59:59";
            this.Params.identifierList[0].identifier = row;
            this.getDevIdentifierList(this.Params.deviceId);
            getDataCenterDeviceHistory(this.Params).then((res) => {
                if (res.code === 200) {
                    this.devDatas = res.data;
                    this.filteredDevDatas = this.devDatas;
                    this.dialogVisibles = true;
                    setTimeout(() => {
                        this.drawSceneLine();
                    }, 500);
                }
            });
        },
        drawSceneLine() {
            // 初始化折线图
            let charts = echarts.init(this.$refs.sceneLineChart);
            charts.clear();
            let series = this.getSceneSeries();

            // 设置折线图数据和样式
            charts.setOption({
                darkMode: true,
                backgroundColor: '#153157',
                tooltip: {
                    trigger: 'axis',
                },
                legend: {
                    align: 'right',
                    left: '3%',
                    top: '15%',
                    textStyle: {
                        color: "#fff"
                    }
                },
                grid: {
                    top: '30%',
                    left: '5%',
                    right: '5%',
                    bottom: '5%',
                    containLabel: true,
                },
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100,
                    },
                    {
                        start: 0,
                        end: 100,
                    },
                ],
                // 自定义：设置x轴刻度
                xAxis: {
                    type: 'category',
                    boundaryGap: true,
                    axisTick: {
                        alignWithLabel: true,
                    },
                    axisLabel: {
                        textStyle: {
                            color: "#fff"
                        }
                    },
                    // 自定义标签
                    data: this.filteredDevDatas.length !== 0 && this.filteredDevDatas.map((item) => Object.keys(item)[0]),
                },
                // 自定义：设置y轴刻度
                yAxis: {
                    type: 'value',
                    boundaryGap: true,
                    splitNumber: 4,
                    interval: 250,
                    axisLabel: {
                        textStyle: {
                            color: "#fff"
                        }
                    },
                },
                // 设置数据
                series: series,
            });
        },
        // 获取设备的series
        getSceneSeries() {
            return this.Params.identifierList.map((item) => {
                return {
                    name: this.devIdentifierList.find((chil) => chil.identifier === item.identifier).modelName,
                    type: 'line',
                    stack: this.$t('dataCenter.history.384934-23'),
                    markPoint: {
                        data: [
                            {type: 'max', name: 'Max'},
                            {type: 'min', name: 'Min'}
                        ]
                    },
                    smooth: true,
                    data: this.devDatas.map((d) => {
                        const ide = Object.values(d)[0].find((f) => {
                            return Object.keys(f)[0] === item.identifier
                        });
                        return Object.values(ide)[0];
                    }),
                };
            });
        },
        getFormattedDate() {
            var now = new Date();
            var year = now.getFullYear();
            var month = now.getMonth() + 1;
            var day = now.getDate();
            // 将月份和日期格式化为两位数
            month = month < 10 ? '0' + month : month;
            day = day < 10 ? '0' + day : day;
            return year + '-' + month + '-' + day;
        },
        getdianwei(e) {
            this.activeDevice = e;
            const productId = e.productId;
            getProduct(productId).then((res) => {
                // 监控设备, 显示视频流
                const isMonitor = res.data.deviceType === 3;
                this.videoUrl = isMonitor ? e.imgUrl : '';

                if (isMonitor) {
                    // 如果是监控设备，显示监控设备对话框
                    this.monitorDialogVisible = true;
                    // 查询监控视频地址
                    this.videoUrl = "http://localhost/dev-api/sip/player/play/" + e.deviceId + "/" + e.deviceId;
                } else {
                    this.videoUrl = '';
                    // 如果不是监控设备，执行以下操作
                    this.monitorDialogVisible = false; // 确保监控设备对话框不显示
                    this.Params.deviceId = e.deviceId;
                    this.Params.serialNumber = e.serialNumber;
                    this.pointList = [];
                    getDeviceRunningStatus({deviceId: e.deviceId}).then((rp) => {
                        this.pointList = rp.data.thingsModels;
                        this.pointList.sort((a, b) => a.order - b.order);
                        this.currentProductId = e.productId;
                        this.selectId = false; // 确保其他对话框的标识符为 false
                        this.dialogVisible = true; // 显示非监控设备的对话框
                        this.deviceSceneScripts = rp.data.sceneScriptList; // 场景脚本
                    });

                    this.invokeReqDto.serialNumber = e.serialNumber;
                    this.invokeReqDto.productId = productId;
                }
            }).catch(() => {
                this.monitorDialogVisible = false;
                this.dialogVisible = true;
            });
        },
        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);
        },
        // 节点单击事件
        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}`;
            }
            if (v.level == 4) {
                // this.getLists()
                let query = {
                    pageNum: 1,
                    pageSize: 9999999,
                    id: data.id
                }
                // 因为每次一都需要重新过滤
                this.tempDataList = this.dataList;
                listUser(query).then((res) => {
                    let list = res.data.list;
                    // 创建一个新的数组，包含过滤后的元素
                    this.tempDataList = this.tempDataList.filter(i => {
                        // 检查list中是否存在相同deviceId的元素
                        return list.some(item => item.deviceId === i.deviceId);
                    });
                });
            } else {
                this.tempDataList = this.dataList;
            }
            this.level = v.level;

        },

        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.ybbh);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        /** 查询设备统计信息 */
        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;
        },
        // 数据
        getLists() {
            this.loading = true;
            listDeviceShort(this.queryParams).then((rp) => {
                // 设备数据
                this.dataList = rp.rows;
                // 设备总条数
                this.total = rp.total;
                this.dataList.forEach((item) => {
                    if (item.thingsModels && item.thingsModels.length > 0) {
                        item.thingsModels.sort((a, b) => a.order - b.order);
                    }
                });
                this.tempDataList = this.dataList;
            });
            getProductList().then((res) => {
                this.productList = res.rows;
            })
            this.loading = false;
        },
        changeOnlineStatus(status) {
            this.deviceStatus = status;
            this.filterDataList()
        },
        changeDeviceName() {
            this.filterDataList()
        },
        changeProduct() {
            this.filterDataList()
        },
        filterDataList() {

            // 首先，重置 tempDataList 为原始 dataList
            this.tempDataList = this.dataList;

            // 根据 deviceName 过滤
            if (this.searchDeviceName.trim() !== '') {
                this.tempDataList = this.dataList.filter(item =>
                    item.deviceName.toLowerCase().includes(this.searchDeviceName.toLowerCase())
                );
            } else {
                this.tempDataList = this.dataList;
            }

            // 根据 productName 过滤
            if (this.selectedProduct.trim() !== '') {
                this.tempDataList = this.tempDataList.filter(item =>
                    this.selectedProduct ? item.productName === this.selectedProduct : true
                );
            }

            // 根据 deviceStatus 过滤
            if (this.deviceStatus !== -1) {
                this.tempDataList = this.tempDataList.filter(item =>
                    this.deviceStatus === -1 || item.status === this.deviceStatus
                );
            }
        },
        handleThresholdSubmit() {
            // 1. 校验数据合法性
            if (!this.isNumeric(this.alertThreshold.maxvalue) || !this.isNumeric(this.alertThreshold.minvalue)) {
                return this.$message.error('请检查数字格式是否有误');
            } else {
                // 3. 如果是报警阈值，先向后台发送数据，然后再发送报警信息
                let values = [this.alertThreshold.maxvalue, this.alertThreshold.minvalue]
                for (let i = 0; i < values.length; i++) {
                    const value = values[i];
                    // 2. 如果是高位或低位，直接向后台发送数据
                    // 构建请求体
                    const identifier = i === 0 ? 'almhigh' : 'almlow';
                    this.invokeReqDto.remoteCommand = {
                        [identifier]: value
                    }
                    this.invokeReqDto.identifier = identifier;
                    this.invokeReqDto.modelName = this.currentPoint.name;
                    serviceInvoke(this.invokeReqDto).then((response) => {
                        if (response.code === 200) {
                            this.$message({
                                type: 'success',
                                message: this.$t('device.running-status.866086-25'),
                            });
                        }
                    });
                }

                // 新增场景联动请求体
                let sceneLinkReq1 = {
                    actions: [{
                        arrayIndex: "",
                        arrayIndexName: "",
                        deviceCount: 0,
                        deviceNums: [],
                        id: "",
                        name: "",
                        parentId: "",
                        parentName: "",
                        productId: "",
                        productName: "",
                        scriptPurpose: 3,
                        source: 4,
                        type: 2,
                        userId: "",
                        value: "",
                    }],
                    applicationName: "yanfan",
                    checkDelay: 0,
                    cond: 1,
                    enable: 1,
                    executeDelay: 0,
                    executeMode: 1,
                    hasAlert: 1,
                    recoverId: null,
                    recoverSceneName: null,
                    remark: null,
                    sceneId: null,
                    sceneName: this.activeDevice.deviceName + this.currentPoint.name + "大于" + this.alertThreshold.maxvalue + "IsFromBigScreen",
                    silentPeriod: 0,
                    triggers: [
                        {
                            arrayIndex: "",
                            arrayIndexName: "",
                            cronExpression: "",
                            deviceCount: 1,
                            deviceNums: [this.activeDevice.serialNumber],
                            id: this.currentPoint.id,
                            isAdvance: 0,
                            name: this.currentPoint.name,
                            operator: ">",
                            parentId: this.currentPoint.id,
                            parentName: this.currentPoint.name,
                            productId: this.currentProductId,
                            productName: this.activeDevice.productName,
                            sceneEneregy: {
                                id: this.currentPoint.id,
                                name: this.currentPoint.name,
                                productId: this.currentProductId,
                                productName: this.activeDevice.productName,
                                serialNumber: this.activeDevice.serialNumber,
                            },
                            sceneRule: [
                                {ruleType: 0, unit: "", ruleValue: ""}
                            ],
                            scriptPurpose: 2,
                            source: 1,
                            type: 1,
                            value: this.alertThreshold.maxvalue,
                        }
                    ],
                    userId: null,
                    userName: null,
                }
                // 先删除后新增
                delSceneByName(this.activeDevice.deviceName + this.currentPoint.name + "大于" + this.alertThreshold.maxvalue + "IsFromBigScreen")
                    .finally(() => {
                        // 删除操作完成后执行的代码，无论删除成功与否
                        addScene(sceneLinkReq1).then((response) => {
                            this.$message.success(response.msg);
                        })
                    });
                let sceneLinkReq2 = {
                    actions: [{
                        arrayIndex: "",
                        arrayIndexName: "",
                        deviceCount: 0,
                        deviceNums: [],
                        id: "",
                        name: "",
                        parentId: "",
                        parentName: "",
                        productId: "",
                        productName: "",
                        scriptPurpose: 3,
                        source: 4,
                        type: 2,
                        userId: "",
                        value: "",
                    }],
                    applicationName: "yanfan",
                    checkDelay: 0,
                    cond: 1,
                    enable: 1,
                    executeDelay: 0,
                    executeMode: 1,
                    hasAlert: 1,
                    recoverId: null,
                    recoverSceneName: null,
                    remark: null,
                    sceneId: null,
                    sceneName: this.activeDevice.deviceName + this.currentPoint.name + "小于" + this.alertThreshold.minvalue + "IsFromBigScreen",
                    silentPeriod: 0,
                    triggers: [
                        {
                            arrayIndex: "",
                            arrayIndexName: "",
                            cronExpression: "",
                            deviceCount: 1,
                            deviceNums: [this.activeDevice.serialNumber],
                            id: this.currentPoint.id,
                            isAdvance: 0,
                            name: this.currentPoint.name,
                            operator: "<",
                            parentId: this.currentPoint.id,
                            parentName: this.currentPoint.name,
                            productId: this.currentProductId,
                            productName: this.activeDevice.productName,
                            sceneEneregy: {
                                id: this.currentPoint.id,
                                name: this.currentPoint.name,
                                productId: this.currentProductId,
                                productName: this.activeDevice.productName,
                                serialNumber: this.activeDevice.serialNumber,
                            },
                            sceneRule: [
                                {ruleType: 0, unit: "", ruleValue: ""}
                            ],
                            scriptPurpose: 2,
                            source: 1,
                            type: 1,
                            value: this.alertThreshold.minvalue,
                        }
                    ],
                    userId: null,
                    userName: null,
                }
                // 在请求之间加入延迟
                this.delayRequest(() => {
                    delSceneByName(this.activeDevice.deviceName + this.currentPoint.name + "小于" + this.alertThreshold.minvalue + "IsFromBigScreen")
                        .finally(() => {
                            // 删除操作完成后执行的代码，无论删除成功与否
                            addScene(sceneLinkReq2).then((response) => {
                                this.$message.success(response.msg);
                            })
                        });
                }, 1000); // 延迟1000毫秒
            }
            this.thresholdDialogVisible = false;
        },
        delayRequest(callback, delay) {
            setTimeout(callback, delay);
        },
        isNumeric(str) {
            return /^-?\d+(\.\d+)?$/.test(str);
        },
        getPlayerData(data) {
            this.$nextTick(() => {
                if (this.channelId) {
                    this.$refs.deviceLiveStream.channelId = this.channelId;
                    this.$refs.deviceLiveStream.changeChannel();
                }
            });
        },
        historyHandle() {
            this.isDataTJ = true;
            this.getview(this.currentRow);
        },
        dataTJHande() {
            this.isDataTJ = false
            const date = this.getFormattedDate();
            this.Params.beginTime = date + " 00:00:00";
            this.Params.endTime = date + " 23:59:59";
            this.Params.identifierList[0].identifier = this.currentRow;
            this.getDevIdentifierList(this.Params.deviceId);
            getDataCenterDeviceHistory(this.Params).then((res) => {
                if (res.code === 200) {
                    this.devDatas = res.data;
                    this.deviceHistoryList = this.processData(this.devDatas)
                    this.tempDeviceHistoryList = this.deviceHistoryList;
                }
            });
        },
        // 转换数据格式
        processData(data) {
            return data.flatMap(item => {
                const time = Object.keys(item)[0];
                const values = item[time];
                return values.map(value => {
                    return {
                        time: time,
                        pointName: Object.keys(value)[0], // 假设只有一个点位名
                        pointValue: value[Object.keys(value)[0]]
                    };
                });
            });
        },
        changeTime(range) {
            const end = new Date();
            let start = new Date();
            start.setHours(end.getHours() - range);
            this.filterDataByTime1(start, end);
            this.drawSceneLine();
        },
        filterDataByTime1(start, end) {
            // 将时间转换为字符串，以便与devDatas中的日期字符串进行比较
            const startTimeStr = this.formatDate(start);
            const endTimeStr = this.formatDate(end);

            // 过滤devDatas数组
            this.filteredDevDatas = this.devDatas.filter(item => {
                return item.time >= startTimeStr && item.time <= endTimeStr;
            });
        },
        formatDate(date) {
            // 将Date对象格式化为"YYYY-MM-DD HH:mm:ss"格式的字符串
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hour = date.getHours().toString().padStart(2, '0');
            const minute = date.getMinutes().toString().padStart(2, '0');
            const second = date.getSeconds().toString().padStart(2, '0');
            return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
        },
        // 根据日期选择器的范围过滤数据
        handleDateRangeChange(value) {
            if (value && value.length) {
                this.filterDataByTime(new Date(value[0]), new Date(value[1]));
            }
        },
        // 过滤数据的方法
        filterDataByTime(start, end) {
            this.tempDeviceHistoryList = this.deviceHistoryList.filter(item => {
                const itemTime = new Date(item.time);
                return itemTime >= start && itemTime <= end;
            });
        },
        // 导出为Excel
        exportToExcel() {
            const worksheet = XLSX.utils.json_to_sheet(this.tempDeviceHistoryList);
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
            XLSX.writeFile(workbook, "数据统计.xlsx");
        },
        setThreshold(val) {
            this.thresholdDialogVisible = true
            this.currentPoint = val;
        }
    }
};
</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: 20px;
    border-radius: 10px;
    background-color: #113160;
    color: white;
    height: 800px;
    width: 300px;
}

.nr {
    display: flex;
}

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

.top-ssjc {
    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-ssjc {
    /* margin-top: 30px; */
    height: 762px;
    flex-shrink: 0;
    border-radius: 20px;
    background: linear-gradient(180deg, #092650 0%, #09265000 100%);
}

/* 滚动条样式 */
.device-list::-webkit-scrollbar {
    width: 8px; /* 滚动条宽度 */
    height: auto;
}

.device-list::-webkit-scrollbar-thumb {
    background-color: #3f83e8; /* 滚动条滑块颜色 */
    border-radius: 4px; /* 滚动条滑块圆角 */
}

.device-list::-webkit-scrollbar-track {
    background-color: #64686e; /* 滚动条轨道颜色 */
    border-radius: 4px; /* 滚动条轨道圆角 */
}

/* 横向滚动条样式 */
.device-list::-webkit-scrollbar-track-piece {
    background-color: #555a5d;
}

/* 滚动条两端的按钮 */
.device-list::-webkit-scrollbar-button {
    display: none; /* 隐藏滚动条两端的按钮 */
}

.threshold-input {
    background: linear-gradient(90deg, #174283 0%, #0e284f);
    border: 0;
    border-radius: 8px;
    height: 26px;
    width: 200px;
    margin-bottom: 20px;
}

.history-data-table {
    background-color: #153768 !important;
}

.history-data-table .el-table__body-wrapper::after,
.history-data-table .el-table__header-wrapper::after {
    height: 0 !important;
}

//.history-data-table > > > .el-table__row {
//    background-color: #153768;
//    font-size: 10px;
//    height: 20px; /* 调整为您需要的行高 */
//}

.history-data-table .el-table__row {
    background-color: #153768 !important;
    font-size: 10px !important;
    height: 20px !important;
}

.history-data-table .el-table__body,
.history-data-table .el-table__header {
    background-color: #153768;
}

</style>
