<template>
    <div class="common_page">
        <el-card class="main-card" shadow="never">
            <div class="card_top">
                <div class="card_title">{{ $t('index.DeviceJianKong.20250324-01') }}</div>
            </div>
            <el-form ref="queryForm" :inline="true" :model="searchData" label-width="68px" style="margin-bottom: -20px">
                <el-row>
                    <el-col :span="6">
                        <el-form-item :label="$t('product.product-authorize.314975-17')" prop="classifyId">
                            <el-select v-model="searchData.classifyId" clearable filterable placeholder="请选择"
                                style="width: 200px" @change="handleDevDeviceChange">
                                <el-option v-for="item in classifyList" :key="item.deviceId" :label="item.deviceName"
                                    :value="item.deviceId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="6" v-if="isExpansion">
              <el-form-item label="设备名称" prop="deviceName">
                <el-input v-model="searchData.deviceName" style="width: 200px" placeholder="请输入设备名称" clearable  />
              </el-form-item>
            </el-col> -->
                    <el-col :span="6">
                        <el-form-item :label="$t('index.DeviceJianKong.20250324-02')" prop="identifiers">
                            <el-select style="width: 200px" v-model="searchData.identifiers" placeholder="请选择"
                                filterable multiple collapse-tags>
                                <el-option v-for="(item, index) in devIdentifierList" :key="index"
                                    :label="item.modelName" :value="item.identifier"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item :label="$t('device.device-timer.433369-19')" prop="date">
                            <!-- :picker-options="pickerOptions" -->
                            <el-date-picker v-model="searchData.date" :end-placeholder="$t('index.time.20250324-03')"
                                format="yyyy-MM-dd" :range-separator="$t('index.time.20250324-04')"
                                :start-placeholder="$t('index.time.20250324-01')" style="width: 225px" type="daterange"
                                value-format="yyyy-MM-dd"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-button :loading="buttonLoading" icon="el-icon-search" size="mini" type="primary"
                            @click="search">{{ $t('search') }}</el-button>
                        <el-button :loading="buttonLoading" icon="el-icon-refresh" size="mini" @click="resetFields">{{
                            $t('reset') }}</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <el-card class="main-card">
            <div class="flex-between mb20">
                <div></div>
                <el-tooltip :loading="buttonLoading" class="item" effect="dark" :content="$t('export')" placement="top">
                    <el-button size="mini" circle icon="el-icon-download" @click="getDialog" />
                </el-tooltip>
            </div>
            <sysTable :columns="setTableColumns" :curr-page="searchData.pageNum" :data="setTableData"
                :page-size="searchData.pageSize" :showPagination="false" :total-page="pageTotal"
                @currentChange="currentChange" @sizeChange="sizeChange">
                <template #operation="scope">
                    <el-button type="primary" icon="el-icon-view" size="small" plain style="padding: 5px"
                        @click="handleEdit(scope.scope.row)">{{ $t('update') }}</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="small" plain style="padding: 5px"
                        @click="handleDelete(scope.scope.row)">{{ $t('del') }}</el-button>
                </template>
            </sysTable>
            <pagination v-show="pageTotal > 0" :total="pageTotal" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" :pageSizes="[12, 24, 36, 60]" @pagination="search" />

            <el-dialog :visible.sync="openData" :title="$t('index.DeviceJianKong.20250324-03')" width="500px">
                <el-form ref="queryForm" :inline="true" label-width="80px">
                    <el-form-item :label="$t('index.DeviceJianKong.20250324-09')" prop="groupName">
                        <el-radio-group v-model="Sjldradio" @change="getradio(Sjldradio)">
                            <el-radio-button label="day">{{ $t('index.index.20250324-14') }}</el-radio-button>
                            <el-radio-button label="month">{{ $t('index.index.20250324-15') }}</el-radio-button>
                            <el-radio-button label="year">{{ $t('index.index.20250324-16') }}</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item>
                        <el-button icon="el-icon-check" size="mini" type="primary" @click="getExport">{{ $t('confirm')
                            }}</el-button>
                        <el-button icon="el-icon-close" size="mini" type="primary" @click="cloneExport">{{ $t('cancel')
                            }}</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
            <el-dialog :title="dialogTitle" :visible.sync="open" append-to-body width="800px" @close="dialogClose">
                <el-form ref="formData" :model="formData" label-width="80px">
                    <el-form-item :label="$t('product.product-authorize.314975-17')">
                        <el-input v-model="formData.deviceName" disabled></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('index.DeviceJianKong.20250324-04')">
                        <el-input v-model="formData.equipmentConPrice" disabled></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('index.DeviceJianKong.20250324-05')">
                        <el-radio-group v-model="formData.resource" @change="changeResource">
                            <el-radio v-for="(item, index) in dialogRadioList" :key="index" :label="item.value">{{
                                item.text
                                }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="dialogTitle === '修改数据' && formData.resource"
                        :label="$t('index.DeviceJianKong.20250324-06')">
                        <el-input v-model="formData.logValue"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button v-if="dialogTitle === '修改数据'" type="primary" @click="editData">{{
                            $t('index.DeviceJianKong.20250324-07') }}</el-button>
                        <el-button v-else type="primary" @click="delData">{{ $t('index.DeviceJianKong.20250324-08')
                            }}</el-button>
                        <el-button @click="dialogClose">{{ $t('cancel') }}</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { getEquipentList } from '../../energy/api/energy/equipmentEnergy';
import { equipentEnergyList } from '../../energy/api/energy/energyMonitoring';
import { getDevice, getDeviceRunningStatus, listAllDeviceShort, listThingsModel } from '@/api/iot/device';
import { deleteHistoryList, listHistory, updateHistoryList } from '@/api/iot/deviceLog';
import { cacheJsonThingsModel } from '@/api/iot/model';
import sysTable from '../components/SysTable';

export default {
    name: 'equipmentEnergy',
    components: {
        sysTable,
    },
    data() {
        return {
            searchData: {
                buildingId: '',
                workshopIds: null,
                floor: null,
                deviceIds: null,
                classifyId: null,
                deviceName: '',
                date: null,
                type: 1,
                dateType: 1,
                pageSize: 10,
                pageNum: 1,
                identifiers: [],
            },
            setTableData: [],
            pageTotal: 0,
            buildList: [],
            floorList: [],
            workShopList: [],
            dimensionList: [
                {
                    id: 1,
                    name: '时',
                },
                {
                    id: 2,
                    name: '日',
                },
                {
                    id: 3,
                    name: '月',
                },
            ],
            deviceList: [],
            classifyList: [],
            devIdentifierList: [],
            setTableColumns: [
                {
                    label: this.$t('product.product-authorize.314975-17'),
                    prop: 'deviceName',
                    minWidth: '180',
                    align: 'center',
                    fixed: 'left',
                    showOverflowTooltip: true,
                },
                {
                    label: this.$t('index.DeviceJianKong.20250324-04'),
                    prop: 'equipmentConPrice',
                    minWidth: '180',
                    align: 'center',
                    showOverflowTooltip: true,
                },
                {
                    label: this.$t('opation'),
                    prop: 'operation',
                    Width: '200',
                    align: 'center',
                    fixed: 'right',
                },
            ],
            setTableColumnsCopy: [
                {
                    label: this.$t('product.product-authorize.314975-17'),
                    prop: 'deviceName',
                    minWidth: '180',
                    align: 'center',
                    fixed: 'left',
                    showOverflowTooltip: true,
                },
                {
                    label: this.$t('index.DeviceJianKong.20250324-04'),
                    prop: 'equipmentConPrice',
                    minWidth: '180',
                    align: 'center',
                    showOverflowTooltip: true,
                },
                {
                    label: this.$t('opation'),
                    prop: 'operation',
                    Width: '200',
                    align: 'center',
                    fixed: 'right',
                },
            ],
            pieEquipentL: [],
            pieEquipentY: [],
            barEquipentX: [],
            barEquipentY: [],
            chartsLoading: false,
            choiceDate0: '',
            dateComponentType: 'daterange', // daterange年月日， monthrange月
            buttonLoading: false,
            isExpansion: false,
            form: {},
            isSubDev: false,
            staticList: [],
            queryParams: {
                serialNumber: null,
                identity: '',
                slaveId: undefined,
                total: 200,
            },
            allDataList: {},
            maxTotal: 0,
            maxTotalName: '',
            open: false,
            formData: {},
            dialogTitle: '修改数据',
            dialogRadioList: [],
            openData: false,
            Sjldradio: 'day',
        };
    },
    computed: {
        ...mapGetters(['theme']),
        cssVars() {
            return {
                '--color': this.theme,
            };
        },
    },
    mounted() {
        // this.initBarEquipment()
        // this.initPieEquipment()
        this.getAllDevice();
        // this.getDetailData()
        // this.getPageList()
    },
    methods: {
        getDevIdentifierList(deviceId) {
            const params = {
                deviceId: deviceId,
                pageNum: 1,
                pageSize: 9999,
            };
            listThingsModel(params).then((res) => {
                if (res.code === 200) {
                    this.devIdentifierList = res.rows;
                }
            });
        },
        getDialog() {
            if (this.searchData.classifyId != null) {
                const item = this.classifyList.find((item) => item.deviceId === this.searchData.classifyId);
                this.queryParams.serialNumber = item.serialNumber;
            }
            if (this.searchData.date === null) {
                this.$message({ message: '请选择查询的日期', type: 'warning' });
                return;
            }
            //日
            if (this.Sjldradio === 'day') {
                this.queryParams.beginTime = this.searchData.date[0] + ' 00:00:00';
                this.queryParams.endTime = this.searchData.date[1] + ' 23:59:59';
            }
            this.openData = true;
        },
        getradio(tab) {
            if (this.searchData.date === null) {
                this.$message({ message: '请选择查询的日期', type: 'warning' });
                return;
            }
            //日
            if (tab === 'day') {
                this.queryParams.beginTime = this.searchData.date[0] + ' 00:00:00';
                this.queryParams.endTime = this.searchData.date[1] + ' 23:59:59';
                console.log(this.queryParams);
            }
            //月
            if (tab === 'month') {
                let dates = this.searchData.date[0];
                this.queryParams.beginTime = this.firstDayOfMonth(dates);
                this.queryParams.endTime = this.firstDayOfNextMonth(dates);
                console.log(this.queryParams);
            }
            if (tab === 'year') {
                let dates = this.searchData.date[0];
                this.queryParams.beginTime = this.firstDayOfCurrentYear(dates);
                this.queryParams.endTime = this.firstDayOfNextYear(dates);
            }
        },
        firstDayOfMonth(dates) {
            // 将字符串转换为Date对象
            const date = new Date(dates);
            // 设置日期为当月的第一天
            date.setDate(1);
            // 格式化日期并返回
            return this.formatDate(date);
        },
        firstDayOfNextMonth(dates) {
            // 将字符串转换为Date对象
            const date = new Date(dates);
            // 设置年份和月份为下一个月
            date.setMonth(date.getMonth() + 1);
            // 设置日期为下个月的第一天
            date.setDate(1);
            // 格式化日期并返回
            return this.formatDate(date);
        },
        formatDate(date) {
            // 获取年月日
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = '01'; // 月份的第一天
            // 返回格式化的日期字符串
            return `${year}-${month}-${day}`;
        },
        firstDayOfCurrentYear() {
            // 将字符串转换为Date对象
            const date = new Date(this.dates);
            // 获取年份
            const year = date.getFullYear();
            // 设置月份为0（即1月），日期为1
            date.setMonth(0);
            date.setDate(1);
            // 返回格式化的日期字符串
            return this.formatDateYear(date, year);
        },
        firstDayOfNextYear() {
            // 获取年份，并加1
            const nextYear = new Date(this.dates).getFullYear() + 1;
            // 设置月份为0（即1月），日期为1
            const date = new Date(nextYear, 0, 1);
            // 返回格式化的日期字符串
            return this.formatDateYear(date, nextYear);
        },
        formatDateYear(date, year) {
            // 获取月份和日期，并确保它们是两位数
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            // 返回格式化的日期字符串
            return `${year}-${month}-${day}`;
        },
        getExport() {
            /*const data = {
                serialNumber : this.queryParams.slaveId ? this.form.serialNumber + '_' + this.queryParams.slaveId : this.form.serialNumber,
                beginTime : this.queryParams.beginTime,
                endTime : this.queryParams.endTime,
                identifiers : this.searchData.identifiers
            }*/
            this.download(
                'iot/deviceLog/exportHistory',
                {
                    serialNumber: this.queryParams.slaveId ? this.form.serialNumber + '_' + this.queryParams.slaveId : this.form.serialNumber,
                    beginTime: this.queryParams.beginTime,
                    endTime: this.queryParams.endTime,
                    identifiers: this.searchData.identifiers
                },
                `设备时序数据_${new Date().getTime()}.xlsx`
            );
            this.cloneExport();
        },
        cloneExport() {
            this.Sjldradio = 'day';
            this.openData = false;
        },
        handleEdit(row) {
            this.open = true;
            this.formData = { ...row };
            console.log(row);
        },
        dialogClose() {
            this.formData = {};
            this.open = false;
            this.dialogTitle = '修改数据';
        },
        delData() {
            const data = {
                ts: this.formData.timeObj[this.formData.resource],
                identity: this.formData.resource,
            };
            deleteHistoryList(data).then((rp) => {
                this.open = false;
                this.search();
            });
        },
        editData() {
            const data = {
                tstime: this.formData.timeObj[this.formData.resource],
                identity: this.formData.resource,
                logValue: this.formData.logValue,
                isMonitor: this.formData.isMonitor,
                logType: this.formData.logType,
                mode: this.formData.mode,
                remark: this.formData.remark,
                serialNumber: this.formData.deviceName,
            };
            updateHistoryList(data).then((rp) => {
                this.open = false;
                this.search();
            });
        },
        changeResource(val) {
            console.log(val, '11');
            this.$set(this.formData, 'logValue', this.formData[val]);
        },
        handleDelete(row) {
            console.log(row, '编辑数据');
            this.open = true;
            this.dialogTitle = '删除数据';
            this.formData = { ...row };
        },
        search() {
            this.buttonLoading = true;
            this.setTableData = [];
            this.pageTotal = 0;
            this.searchData.pageNum = 1;
            this.setTableColumns = JSON.parse(JSON.stringify(this.setTableColumnsCopy));
            this.getDetailData();
            this.dialogRadioList = [];
        },
        resetFields() {
            this.workShopList = [];
            this.floorList = [];
            this.deviceList = [];
            this.searchData = {
                classifyId: '',
                date: [],
                pageSize: 10,
                pageNum: 1,
            };
            this.setTableData = [];
            this.pageTotal = 0;
        },
        getDetailData() {
            if (!this.searchData.classifyId) {
                this.$message({ message: '请选择查询的设备', type: 'warning' });
                this.buttonLoading = false;
                return false;
            }
            if (this.searchData.date.length === 0) {
                this.$message({ message: '请选择查询的日期', type: 'warning' });
                this.buttonLoading = false;
                return false;
            }
            getDevice(this.searchData.classifyId).then((response) => {
                this.getDeviceStatusWitchThingsModel(response);
            });
        },
        /** 获取设备状态和物模型 **/
        async getDeviceStatusWitchThingsModel(response) {
            // 获取缓存物模型
            response.data.cacheThingsModel = await this.getCacheThingsModdel(response.data.productId);
            // 获取设备运行状态
            response.data.thingsModels = await this.getDeviceStatus(response.data);
            //分享设备过滤没有权限的物模型
            if (response.data.isOwner == 0) {
                for (let i = 0; i < response.data.thingsModels.length; i++) {
                    if (response.data.userPerms.indexOf(response.data.thingsModels[i].id) == -1) {
                        response.data.thingsModels.splice(i--, 1);
                    }
                }
            }
            // 格式化物模型，拆分出监测值,数组添加前缀
            this.formatThingsModel(response.data);
            this.form = response.data;
            this.isSubDev = this.form.subDeviceList && this.form.subDeviceList.length > 0;
            this.queryParams.slaveId = this.form.slaveId;
            this.queryParams.serialNumber = this.form.serialNumber;
            console.log(this.form, '处理后的数据33333');
            // 监测数据
            if (this.isSubDev) {
                this.staticList = this.form.cacheThingsModel['properties'].filter((item) => {
                    return item.tempSlaveId == this.queryParams.slaveId;
                });
            } else {
                this.staticList = this.form.staticList;
            }
            this.getListHistory();
            // // 解析设备摘要
            // if (this.form.summary != null && this.form.summary != '') {
            //   this.summary = JSON.parse(this.form.summary);
            // }
            // this.isSubDev = this.form.subDeviceList && this.form.subDeviceList.length > 0;
            // this.oldDeviceStatus = this.form.status;
            // this.loadMap();
            // //Mqtt订阅
            // this.connectMqtt();
            // this.mqttSubscribe(this.form);
        },
        /** 获取缓存物模型*/
        getCacheThingsModdel(productId) {
            return new Promise((resolve, reject) => {
                cacheJsonThingsModel(productId)
                    .then((response) => {
                        resolve(JSON.parse(response.data));
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
        /* 获取监测历史数据*/
        getListHistory() {
            this.loading = true;
            /*this.queryParams.serialNumber = this.queryParams.slaveId ? this.form.serialNumber + '_' + this.queryParams.slaveId : this.form.serialNumber;
            this.queryParams.beginTime = this.searchData.date[0] + ' 00:00:00';
            this.queryParams.endTime = this.searchData.date[1] + ' 23:59:59';
            this.queryParams.identifiers = this.searchData.identifiers;*/
            const data = {
                serialNumber: this.queryParams.slaveId ? this.form.serialNumber + '_' + this.queryParams.slaveId : this.form.serialNumber,
                beginTime: this.searchData.date[0] + ' 00:00:00',
                endTime: this.searchData.date[1] + ' 23:59:59',
                identifiers: this.searchData.identifiers,
            }
            listHistory(data).then((res) => {
                if (Object.keys(res.data).length === 0) {
                    this.setTableData = [];
                    this.buttonLoading = false;
                    return false;
                }
                console.log(res.data, this.staticList, '999999', this.setTableColumns);
                for (let key in res.data) {
                    for (let i = 0; i < this.staticList.length; i++) {
                        if (key == this.staticList[i].id) {
                            this.setTableColumns.push({
                                label: this.staticList[i].name,
                                prop: this.staticList[i].id,
                                minWidth: '180',
                                align: 'center',
                                showOverflowTooltip: true,
                            });
                            this.dialogRadioList.push({
                                value: this.staticList[i].id,
                                text: this.staticList[i].name,
                            });
                            // 对象转数组
                            let dataList = [];
                            for (let j = 0; j < res.data[key].length; j++) {
                                let item = [];
                                item[0] = res.data[key][j].time;
                                item[1] = res.data[key][j].value;
                                item[2] = res.data[key][j].datetime;
                                item[3] = res.data[key][j].isMonitor;
                                item[4] = res.data[key][j].logType;
                                item[5] = res.data[key][j].mode;
                                item[6] = res.data[key][j].remark;
                                item[7] = res.data[key][j].identity;
                                dataList.push(item);
                            }
                            if (dataList.length > this.maxTotal) {
                                this.maxTotal = dataList.length;
                                this.maxTotalName = this.staticList[i].id;
                            }
                            this.allDataList[this.staticList[i].id] = dataList;
                        }
                    }
                }
                console.log(this.allDataList, this.maxTotal, this.maxTotalName, this.setTableColumns, '33333333333333111');
                this.allDataList[this.maxTotalName].map((item, index) => {
                    const obj = {};
                    obj.deviceName = this.form.deviceName;
                    obj.deviceName = this.form.serialNumber;
                    obj.equipmentConPrice = item[0];
                    obj.equipmentConPrices = item[2];
                    obj.isMonitor = item[3];
                    obj.logType = item[4];
                    obj.mode = item[5];
                    obj.remark = item[6];
                    obj.identity = item[7];
                    obj.timeObj = {};
                    for (let keys in this.allDataList) {
                        const filterData = this.allDataList[keys].filter((items) => items[0] == item[0]);
                        console.log(filterData, keys, '33333333333333333333333333333333333333333333333333333333');
                        if (filterData.length > 0) {
                            obj.timeObj[keys] = filterData[0][2];
                            obj[keys] = filterData[0][1];
                        } else {
                            obj[keys] = null;
                        }
                    }
                    console.log(obj, 'obj1111111111111111111111111111111');
                    this.setTableData.push(obj);
                });
                console.log(this.setTableData, 'setTableData');
                this.pageTotal = this.allDataList[this.maxTotalName].length || 0;
                this.buttonLoading = false;
                this.loading = false;
            });
        },
        /**获取设备运行状态*/
        getDeviceStatus(data) {
            const params = {
                deviceId: data.deviceId,
                slaveId: data.slaveId,
            };
            return new Promise((resolve, reject) => {
                getDeviceRunningStatus(params)
                    .then((response) => {
                        resolve(response.data.thingsModels);
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
        /**查询所有设备 */
        getAllDevice() {
            listAllDeviceShort().then((response) => {
                console.log(response, '数据3333');
                this.classifyList = response.rows || [];
            });
        },
        // 选择设备后
        handleDevDeviceChange(val) {
            this.getDevIdentifierList(val);
        },
        sizeChange(val) {
            this.searchData.pageSize = val;
            this.getPageList();
        },
        currentChange(val) {
            this.searchData.pageNum = val;
            this.getPageList();
        },
        getPageList() {
            const objs = {
                buildingId: this.searchData.buildingId,
                workshopIds: this.searchData.workshopIds,
                floor: this.searchData.floor,
                deviceIds: this.searchData.deviceIds,
                classifyId: this.searchData.classifyId,
                deviceName: this.searchData.deviceName,
                begin: this.searchData.date ? this.searchData.date[0] : '',
                end: this.searchData.date ? this.searchData.date[1] : '',
                timeType: this.searchData.type,
                dateType: this.searchData.dateType,
                pageSize: this.searchData.pageSize,
                pageNum: this.searchData.pageNum,
            };
            // const objss = {
            //   equipmentEnergyParam: objs
            // }
            equipentEnergyList(objs).then((res) => {
                this.setTableData = res.data.list;
                this.pageTotal = res.data.total || 0;
            });
        },
        handleExport() {
            this.buttonLoading = true;
            var datas = {
                buildingId: this.searchData.buildingId,
                workshopIds: this.searchData.workshopIds,
                deviceIds: this.searchData.deviceIds,
                classifyId: this.searchData.classifyId,
                deviceName: this.searchData.deviceName,
                begin: this.searchData.date ? this.searchData.date[0] : '',
                end: this.searchData.date ? this.searchData.date[1] : '',
                timeType: this.searchData.type,
                pageSize: '',
                pageNum: '',
            };
            const obj = JSON.parse(JSON.stringify(datas));
            // exportEquipent(obj).then(res=> {
            //   const fileName = '设备能源监控记录.xlsx'
            //   saveExcel(res.data, fileName)
            // })
            this.download(
                'energy/monitoring/equipmentByReport',
                {
                    ...obj,
                },
                '设备能源监控记录.xlsx'
            );
            this.buttonLoading = false;
        },
        formatThingsModel(data) {
            data.chartList = [];
            data.monitorList = [];
            data.staticList = [];
            // 物模型格式化
            for (let i = 0; i < data.thingsModels.length; i++) {
                // 数字类型设置默认值并转换未数值
                if (data.thingsModels[i].datatype.type == 'integer' || data.thingsModels[i].datatype.type == 'decimal') {
                    if (data.thingsModels[i].shadow == '') {
                        data.thingsModels[i].shadow = Number(data.thingsModels[i].datatype.min);
                    } else {
                        data.thingsModels[i].shadow = Number(data.thingsModels[i].shadow);
                    }
                }

                // 物模型分类放置
                if (data.thingsModels[i].datatype.type == 'array') {
                    if (data.thingsModels[i].datatype.arrayType == 'object') {
                        for (let k = 0; k < data.thingsModels[i].datatype.arrayParams.length; k++) {
                            for (let j = 0; j < data.thingsModels[i].datatype.arrayParams[k].length; j++) {
                                // 数组元素中参数ID添加前缀，例如：array_00_
                                let index = k > 9 ? String(k) : '0' + k;
                                let prefix = 'array_' + index + '_';
                                data.thingsModels[i].datatype.arrayParams[k][j].id = prefix + data.thingsModels[i].datatype.arrayParams[k][j].id;
                                // 图表、实时监测、监测统计分类放置
                                if (data.thingsModels[i].datatype.arrayParams[k][j].isChart == 1) {
                                    // 图表
                                    data.thingsModels[i].datatype.arrayParams[k][j].name = '[' + data.thingsModels[i].name + (k + 1) + '] ' + data.thingsModels[i].datatype.arrayParams[k][j].name;
                                    data.thingsModels[i].datatype.arrayParams[k][j].datatype.arrayType = 'object';
                                    data.chartList.push(data.thingsModels[i].datatype.arrayParams[k][j]);
                                    if (data.thingsModels[i].datatype.arrayParams[k][j].isHistory == 1) {
                                        // 监测统计
                                        data.staticList.push(data.thingsModels[i].datatype.arrayParams[k][j]);
                                    }
                                    if (data.thingsModels[i].datatype.arrayParams[k][j].isMonitor == 1) {
                                        // 实时监测
                                        data.monitorList.push(data.thingsModels[i].datatype.arrayParams[k][j]);
                                    }
                                    data.thingsModels[i].datatype.arrayParams[k].splice(j--, 1);
                                }
                            }
                        }
                    } else {
                        // 字符串拆分为物模型数组 model=id/name/type/isReadonly/value/shadow
                        let values = data.thingsModels[i].value != '' ? data.thingsModels[i].value.split(',') : [];
                        let shadows = data.thingsModels[i].shadow != '' ? data.thingsModels[i].shadow.split(',') : [];
                        for (let j = 0; j < data.thingsModels[i].datatype.arrayCount; j++) {
                            if (!data.thingsModels[i].datatype.arrayModel) {
                                data.thingsModels[i].datatype.arrayModel = [];
                            }
                            // 数组里面的ID需要添加前缀和索引，例如：array_00_temperature
                            let index = j > 9 ? String(j) : '0' + j;
                            let prefix = 'array_' + index + '_';
                            data.thingsModels[i].datatype.arrayModel[j] = {
                                id: prefix + data.thingsModels[i].id,
                                name: data.thingsModels[i].name,
                                type: data.thingsModels[i].type,
                                isReadonly: data.thingsModels[i].isReadonly,
                                value: values[j] ? values[j] : '',
                                shadow: shadows[j] ? shadows[j] : '',
                            };
                        }
                    }
                } else if (data.thingsModels[i].datatype.type == 'object') {
                    for (let j = 0; j < data.thingsModels[i].datatype.params.length; j++) {
                        // 图表、实时监测、监测统计分类放置
                        if (data.thingsModels[i].datatype.params[j].isChart == 1) {
                            // 图表
                            data.thingsModels[i].datatype.params[j].name = '[' + data.thingsModels[i].name + '] ' + data.thingsModels[i].datatype.params[j].name;
                            data.chartList.push(data.thingsModels[i].datatype.params[j]);
                            if (data.thingsModels[i].datatype.params[j].isHistory == 1) {
                                // 监测统计
                                data.staticList.push(data.thingsModels[i].datatype.params[j]);
                            }
                            if (data.thingsModels[i].datatype.params[j].isMonitor == 1) {
                                // 实时监测
                                data.monitorList.push(data.thingsModels[i].datatype.params[j]);
                            }
                            data.thingsModels[i].datatype.params.splice(j--, 1);
                        }
                    }
                } else if (data.thingsModels[i].isChart == 1) {
                    // // 图表、实时监测、监测统计分类放置
                    data.chartList.push(data.thingsModels[i]);
                    if (data.thingsModels[i].isHistory == 1) {
                        // 监测统计
                        data.staticList.push(data.thingsModels[i]);
                    }
                    if (data.thingsModels[i].isMonitor == 1) {
                        // 实时监测
                        data.monitorList.push(data.thingsModels[i]);
                    }
                    // 使用i--解决索引变更问题
                    data.thingsModels.splice(i--, 1);
                }
            }
        },
        dateTypeChange() {
            this.searchData.date = [];
        },
    },
};
</script>

<style lang="scss" scoped>
@import '~@/assets/styles/element-variables.scss';

.common_page {
    height: 100%;
    width: 100%;
}

.main_content {
    padding: 6px;
}

.page_content {
    padding: 0 20px;

    .page_content_head {
        display: flex;
        padding: 16px;

        .right_echat {
            height: 246px;
            width: 460px;
            padding-left: 20px;
            border-left: 1px solid rgba(0, 0, 0, 0.08);
        }

        .left_echat {
            flex: 1;
        }
    }
}

::v-deep.sys_table {
    .tableHeaderRow {
        cursor: pointer;

        .tableHeaderCell:active {
            opacity: 0.6;
        }

        .tableHeaderCell:last-of-type:active {
            opacity: 1;
        }

        .tableHeaderCell:first-of-type:active {
            opacity: 1;
        }

        .tableHeaderCell:last-of-type {
            cursor: default;
        }

        .tableHeaderCell:first-of-type {
            cursor: default;
        }
    }
}

::v-deep.el-radio-group {
    .el-radio-button {
        .el-radio-button__inner {
            padding: 10px 12px;
            color: #666666;
            font-size: 14px;
        }
    }

    .is-active {
        .el-radio-button__inner {
            background: #fff;
            color: $--color-primary;
        }
    }
}

::v-deep.el-form {
    .el-form-item {
        .el-form-item__content {
            line-height: 32px;
        }
    }
}
</style>
