<template>
    <div>
        <el-card v-show="showSearch">
            <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px"
                style="margin-bottom: -20px">
                <el-form-item :label="$t('alert.index.236501-0')" prop="alertName">
                    <el-input v-model="queryParams.alertName" :placeholder="$t('alert.index.236501-1')" clearable
                        size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item :label="$t('alert.index.236501-2')" prop="alertLevel">
                    <el-select v-model="queryParams.alertLevel" :placeholder="$t('alert.index.236501-3')" clearable
                        size="small">
                        <el-option v-for="dict in dict.type.iot_alert_level" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('alert.log.491272-4')" prop="status">
                    <el-select v-model="queryParams.status" :placeholder="$t('alert.log.491272-5')" clearable
                        size="small">
                        <el-option v-for="dict in dict.type.iot_process_status" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('index.alert.20250324-1')" prop="dateType">
                    <el-select v-model="queryParams.dateType" @change="dateTypeChange" style="width: 200px" clearable
                        :placeholder="$t('index.alert.20250324-2')">
                        <el-option v-for="item in dimensionList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('device.device-timer.433369-19')" prop="date"
                    v-if="queryParams.dateType != null && queryParams.dateType != ''">
                    <el-date-picker v-if="queryParams.dateType == 2" v-model="daterange" type="monthrange"
                        format="yyyy-MM" value-format="yyyy-MM" :range-separator="$t('index.time.20250324-04')"
                        :start-placeholder="$t('index.time.20250324-03')"
                        :end-placeholder="$t('index.time.20250324-03')"></el-date-picker>
                    <el-date-picker v-if="queryParams.dateType == 3" v-model="daterange" type="daterange" format="yyyy"
                        value-format="yyyy" :start-placeholder="$t('index.time.20250324-03')"
                        :end-placeholder="$t('index.time.20250324-02')"></el-date-picker>
                    <el-date-picker v-if="queryParams.dateType == 1" v-model="daterange" type="daterange"
                        format="yyyy-MM-dd" value-format="yyyy-MM-dd" :range-separator="$t('index.time.20250324-04')"
                        :start-placeholder="$t('index.time.20250324-03')"
                        :end-placeholder="$t('index.time.20250324-03')"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('search')
                    }}</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('reset')
                    }}</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="main-card" shadow="never">
            <div ref="bar_chart_equipment" style="width: 100%; height: 246px" />
        </el-card>
        <el-card class="main-card" shadow="never">
            <el-table class="base-table" v-loading="loading" :data="alertLogList"
                @selection-change="handleSelectionChange">
                <el-table-column :label="$t('alert.index.236501-0')" align="center" prop="alertName" />
                <el-table-column :label="$t('alert.log.491272-8')" align="center" prop="serialNumber" />
                <el-table-column :label="$t('alert.log.491272-9')" align="center" prop="deviceName" />
                <el-table-column :label="$t('alert.index.236501-2')" align="center" prop="alertLevel" width="120">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.iot_alert_level" :value="scope.row.alertLevel" />
                    </template>
                </el-table-column>
                <el-table-column :label="$t('alert.log.491272-10')" align="center" prop="createTime" width="170">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('alert.log.491272-24')" align="left" header-align="center" prop="detail">
                    <template slot-scope="scope">
                        <div v-html="formatDetail(scope.row.detail)"></div>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('alert.log.491272-4')" align="center" prop="status">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.iot_process_status" :value="scope.row.status" />
                    </template>
                </el-table-column>
                <el-table-column :label="$t('opation')" align="center" width="100">
                    <template slot-scope="scope">
                        <el-button size="mini" plain style="padding: 5px" type="primary" icon="el-icon-edit"
                            @click="handleUpdate(scope.row)" v-hasPermi="['iot:alertLog:edit']">{{
                                $t('alert.log.491272-25') }}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
        <!-- 添加或修改设备告警对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item :label="$t('alert.log.491272-26')" prop="remark">
                    <el-input v-model="form.remark" type="textarea" :placeholder="$t('index.alert.20250324-2')"
                        rows="8" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">{{ $t('confirm') }}</el-button>
                <el-button @click="cancel">{{ $t('cancel') }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listAlertLog, getAlertLog, delAlertLog, addAlertLog, updateAlertLog, listAlertLogEcharts } from '@/api/iot/alertLog';
