<template>
    <div style="padding: 6px">
        <el-card v-if="showType == 'card'" style="padding-bottom: 100px">
            <el-row v-loading="loading" :gutter="30">
                <el-col v-for="(item, index) in deviceList" :key="index" :lg="8" :md="12" :sm="12" :xl="6" :xs="24" style="margin-bottom: 30px; text-align: center">
                    <el-card :body-style="{ padding: '20px' }" class="card-item" shadow="always">
                        <el-row :gutter="10" justify="space-between" type="flex">
                            <el-col :span="20" style="text-align: left">
                                <el-link :underline="false" style="font-weight: bold; font-size: 16px; line-height: 32px" type="" @click="handleDeviceDetail(item)">
                                    <el-tooltip class="item" content="分享的设备" effect="dark" placement="top-start">
                                        <svg-icon v-if="item.isOwner != 1" icon-class="share" style="font-size: 20px" />
                                    </el-tooltip>
                                    <svg-icon v-if="item.isOwner == 1" icon-class="device" />
                                    <span style="margin: 0 5px">{{ item.deviceName }}</span>
                                </el-link>
                            </el-col>
                            <el-col :span="3">
                                <div style="font-size: 28px; color: #ccc">
                                    <svg-icon v-if="item.status == 3 && item.rssi >= '-55'" icon-class="wifi_4" />
                                    <svg-icon v-else-if="item.status == 3 && item.rssi >= '-70' && item.rssi < '-55'" icon-class="wifi_3" />
                                    <svg-icon v-else-if="item.status == 3 && item.rssi >= '-85' && item.rssi < '-70'" icon-class="wifi_2" />
                                    <svg-icon v-else-if="item.status == 3 && item.rssi >= '-100' && item.rssi < '-85'" icon-class="wifi_1" />
                                    <svg-icon v-else icon-class="wifi_0" />
                                </div>
                            </el-col>
                        </el-row>
                        <el-row :gutter="10">
                            <el-col :span="17">
                                <div style="text-align: left; line-height: 40px; white-space: nowrap">
                                    <dict-tag :options="dict.type.iot_device_status" :value="item.status" size="small" style="display: inline-block" />
                                    <span style="display: inline-block; margin: 0 10px">
                                        <el-tag v-if="item.protocolCode" size="small" type="primary">{{ item.protocolCode }}</el-tag>
                                    </span>
                                    <el-tag v-if="item.transport" size="small" type="primary">{{ item.transport }}</el-tag>
                                </div>
                                <el-descriptions :column="1" size="mini" style="white-space: nowrap">
                                    <el-descriptions-item label="编号">
                                        {{ item.serialNumber }}
                                    </el-descriptions-item>
                                    <el-descriptions-item label="产品">
                                        {{ item.productName }}
                                    </el-descriptions-item>
                                    <el-descriptions-item label="激活时间">
                                        {{ parseTime(item.activeTime, '{y}-{m}-{d}') }}
                                    </el-descriptions-item>
                                </el-descriptions>
                            </el-col>
                            <el-col :span="7">
                                <div style="margin-top: 10px">
                                    <el-image
                                        v-if="item.imgUrl != null && item.imgUrl != ''"
                                        :preview-src-list="[baseUrl + item.imgUrl]"
                                        :src="baseUrl + item.imgUrl"
                                        fit="cover"
                                        lazy
                                        style="width: 100%; height: 100px; border-radius: 10px"
                                    ></el-image>
                                    <el-image
                                        v-else-if="item.deviceType == 2"
                                        :preview-src-list="[require('@/assets/images/gateway.png')]"
                                        :src="require('@/assets/images/gateway.png')"
                                        fit="cover"
                                        style="width: 100%; height: 100px; border-radius: 10px"
                                    ></el-image>
                                    <el-image
                                        v-else-if="item.deviceType == 3"
                                        :preview-src-list="[require('@/assets/images/video.png')]"
                                        :src="require('@/assets/images/video.png')"
                                        fit="cover"
                                        style="width: 100%; height: 100px; border-radius: 10px"
                                    ></el-image>
                                    <el-image
                                        v-else
                                        :preview-src-list="[require('@/assets/images/product.png')]"
                                        :src="require('@/assets/images/product.png')"
                                        fit="cover"
                                        style="width: 100%; height: 100px; border-radius: 10px"
                                    ></el-image>
                                </div>
                            </el-col>
                        </el-row>
                        <el-button-group style="margin-top: 15px">
                            <el-button v-hasPermi="['iot:device:query']" icon="el-icon-view" size="mini" style="padding: 5px 15px" type="primary" @click="handleEditDevice(item, 'basic')">查看</el-button>
                        </el-button-group>
                    </el-card>
                </el-col>
            </el-row>
            <el-empty v-if="total == 0" description="暂无数据，请添加设备"></el-empty>
            <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :pageSizes="[12, 24, 36, 60]" :total="total" @pagination="getList" />
        </el-card>

        <!--显示里面物模型的信息-->
        <el-dialog :visible.sync="open" append-to-body title="物模型" width="800px">
            <el-table :border="false" :data="tableData" border style="width: 100%">
                <el-table-column align="center" label="物模型" prop="name"></el-table-column>
                <el-table-column align="center" label="值" prop="shadow"></el-table-column>
                <el-table-column align="center" label="标识符" prop="id"></el-table-column>
                <el-table-column align="center" label="阈值下限" prop="address"></el-table-column>
                <el-table-column align="center" label="阈值上限" prop="address"></el-table-column>
                <el-table-column align="center" label="操作">
                    <template slot-scope="scope">
                        <el-button icon="el-icon-delete" size="mini" type="text">阈值设置</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
