<template>
    <div class="iot-device">
        <el-card v-show="showSearch" style="margin-bottom: 15px; border-radius: 8px; width: 100%; padding-bottom: 22.5px">
            <el-form @submit.native.prevent :model="queryParams" ref="queryForm" :inline="true" label-width="75px" style="margin-bottom: -18px; height: 36px; padding: 3px 0 0 0">
                <el-form-item prop="deviceName">
                    <el-input v-model="queryParams.deviceName" :placeholder="$t('device.index.105953-1')" clearable @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item prop="serialNumber">
                    <el-input v-model="queryParams.serialNumber" :placeholder="$t('device.index.105953-3')" clearable @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item prop="status">
                    <el-select v-model="queryParams.status" :placeholder="$t('device.index.105953-5')" clearable>
                        <el-option v-for="dict in dict.type.iot_device_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>

                <template v-if="searchShow">
                    <el-form-item>
                        <el-select v-model="queryParams.groupId" :placeholder="$t('device.index.105953-7')" clearable>
                            <el-option v-for="group in myGroupList" :key="group.groupId" :label="group.groupName" :value="group.groupId" />
                        </el-select>
                    </el-form-item>
                </template>

                <div style="float: right">
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{ $t('search') }}</el-button>
                    <el-button icon="el-icon-refresh" @click="resetQuery">{{ $t('reset') }}</el-button>
                    <el-button type="text" @click="searchChange">
                        <span style="color: #486ff2; margin-left: 14px">{{ searchShow ? $t('template.index.891112-113') : $t('template.index.891112-112') }}</span>
                        <i style="color: #486ff2; margin-left: 10px" :class="{ 'el-icon-arrow-down': !searchShow, 'el-icon-arrow-up': searchShow }"></i>
                    </el-button>
                </div>
            </el-form>
        </el-card>

        <el-card>
            <el-row :gutter="10">
                <el-col :span="1.5">
                    <el-dropdown @command="(command) => handleCommand(command)" v-hasPermi="['iot:device:add']">
                        <el-button size="small" type="primary" plain icon="el-icon-plus">
                            {{ $t('device.index.105953-10') }}
                            <i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="handleEditDevice" v-hasPermi="['iot:device:add']">{{ $t('device.index.105953-11') }}</el-dropdown-item>
                            <el-dropdown-item command="handleBatchImport" v-hasPermi="['iot:device:add']">{{ $t('device.index.105953-12') }}</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </el-col>
                <el-col :span="1.5" v-if="showType == 'list'">
                    <el-button plain icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete" v-hasPermi="['iot:device:remove']">{{ $t('del') }}</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-dropdown @command="(command) => handleCommand1(command)" v-hasPermi="['iot:device:assignment']">
                        <el-button size="small" type="primary" plain class="btn-wrap" icon="el-icon-folder-opened">
                            {{ $t('device.index.105953-13') }}
                            <i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="handleSelectAllot" v-hasPermi="['iot:device:assignment']">{{ $t('device.index.105953-14') }}</el-dropdown-item>
                            <el-dropdown-item command="handleImportAllot" v-hasPermi="['iot:device:assignment']">{{ $t('device.index.105953-15') }}</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </el-col>
                <el-col :span="1.5">
                    <el-button size="small" type="primary" plain icon="el-icon-delete" @click="recycleDevice" v-hasPermi="['iot:device:recovery']" class="btn-wrap">{{ $t('device.index.105953-16') }}</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-dropdown @command="(command) => handleCommandMore(command)" v-hasPermi="['iot:device:record:list', 'iot:device:batchGenerator']">
                        <el-button size="small" type="primary" plain class="btn-wrap" icon="el-icon-more-outline">
                            {{ $t('device.index.105953-48') }}
                            <i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="importRecord" v-hasPermi="['iot:device:record:list']">{{ $t('device.index.105953-49') }}</el-dropdown-item>
                            <el-dropdown-item command="generateSerialNumber" v-hasPermi="['iot:device:batchGenerator']">{{ $t('device.index.105953-50') }}</el-dropdown-item>
                            <el-dropdown-item command="recycleRecord" v-hasPermi="['iot:device:record:list']">{{ $t('device.index.105953-51') }}</el-dropdown-item>
                            <el-dropdown-item command="allotRecord" v-hasPermi="['iot:device:record:list']">{{ $t('device.index.105953-52') }}</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </el-col>

                <el-col :span="1.5" style="line-height: 32px; margin: 0px 10px">
                    <el-checkbox v-model="queryParams.showChild" @change="handleQuery">
                        <div style="color: #606266 !important; font-size: 14px">{{ $t('device.index.105953-18') }}</div>
                    </el-checkbox>
                    <el-tooltip :content="$t('device.index.105953-19')" placement="top"><i class="el-icon-question" style="color: #909399; font-size: 16px"></i></el-tooltip>
                </el-col>

                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList">
                    <div class="button-group">
                        <el-tooltip effect="dark" content="切换到卡片视图" placement="top">
                            <el-button size="small" icon="el-icon-s-claim" @click="handleShowCard" :class="['toggle-button card-button', { active: isListView }]" />
                        </el-tooltip>
                        <div class="separator"></div>
                        <!-- 分割线 -->
                        <el-tooltip effect="dark" content="切换到列表视图" placement="top">
                            <el-button size="small" icon="el-icon-s-grid" @click="handleShowList" :class="['toggle-button list-button', { active: !isListView }]" />
                        </el-tooltip>
                    </div>
                </right-toolbar>
            </el-row>

            <!-- list形式 -->
            <div v-if="showType == 'list'" style="margin-top: 16px">
                <el-table v-loading="loading" :data="deviceList" :border="false" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" align="center" width="55" />
                    <el-table-column :label="$t('device.index.105953-20')" align="center" prop="deviceId" width="60" />
                    <el-table-column :label="$t('device.index.105953-0')" align="left" prop="deviceName" min-width="190" />
                    <el-table-column :label="$t('device.index.105953-2')" align="left" prop="serialNumber" min-width="180" />
                    <el-table-column :label="$t('device.index.105953-21')" align="left" prop="productName" min-width="190" />
                    <el-table-column :label="$t('device.index.105953-59')" align="center" prop="deptName" min-width="190" />
                    <el-table-column :label="$t('device.index.105953-22')" align="center" prop="transport" min-width="90" />
                    <el-table-column :label="$t('device.index.105953-23')" align="center" prop="protocolCode" min-width="120" />
                    <el-table-column :label="$t('device.index.105953-24')" align="center" prop="subDeviceCount" width="80">
                        <template slot-scope="scope">
                            {{ scope.row.subDeviceCount }}
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('device.index.105953-25')" align="center" prop="isShadow" width="80">
                        <template slot-scope="scope">
                            <el-tag type="success" size="small" v-if="scope.row.isShadow == 1">{{ $t('device.index.105953-26') }}</el-tag>
                            <el-tag type="info" size="small" v-else>{{ $t('device.index.105953-27') }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('device.index.105953-28')" align="center" prop="status" width="80">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.iot_device_status" :value="scope.row.status" size="small" />
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('device.index.105953-29')" align="center" prop="rssi" width="60">
                        <template slot-scope="scope">
                            <svg-icon v-if="scope.row.status == 3 && scope.row.rssi >= '-55'" icon-class="wifi_4" />
                            <svg-icon v-else-if="scope.row.status == 3 && scope.row.rssi >= '-70' && scope.row.rssi < '-55'" icon-class="wifi_3" />
                            <svg-icon v-else-if="scope.row.status == 3 && scope.row.rssi >= '-85' && scope.row.rssi < '-70'" icon-class="wifi_2" />
                            <svg-icon v-else-if="scope.row.status == 3 && scope.row.rssi >= '-100' && scope.row.rssi < '-85'" icon-class="wifi_1" />
                            <svg-icon v-else icon-class="wifi_0" />
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('device.index.105953-30')" align="center" prop="locationWay" width="100">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.iot_location_way" :value="scope.row.locationWay" size="small" />
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('device.index.105953-31')" align="center" prop="firmwareVersion" width="80">
                        <template slot-scope="scope">
                            <el-tag size="mini" type="info">Ver {{ scope.row.firmwareVersion }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('device.index.105953-32')" align="center" prop="activeTime" width="120">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.activeTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('device.index.105953-33')" align="center" prop="createTime" width="120">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column fixed="right" :label="$t('device.index.105953-34')" align="center" width="200">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" icon="el-icon-view" @click="handleEditDevice(scope.row)" v-hasPermi="['iot:device:query']">{{ $t('device.index.105953-60') }}</el-button>
                            <el-button type="text" size="small" icon="el-icon-picture-outline" @click="openSummaryDialog(scope.row)" v-if="form.deviceId != 0" v-hasPermi="['iot:device:query']">
                                {{ $t('device.index.105953-37') }}
                            </el-button>
                            <el-button type="text" size="small" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['iot:device:remove']">
                                {{ $t('del') }}
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination style="margin-bottom: 20px" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :pageSizes="[12, 24, 36, 60]" @pagination="getList" />
            </div>
            <!-- 卡片形式 -->
            <div v-if="showType == 'card'" style="margin-top: 20px">
                <el-row :gutter="20" v-loading="loading">
                    <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" v-for="(item, index) in deviceList" :key="index" class="device-item">
                        <el-card :body-style="{ padding: '0px' }" shadow="always" class="card-item">
                            <div class="item-title">
                                <div>
                                    <el-image class="img" lazy :preview-src-list="[baseUrl + item.imgUrl]" :src="baseUrl + item.imgUrl" fit="cover" v-if="item.imgUrl != null && item.imgUrl != ''"></el-image>
                                    <el-image
                                        class="img"
                                        :preview-src-list="[require('@/assets/images/gateway.png')]"
                                        :src="require('@/assets/images/gateway.png')"
                                        fit="cover"
                                        v-else-if="item.deviceType == 2"
                                    ></el-image>
                                    <el-image class="img" :preview-src-list="[require('@/assets/images/video.png')]" :src="require('@/assets/images/video.png')" fit="cover" v-else-if="item.deviceType == 3"></el-image>
                                    <el-image class="img" :preview-src-list="[require('@/assets/images/product.png')]" :src="require('@/assets/images/product.png')" fit="cover" v-else></el-image>
                                </div>
                                <div class="title">
                                    <div class="name" @click="handleDeviceDetail(item)">{{ item.deviceName }}</div>
                                    <div class="tag-wrap">
                                        <dict-tag :options="dict.type.iot_device_status" :value="item.status" size="mini" style="line-height: 15px" />
                                        <el-tag style="margin-left: 6px" v-if="item.protocolCode" type="info" size="mini">{{ item.protocolCode }}</el-tag>
                                        <el-tag style="margin-left: 6px" v-if="item.transport" type="info" size="mini">{{ item.transport }}</el-tag>
                                        <el-tag style="margin-left: 6px" v-if="item.alertCount" type="danger" size="mini">{{ $t('device.index.105953-53') }}{{ item.alertCount.unprocessedCount }}</el-tag>
                                    </div>
                                </div>
                                <div style="width: 45px"></div>
                                <div class="status">
                                    <div class="icon-wrap">
                                        <svg-icon class="item" style="cursor: pointer" icon-class="qrcode" @click="openSummaryDialog(item)" v-hasPermi="['iot:device:query']" />
                                        <svg-icon class="item" v-if="item.status == 3 && item.rssi >= '-55'" icon-class="wifi_4" />
                                        <svg-icon class="item" v-else-if="item.status == 3 && item.rssi >= '-70' && item.rssi < '-55'" icon-class="wifi_3" />
                                        <svg-icon class="item" v-else-if="item.status == 3 && item.rssi >= '-85' && item.rssi < '-70'" icon-class="wifi_2" />
                                        <svg-icon class="item" v-else-if="item.status == 3 && item.rssi >= '-100' && item.rssi < '-85'" icon-class="wifi_1" />
                                        <svg-icon class="item" v-else icon-class="wifi_0" />
                                    </div>
                                </div>
                            </div>

                            <el-row :gutter="10">
                                <el-col :span="14" style="padding: 0px 0 0 30px; margin-bottom: -10px">
                                    <el-descriptions :column="1" size="small" style="margin-top: 10px; white-space: nowrap; overflow: hidden">
                                        <el-descriptions-item :label="$t('device.index.105953-20')">
                                            {{ item.serialNumber }}
                                        </el-descriptions-item>
                                    </el-descriptions>
                                </el-col>
                                <el-col :span="10" style="padding: 0px 30px 0 0px; margin-bottom: -10px">
                                    <el-descriptions :column="1" size="small" style="margin-top: 10px; white-space: nowrap">
                                        <el-descriptions-item :label="$t('device.index.105953-59')">
                                            {{ item.deptName }}
                                        </el-descriptions-item>
                                    </el-descriptions>
                                </el-col>
                            </el-row>
                            <el-row :gutter="10">
                                <el-col :span="14" style="padding: 0px 0 0 30px">
                                    <el-descriptions :column="1" size="small" style="margin-top: 10px; white-space: nowrap">
                                        <el-descriptions-item :label="$t('device.index.105953-39')">
                                            {{ item.productName }}
                                        </el-descriptions-item>
                                    </el-descriptions>
                                </el-col>
                                <el-col :span="10" style="padding: 0px 30px 0 0px">
                                    <el-descriptions :column="1" size="small" style="margin-top: 10px; white-space: nowrap">
                                        <el-descriptions-item :label="$t('device.index.105953-32')">
                                            {{ parseTime(item.activeTime, '{y}-{m}-{d}') || 'xxxx-xx-xx' }}
                                        </el-descriptions-item>
                                    </el-descriptions>
                                </el-col>
                            </el-row>
                            <el-divider class="divider" />

                            <div style="height: 39px; padding: 0 10px; display: flex; align-items: center; justify-content: space-evenly">
                                <el-button size="mini" type="text" @click="handleEditDevice(item, 'basic')" v-hasPermi="['iot:device:query']">{{ $t('device.index.105953-36') }}</el-button>
                                <span style="width: 1px; margin: 0px 10px; font-size: 16px; color: #dcdfe6" v-hasPermi="['iot:device:query']">|</span>
                                <el-button size="mini" type="text" @click="handleRunDevice(item)" v-hasPermi="['iot:device:query']">
                                    {{ $t('device.index.105953-40') }}
                                </el-button>
                                <span style="width: 1px; margin: 0px 10px; font-size: 16px; color: #dcdfe6" v-hasPermi="['iot:device:remove']">|</span>
                                <el-button size="mini" type="text" @click="handleDelete(item)" v-hasPermi="['iot:device:remove']">{{ $t('device.index.105953-35') }}</el-button>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
                <el-empty :description="$t('device.index.105953-41')" v-if="total == 0"></el-empty>
                <pagination style="margin: 0 0 20px 0" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :pageSizes="[12, 24, 36, 60]" @pagination="getList" />
            </div>
        </el-card>

        <!-- 二维码 -->
        <el-dialog :visible.sync="openSummary" width="300px" append-to-body>
            <div style="border: 1px solid #ccc; width: 220px; text-align: center; margin: 0 auto; margin-top: -15px">
                <vue-qr :text="qrText" :size="200"></vue-qr>
                <div style="padding-bottom: 10px">{{ $t('device.index.105953-42') }}</div>
            </div>
        </el-dialog>

        <el-dialog :title="$t('device.index.105953-54')" :visible.sync="openGenerate" width="500px" append-to-body>
            <el-form v-model="elForm">
                <el-form-item label-width="95px" :label="$t('device.index.105953-55')">
                    <el-input v-model="elForm.count" type="number" style="width: 310px" :max="200" oninput="if(value>200)value=200;if(value<0)value=0"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" v-hasPermi="['iot:device:batchGenerator']">{{ $t('device.index.105953-56') }}</el-button>
                <el-button @click="openGenerate = false">{{ $t('device.index.105953-57') }}</el-button>
            </div>
        </el-dialog>
        <!-- 批量导入设备 -->
        <batchImport ref="batchImport" @save="saveDialog"></batchImport>
        <!-- 导入分配 -->
        <allotImport ref="allotImport" @save="saveAllotDialog"></allotImport>
        <!-- 导入记录 -->
        <importRecord ref="importRecord"></importRecord>
        <!-- 设备回收记录 -->
        <recycleRecord ref="recycleRecord"></recycleRecord>
        <!-- 设备分配记录 -->
        <allotRecord ref="allotRecord"></allotRecord>
        <!-- 新增设备 -->
        <deviceAdd ref="deviceAdd"></deviceAdd>
    </div>
</template>

<script>
import vueQr from 'vue-qr';
import { listDeviceShort, delDevice } from '@/api/iot/device';
import { listGroup } from '@/api/iot/group';
import { delSipDeviceBySipId } from '@/api/iot/sipdevice';
import auth from '@/plugins/auth';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import batchImport from './batch-import-dialog';
import allotImport from './allot-import-dialog';
import importRecord from './import-record';
import recycleRecord from './recycle-record';
import allotRecord from './allot-record';
import deviceAdd from './device-add';
export default {
    name: 'Device',
    dicts: ['iot_device_status', 'iot_is_enable', 'iot_location_way', 'iot_transport_type'],
    components: {
        vueQr,
        Treeselect,
        batchImport,
        allotImport,
        importRecord,
        recycleRecord,
        allotRecord,
        deviceAdd,
    },
    data() {
        return {
            qrText: 'fastbee', // 二维码内容
            openSummary: false, // 打开设备配置对话框
            openGenerate: false,
            showSearch: true, // 显示搜索条件
            searchShow: false, //搜索展开
            showType: 'card', // 展示方式
            ids: [], // 选中数组
            loading: true, // 遮罩层
            single: true, // 非单个禁用
            multiple: true,
            total: 0, // 总条数
            deviceList: [], // 设备列表数据
            myGroupList: [], // 我的分组列表数据
            baseUrl: process.env.VUE_APP_BASE_API, // 根路径
            isListView: true, // 默认选中列表视图
            // 查询参数
            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,
                productName: '',
            },
            productList: [],
            elForm: {
                count: 1,
            },
            // 批量导入参数
            isSubDev: false,
        };
    },
    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();
    },
    activated() {
        const time = this.$route.query.t;
        if (time != null && time != this.uniqueId) {
            this.uniqueId = time;
            // 页码筛选
            let pageNum = this.$route.query.pageNum;
            if (pageNum != null) {
                this.queryParams.pageNum = Number(pageNum);
            }
            // 产品筛选
            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.getList();
        }
    },
    methods: {
        /* 连接Mqtt消息服务器 */
        async connectMqtt() {
            if (this.$mqttTool.client == null) {
                await this.$mqttTool.connect();
            }
            // 删除所有message事件监听器
            // this.$mqttTool.client.removeAllListeners('message');
            // 添加message事件监听器
            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(this.$t('device.index.105953-43'), topic);
                    console.log(this.$t('device.index.105953-44'), 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;
                        }
                    }
                }
            });
        },
        // 新增设备更多操作触发
        handleCommand(command) {
            switch (command) {
                case 'handleEditDevice':
                    this.handleAddDevice();
                    break;
                case 'handleBatchImport':
                    this.handleBatchImport();
                    break;
                default:
                    break;
            }
        },
        //新增设备
        handleAddDevice() {
            this.$refs.deviceAdd.open = true;
            this.$refs.deviceAdd.reset();
        },
        //批量导入设备
        handleBatchImport() {
            this.$refs.batchImport.upload.importDeviceDialog = true;
            this.$refs.batchImport.importForm.productName = null;
        },
        //导入分配设备
        handleImportAllot() {
            this.$refs.allotImport.upload.importAllotDialog = true;
            this.$refs.allotImport.allotForm.productName = null;
            this.$refs.allotImport.allotForm.deptId = null;
        },
        // dialog 保存响应
        saveDialog() {
            this.getList();
        },
        // dialog 保存响应
        saveAllotDialog() {
            this.getList();
        },
        // 分配设备更多操作触发
        handleCommand1(command) {
            switch (command) {
                case 'handleSelectAllot':
                    this.handleSelectAllot();
                    break;
                case 'handleImportAllot':
                    this.handleImportAllot();
                    break;
                default:
                    break;
            }
        },
        // 跳转选择分配设备页面
        handleSelectAllot() {
            this.$router.push({
                path: '/iot/device-select-allot',
            });
        },
        // 跳转回收设备页面
        recycleDevice() {
            this.$router.push({
                path: '/iot/device-recycle',
            });
        },
        // 更多操作
        handleCommandMore(command) {
            switch (command) {
                case 'importRecord':
                    this.handleImportRecord();
                    break;
                case 'generateSerialNumber':
                    this.generateSerialNumber();
                    break;
                case 'recycleRecord':
                    this.handleRecycleRecord();
                    break;
                case 'allotRecord':
                    this.handleAllotRecord();
                    break;
                default:
                    break;
            }
        },
        //导入记录
        handleImportRecord() {
            this.$refs.importRecord.open = true;
            this.$refs.importRecord.getList();
        },
        //设备回收记录
        handleRecycleRecord() {
            this.$refs.recycleRecord.open = true;
            this.$refs.recycleRecord.getList();
        },
        //设备分配记录
        handleAllotRecord() {
            this.$refs.allotRecord.open = true;
            this.$refs.allotRecord.getList();
        },
        // 生成设备编号
        generateSerialNumber() {
            this.openGenerate = true;
        },
        //生成设备编号确定操作
        submitForm() {
            this.download(
                'iot/device/batchGenerator',
                {
                    ...this.elForm,
                },
                `batchGenerator_${new Date().getTime()}.xlsx`
            );
            this.openGenerate = false;
        },
        openSummaryDialog(row) {
            let json = {
                type: 1, // 1=扫码关联设备
                deviceNumber: row.serialNumber,
                productId: row.productId,
                productName: row.productName,
            };
            this.qrText = JSON.stringify(json);
            this.openSummary = true;
        },
        /* 订阅消息 */
        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;
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams.productId = null;
            this.queryParams.groupId = null;
            this.queryParams.serialNumber = null;
            this.resetForm('queryForm');
            this.handleQuery();
        },
        /** 切换显示方式 */
        handleChangeShowType() {
            this.showType = this.showType == 'card' ? 'list' : 'card';
        },
        handleShowList() {
            this.isListView = false; // 切换到列表视图
            this.showType = 'list'; // 切换显示方式为列表视图
            console.log('切换到列表视图');
        },
        handleShowCard() {
            this.isListView = true; // 切换到卡片视图
            this.showType = 'card'; // 切换显示方式为列表视图

            console.log('切换到卡片视图');
        },
        // 点击名称查看
        handleDeviceDetail(item) {
            if (auth.hasPermi('iot:device:query')) {
                this.handleEditDevice(item);
            }
        },
        /** 修改按钮操作 */
        handleEditDevice(row, activeName) {
            let deviceId = 0;
            let isSubDev = 0;
            if (row != 0) {
                deviceId = row.deviceId || this.ids;
                isSubDev = row.subDeviceCount > 0 ? 1 : 0;
            }
            this.$router.push({
                path: '/iot/device-edit',
                query: {
                    deviceId: deviceId,
                    isSubDev: isSubDev,
                    pageNum: this.queryParams.pageNum,
                    activeName: activeName,
                },
            });
        },
        /** 运行状态按钮操作 */
        handleRunDevice(row) {
            let deviceId = 0;
            let isSubDev = 0;
            if (row != 0) {
                deviceId = row.deviceId || this.ids;
                isSubDev = row.subDeviceCount > 0 ? 1 : 0;
            }
            if (row.deviceType === 3) {
                this.$router.push({
                    path: '/iot/device-edit',
                    query: {
                        deviceId: deviceId,
                        isSubDev: isSubDev,
                        pageNum: this.queryParams.pageNum,
                        activeName: 'sipChannel',
                    },
                });
            } else {
                this.$router.push({
                    path: '/iot/device-edit',
                    query: {
                        deviceId: deviceId,
                        isSubDev: isSubDev,
                        pageNum: this.queryParams.pageNum,
                        activeName: 'runningStatus',
                    },
                });
            }
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const loading = this.$loading({ lock: true });
            const deviceIds = row.deviceId || this.ids;
            this.$modal
                .confirm(this.$t('device.index.105953-45', [deviceIds]))
                .then(function () {
                    if (row.deviceType === 3) {
                        delSipDeviceBySipId(row.serialNumber);
                    }
                    return delDevice(deviceIds);
                })
                .then(() => {
                    loading.close();
                    this.getList();
                    this.$modal.msgSuccess(this.$t('device.index.105953-47'));
                })
                .catch(() => {
                    loading.close();
                });
        },
        /** 未启用设备影子*/
        shadowUnEnable(device, thingsModel) {
            // 1-未激活，2-禁用，3-在线，4-离线
            if (device.status != 3 && device.isShadow == 0) {
                return true;
            }
            if (thingsModel.isReadonly) {
                return true;
            }
            return false;
        },
        // 搜索展开隐藏
        searchChange() {
            this.searchShow = !this.searchShow;
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.deviceId);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
    },
};
</script>