import * as echarts from 'echarts';
import moment from 'moment';
export default {
    name: 'AlertLog',
    dicts: ['iot_alert_level', 'iot_process_status'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 设备告警表格数据
            alertLogList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                alertName: null,
                alertLevel: null,
                status: null,
                productId: null,
                productName: null,
                deviceId: null,
                deviceName: null,
                StartDate: null,
                endDate: null,
                dateType: null,
            },
            // 表单参数
            form: {},
            daterange: null,
            // 表单校验
            rules: {
                remark: [
                    {
                        required: true,
                        message: '处理内容不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            dimensionList: [
                {
                    id: 1,
                    name: '日',
                },
                {
                    id: 2,
                    name: '月',
                },
                {
                    id: 3,
                    name: '年',
                },
            ],
            dateArray: [],
            datesArray: [],
        };
    },
    created() {
        this.getList();
    },
    mounted() {
        this.initbarEquipments();
    },
    methods: {
        dateTypeChange() {
            this.daterange = [];
        },
        dateYYYYMMDD() {
            if (this.queryParams.dateType == '1') {
                if (this.daterange != null) {
                    this.queryParams.StartDate = moment(this.daterange[0]).format('YYYY-MM-DD');
                    this.queryParams.endDate = moment(this.daterange[1]).format('YYYY-MM-DD');
                }
            }
            if (this.queryParams.dateType == '2') {
                if (this.daterange != null) {
                    this.queryParams.StartDate = moment(this.daterange[0]).format('YYYY-MM');
                    this.queryParams.endDate = moment(this.daterange[1]).format('YYYY-MM');
                }
            }
            if (this.queryParams.dateType == '3') {
                if (this.daterange != null) {
                    this.queryParams.StartDate = moment(this.daterange[0]).format('YYYY');
                    this.queryParams.endDate = moment(this.daterange[1]).format('YYYY');
                }
            }
        },
        /** 查询设备告警列表 */
        getList() {
            this.loading = true;
            this.dateYYYYMMDD();
            listAlertLog(this.queryParams).then((response) => {
                this.alertLogList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
            listAlertLogEcharts(this.queryParams).then((response) => {
                this.generateDateArray();
                this.dailyAlertCounts(response.data);
                this.initbarEquipments();
            });
        },
        generateDateArray() {
            if (this.daterange == null) {
                return;
            }
            this.dateArray = [];
            if (this.queryParams.dateType == '1') {
                const startDate = this.parseDate(this.daterange[0]);
                const endDate = this.parseDate(this.daterange[1]);
                for (let day = startDate.getDate(); day <= endDate.getDate(); day++) {
                    this.dateArray.push(String(day).padStart(2, '0'));
                }
            }
            if (this.queryParams.dateType == '2') {
                const startMonth = this.daterange[0].substring(5, 7); // 提取月份部分 "07"
                const endMonth = this.daterange[1].substring(5, 7); // 提取月份部分 "08"
                const start = parseInt(startMonth, 10); // 将月份字符串转换为数字
                const end = parseInt(endMonth, 10); // 将月份字符串转换为数字
                for (let month = start; month <= end; month++) {
                    this.dateArray.push(String(month).padStart(2, '0')); // 添加到数组中，并确保是两位数格式
                }
            }
            if (this.queryParams.dateType == '3') {
                const startYear = parseInt(this.daterange[0], 10); // 将年份字符串转换为数字
                const endYear = parseInt(this.daterange[1], 10); // 将年份字符串转换为数字
                for (let year = startYear; year <= endYear; year++) {
                    this.dateArray.push(year);
                }
            }
        },
        parseDate(dateString) {
            return new Date(dateString);
        },
        dailyAlertCounts(data) {
            this.datesArray = [];
            const counts = new Map();
            if (this.queryParams.dateType == null) {
                return;
            }
            if (this.queryParams.dateType == '1') {
                // 初始化日期范围内每天的计数为0
                const startDate = new Date(this.queryParams.StartDate).toISOString().split('T')[0];
                const endDate = new Date(this.queryParams.endDate).toISOString().split('T')[0];
                console.log(startDate);
                console.log(endDate);
                let currentDate = new Date(startDate);
                while (currentDate <= new Date(endDate)) {
                    counts.set(currentDate.toISOString().split('T')[0], 0);
                    currentDate.setDate(currentDate.getDate() + 1);
                }
                console.log(counts);
                // 更新计数
                data.forEach((alert) => {
                    const date = new Date(alert.createTime).toISOString().slice(0, 10);
                    if (counts.has(date)) {
                        let currentValue = counts.get(date);
                        counts.set(date, currentValue + 1);
                    }
                });
                this.datesArray = Array.from(counts.values());
            }
            if (this.queryParams.dateType == '2') {
                const startDate = new Date(this.queryParams.StartDate).toISOString().slice(5, 7);
                const endDate = new Date(this.queryParams.endDate).toISOString().slice(5, 7);
                const start = parseInt(startDate, 10); // 将月份字符串转换为数字
                const end = parseInt(endDate, 10); // 将月份字符串转换为数字
                // 初始化日期范围内每天的计数为0
                for (let month = start; month <= end; month++) {
                    counts.set(String(month).padStart(2, '0'), 0);
                }
                // 更新计数
                data.forEach((alert) => {
                    const date = new Date(alert.createTime).toISOString().slice(5, 7);
                    const dates = parseInt(date, 10);
                    const paddate = String(dates).padStart(2, '0');
                    if (counts.has(String(paddate).padStart(2, '0'))) {
                        let currentValue = counts.get(paddate);
                        counts.set(paddate, currentValue + 1);
                    }
                });
                this.datesArray = Array.from(counts.values());
            }
            if (this.queryParams.dateType == '3') {
                const startYear = parseInt(this.daterange[0], 10); // 将年份字符串转换为数字
                const endYear = parseInt(this.daterange[1], 10); // 将年份字符串转换为数字
                for (let year = startYear; year <= endYear; year++) {
                    counts.set(String(year).padStart(2, '0'), 0);
                }
                console.log(counts);
                data.forEach((alert) => {
                    const date = new Date(alert.createTime).toISOString().slice(0, 4);
                    console.log(counts.has(date));
                    if (counts.has(date)) {
                        let currentValue = counts.get(date);
                        counts.set(date, currentValue + 1);
                    }
                });
                this.datesArray = Array.from(counts.values());
            }
            console.log(this.datesArray);
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                alertLogId: null,
                alertName: null,
                alertLevel: null,
                status: null,
                productId: null,
                productName: null,
                deviceId: null,
                deviceName: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
            };
            this.resetForm('form');
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm');
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.alertLogId);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = '添加设备告警';
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const alertLogId = row.alertLogId || this.ids;
            getAlertLog(alertLogId).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = this.$t('index.alert.20250324-5');
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.form.alertLogId != null) {
                        updateAlertLog(this.form).then((response) => {
                            this.$modal.msgSuccess('修改成功');
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addAlertLog(this.form).then((response) => {
                            this.$modal.msgSuccess('新增成功');
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const alertLogIds = row.alertLogId || this.ids;
            this.$modal
                .confirm('是否确认删除设备告警编号为"' + alertLogIds + '"的数据项？')
                .then(function () {
                    return delAlertLog(alertLogIds);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess('删除成功');
                })
                .catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'iot/alertLog/export',
                {
                    ...this.queryParams,
                },
                `alertLog_${new Date().getTime()}.xlsx`
            );
        },
        /**格式化显示物模型**/
        formatDetail(json) {
            if (json == null || json == '') {
                return;
            }
            let item = JSON.parse(json);
            let result = 'id：<span style="color:#F56C6C">' + item.id + '</span><br />';
            result = result + 'value：<span style="color:#F56C6C">' + item.value + '</span><br />';
            result = result + 'remark：<span style="color:#F56C6C">' + item.remark + '</span>';
            return result;
        },
        //柱状图
        initbarEquipments() {
            const myEcharts = echarts.init(this.$refs.bar_chart_equipment);
            myEcharts.setOption(
                {
                    title: {
                        text: this.$t('index.alert.20250324-4'),
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow',
                        },
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true,
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: this.dateArray,
                            axisTick: {
                                alignWithLabel: true,
                            },
                        },
                    ],
                    yAxis: [
                        {
                            type: 'value',
                        },
                    ],
                    series: [
                        {
                            name: 'Direct',
                            type: 'bar',
                            barWidth: '60%',
                            data: this.datesArray,
                        },
                    ],
                },
                true
            );
        },
    },
};
</script>
<style>
.echat {
    width: 100%;
    height: 300px;
}

.tableClass {
    width: 100%;
}
</style>
