﻿<template>
    <div class="NCC-common-layout">
        <div class="NCC-common-layout-center">
            <el-row class="NCC-common-search-box" :gutter="16">
                <el-form @submit.native.prevent>
                    <el-col :span="6">
                        <el-form-item label="设备名称">
                            <el-input v-model="query.deviceName" placeholder="设备名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="设备编号">
                            <el-input v-model="query.deviceCode" placeholder="设备编号" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="归属用户ID">
                            <el-input v-model="query.belongUserId" placeholder="归属用户ID" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item>
                            <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
                            <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
            <div class="NCC-common-layout-main NCC-flex-main">
                <div class="NCC-common-head">
                    <div class="head-left">
                        <el-button 
                            type="primary" 
                            icon="el-icon-refresh" 
                            @click="refreshOnlineStatus()"
                            :loading="statusLoading"
                            size="small"
                        >
                            刷新在线状态
                        </el-button>
                        
                        <!-- 设备统计信息 -->
                        <div class="device-stats-inline">
                            <div class="stats-item">
                                <span class="stats-label">在线:</span>
                                <span class="stats-number online">{{ onlineDeviceCount }}</span>
                            </div>
                            <div class="stats-item">
                                <span class="stats-label">离线:</span>
                                <span class="stats-number offline">{{ offlineDeviceCount }}</span>
                            </div>
                            <div class="stats-item">
                                <span class="stats-label">总数:</span>
                                <span class="stats-number total">{{ totalDeviceCount }}</span>
                            </div>
                            <div class="stats-item">
                                <span class="stats-label">在线率:</span>
                                <span class="stats-number rate">{{ onlineRate }}%</span>
                            </div>
                        </div>
                    </div>
                    <div class="NCC-common-head-right">
                        <el-tooltip effect="dark" content="刷新" placement="top">
                            <el-link icon="icon-ym icon-ym-Refresh NCC-common-head-icon" :underline="false"
                                @click="reset()" />
                        </el-tooltip>
                        <screenfull isContainer />
                    </div>
                </div>
                <!-- 这里显示类似机柜的样式 -->
                <div class="cabinet-list">
                    <div v-loading="listLoading" v-for="item in list" :key="item.id" class="cabinet-wrapper">
                        <div class="cabinet">
                            <div class="cabinet-top">
                                <div class="device-name-row">
                                    <span>名称：{{ item.deviceName }}</span>
                                    <div class="device-status">
                                        <span class="status-dot" :class="{ 'online': item.isOnline, 'offline': !item.isOnline }"></span>
                                        <span>{{ item.isOnline ? '在线' : '离线' }}</span>
                                    </div>
                                </div>
                                <div class="device-info-row">
                                    <span>编号：{{ item.deviceCode ? item.deviceCode.toUpperCase() : '' }}</span>
                                    <i class="el-icon-menu" style="cursor: pointer; margin-left: 5px;" @click="CreateQrCode(item.deviceCode)"></i>
                                </div>
                                <div class="device-info-row">
                                    <span>代理商：{{ item.belongUserName }}</span>
                                    <span>APP版本：{{ item.appVersion || '未知' }}</span>
                                </div>
                                <!-- <div class="cabinet-bottom-right">状态：{{ item.status }}</div> -->
                            </div>
                            <div <div class="cabinet-middle">
                                <div class="slot" v-for="(n, index) in item.uavDeviceCells"
                                    :style="{ backgroundColor: getStatusColor(n.status) }" :key="n">货道{{ n.cellCode
                                    }}:{{ n.statusName }}
                                    <el-tooltip :content="n.uavCode" placement="top" effect="dark">
                                        <img style="width: 20px; height: 20px;margin-left: 10px;"
                                            :src="n.uavCode ? require('@/assets/images/wrj_1.png') : require('@/assets/images/wrj_2.png')"
                                            alt="无人机图标" />
                                    </el-tooltip>
                                    <el-tooltip :content="n.rfid1" placement="top" effect="dark">
                                        <img style="width: 20px; height: 20px;margin-left: 10px;"
                                            :src="n.rfid1 ? require('@/assets/images/dc_1.png') : require('@/assets/images/dc_2.png')"
                                            alt="电池图标" />
                                    </el-tooltip>
                                    <el-tooltip :content="n.rfid2" placement="top" effect="dark">
                                        <img style="width: 20px; height: 20px;margin-left: 10px;"
                                            :src="n.rfid2 ? require('@/assets/images/dc_1.png') : require('@/assets/images/dc_2.png')"
                                            alt="电池图标" />
                                    </el-tooltip>
                                </div>
                            </div>
                            <div class="cabinet-bottom">

                            </div>
                        </div>
                    </div>
                </div>

                <!-- <NCC-table v-loading="listLoading" :data="list">
                    <el-table-column prop="deviceName" label="设备名称" align="left" />
                    <el-table-column prop="deviceCode" label="设备编号" align="left" />
                    <el-table-column label="所属场地ID" prop="siteId" align="left">
                        <template slot-scope="scope">{{ scope.row.siteId | dynamicText(siteIdOptions) }}</template>