<style lang="scss" scoped>
.iot-device {
    padding: 20px;

    ::v-deep .el-upload-dragger {
        width: 510px;
    }

    ::v-deep .el-dropdown-menu__item {
        font-size: 12px;
    }

    .device-item {
        margin-bottom: 20px;
        text-align: center;

        .card-item {
            background: #ffffff;
            border-radius: 8px;
            border: 1px solid #dcdfe6;

            .item-title {
                display: -webkit-box;
                flex-direction: row;
                align-items: center;
                position: relative;
                padding: 18px;

                .img {
                    height: 58px;
                    width: 58px;
                    border-radius: 10px;
                }

                .title {
                    flex: 1;
                    text-align: left;
                    margin-left: 16px;

                    .name {
                        font-weight: 500;
                        font-size: 16px;
                        color: #303133;
                        line-height: 22px;
                        white-space: nowrap; /* 不换行 */
                        overflow: hidden; /* 隐藏超出部分 */
                        text-overflow: ellipsis; /* 使用省略号 */
                        cursor: pointer;
                    }

                    .tag-wrap {
                        margin-top: 10px;
                        display: flex;
                        flex-direction: row;
                    }
                }

                .status {
                    position: absolute;
                    right: -1px;
                    top: 24px;

                    .icon-wrap {
                        display: flex;
                        flex-direction: row;
                        align-items: center;
                        padding: 0 8px;

                        .item {
                            width: 22px;
                            height: 22px;
                            margin: 0 5px;
                            color: #909399;
                        }
                    }
                }
            }
        }
    }

    .btn-wrap {
        background-color: #fff !important;
        color: #606266 !important;
        border-radius: 4px !important;
        border: 1px solid #dcdfe6 !important;
    }
}

.divider {
    margin: 20px 0 0;
    height: 1px;
    background: #dcdfe6;
}

.button-group {
    width: 65px;
    height: 32.5px;
    display: flex; /* 让按钮在同一行显示 */
    align-items: center; /* 垂直居中对齐 */
    margin-right: 10px;
    background: #ffffff;

    .toggle-button {
        width: 32.5px;
        height: 32.5px;
        display: flex; /* 使用 flexbox */
        justify-content: center; /* 水平居中 */
        align-items: center; /* 垂直居中 */
        border: 1px solid #dcdfe6;
        background: #fff;
    }

    ::v-deep .el-button:hover,
    .el-button:focus {
        color: unset;
    }

    .active {
        background-color: #e0e0e0; /* 被选中按钮的背景色 */
        border-color: #dcdfe6; /* 被选中按钮的边框色 */
    }

    .card-button {
        border-radius: 4px 0px 0px 4px !important;
    }

    .list-button {
        border-radius: 0px 4px 4px 0px !important;
    }

    .separator {
        width: 1px; /* 分割线的宽度 */
        height: 32px; /* 分割线的高度 */
        background: #dcdfe6; /* 分割线的颜色 */
    }
}
</style>