import { listDeviceShort } from '@/api/iot/device';
import { listGroup } from '@/api/iot/group';
import auth from '@/plugins/auth';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import { getDeviceRunningStatus } from '@/api/iot/device';

export default {
    name: 'Device',
    dicts: ['iot_device_status'],
    data() {
        return {
            // 展示方式
            showType: 'card',
            // 遮罩层
            loading: true,
            // 总条数
            total: 0,
            // 设备列表数据
            deviceList: [],
            // 我的分组列表数据
            myGroupList: [],
            // 根路径
            baseUrl: process.env.VUE_APP_BASE_API,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 12,
                showChild: true,
                deviceName: null,
                productId: null,
                groupId: null,
                productName: null,
                userId: null,
                userName: null,
                tenantId: null,
                tenantName: null,
                serialNumber: null,
                status: null,
                networkAddress: null,
                activeTime: null,
            },
            // 表单参数
            form: {
                productId: 0,
                status: 1,
                locationWay: 1,
                firmwareVersion: 1.0,
                serialNumber: '',
                deviceType: 1,
                isSimulate: 0,
            },
            // 批量导入参数
            isSubDev: false,
            open: false,
            tableData: [],
        };
    },
    created() {
        // 产品筛选
        let productId = this.$route.query.productId;
        if (productId != null) {
            this.queryParams.productId = Number(productId);
            this.queryParams.groupId = null;
            this.queryParams.serialNumber = null;
        }
        // 分组筛选
        let groupId = this.$route.query.groupId;
        if (groupId != null) {
            this.queryParams.groupId = Number(groupId);
            this.queryParams.productId = null;
            this.queryParams.serialNumber = null;
        }
        // 设备编号筛选
        let sn = this.$route.query.sn;
        if (sn != null) {
            this.queryParams.serialNumber = sn;
            this.queryParams.productId = null;
            this.queryParams.groupId = null;
        }
        this.connectMqtt();
    },
    methods: {
        /* 连接Mqtt消息服务器 */
        async connectMqtt() {
            if (this.$mqttTool.client == null) {
                await this.$mqttTool.connect();
            }
            this.mqttCallback();
            this.getList();
        },
        /* Mqtt回调处理  */
        mqttCallback() {
            this.$mqttTool.client.on('message', (topic, message, buffer) => {
                let topics = topic.split('/');
                let productId = topics[1];
                let deviceNum = topics[2];
                message = JSON.parse(message.toString());
                if (!message) {
                    return;
                }
                if (topics[3] == 'status') {
                    console.log('接收到【设备状态】主题：', topic);
                    console.log('接收到【设备状态】内容：', message);
                    // 更新列表中设备的状态
                    for (let i = 0; i < this.deviceList.length; i++) {
                        if (this.deviceList[i].serialNumber == deviceNum) {
                            this.deviceList[i].status = message.status;
                            this.deviceList[i].isShadow = message.isShadow;
                            this.deviceList[i].rssi = message.rssi;
                            return;
                        }
                    }
                }
            });
        },
        /* 订阅消息 */
        mqttSubscribe(list) {
            // 订阅当前页面设备状态和实时监测
            let topics = [];
            for (let i = 0; i < list.length; i++) {
                let topicStatus = '/' + '+' + '/' + list[i].serialNumber + '/status/post';
                topics.push(topicStatus);
            }
            this.$mqttTool.subscribe(topics);
        },
        /** 查询设备分组列表 */
        getGroupList() {
            this.loading = true;
            let queryParams = {
                pageSize: 30,
                pageNum: 1,
                userId: this.$store.state.user.userId,
            };
            listGroup(queryParams).then((response) => {
                this.myGroupList = response.rows;
            });
        },
        /** 查询所有简短设备列表 */
        getList() {
            this.loading = true;
            this.queryParams.params = {};
            this.getGroupList();
            listDeviceShort(this.queryParams).then((response) => {
                this.deviceList = response.rows;
                this.total = response.total;
                // 订阅消息
                if (this.deviceList && this.deviceList.length > 0) {
                    this.mqttSubscribe(this.deviceList);
                }
                this.loading = false;
            });
        },
        // 点击名称查看
        handleDeviceDetail(item) {
            if (auth.hasPermi('iot:device:query')) {
                this.handleEditDevice(item);
            }
        },
        /** 查看按钮操作 */
        handleEditDevice(row, activeName) {
            this.open = true;
            let deviceId = 0;
            let isSubDev = 0;
            if (row != 0) {
                deviceId = row.deviceId || this.ids;
                isSubDev = row.subDeviceCount > 0 ? 1 : 0;
            }
            const date = {
                deviceId: deviceId,
                isSubDev: isSubDev,
            };
            getDeviceRunningStatus(date).then((response) => {
                const list = response.data.thingsModels;
                this.tableData = list;
            });
        },
    },
};
</script>

<style scoped>
.card-item {
    border-radius: 15px;
}
</style>