</el-table-column>
<el-table-column prop="belongUserId" label="归属用户ID" align="left" />
<el-table-column prop="status" label="状态" align="left" />
<el-table-column prop="remark" label="备注" align="left" />
<el-table-column label="操作" fixed="right" width="170">
    <template slot-scope="scope">
                            <el-button type="text" @click="CreateQrCode(scope.row.deviceCode)">查看二维码</el-button>
                            <el-button type="text" @click="addOrUpdateHandle(scope.row.id)">编辑</el-button>
                            <el-button type="text" @click="handleDel(scope.row.id)"
                                class="NCC-table-delBtn">删除</el-button>
                        </template>
</el-table-column>
</NCC-table> -->
                <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
                    :page-sizes="[10, 20]" @pagination="initData" />
            </div>
        </div>
        <!-- 弹出框 -->
        <div v-if="showQr" class="qr-popup">
            <div class="qr-mask" @click="showQr = false"></div>
            <div class="qr-content">
                <template v-if="qrImgUrl">
                    <img :src="qrImgUrl" class="qr-img" />
                </template>
                <template v-else>
                    <div class="no-qr-tip">{{ qrmessage }}</div>
                </template>
            </div>
        </div>
        <NCC-Form v-if="formVisible" ref="NCCForm" @refresh="refresh" />
        <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    </div>
