<template>
    <div class="firmware-task">
        <el-card>
            <!-- 固件信息 -->
            <el-descriptions :title="$t('firmware.task.222543-0')">
                <el-descriptions-item v-for="(item, index) in firmwareInfo" :key="index" :label="item.name" label-class-name="feint">{{ item.value }}</el-descriptions-item>
            </el-descriptions>
        </el-card>
        <el-card>
            <!-- 固件升级设备统计 -->
            <div class="firmwareDeviceHeader">
                <h1>{{ $t('firmware.task.222543-1') }}</h1>
                <i class="el-icon-refresh icon" @click="updateFirmwareDevice()"></i>
            </div>
            <div class="firmwareDevice">
                <div class="box" v-for="(item, index) in firmwareDevice" :key="index">
                    <span class="title">{{ item.title }}</span>
                    <span class="num">{{ item.num }}</span>
                </div>
            </div>
        </el-card>
        <el-card>
            <div class="firmwareDeviceHeader">
                <h1>{{ $t('firmware.task.222543-2') }}</h1>
            </div>
            <div class="task">
                <div class="taskHeader">
                    <div class="taskTitle">
                        <!-- 新增 -->
                        <el-button @click="otaUpGrade()" type="primary" size="small" icon="el-icon-plus" plain v-hasPermi="['iot:task:add']">{{ $t('firmware.task.222543-50') }}</el-button>
                    </div>
                    <!-- 搜索 -->
                    <div class="taskInput">
                        <el-input class="searchInput" v-model="taskName" :placeholder="$t('firmware.task.222543-51')" clearable size="small" @keyup.enter.native="taskQuery()" />
                    </div>
                </div>
                <div class="taskBody">
                    <el-table v-loading="loading" :data="firmwareTaskList" :border="false">
                        <el-table-column :label="$t('firmware.task.222543-8')" align="center" prop="id" width="80"></el-table-column>
                        <el-table-column :label="$t('firmware.task.222543-9')" align="left" prop="taskName" min-width="180"></el-table-column>
                        <el-table-column :label="$t('firmware.task.222543-10')" align="center" prop="upgradeType" min-width="140">
                            <template slot-scope="scope">
                                <el-tag type="warning" v-if="scope.row.upgradeType == 1">{{ $t('firmware.task.222543-11') }}</el-tag>
                                <el-tag v-else>{{ $t('firmware.task.222543-12') }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('firmware.task.222543-13')" align="center" prop="deviceAmount" min-width="80"></el-table-column>
                        <el-table-column :label="$t('firmware.task.222543-14')" align="center" prop="bookTime" width="160"></el-table-column>
                        <el-table-column :label="$t('firmware.task.222543-52')" align="center" prop="createTime" width="160"></el-table-column>
                        <el-table-column :label="$t('firmware.task.222543-15')" align="left" prop="taskDesc" min-width="180"></el-table-column>
                        <el-table-column :label="$t('opation')" align="center" fixed="right" width="125">
                            <template slot-scope="scope">
                                <el-button @click="taskDetailClick(scope.row)" type="text" size="small" icon="el-icon-view" v-hasPermi="['iot:task:query']">{{ $t('firmware.task.222543-17') }}</el-button>
                                <el-button @click="handleDelete(scope.row)" type="text" size="small" icon="el-icon-delete" v-hasPermi="['iot:task:remove']">{{ $t('firmware.task.222543-53') }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination v-show="taskTotal > 0" :total="taskTotal" :page.sync="taskParams.pageNum" :limit.sync="taskParams.pageSize" @pagination="getTaskList" />
                </div>
            </div>
        </el-card>

        <!-- 任务详情弹框-->
        <el-dialog :title="$t('firmware.task.222543-31')" width="960px" :visible.sync="taskDialogVisible">
            <div class="dialogBox">
                <el-card style="margin-right: 5px">
                    <el-descriptions :title="$t('firmware.task.222543-32')" :column="1">
                        <el-descriptions-item v-for="(item, index) in taskDialogData" :key="index" :label="item.name" label-class-name="feint">{{ item.value }}</el-descriptions-item>
                    </el-descriptions>
                </el-card>
                <el-card style="margin-left: 5px">
                    <el-descriptions :title="$t('firmware.task.222543-33')">
                        <template slot="extra">
                            <el-button size="mini" type="text" icon="el-icon-refresh" @click="chartRefresh"></el-button>
                        </template>
                    </el-descriptions>
                    <div class="chart" ref="taskChart"></div>
                </el-card>
            </div>
            <el-card>
                <div class="firmwareDeviceHeader">
                    <h1>{{ $t('firmware.task.222543-32') }}</h1>
                </div>
                <div class="deviceDialogSearch">
                    <div class="left" id="left">
                        <span :class="{ active: deviceStatus === 'all' }" @click="deviceStatusClick('all')">{{ $t('firmware.task.222543-35') }}（{{ deviceDialogSearchStatus[0] }}）</span>
                        <span :class="{ active: deviceStatus === 0 }" @click="deviceStatusClick(0)">{{ $t('firmware.task.222543-37') }}（{{ deviceDialogSearchStatus[2] }}）</span>
                        <span :class="{ active: deviceStatus === 2 }" @click="deviceStatusClick(2)">{{ $t('firmware.task.222543-38') }}（{{ deviceDialogSearchStatus[4] }}）</span>
                        <span :class="{ active: deviceStatus === 3 }" @click="deviceStatusClick(3)">{{ $t('firmware.task.222543-36') }}（{{ deviceDialogSearchStatus[1] }}）</span>
                        <span :class="{ active: deviceStatus === 4 }" @click="deviceStatusClick(4)">{{ $t('firmware.task.222543-39') }}（{{ deviceDialogSearchStatus[5] }}）</span>
                        <span :class="{ active: deviceStatus === 5 }" @click="deviceStatusClick(5)">{{ $t('firmware.task.222543-40') }}（{{ deviceDialogSearchStatus[6] }}）</span>
                    </div>
                    <div class="right">
                        <!-- 刷新 -->
                        <el-button size="small" @click="deviceInfoQuery" style="height: 32px; width: 32px; padding: 0">
                            <i class="el-icon-refresh"></i>
                        </el-button>
                        <!-- 输入设备编号 -->
                        <el-input class="input3" v-model="deviceSerialNumber" :placeholder="$t('firmware.task.222543-54')" clearable size="small" @keyup.enter.native="deviceInfoQuery" />
                    </div>
                </div>
                <el-table v-loading="loading" :data="deviceDialogList" :border="false">
                    <el-table-column :label="$t('firmware.deviceList.index.222542-1')" align="left" prop="deviceName" min-width="150"></el-table-column>
                    <el-table-column :label="$t('firmware.deviceList.index.222542-5')" align="left" prop="serialNumber" min-width="140"></el-table-column>
                    <el-table-column :label="$t('firmware.task.222543-8')" align="center" prop="taskId" width="80"></el-table-column>
                    <el-table-column :label="$t('firmware.task.222543-9')" align="center" prop="taskName" min-width="150"></el-table-column>
                    <el-table-column :label="$t('firmware.task.222543-19')" align="center" prop="version" width="120">
                        <template slot-scope="scope">
                            <span>Version {{ scope.row.version }}</span>
                        </template>
                    </el-table-column>
                    <!-- 升级状态 -->
                    <el-table-column :label="$t('firmware.task.222543-21')" align="center" prop="upgradeStatus" width="100">
                        <template slot-scope="scope">
                            <el-tag type="info" v-if="scope.row.upgradeStatus == 0">{{ $t('firmware.task.222543-37') }}</el-tag>
                            <el-tag type="" v-else-if="scope.row.upgradeStatus == 2">{{ $t('firmware.task.222543-38') }}</el-tag>
                            <el-tag type="success" v-else-if="scope.row.upgradeStatus == 3">{{ $t('firmware.task.222543-25') }}</el-tag>
                            <el-tag type="danger" v-else-if="scope.row.upgradeStatus == 4">{{ $t('firmware.task.222543-26') }}</el-tag>
                            <el-tag type="info" v-else-if="scope.row.upgradeStatus == 5">{{ $t('firmware.task.222543-27') }}</el-tag>
                            <el-tag type="info" v-else>{{ $t('firmware.task.222543-28') }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('firmware.task.222543-55')" align="center" prop="progress" width="210">
                        <template slot-scope="scope">
                            <el-progress :percentage="parseInt(scope.row.progress)"></el-progress>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('firmware.task.222543-29')" align="center" prop="detailMsg" width="100"></el-table-column>
                    <el-table-column :label="$t('firmware.task.222543-30')" align="center" prop="updateTime" width="160"></el-table-column>
                    <el-table-column fixed="right" :label="$t('firmware.task.222543-56')" align="center" width="95">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" :disabled="![4, 5].includes(scope.row.upgradeStatus)" @click="upgradeTaskHandle(scope.row)" v-hasPermi="['iot:task:upgrade']">
                                {{ $t('firmware.task.222543-57') }}
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination
                    v-show="deviceInfoTotal > 0"
                    layout="prev, pager, next"
                    :total="deviceInfoTotal"
                    :page.sync="deviceInfoParams.pageNum"
                    :limit.sync="deviceInfoParams.pageSize"
                    @pagination="getDeviceInfoList"
                />
            </el-card>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleDialogCancel">{{ $t('cancel') }}</el-button>
                <el-button type="primary" @click="handleDialogCancel">{{ $t('confirm') }}</el-button>
            </span>
        </el-dialog>

        <!-- 新增-固件升级 -->
        <el-dialog :title="title" :visible.sync="openUpGrade" width="650px" append-to-body>
            <el-form ref="formUpGrade" :model="formUpGrade" :rules="rulesUpGrade" label-width="135px">
                <el-form-item :label="$t('firmware.index.222541-0')" prop="firmwareName">
                    {{ form.firmwareName }}
                </el-form-item>
                <el-form-item :label="$t('firmware.index.222541-2')" prop="productId">
                    {{ form.productName }}
                </el-form-item>
                <el-form-item :label="$t('firmware.index.222541-15')" prop="version">Version {{ form.version }}</el-form-item>
                <el-form-item :label="$t('firmware.index.222541-20')" prop="taskName">
                    <el-input v-model="formUpGrade.taskName" :placeholder="$t('firmware.index.222541-22')" maxlength="20" style="width: 400px" />
                </el-form-item>
                <el-form-item :label="$t('firmware.task.222543-58')" prop="upgradeType">
                    <el-select v-model="formUpGrade.upgradeType" :placeholder="$t('firmware.task.222543-59')" clearable @change="changeUpType">
                        <el-option v-for="type in dict.type.oat_update_limit" :key="type.value" :label="type.label" :value="type.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('firmware.task.222543-60')" v-if="formUpGrade.upgradeType != 1">
                    <el-badge :value="formUpGrade.deviceAmount" class="item">
                        <el-button type="primary" size="mini" plain class="mr5" @click="selectDeviceList">{{ $t('firmware.task.222543-61') }}</el-button>
                    </el-badge>
                    <el-tag style="margin-left: 10px" :key="tag" v-for="tag in formUpGrade.deviceList" closable size="small" :disable-transitions="false" @close="handleClose(tag)">
                        {{ tag }}
                    </el-tag>
                </el-form-item>
                <el-form-item :label="$t('firmware.index.222541-32')" prop="bookTime">
                    <el-date-picker v-model="formUpGrade.bookTime" type="datetime" :placeholder="$t('firmware.index.222541-33')"></el-date-picker>
                </el-form-item>
                <el-form-item :label="$t('firmware.index.222541-34')" prop="taskDesc">
                    <el-input v-model="formUpGrade.taskDesc" type="textarea" :placeholder="$t('firmware.index.222541-35')" :autosize="{ minRows: 3, maxRows: 5 }" style="width: 400px" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button v-if="!istrue" type="primary" @click="submitFormUpGrade">{{ $t('save') }}</el-button>
                <el-button v-else type="primary" size="mini" icon="el-icon-odometer" :loading="true" disabled>{{ $t('firmware.task.222543-24') }}</el-button>
                <el-button @click="canceUpGrade">{{ $t('cancel') }}</el-button>
            </div>
        </el-dialog>
        <!-- 分组设备列表 -->
        <selectDeviceList ref="deviceList" :upGrade="formUpGrade"></selectDeviceList>
    </div>
</template>

<script>
import { listTask, deviceList, deviceStatistic, upgradeTask, delTask, updateTask } from '@/api/iot/firmwareTask';
import { formatDate } from '@/utils/common';
import * as echarts from 'echarts';
import { listFirmware, upGradeVersionList, getFirmware, delFirmware, addFirmware, updateFirmware } from '@/api/iot/firmware';
import selectDeviceList from './device-list';
import { listDeviceByGroup } from '@/api/iot/device';
import { addTask } from '@/api/iot/firmwareTask';

export default {
    name: 'firmware-task',
    dicts: ['iot_yes_no', 'oat_update_limit'],
    components: {
        selectDeviceList,
    },
    data() {
        return {
            firmwareId: '',
            firmwareInfo: [
                {
                    name: this.$t('firmware.index.222541-0'),
                    value: '',
                },
                {
                    name: this.$t('firmware.index.222541-2'),
                    value: '',
                },
                {
                    name: this.$t('firmware.task.222543-42'),
                    value: '',
                },
                {
                    name: this.$t('firmware.task.222543-62'),
                    value: '',
                },
                {
                    name: this.$t('firmware.index.222541-15'),
                    value: '',
                },
                {
                    name: this.$t('firmware.task.222543-16'),
                    value: '',
                },
                {
                    name: this.$t('firmware.task.222543-44'),
                    value: '',
                },
            ],
            firmwareDevice: [
                {
                    title: this.$t('firmware.task.222543-45'),
                    num: 0,
                },
                {
                    title: this.$t('firmware.task.222543-36'),
                    num: 0,
                },
                {
                    title: this.$t('firmware.task.222543-46'),
                    num: 0,
                },
                {
                    title: this.$t('firmware.task.222543-39'),
                    num: 0,
                },
            ],
            // 以下为任务管理相关
            // changeIndex: 0,
            // 任务明细参数
            loading: false,
            istrue: false,
            taskParams: {
                pageNum: 1,
                pageSize: 10,
                firmwareId: '',
                id: '',
            },
            formUpGrade: {
                taskName: null,
                firmwareId: 0,
                deviceAmount: 0,
                bookTime: null,
                upgradeType: null,
                upType: null,
                deviceList: [],
                version: null,
                flag: false,
            },
            taskTotal: 0,
            firmwareTaskList: [],
            // 任务明细查询
            taskName: '',
            // 设备明细参数
            deviceParams: {
                pageNum: 1,
                pageSize: 10,
                firmwareId: '',
                taskId: '',
                serialNumber: '',
                deviceName: '',
            },
            deviceTotal: 0,
            firmwareDeviceList: [],
            // 设备明细查询
            deviceId: '',
            deviceName: '',
            serialNumber: '',
            // 任务详情弹框
            taskDialogVisible: false,
            taskDialogData: [
                {
                    name: this.$t('firmware.task.222543-8'),
                    value: '',
                },
                {
                    name: this.$t('firmware.task.222543-9'),
                    value: '',
                },
                {
                    name: this.$t('firmware.task.222543-10'),
                    value: '',
                },
                {
                    name: this.$t('firmware.task.222543-13'),
                    value: '',
                },
                {
                    name: this.$t('firmware.task.222543-14'),
                    value: '',
                },
                {
                    name: this.$t('firmware.task.222543-15'),
                    value: '',
                },
                {
                    name: this.$t('firmware.task.222543-16'),
                    value: '',
                },
            ],
            myChart: null,
            option: null,
            chartData: [],
            chartParam: {},
            // 设备详情
            deviceDialogList: [],
            deviceInfoParams: {
                pageNum: 1,
                pageSize: 10,
                firmwareId: '',
                taskId: '',
                upgradeStatus: '',
                serialNumber: '',
            },
            title: '',
            openUpGrade: false,
            deviceSerialNumber: '',
            deviceInfoTotal: 0,
            //设备数量
            deviceDialogSearchStatus: [0, 0, 0, 0, 0, 0, 0],
            deviceStatus: 'all',
            rulesUpGrade: {
                taskName: [
                    {
                        required: true,
                        message: this.$t('firmware.index.222541-41'),
                        trigger: 'blur',
                    },
                ],
                upgradeType: [
                    {
                        required: true,
                        message: this.$t('firmware.task.222543-22'),
                        trigger: 'blur',
                    },
                ],
            },
            queryDeviceByVersion: {
                productId: null,
                firmwareVersion: 0,
            },
            // 表单参数
            form: {
                version: 1.0,
            },
        };
    },
    created() {
        const data = JSON.parse(sessionStorage.getItem('firmwareTaskInfo'));
        this.firmwareId = data.firmwareId;
        this.taskParams.firmwareId = data.firmwareId;
        this.deviceParams.firmwareId = data.firmwareId;
        this.formUpGrade.firmwareId = data.firmwareId;
        this.deviceInfoParams.firmwareId = data.firmwareId;
        this.firmwareInfo[0].value = data.firmwareName;
        this.firmwareInfo[1].value = data.productName;
        this.firmwareInfo[2].value = data.isLatest == 1 ? this.$t('firmware.task.222543-63') : this.$t('firmware.task.222543-64');
        this.firmwareInfo[3].value = data.firmwareType == 1 ? this.$t('firmware.task.222543-65') : 'http';
        this.firmwareInfo[4].value = 'Version ' + data.version;
        this.firmwareInfo[5].value = data.createTime;
        this.firmwareInfo[6].value = data.remark;
        this.getDeviceStatistic();
        this.getTaskList();
        // Mqtt订阅
        this.connectMqtt();
    },
    destroyed() {
        // 取消订阅
        this.mqttUnSubscribe(this.taskDialogData[0]?.value);
    },
    watch: {
        chartData: {
            immediate: true,
            deep: true,
            handler(newVal, oldVal) {
                if (newVal.length > 0) {
                    this.$nextTick(() => {
                        this.myChart = echarts.init(this.$refs.taskChart);
                        this.option = {
                            grid: {
                                top: 0,
                                bottom: 0,
                                containLabel: true,
                            },
                            tooltip: {
                                trigger: 'item',
                                formatter: '{b}:{c}',
                            },
                            series: [
                                {
                                    name: this.$t('firmware.task.222543-33'),
                                    type: 'pie',
                                    radius: ['45%', '70%'],
                                    label: {
                                        show: true,
                                        formatter: '{b}:{c}\n占比:{d}%',
                                    },
                                    data: newVal,
                                },
                            ],
                        };
                        this.myChart.setOption(this.option);
                    });
                }
            },
        },
    },
    methods: {
        // 固件升级设备统计
        getDeviceStatistic() {
            deviceStatistic({
                firmwareId: this.firmwareId,
            }).then((res) => {
                if (res.code == 200) {
                    const data = res.data;
                    let now = 0;
                    let success = 0;
                    let fail = 0;
                    let total = 0;
                    data.map((item) => {
                        total += item.deviceCount;
                        if (item.upgradeStatus == 0 || item.upgradeStatus == 1 || item.upgradeStatus == 2) {
                            now += item.deviceCount;
                        } else if (item.upgradeStatus == 4 || item.upgradeStatus == 5) {
                            fail += item.deviceCount;
                        } else {
                            success += item.deviceCount;
                        }
                    });
                    this.firmwareDevice[0].num = total;
                    this.firmwareDevice[1].num = success;
                    this.firmwareDevice[2].num = now;
                    this.firmwareDevice[3].num = fail;
                }
            });
        },
        //保存时间过长，防止重复点击，增加延迟
        delay() {
            let n = 5;
            // 定义定时器time
            const time = setInterval(() => {
                this.istrue = true;
                n--;
                // 如果n<0，清除定时器，禁用状态取消，文字提示为空（不显示）
                if (n < 0) {
                    this.istrue = false;
                    clearInterval(time);
                }
            }, 2000);
        },
        //删除
        handleDelete(row) {
            const taskIds = row.id;
            this.$modal
                .confirm(this.$t('firmware.task.222543-66', [taskIds]))
                .then(function () {
                    return delTask(taskIds);
                })
                .then(() => {
                    this.getTaskList();
                    this.getDeviceStatistic();
                    this.$modal.msgSuccess(this.$t('firmware.task.222543-67'));
                })
                .catch(() => {});
        },
        /**获取选中的产品 */
        getProductData(product) {
            this.form.productId = product.productId;
            this.form.productName = product.productName;
        },
        canceUpGrade() {
            this.openUpGrade = false;
            this.reset();
        },
        submitFormUpGrade() {
            this.$refs['formUpGrade'].validate((valid) => {
                if (valid) {
                    this.delay();
                    if (this.formUpGrade.deviceAmount > 0) {
                        addTask(this.formUpGrade).then((response) => {
                            if (response.code == 200) {
                                this.$modal.msgSuccess(this.$t('addSuccess'));
                                this.openUpGrade = false;
                                // this.reset();
                                this.getTaskList();
                                this.getDeviceStatistic();
                            } else {
                                this.$modal.msgError(res.data.message);
                            }
                        });
                    } else {
                        this.$modal.msgError(this.$t('firmware.index.222541-47'));
                    }
                }
            });
        },
        /*选择设备*/
        selectDeviceList() {
            // 刷新子组件
            this.formUpGrade.flag = true;
            this.$refs.deviceList.openDeviceList = true;
        },
        // 设备明细列表
        getDeviceList() {
            deviceList(this.deviceParams).then((res) => {
                this.firmwareDeviceList = res.rows;
                this.deviceTotal = res.total;
            });
        },
        // 表单重置
        reset() {
            this.form = {
                firmwareId: 0,
                firmwareName: null,
                productId: null,
                productName: null,
                tenantId: null,
                tenantName: null,
                isLatest: 0,
                isSys: null,
                version: 1.0,
                filePath: null,
                delFlag: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
            };
        },
        //ota升级
        otaUpGrade(row) {
            this.formUpGrade.deviceList = [];
            this.formUpGrade.deviceAmount = 0;
            this.resetForm('formUpGrade');
            const firmwareId = this.taskParams.firmwareId || this.ids;
            getFirmware(firmwareId).then((response) => {
                this.form = response.data;
                this.openUpGrade = true;
                this.title = this.$t('firmware.task.222543-23');
                this.formUpGrade.productId = this.form.productId;
                this.formUpGrade.firmwareId = firmwareId;
            });
        },
        // 固件升级设备统计刷新
        updateFirmwareDevice() {
            this.getDeviceStatistic();
        },
        //任务明细列表
        getTaskList() {
            listTask(this.taskParams).then((res) => {
                this.firmwareTaskList = res.rows;
                this.taskTotal = res.total;
            });
        },
        // 任务明细列表查询
        taskQuery() {
            this.taskParams.taskName = this.taskName;
            this.getTaskList();
        },
        // 以下为任务管理-任务明细 详情弹出框相关
        // 任务信息
        taskDetailClick(data) {
            this.taskDialogData[0].value = data.id;
            this.taskDialogData[1].value = data.taskName;
            this.taskDialogData[2].value = data.upgradeType == 1 ? this.$t('firmware.task.222543-68') : this.$t('firmware.task.222543-69');
            this.taskDialogData[3].value = data.deviceAmount;
            this.taskDialogData[4].value = data.bookTime;
            this.taskDialogData[5].value = data.taskDesc;
            this.taskDialogData[6].value = data.createTime;
            this.deviceDialogSearchStatus[0] = data.deviceAmount;
            this.taskDialogVisible = true;
            this.chartParam = {
                taskId: data.id,
                firmwareId: data.firmwareId,
            };
            this.deviceInfoParams.taskId = data.id;
            this.getChartData();
            this.getDeviceInfoList();
            // this.getDeviceList()
            // mqtt订阅
            this.mqttSubscribe(data.id);
        },
        // 任务统计
        getChartData() {
            deviceStatistic(this.chartParam).then((res) => {
                const data = res.data;
                let chartData = [];
                let totalStatistics = [this.deviceDialogSearchStatus[0], 0, 0, 0, 0, 0, 0];
                data.map((item) => {
                    switch (item.upgradeStatus) {
                        case 0:
                            // 等待升级--待推送
                            chartData.push({
                                name: this.$t('firmware.task.222543-48'),
                                value: item.deviceCount,
                            });
                            totalStatistics[2] = item.deviceCount;
                            break;
                        case 2:
                            // 升级中
                            chartData.push({
                                name: this.$t('firmware.task.222543-38'),
                                value: item.deviceCount,
                            });
                            totalStatistics[4] = item.deviceCount;
                            break;
                        case 3:
                            chartData.push({
                                name: this.$t('firmware.task.222543-36'),
                                value: item.deviceCount,
                            });
                            totalStatistics[1] = item.deviceCount;
                            break;
                        case 4:
                            chartData.push({
                                name: this.$t('firmware.task.222543-39'),
                                value: item.deviceCount,
                            });
                            totalStatistics[5] = item.deviceCount;
                            break;
                        case 5:
                            chartData.push({
                                name: this.$t('firmware.task.222543-40'),
                                value: item.deviceCount,
                            });
                            totalStatistics[6] = item.deviceCount;
                            break;
                    }
                });
                this.chartData = chartData;
                this.deviceDialogSearchStatus = totalStatistics;
            });
        },
        //任务统计刷新
        chartRefresh() {
            this.getChartData();
        },
        // 设备详情
        getDeviceInfoList() {
            deviceList(this.deviceInfoParams).then((res) => {
                this.deviceDialogList = res.rows;
                this.deviceInfoTotal = res.total;
            });
        },
        // 设备详情查询
        deviceInfoQuery() {
            this.deviceInfoParams.serialNumber = this.deviceSerialNumber;
            this.getDeviceInfoList();
        },
        // 设备详情不同状态切换
        deviceStatusClick(id) {
            this.deviceStatus = id;
            if (id === 'all') {
                this.deviceInfoParams.upgradeStatus = '';
            } else {
                this.deviceInfoParams.upgradeStatus = id;
            }
            this.getDeviceInfoList();
        },
        handleDialogCancel() {
            this.taskDialogVisible = false;
            this.deviceStatus = 'all';
            this.deviceSerialNumber = '';
            this.deviceInfoParams.upgradeStatus = '';
            this.deviceInfoParams.serialNumber = '';

            // 取消订阅
            this.mqttUnSubscribe(this.taskDialogData[0]?.value);
        },
        // 连接Mqtt消息服务器
        async connectMqtt() {
            if (this.$mqttTool.client == null) {
                await this.$mqttTool.connect(this.vuex_token);
            } else {
                // 删除所有message事件监听器
                this.$mqttTool.client.removeAllListeners('message');
            }
            this.mqttCallback();
        },
        // Mqtt回调处理
        mqttCallback() {
            this.$mqttTool.client.on('message', (topic, message, buffer) => {
                message = JSON.parse(message.toString('utf8'));
                if (!message) {
                    return;
                }
                this.setMqttData(message);
                console.log(message, 'Mqtt message');
            });
        },
        // 订阅消息
        mqttSubscribe(taskId) {
            if (!taskId) return;
            // 订阅当前页面设备状态和实时监测
            let topics = [];
            let topicStatus = '/' + taskId + '/ws/ota/status';
            topics.push(topicStatus);
            this.$mqttTool.subscribe(topics);
        },
        // 取消订阅
        mqttUnSubscribe(taskId) {
            if (!taskId) return;
            let topics = [];
            let topicStatus = '/' + taskId + '/ws/ota/status';
            topics.push(topicStatus);
            this.$mqttTool.unsubscribe(topics);
        },
        setMqttData(data) {
            for (let i = 0; i < this.deviceDialogList.length; i++) {
                const item = this.deviceDialogList[i];
                if (item.serialNumber === data.serialNumber) {
                    item.upgradeStatus = data.status;
                    item.updateTime = formatDate(data.timestamp, 'Y-M-D h:m:s');
                    item.detailMsg = this.getDetailMsg(data.status);
                    if (data.progress) {
                        item.progress = data.progress;
                    }
                    break;
                }
            }
        },
        getDetailMsg(status) {
            const statusObj = {
                0: this.$t('firmware.task.222543-70'),
                1: this.$t('firmware.task.222543-71'),
                2: this.$t('firmware.task.222543-72'),
                3: this.$t('firmware.task.222543-73'),
                4: this.$t('firmware.task.222543-74'),
                5: this.$t('firmware.task.222543-75'),
                6: this.$t('firmware.task.222543-76'),
            };
            return statusObj[status] || '';
        },
        /** 升级范围 */
        changeUpType(val) {
            this.resetDeviceList();
            if (val == '1') {
                this.queryDeviceByVersion.productId = this.formUpGrade.productId;
                this.queryDeviceByVersion.firmwareVersion = this.formUpGrade.version;
                listDeviceByGroup(this.queryDeviceByVersion).then((response) => {
                    response.rows.forEach((row) => {
                        this.formUpGrade.deviceList.push(row.serialNumber);
                    });
                    this.formUpGrade.deviceAmount = response.total;
                });
            }
        },
        /** 切换升级类型*/
        changeUpgradeType(val) {
            this.resetDeviceList();
            if (val == 2) {
                this.formUpGrade.version = null;
            }
        },

        resetDeviceList() {
            this.formUpGrade.upgradeType = this.formUpGrade.upgradeType;
            this.formUpGrade.deviceList = [];
            this.formUpGrade.deviceAmount = 0;
        },
        upgradeTaskHandle(row) {
            const { firmwareId, taskId, serialNumber } = row;
            const data = {
                firmwareId,
                taskId,
                devices: [serialNumber],
                upgradeType: 2,
            };
            upgradeTask(data).then((res) => {
                if (res.code === 200) {
                    this.$message({
                        message: res.msg || this.$t('firmware.task.222543-77'),
                        type: 'success',
                    });
                } else {
                    this.$message.error(res.msg || this.$t('firmware.task.222543-78'));
                }
            });
        },
    },
};
</script>

<style scoped>
.firmware-task {
    padding: 20px;
}

.firmware-task /deep/ .feint {
    color: #999;
}

.firmware-task /deep/ .el-card {
    margin-bottom: 10px;
}

.firmwareDeviceHeader {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
}

h1 {
    margin: 0;
    height: 28px;
    line-height: 28px;
    font-size: 16px;
    font-weight: bold;
}

.icon {
    width: 20px;
    line-height: 28px;
}

.icon:hover {
    color: #5cb6ff;
    cursor: pointer;
}

.firmware-task /deep/ .searchInput {
    width: 200px;
}

.firmwareDevice {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.box {
    flex: 1;
    padding: 0 10px;
    height: 60px;
    border-right: 1px solid #999;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
}

.box:last-child {
    border-right: none;
}

.title {
    font-size: 14px;
    color: #999;
    margin-bottom: 10px;
    text-align: left;
}

.num {
    font-weight: bold;
}

.box:nth-child(1) .num {
    color: #5cb6ff;
}

.box:nth-child(2) .num {
    color: #67c23a;
}

.box:nth-child(3) .num {
    color: #e6a23c;
}

.box:nth-child(4) .num {
    color: #f56c6c;
}

.taskHeader {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}

.taskTitle span {
    display: inline-block;
    width: 130px;
    text-align: center;
    height: 32px;
    line-height: 32px;
    font-size: 14px;
    border: 1px solid #999;
}

.input2 {
    margin: 0 10px;
}

.taskTitle span:hover,
.taskTitle .active,
#left .active {
    color: #5cb6ff;
    border: 1px solid #5cb6ff;
}

.taskTitle .noRight {
    border-right: none;
}

.taskTitle .noLeft {
    border-left: none;
}

.dialogBox {
    display: flex;
    justify-content: space-between;
}

.chart {
    height: 218px;
}

/*设备明细详情弹框*/
.deviceDialogSearch {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}

.left span {
    display: inline-block;
    width: 98px;
    text-align: center;
    height: 30px;
    line-height: 28px;
    cursor: pointer;
    border: 1px solid #999;
    font-size: 12px;
}

.left span:not(:first-child) {
    border-left: none;
}

.right {
    display: flex;
    justify-content: flex-end;
}

.input3 {
    margin-left: 10px;
    width: 170px;
}
</style>
