<template>
    <div class="device-variable">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
            <el-form-item prop="type">
                <el-select v-model="queryParams.type" :placeholder="$t('device.variable-case.347856-1')" clearable @keyup.enter.native="handleQuery">
                    <el-option v-for="dict in dict.type.iot_things_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item prop="modelName">
                <el-input v-model="queryParams.modelName" :placeholder="$t('device.variable-case.347856-3')" clearable />
            </el-form-item>
            <el-form-item prop="subDeviceId" v-if="device.deviceType === 2">
                <el-select v-model="subDeviceId" :placeholder="$t('device.variable-case.347856-17')" clearable @keyup.enter.native="handleQuery">
                    <el-option v-for="item in subDeviceList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{ $t('device.variable-case.347856-4') }}</el-button>
                <el-button icon="el-icon-refresh" @click="handleResetQuery">{{ $t('device.variable-case.347856-5') }}</el-button>
                <el-button v-if="device.protocolCode === 'MODBUS-TCP' || device.protocolCode === 'MODBUS-RTU'" icon="el-icon-refresh" @click="activeCollectionAll">
                    {{ $t('device.variable-case.347856-16') }}
                </el-button>
            </el-form-item>
            <el-form-item style="line-height: 28px">
                <el-checkbox v-model="queryParams.isMonitor" :true-label="1" style="margin: 0px 10px" @change="handleQuery">
                    <div style="color: #606266 !important; font-size: 14px">{{ $t('device.running-status.866086-33') }}</div>
                </el-checkbox>
                <el-tooltip :content="$t('device.running-status.866086-34')" placement="top"><i class="el-icon-question" style="color: #909399; font-size: 16px"></i></el-tooltip>
            </el-form-item>
        </el-form>
        <el-row :gutter="20" v-if="queryParams.isMonitor !== 1">
            <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="4" v-for="(item, index) in variableList" :key="index" style="margin-bottom: 20px">
                <el-card :body-style="{ padding: '20px' }" shadow="always" style="height: 130px">
                    <el-row type="flex" :gutter="10" justify="space-between" align="middle">
                        <el-col :span="8" style="text-align: left; font-size: 16px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-shadow: 1rpx 1rpx 2rpx rgba(0, 0, 0, 0.1)">
                            <el-tooltip :content="item.identifier + ' / ' + item.modelName" placement="top-start">
                                <span>{{ item.modelName }}</span>
                            </el-tooltip>
                        </el-col>

                        <el-col :span="16" style="text-align: right">
                            <el-tooltip class="item" effect="dark" :content="$t('device.variable-case.347856-13')" placement="top-start">
                                <svg-icon
                                    icon-class="gather"
                                    style="color: #007aff; margin-right: 10px; cursor: pointer"
                                    @click="activeCollection(item)"
                                    v-if="device.protocolCode === 'MODBUS-TCP' || device.protocolCode === 'MODBUS-RTU'"
                                ></svg-icon>
                            </el-tooltip>
                            <el-tooltip class="item" effect="dark" :content="item.isReadonly === 0 && item.type != 3 ? $t('device.running-status.866086-36') : $t('device.running-status.866086-45')" placement="top">
                                <i class="el-icon-position" style="color: #007aff; margin-right: 10px; cursor: pointer" @click="editFunc(item)" v-if="item.isReadonly === 0 && item.type != 3"></i>
                                <i class="el-icon-position" style="color: #909399; margin-right: 10px; cursor: pointer" v-else disabled></i>
                            </el-tooltip>
                            <el-tooltip class="item" effect="dark" :content="item.isHistory === 1 ? $t('device.running-status.866086-37') : $t('device.running-status.866086-46')" placement="top-start">
                                <svg-icon style="cursor: pointer" aria-hidden="true" iconClass="history" @click="handleHistory(item)" v-if="item.isHistory === 1"></svg-icon>
                                <svg-icon style="cursor: pointer" aria-hidden="true" iconClass="history_disable" v-else></svg-icon>
                            </el-tooltip>
                            <dict-tag style="float: right; margin-left: 10px; margin-top: -2px" :options="dict.type.iot_things_type" :value="item.type" size="mini" />
                        </el-col>
                    </el-row>
                    <el-row type="flex" :gutter="10" justify="space-between" align="middle" style="margin-top: 10px" v-if="device.deviceType === 2">
                        <el-col :span="8" style="text-align: left; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-shadow: 1rpx 1rpx 2rpx rgba(0, 0, 0, 0.1)">
                            <el-tooltip :content="item.deviceName" placement="top-start">
                                <span>{{ item.deviceName ? item.deviceName : '-' }}</span>
                            </el-tooltip>
                        </el-col>
                        <el-col :span="16" style="text-align: right; font-size: 12px">{{ $t('device.variable-case.347856-18') }}{{ item.slaveId ? item.slaveId : '-' }}</el-col>
                    </el-row>
                    <el-row type="flex" :gutter="10" justify="space-between">
                        <!-- 非布尔型直接展示value值 -->
                        <el-col :span="12.5" style="text-align: left">
                            <div v-if="item.datatype.type !== 'bool' && item.datatype.type !== 'enum'" style="font-size: 14px; margin-top: 20px; display: inline-block">{{ item.value ? item.value : '-' }}</div>
                            <div v-if="item.datatype.type !== 'bool' && item.datatype.type !== 'enum'" style="font-size: 15px; margin: 20px 0 0 5px; display: inline-block">
                                {{ item.datatype.unit ? item.datatype.unit : '' }}
                            </div>
                            <!-- bool型 -->
                            <div v-if="item.datatype.type == 'bool'">
                                <div style="font-size: 14px; margin-top: 20px; display: inline-block">{{ item.valueName ? item.valueName : '--' }}</div>
                            </div>
                            <!-- 枚举型 -->
                            <div v-if="item.datatype.type == 'enum'">
                                <div v-if="item.showWay && item.showWay == 'button'">
                                    <el-button
                                        type=""
                                        :plain="true"
                                        style="margin-top: 20px"
                                        size="mini"
                                        :disabled="shadowUnEnable || item.isReadonly == 1 || item.type == 3"
                                        v-if="item.valueName !== null && item.valueName !== '' && item.valueName !== '-'"
                                    >
                                        {{ item.valueName }}
                                    </el-button>
                                </div>
                                <div v-else style="font-size: 14px; margin-top: 20px; display: inline-block">
                                    {{ item.valueName ? item.valueName : '--' }}
                                </div>
                            </div>
                        </el-col>
                        <el-col :span="11.5" style="text-align: right">
                            <div style="font-size: 12px; margin-top: 25px; display: inline-block">
                                {{ item.ts ? item.ts : '-' }}
                            </div>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
        </el-row>
        <!-- 图表 -->
        <el-row :gutter="20" v-if="queryParams.isMonitor === 1">
            <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" v-for="(item, index) in chartList" :key="index">
                <el-card shadow="hover" style="border-radius: 30px; margin-bottom: 20px">
                    <div ref="map" style="height: 250px; width: 185px; margin: 0 auto"></div>
                </el-card>
            </el-col>
        </el-row>
        <el-empty :description="$t('device.device-recycle.864193-8')" v-if="total == 0"></el-empty>
        <pagination style="" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :pageSizes="[24, 48, 72, 96]" @pagination="getVariableList" />

        <!-- 服务下发 -->
        <el-dialog :title="$t('device.realTime-status.099127-26')" :visible.sync="dialogValue" width="480px">
            <el-form>
                <el-form-item v-for="(item, index) in opationList" :label="`${item.label}：`" :key="index" label-width="120px">
                    <el-input
                        v-model="funVal[item.key]"
                        :precision="0"
                        :controls="false"
                        @input="justNumber(item)"
                        type="number"
                        v-if="
                            item.dataTypeName == 'integer' ||
                            item.dataTypeName == 'decimal' ||
                            (item.dataTypeName == 'array' && item.arrayType == 'integer') ||
                            (item.dataTypeName == 'array' && item.arrayType == 'decimal')
                        "
                        style="width: 200px"
                    ></el-input>
                    <el-input
                        v-model="funVal[item.key]"
                        :precision="0"
                        :controls="false"
                        :placeholder="$t('device.running-status.866086-35')"
                        type="text"
                        v-if="item.dataTypeName == 'string' || (item.dataTypeName == 'array' && item.arrayType == 'string')"
                        style="width: 230px"
                        @input="justNumber(item)"
                    ></el-input>

                    <el-select v-if="item.dataTypeName == 'bool'" v-model="funVal[item.key]" @change="changeSelect()" style="width: 230px">
                        <el-option v-for="option in item.options" :key="option.value" :label="option.label" :value="option.value"></el-option>
                    </el-select>
                    <div v-if="item.dataTypeName == 'enum'">
                        <div v-if="item.showWay && item.showWay == 'button'">
                            <el-button
                                style="margin: 5px"
                                size="mini"
                                @click="enumButtonClick(deviceInfo, item, subItem.value)"
                                v-for="subItem in item.options"
                                :key="subItem.value"
                                v-model="funVal[item.key]"
                                :disabled="shadowUnEnable || item.isReadonly == 1 || item.type == 3"
                                :class="{ 'is-active-btn': subItem.value === (item.shadow || item.value) }"
                            >
                                {{ subItem.label }}
                            </el-button>
                        </div>
                        <el-select v-else v-model="funVal[item.key]" @change="changeSelect()">
                            <el-option v-for="option in item.options" :key="option.value" :label="option.label" :value="option.value"></el-option>
                        </el-select>
                    </div>
                    <span
                        v-if="
                            (item.dataTypeName == 'integer' ||
                                item.dataTypeName == 'decimal' ||
                                (item.dataTypeName == 'array' && item.arrayType == 'integer') ||
                                (item.dataTypeName == 'array' && item.arrayType == 'decimal')) &&
                            item.unit &&
                            item.unit != 'un' &&
                            item.unit != '/'
                        "
                    >
                        ({{ item.unit }})
                    </span>
                    <span
                        style="margin-left: 5px"
                        v-if="
                            item.dataTypeName == 'integer' ||
                            item.dataTypeName == 'decimal' ||
                            (item.dataTypeName == 'array' && item.arrayType == 'integer') ||
                            (item.dataTypeName == 'array' && item.arrayType == 'decimal')
                        "
                    >
                        （{{ item.min }} ~ {{ item.max }}）
                    </span>
                </el-form-item>
                <el-form-item style="display: none">
                    <el-input v-model="functionName"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="dialogValue = false">{{ $t('cancel') }}</el-button>
                <el-button type="primary" @click="sendService" :loading="btnLoading" :disabled="!canSend">{{ $t('confirm') }}</el-button>
            </span>
        </el-dialog>

        <el-dialog :title="$t('device.variable-case.347856-15')" :visible.sync="centerDialogVisible" width="380px">
            <span>{{ $t('device.variable-case.347856-14') }}</span>
            <span slot="footer">
                <el-button @click="centerDialogVisible = false">{{ $t('iot.group.device-list.849593-12') }}</el-button>
                <el-button type="primary" @click="confirmCollection">{{ $t('iot.group.device-list.849593-11') }}</el-button>
            </span>
        </el-dialog>
        <history-list ref="historyList" :model="modelParams"></history-list>
    </div>
