﻿<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">
                    </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" :class="{ 'status-online': item.isOnline, 'status-offline': !item.isOnline }">
                                        <span class="status-dot" :class="{ 'online': item.isOnline, 'offline': !item.isOnline }"></span>
                                        <span class="status-text">{{ item.isOnline ? '在线' : '离线' }}</span>
                                    </div>
                                </div>
                                <div class="device-info-row">
                                    <span>编号：{{ item.deviceCode ? item.deviceCode.toUpperCase() : '' }}</span>
                                    <div class="device-actions">
                                        <i class="el-icon-menu" style="cursor: pointer; margin-left: 5px;" @click="CreateQrCode(item.deviceCode)" title="查看二维码"></i>
                                        <i class="el-icon-upload" style="cursor: pointer; margin-left: 8px; color: #409EFF;" @click="pushAppUpdate(item)" title="推送APP更新"></i>
                                    </div>
                                </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: '暂无二维码', // 二维码提示信息

        }
    },

    created() {
        this.initData()
        this.getsiteIdOptions();
    },
    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()
        },
        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()
        },
        
        // 推送APP更新
        pushAppUpdate(device) {
            if (!device.isOnline) {
                this.$message.warning('设备离线，无法推送更新');
                return;
            }
            
            this.$confirm(`确定要推送APP更新到设备 "${device.deviceName}" 吗？`, '确认推送', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$message.info('正在推送APP更新，请稍候...');
                
                // 调用推送更新接口
                request({
                    url: `/api/Extend/UavDevice/PushAppUpdate`,
                    method: 'POST',
                    data: {
                        deviceCode: device.deviceCode,
                        downloadUrl: "" // 可选参数，传空字符串使用默认下载地址
                    }
                }).then(res => {
                    if (res.code === 200) {
                        this.$message.success(`APP更新推送成功！设备：${device.deviceName}`);
                        
                        // 可选：刷新设备状态
                        setTimeout(() => {
                            this.getDeviceOnlineStatus();
                        }, 2000);
                    } else {
                        this.$message.error(res.msg || 'APP更新推送失败');
                    }
                }).catch(error => {
                    console.error('推送APP更新失败:', error);
                    this.$message.error('APP更新推送失败，请检查网络连接');
                });
            }).catch(() => {
                this.$message.info('已取消推送');
            });
        },


    }
}
</script>

<style>
/* 头部样式 */
.head-left {
    display: flex;
    align-items: center;
    gap: 20px;
}

.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-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: 6px;
    font-size: 11px;
    padding: 4px 8px;
    border-radius: 12px;
    font-weight: 600;
    transition: all 0.3s ease;
}

.device-status.status-online {
    background: rgba(103, 194, 58, 0.2);
    border: 1px solid #67C23A;
    color: #67C23A;
}

.device-status.status-offline {
    background: rgba(245, 108, 108, 0.2);
    border: 1px solid #F56C6C;
    color: #F56C6C;
}

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

.device-actions {
    display: flex;
    align-items: center;
    gap: 4px;
}

.device-actions i {
    transition: all 0.3s ease;
    padding: 2px;
    border-radius: 3px;
}

.device-actions i:hover {
    background-color: rgba(255, 255, 255, 0.2);
    transform: scale(1.1);
}

.status-dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    display: inline-block;
    box-shadow: 0 0 4px rgba(0, 0, 0, 0.3);
    animation: pulse 2s infinite;
}

.status-dot.online {
    background-color: #67C23A;
    box-shadow: 0 0 6px rgba(103, 194, 58, 0.6);
}

.status-dot.offline {
    background-color: #F56C6C;
    box-shadow: 0 0 6px rgba(245, 108, 108, 0.6);
    animation: none;
}

.status-text {
    font-weight: 600;
    letter-spacing: 0.5px;
}

@keyframes pulse {
    0% {
        transform: scale(1);
        opacity: 1;
    }
    50% {
        transform: scale(1.1);
        opacity: 0.8;
    }
    100% {
        transform: scale(1);
        opacity: 1;
    }
}
</style>