</template>
<script>
import request from '@/utils/request'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import NCCForm from './Form'
import ExportBox from './ExportBox'
import { previewDataInterface } from '@/api/systemData/dataInterface'
export default {
    components: { NCCForm, ExportBox },
    data() {
        return {
            showAll: false,
            query: {
                deviceName: undefined,
                deviceCode: undefined,
                belongUserId: undefined,
            },
            list: [],
            listLoading: true,
            multipleSelection: [], total: 0,
            listQuery: {
                currentPage: 1,
                pageSize: 10,
                sort: "desc",
                sidx: "",
            },
            formVisible: false,
            exportBoxVisible: false,
            columnList: [
                { prop: 'deviceName', label: '设备名称' },
                { prop: 'deviceCode', label: '设备编号' },
                { prop: 'siteId', label: '所属场地ID' },
                { prop: 'belongUserId', label: '归属用户ID' },
                { prop: 'lng', label: '经度' },
                { prop: 'lat', label: '纬度' },
                { prop: 'status', label: '状态' },
                { prop: 'remark', label: '备注' },
            ],
            siteIdOptions: [],
            showQr: false,
            qrImgUrl: '',// 二维码图片地址
            qrmessage: '暂无二维码', // 二维码提示信息
            statusLoading: false, // 在线状态加载状态
            deviceStats: {
                onlineCount: 0,
                offlineCount: 0,
                totalCount: 0
            } // 设备统计数据
        }
    },
    computed: {
        // 计算在线设备数量
        onlineDeviceCount() {
            return this.deviceStats.onlineCount || 0;
        },
        // 计算离线设备数量
        offlineDeviceCount() {
            return this.deviceStats.offlineCount || 0;
        },
        // 计算总设备数量
        totalDeviceCount() {
            return this.deviceStats.totalCount || 0;
        },
        // 计算在线率
        onlineRate() {
            if (this.totalDeviceCount === 0) return 0;
            return Math.round((this.onlineDeviceCount / this.totalDeviceCount) * 100);
        }
    },
    created() {
        this.initData()
        this.getsiteIdOptions();
        this.getDeviceStats(); // 获取设备统计数据
    },
    methods: {
        getStatusColor(status) {
            const colorMap = {
                1: '#67C23A', // 空闲 - 绿色
                2: '#909399', // 停用 - 灰色  
                3: '#E6A23C', // 充电 - 橙色
                4: '#F56C6C', // 损坏 - 红色
                5: '#409EFF'  // 已租接 - 蓝色
            }
            return colorMap[status] || '#67C23A'
        },
        CreateQrCode(code) {
            this.qrImgUrl = "";
            this.qrmessage = "正在加载二维码"
            this.showQr = true; // 弹出框显示
            // 示例二维码链接，换成你自己的生成逻辑或接口地址
            //http://localhost:2011/api/Extend/alipay/CreateQrCode?queryParams=1
            // var query = `query=terminalId=${code}`;
            var query = code;
            request({
                url: `/api/Extend/alipay/CreateQrCode?queryParams=${code}`,
                method: 'POSt',
            }).then(res => {
                if (res.code == 200) {
                    this.qrImgUrl = res.data.Item2;
                } else {
                    this.qrmessage = "暂无二维码"
                }

            })
        },
        getsiteIdOptions() {
            previewDataInterface('702758837928592645').then(res => {
                this.siteIdOptions = res.data
            });
        },
        initData() {
            this.listLoading = true;
            let _query = {
                ...this.listQuery,
                ...this.query
            };
            let query = {}
            for (let key in _query) {
                if (Array.isArray(_query[key])) {
                    query[key] = _query[key].join()
                } else {
                    query[key] = _query[key]
                }
            }
            request({
                url: `/api/Extend/UavDevice`,
                method: 'GET',
                data: query
            }).then(res => {
                this.list = res.data.list
                this.total = res.data.pagination.total
                
                // 获取设备在线状态
                this.getDeviceOnlineStatus();
                
                this.listLoading = false
            })
        },
        
        // 获取设备在线状态
        getDeviceOnlineStatus() {
            if (this.list.length === 0) return;
            
            // 提取设备编号列表
            const deviceCodes = this.list.map(item => item.deviceCode).filter(code => code);
            
            if (deviceCodes.length === 0) return;
            
            // 调用批量查询在线状态接口
            request({
                url: `/api/Extend/UavDevice/BatchCheckOnlineStatus`,
                method: 'POST',
                data: {
                    deviceIds: deviceCodes
                }
            }).then(res => {
                if (res.data && res.data.length > 0) {
                    // 更新设备在线状态
                    this.list.forEach(device => {
                        const statusInfo = res.data.find(item => item.deviceId === device.deviceCode);
                        if (statusInfo) {
                            device.isOnline = statusInfo.isOnline;
                        } else {
                            device.isOnline = false; // 默认离线
                        }
                    });
                }
            }).catch(error => {
                console.error('获取设备在线状态失败:', error);
                // 如果查询失败，将所有设备标记为离线
                this.list.forEach(device => {
                    device.isOnline = false;
                });
            });
        },
        handleDel(id) {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                type: 'warning'
            }).then(() => {
                request({
                    url: `/api/Extend/UavDevice/${id}`,
                    method: 'DELETE'
                }).then(res => {
                    this.$message({
                        type: 'success',
                        message: res.msg,
                        onClose: () => {
                            this.initData()
                        }
                    });
                })
            }).catch(() => {
            });
        },
        addOrUpdateHandle(id, isDetail) {
            this.formVisible = true
            this.$nextTick(() => {
                this.$refs.NCCForm.init(id, isDetail)
            })
        },
        search() {
            this.listQuery = {
                currentPage: 1,
                pageSize: 20,
                sort: "desc",
                sidx: "",
            }
            this.initData()
            this.getDeviceStats() // 更新统计数据
        },
        refresh(isrRefresh) {
            this.formVisible = false
            this.listQuery = {
                currentPage: 1,
                pageSize: 10,
                sort: "desc",
                sidx: "",
            }
            if (isrRefresh) this.reset()
        },
        reset() {
            for (let key in this.query) {
                this.query[key] = undefined
            }

            this.initData()
            this.getDeviceStats() // 更新统计数据
        },
        
        // 刷新在线状态
        refreshOnlineStatus() {
            this.statusLoading = true;
            this.getDeviceOnlineStatus();
            this.getDeviceOnlineStatusAsync(); // 直接调用异步获取在线状态
            
            // 延迟结束loading状态
            setTimeout(() => {
                this.statusLoading = false;
            }, 1000);
        },
        
        // 获取设备统计数据（快速版本）
        getDeviceStats() {
            // 先获取设备总数，快速显示
            request({
                url: `/api/Extend/UavDevice`,
                method: 'GET',
                data: {
                    currentPage: 1,
                    pageSize: 1, // 只获取1条数据来获取总数
                    sort: "desc",
                    sidx: "",
                    ...this.query
                }
            }).then(res => {
                if (res.data && res.data.pagination) {
                    const totalCount = res.data.pagination.total || 0;
                    
                    // 先显示总数，在线状态默认为0
                    this.deviceStats = {
                        onlineCount: 0,
                        offlineCount: totalCount,
                        totalCount: totalCount
                    };
                    
                    // 如果有设备，异步获取在线状态
                    if (totalCount > 0) {
                        this.getDeviceOnlineStatusAsync();
                    }
                } else {
                    this.deviceStats = {
                        onlineCount: 0,
                        offlineCount: 0,
                        totalCount: 0
                    };
                }
            }).catch(error => {
                console.error('获取设备总数失败:', error);
                this.deviceStats = {
                    onlineCount: 0,
                    offlineCount: 0,
                    totalCount: 0
                };
            });
        },
        
        // 异步获取设备在线状态
        getDeviceOnlineStatusAsync() {
            // 获取所有设备
            request({
                url: `/api/Extend/UavDevice`,
                method: 'GET',
                data: {
                    currentPage: 1,
                    pageSize: 10000,
                    sort: "desc",
                    sidx: "",
                    ...this.query
                }
            }).then(res => {
                if (res.data && res.data.list) {
                    const allDevices = res.data.list;
                    const deviceCodes = allDevices.map(item => item.deviceCode).filter(code => code);
                    
                    if (deviceCodes.length > 0) {
                        // 显示查询提示
                        this.$message.info('正在查询设备在线状态，请稍候...');
                        
                        request({
                            url: `/api/Extend/UavDevice/BatchCheckOnlineStatus`,
                            method: 'POST',
                            data: {
                                deviceIds: deviceCodes
                            }
                        }).then(statusRes => {
                            if (statusRes.data && statusRes.data.length > 0) {
                                let onlineCount = 0;
                                let offlineCount = 0;
                                
                                statusRes.data.forEach(statusInfo => {
                                    if (statusInfo.isOnline) {
                                        onlineCount++;
                                    } else {
                                        offlineCount++;
                                    }
                                });
                                
                                // 更新统计数据
                                this.deviceStats = {
                                    onlineCount: onlineCount,
                                    offlineCount: offlineCount,
                                    totalCount: allDevices.length
                                };
                                
                                // 显示查询结果
                                this.$message.success(`设备状态查询完成，在线：${onlineCount}个，离线：${offlineCount}个`);
                            } else {
                                this.deviceStats = {
                                    onlineCount: 0,
                                    offlineCount: allDevices.length,
                                    totalCount: allDevices.length
                                };
                            }
                        }).catch(error => {
                            console.error('获取设备在线状态失败:', error);
                            this.$message.warning('在线状态查询失败，将显示为离线状态');
                        });
                    }
                }
            }).catch(error => {
                console.error('获取设备列表失败:', error);
            });
        }
    }
}
</script>