</template>

<script>
import moment from 'moment';
import { listThingsModel } from '@/api/iot/device';
import { serviceInvokeReply, serviceInvoke } from '@/api/iot/runstatus.js';
import { propGet } from '@/api/iot/runstatus';
import { getOrderControl } from '@/api/iot/control';
import { listGateway } from '@/api/iot/gateway';
import historyList from './historyData.vue';

export default {
    name: 'DeviceVariable',
    dicts: ['iot_things_type'],
    components: {
        historyList,
    },
    props: {
        device: {
            type: Object,
            default: null,
        },
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            dialogValue: false,
            opationList: [],
            functionName: '',
            btnLoading: false,
            canSend: false,
            chooseFun: {},
            variableList: [],
            chartList: [],
            monitorChart: [],
            invokeForm: {
                type: '',
            },
            // 设备状态
            deviceStatus: {
                status: '',
                rssi: '',
            },
            total: 0,
            modelParams: {
                identifier: '',
                modelId: '',
                modelName: '',
                modelType: '',
                serialNumber: '',
                productId: '',
                deviceName: '',
            },
            // 设备信息
            deviceInfo: {
                boolList: [],
                enumList: [],
                stringList: [],
                integerList: [],
                decimalList: [],
                arrayList: [],
                thingsModels: [],
                chartList: [],
            },

            remoteCommand: {},
            // 表单校验
            rules: {
                firmwareType: [
                    {
                        required: true,
                        message: this.$t('device.running-status.866086-43'),
                        trigger: 'blur',
                    },
                ],
            },
            loading: false,
            queryParams: {
                deviceId: null,
                type: null,
                modelName: '',
                pageNum: 1,
                pageSize: 24,
                isMonnitor: '',
                showSubDevice: true,
            },
            // 查询参数
            querySubParams: {
                pageNum: 1,
                pageSize: 10,
            },
            subDeviceId: null, //子设备ID
            //子设备列表
            subDeviceList: [],
            dialogValue: false,
            centerDialogVisible: false,
            form: {},
            canSend: false, //是否可以下发，主要判断数值在不在范围
            btnLoading: false,
            funVal: {},
            chooseFun: {},
            deviceInfo: {},
            //下发的设备
            serialNumber: '',
            opationList: [],
            functionName: '',
            variableList: [],
        };
    },
    watch: {
        device: {
            deep: true,
            handler(newVal, oldVal) {
                if (newVal.deviceId && newVal.deviceId !== oldVal.deviceId) {
                    this.deviceInfo = newVal;
                    this.queryParams.deviceId = newVal.deviceId;
                    // 排序
                    this.getVariableList();
                }
            },
        },
    },
    mounted() {
        const { deviceId, serialNumber } = this.device;
        if (deviceId) {
            this.queryParams.deviceId = deviceId;
            this.serialNumber = serialNumber;
            this.getVariableList();
            this.getSubDeviceList();
        }
        this.initData();
    },
    methods: {
        initData() {
            // 监听值的实时更新
            this.$busEvent.$on('updateData', (params) => {
                this.updateParam(params);
            });
        },
        /** 查询子设备列表 */
        getSubDeviceList() {
            this.querySubParams.gwDeviceId = this.device.deviceId;
            listGateway(this.querySubParams).then((response) => {
                this.subDeviceList = response.rows.map((item) => {
                    return {
                        label: item.subDeviceName,
                        value: item.subDeviceId,
                    };
                });
                this.total = response.total;
                this.loading = false;
            });
        },
        // 获取变量情况列表
        getVariableList() {
            this.loading = true;
            if (this.device.deviceType === 2 && this.subDeviceId) {
                this.queryParams.showSubDevice = false;
            } else {
                this.queryParams.showSubDevice = true;
            }
            this.queryParams.deviceId = this.subDeviceId ? this.subDeviceId : this.device.deviceId;
            listThingsModel(this.queryParams).then((res) => {
                if (res.code === 200) {
                    if (this.queryParams.isMonitor === 1) {
                        this.chartList = res.rows;
                        this.$nextTick(function () {
                            this.MonitorChart();
                        });
                    } else {
                        this.variableList = res.rows.map((item) => {
                            return {
                                ...item,
                                valueName: this.getValueName(item) || '-',
                                // dataTypeName: item.datatype.type || '',
                                // showWay: item.datatype.showWay,
                            };
                        });
                        // 排序
                        this.variableList = this.variableList.sort((a, b) => b.order - a.order);
                        this.chartList = this.chartList.sort((a, b) => b.order - a.order);
                    }
                    this.total = res.total;
                }
                this.loading = false;
            });
        },
        /**图表展示*/
        MonitorChart() {
            if (this.chartList && this.chartList.length > 0) {
                for (let i = 0; i < this.chartList.length; i++) {
                    this.monitorChart[i] = {
                        chart: this.$echarts.init(this.$refs.map[i]),
                        data: {
                            id: this.chartList[i].identifier,
                            name: this.chartList[i].modelName,
                            value: this.chartList[i].shadow ? this.chartList[i].shadow : this.chartList[i].datatype.min,
                        },
                    };
                    var option;
                    option = {
                        tooltip: {
                            formatter: ' {b} <br/> {c}' + this.chartList[i].datatype.unit,
                        },
                        series: [
                            {
                                name: this.chartList[i].datatype.type,
                                type: 'gauge',
                                min: this.chartList[i].datatype.min,
                                max: this.chartList[i].datatype.max,
                                colorBy: 'data',
                                splitNumber: 10,
                                radius: '100%',
                                // 分割线
                                splitLine: {
                                    distance: 4,
                                },
                                axisLabel: {
                                    fontSize: 10,
                                    distance: 10,
                                },
                                // 刻度线
                                axisTick: {
                                    distance: 4,
                                },
                                // 仪表盘轴线
                                axisLine: {
                                    lineStyle: {
                                        width: 8,
                                        color: [
                                            [0.2, '#486FF2'], // 0~20%
                                            [0.8, '#12d09f'], // 40~60%
                                            [1, '#F56C6C'], // 80~100%
                                        ],
                                        opacity: 0.3,
                                    },
                                },
                                pointer: {
                                    icon: 'triangle',
                                    length: '60%',
                                    width: 7,
                                },
                                progress: {
                                    show: true,
                                    width: 8,
                                },
                                detail: {
                                    valueAnimation: true,
                                    formatter: '{value}' + ' ' + this.chartList[i].datatype.unit,
                                    offsetCenter: [0, '80%'],
                                    fontSize: 20,
                                },
                                data: [
                                    {
                                        value: this.chartList[i].shadow ? this.chartList[i].shadow : this.chartList[i].datatype.min,
                                        name: this.chartList[i].modelName,
                                    },
                                ],
                                title: {
                                    offsetCenter: [0, '115%'],
                                    fontSize: 16,
                                },
                            },
                        ],
                    };
                    option && this.monitorChart[i].chart.setOption(option);
                }
            }
        },
        // 搜索按钮操作
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getVariableList();
        },
        // 重置按钮操作
        handleResetQuery() {
            this.resetForm('queryForm');
            this.handleQuery();
        },
        //指令下发
        async editFunc(item) {
            //判断是否有权限
            const params = {
                deviceId: this.device.deviceId,
                modelId: item.modelId,
            };
            const response = await getOrderControl(params);
            if (response.code != 200) {
                this.$message({
                    type: 'warning',
                    message: response.msg,
                });
                return;
            }
            //这里兼容子设备的下发，在网关设备下发的时候选择实际子设备的编号
            this.serialNumber = item.serialNumber;
            let title = '';
            if (this.device.status !== 3) {
                if (this.device.status === 1) {
                    title = this.$t('device.device-variable.930930-0');
                } else if (this.device.status === 2) {
                    title = this.$t('device.device-variable.930930-1');
                } else {
                    title = this.$t('device.device-variable.930930-2');
                }
                this.$message({
                    type: 'warning',
                    message: title,
                });
                return;
            }
            this.dialogValue = true;
            this.canSend = true;
            this.funVal = {};
            this.chooseFun = item;
            this.getOpationList(item);
        },
        // 历史数据
        handleHistory(item) {
            if (item.isHistory === 1) {
                this.modelParams.identifier = item.identifier;
                this.modelParams.type = item.type;
                this.modelParams.deviceId = this.device.deviceId;
                this.modelParams.serialNumber = item.serialNumber;
                this.$refs.historyList.drawer = true;
                this.$refs.historyList.getDevChartDatas();
            }
        },
        // 封装操作列表
        getOpationList(item) {
            this.opationList = [];
            let options = [];
            this.funVal = {};
            const datatype = item.datatype;
            if (datatype.type == 'enum') {
                options =
                    datatype.enumList?.map((option) => {
                        return {
                            label: option.text,
                            value: option.value + '',
                        };
                    }) || [];
            }
            if (datatype.type == 'bool') {
                options = [
                    {
                        label: datatype.falseText || '',
                        value: '0',
                    },
                    {
                        label: datatype.trueText || '',
                        value: '1',
                    },
                ];
            }
            this.opationList.push({
                dataTypeName: datatype.type,
                arrayType: datatype.arrayType,
                label: item.modelName,
                key: item.identifier,
                max: parseInt(datatype?.max || 100),
                min: parseInt(datatype?.min || -100),
                options: options,
                value: item.value,
            });
            this.opationList.forEach((item) => {
                let value = item.value;
                if (item.datatype == 'integer' || item.datatype == 'decimal' || (item.dataTypeName == 'array' && item.arrayType == 'integer') || (item.dataTypeName == 'array' && item.arrayType == 'decimal')) {
                    value = parseInt(value);
                }
                this.funVal[item.key] = value;
            });
        },

        // 发送指令
        async sendService() {
            try {
                let params = this.funVal;
                const pas = {
                    serialNumber: this.serialNumber,
                    identifier: this.chooseFun.identifier,
                    remoteCommand: params,
                };
                this.btnLoading = true;
                if (this.deviceInfo.protocolCode === 'MODBUS-TCP' || this.deviceInfo.protocolCode === 'MODBUS-RTU') {
                    await serviceInvokeReply(pas).then((response) => {
                        if (response.code === 200) {
                            this.$message({
                                type: 'success',
                                message: this.$t('device.running-status.866086-25'),
                            });
                        } else {
                            this.$message.error(response.msg);
                        }
                    });
                } else {
                    await serviceInvoke(pas).then((response) => {
                        if (response.code === 200) {
                            this.$message({
                                type: 'success',
                                message: this.$t('device.running-status.866086-25'),
                            });
                        } else {
                            this.$message.error(response.msg);
                        }
                    });
                }
                for (let i = 0; i < this.variableList.length; i++) {
                    if (this.variableList[i].identifier == this.chooseFun.identifier) {
                        const variable = Object.values(this.funVal)[0];
                        this.variableList[i].value = variable;
                        this.variableList[i].valueName = this.getValueName(this.variableList[i]);
                        break;
                    }
                }
            } finally {
                this.btnLoading = false;
                this.dialogValue = false;
            }
        },

        //下拉选择修改触发
        changeSelect() {
            this.$forceUpdate();
        },

        //判断输入是否超过范围
        justNumber(val) {
            this.canSend = true;
            this.opationList.some((item) => {
                if (item.max < this.funVal[item.key] || item.min > this.funVal[item.key]) {
                    this.canSend = false;
                    return true;
                }
            });
            this.$forceUpdate();
        },
        // 编辑变量值
        handleEditVariable(item) {
            this.$prompt(this.$t('device.device-variable.930930-4'), this.$t('device.device-variable.930930-5'), {
                confirmButtonText: this.$t('device.device-variable.930930-6'),
                cancelButtonText: this.$t('device.device-variable.930930-7'),
                inputPattern: /\S/,
                inputErrorMessage: this.$t('device.device-variable.930930-8'),
                inputPlaceholder: item.value,
            }).then(({ value }) => {
                if (this.device.status !== 3) {
                    let title = '';
                    if (this.device.status === 1) {
                        title = this.$t('device.device-variable.930930-9');
                    } else if (this.device.status === 2) {
                        title = this.$t('device.device-variable.930930-10');
                    } else {
                        title = this.$t('device.device-variable.930930-11');
                    }
                    this.$message({
                        type: 'warning',
                        message: title,
                    });
                    return;
                }
                const command = {};
                command[item.identifier] = value;
                const data = {
                    serialNumber: item.serialNumber,
                    remoteCommand: command,
                    identifier: item.identifier,
                };
                serviceInvoke(data).then((res) => {
                    if (res.code === 200) {
                        item.ts = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
                        item.value = value;
                    } else if (res.code === 204) {
                        this.$message({
                            type: 'warning',
                            message: res.msg,
                        });
                    }
                });
            });
        },

        // 查询历史数据
        handleQueryHistory(item) {
            this.$router.push({
                path: '/dataCenter/history',
                query: {
                    deviceId: this.device.deviceId,
                    identifier: item.identifier,
                    activeName: 'device',
                },
            });
        },
        //更新参数值
        updateParam(params) {
            let { serialNumber, productId, data } = params;
            if (data) {
                data = data.message;
                data.forEach((msg) => {
                    this.variableList.some((item, index) => {
                        if (msg.id === item.identifier) {
                            const variable = this.variableList[index];
                            variable.ts = msg.ts;
                            variable.value = msg.value;
                            variable.valueName = this.getValueName(item);
                            this.$set(this.variableList, index, variable);
                            return true;
                        }
                    });
                    // 图表数据
                    for (let k = 0; k < this.chartList.length; k++) {
                        console.log(msg.id, this.chartList[k].identifier, 'kkkkkkkkkk');
                        // 普通类型匹配
                        if (this.chartList[k].id == msg.identifier) {
                            this.chartList[k].value = msg.value;
                            // 更新图表
                            for (let m = 0; m < this.monitorChart.length; m++) {
                                if (msg.id == this.monitorChart[m].data.id) {
                                    let data = [
                                        {
                                            value: this.chartList[k].value,
                                            name: this.monitorChart[m].data.name,
                                        },
                                    ];
                                    this.monitorChart[m].chart.setOption({
                                        series: [
                                            {
                                                data: data,
                                            },
                                        ],
                                    });
                                    break;
                                }
                            }
                        }
                    }
                });
            }
        },
        getValueName(item) {
            //返回的数据
            let res = item.value || '-';
            //需要解析的类型
            const optionsType = ['bool', 'enum'];
            //如果有datatype并且需要解析就遍历解析
            if (item.datatype) {
                switch (item.datatype.type) {
                    case 'bool':
                        if (0 == item.value) res = item.datatype.falseText;
                        if (1 == item.value) res = item.datatype.trueText;
                        break;
                    case 'enum':
                        item.datatype.enumList?.some((enumOpt) => {
                            if (enumOpt.value == item.value) {
                                res = enumOpt.text;
                                return true;
                            }
                        });
                        break;
                }
            }
            return res;
        },
        //主动采集数据
        activeCollection(item) {
            if (this.device.status !== 3) {
                let title = '';
                if (this.device.status === 1) {
                    title = this.$t('device.device-variable.930930-9');
                } else if (this.device.status === 2) {
                    title = this.$t('device.device-variable.930930-10');
                } else {
                    title = this.$t('device.device-variable.930930-11');
                }
                this.$message({
                    type: 'warning',
                    message: title,
                });
                return;
            }
            this.centerDialogVisible = true;
            this.form.serialNumber = item.serialNumber;
            this.form.type = 1;
            this.form.identifier = item.identifier;
            this.form.parentSerialNumber = item.parentSerialNumber;
        },
        //确认采集
        confirmCollection() {
            propGet(this.form).then((response) => {
                if (response.code == 200) {
                    this.centerDialogVisible = false;
                }
            });
        },
        //采集所有
        activeCollectionAll() {
            if (this.device.status !== 3) {
                let title = '';
                if (this.device.status === 1) {
                    title = this.$t('device.device-variable.930930-9');
                } else if (this.device.status === 2) {
                    title = this.$t('device.device-variable.930930-10');
                } else {
                    title = this.$t('device.device-variable.930930-11');
                }
                this.$message({
                    type: 'warning',
                    message: title,
                });
                return;
            }
            this.centerDialogVisible = true;
            this.form.serialNumber = this.serialNumber;
            this.form.type = 2;
        },
    },
};
</script>

<style lang="scss" scoped>
.device-variable {
    width: 100%;
}

.is-active-btn {
    color: #1890ff;
    border-color: #badeff;
    background-color: #e8f4ff;
}
.disabled {
    pointer-events: none;
    opacity: 0.5;
}
</style>