<style>
/* 设备统计信息样式 */
.head-left {
    display: flex;
    align-items: center;
    gap: 20px;
}

.device-stats-inline {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-left: 20px;
}

.stats-item {
    display: flex;
    align-items: center;
    gap: 4px;
}

.stats-item .stats-label {
    font-size: 12px;
    color: #909399;
    font-weight: 500;
}

.stats-item .stats-number {
    font-size: 14px;
    font-weight: 600;
    padding: 2px 6px;
    border-radius: 4px;
    min-width: 20px;
    text-align: center;
}

.stats-item .stats-number.online {
    background: rgba(103, 194, 58, 0.1);
    color: #67C23A;
}

.stats-item .stats-number.offline {
    background: rgba(245, 108, 108, 0.1);
    color: #F56C6C;
}

.stats-item .stats-number.total {
    background: rgba(64, 158, 255, 0.1);
    color: #409EFF;
}

.stats-item .stats-number.rate {
    background: rgba(230, 162, 60, 0.1);
    color: #E6A23C;
}

@media (max-width: 1200px) {
    .device-stats-inline {
        gap: 12px;
        margin-left: 16px;
    }
    
    .stats-item .stats-number {
        font-size: 13px;
        padding: 1px 4px;
    }
}

@media (max-width: 768px) {
    .head-left {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }
    
    .device-stats-inline {
        margin-left: 0;
        gap: 8px;
        flex-wrap: wrap;
    }
    
    .stats-item .stats-number {
        font-size: 12px;
        padding: 1px 3px;
    }
}

.stats-card {
    flex: 1;
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    transition: all 0.3s ease;
}

.stats-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stats-icon {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    font-size: 24px;
    color: white;
}

.stats-icon.online {
    background: linear-gradient(135deg, #67C23A, #85CE61);
}

.stats-icon.offline {
    background: linear-gradient(135deg, #F56C6C, #F78989);
}

.stats-icon.total {
    background: linear-gradient(135deg, #409EFF, #66B1FF);
}

.stats-icon.online-rate {
    background: linear-gradient(135deg, #E6A23C, #EEBE77);
}

.stats-content {
    flex: 1;
}

.stats-number {
    font-size: 28px;
    font-weight: 700;
    color: #303133;
    line-height: 1;
    margin-bottom: 4px;
}

.stats-label {
    font-size: 14px;
    color: #909399;
    font-weight: 500;
}

.qr-popup {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 999;
}

.qr-mask {
    position: absolute;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
}

.qr-content {
    position: absolute;
    top: 30%;
    left: 50%;
    transform: translate(-50%, -30%);
    background: #fff;
    padding: 30rpx;
    border-radius: 20rpx;
    text-align: center;
    padding: 20px;
    border-radius: 10px;
}

.qr-img {
    width: 300px;
    margin-bottom: 20rpx;
}

.cabinet-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    margin-left: 10px;
    /* 元素间距 */
}

.cabinet-wrapper {
    width: 300px;
}

.cabinet {
    border: 2px solid #000;
    border-radius: 10px;
    padding: 10px;
    background: #f9f9f9;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    display: flex;
    flex-direction: column;
    height: 260px;
    /* justify-content: space-between; */
}

.cabinet-top {
    font-size: 12px;
    line-height: 16px;
    background-color: black;
    color: #FFF;
    padding: 6px 8px;
    border-radius: 6px;
    margin-bottom: 8px;
}

.cabinet-bottom {}

.cabinet-middle {
    /* display: grid;
    grid-template-columns: repeat(3, 1fr); */
    grid-gap: 6px;
    margin: 3px 0;
    /* flex-grow: 1; */
    align-items: top;
    flex-grow: 1;
}

.slot {
    width: 100%;
    height: 20px;
    color: #FFF;
    margin-bottom: 4px;
    border-radius: 4px;
    display: flex;
    padding-left: 8px;
    align-items: center;
    font-size: 11px;
    user-select: none;
}

.device-status {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 11px;
}

.device-name-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 3px;
}

.device-info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2px;
}

.status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    display: inline-block;
}

.status-dot.online {
    background-color: #67C23A;
}

.status-dot.offline {
    background-color: #F56C6C;
}
</style>