<template>
    <div style="padding: 6px">
        <el-card v-show="showSearch" style="margin-bottom: 6px">
            <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" 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.log.491272-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>
                    <el-button icon="el-icon-search" size="mini" type="primary" @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 class="card-toolbar mb8">
                <div>
                    <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd"
                        v-hasPermi="['iot:alert:add']">{{ $t('add') }}</el-button>
                </div>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </div>
            <el-table class="base-table" v-loading="loading" :data="alertList" border
                @selection-change="handleSelectionChange" size="mini">
                <el-table-column :label="$t('alert.index.236501-0')" align="center" prop="alertName" />
                <el-table-column :label="$t('alert.index.236501-44')" align="center" prop="status">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status == 1" size="small" type="success">{{ $t('alert.index.236501-45')
                            }}</el-tag>
                        <el-tag v-if="scope.row.status == 2" size="small" type="danger">{{ $t('alert.index.236501-46')
                            }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('alert.index.236501-2')" align="center" prop="alertLevel">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.iot_alert_level" :value="scope.row.alertLevel" size="small" />
                    </template>
                </el-table-column>
                <el-table-column :label="$t('sip.user-list.558539-5')" align="center" prop="createTime">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('alert.index.236501-11')" align="center" prop="remark" />
                <el-table-column :label="$t('opation')" align="center" width="180">
                    <template slot-scope="scope">
                        <el-button v-hasPermi="['iot:alert:query']" icon="el-icon-view" size="small" plain
                            style="padding: 5px" type="primary" @click="handleUpdate(scope.row)">{{ $t('look')
                            }}</el-button>
                        <el-button v-hasPermi="['iot:alert:remove']" icon="el-icon-delete" size="small" plain
                            style="padding: 5px" type="danger" @click="handleDelete(scope.row)">{{ $t('del')
                            }}</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum"
                :total="total" @pagination="getList" />
        </el-card>

        <!-- 添加或修改设备告警对话框 -->
        <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :title="title" :visible.sync="open"
            append-to-body width="900px">
            <div class="el-divider el-divider--horizontal" style="margin-top: -25px"></div>
            <el-form ref="form" :model="form" :rules="rules" label-width="90px">
                <el-row :gutter="50">
                    <el-col :span="12">
                        <el-form-item :label="$t('alert.index.236501-0')" prop="alertName">
                            <el-input v-model="form.alertName" :placeholder="$t('alert.log.491272-1')" />
                        </el-form-item>
                        <el-form-item :label="$t('alert.index.236501-2')" prop="alertLevel">
                            <el-select v-model="form.alertLevel" :placeholder="$t('alert.index.236501-3')"
                                style="width: 100%">
                                <el-option v-for="dict in dict.type.iot_alert_level" :key="dict.value"
                                    :label="dict.label" :value="parseInt(dict.value)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('alert.index.236501-11')" prop="remark">
                            <el-input v-model="form.remark" :placeholder="$t('product.category.142342-3')" rows="1"
                                type="textarea" />
                        </el-form-item>
                        <el-form-item :label="$t('alert.index.236501-16')">
                            <el-switch v-model="form.status" :active-value="1" :inactive-value="2" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <el-tabs v-model="activeName" style="padding: 10px">
                <el-tab-pane :label="$t('alert.index.236501-17')" name="relateScene">
                    <el-table :border="false" v-loading="sceneLoading" :data="form.scenes" border size="mini">
                        <el-table-column :label="$t('alert.index.236501-18')" align="center"
                            prop="sceneName"></el-table-column>
                        <el-table-column :label="$t('alert.index.236501-44')" align="center" prop="enable">
                            <template slot-scope="scope">
                                <el-tag v-if="scope.row.enable == 1" size="small" type="success">{{
                                    $t('alert.index.236501-45') }}</el-tag>
                                <el-tag v-if="scope.row.enable == 2" size="small" type="danger">{{
                                    $t('alert.index.236501-46') }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('alert.index.236501-19')" align="center" prop="cond">
                            <template slot-scope="scope">
                                <span v-if="scope.row.cond == 1">{{ $t('alert.index.236501-20') }}</span>
                                <span v-if="scope.row.cond == 2">{{ $t('alert.index.236501-21') }}</span>
                                <span v-if="scope.row.cond == 3">{{ $t('alert.index.236501-22') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('alert.index.236501-23')" align="center" prop="executeMode">
                            <template slot-scope="scope">
                                <span v-if="scope.row.executeMode == 1">{{ $t('alert.index.236501-24') }}</span>
                                <span v-if="scope.row.executeMode == 2">{{ $t('alert.index.236501-25') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('opation')" align="center" width="120">
                            <template slot-scope="scope">
                                <el-button v-hasPermi="['iot:alert:remove']" icon="el-icon-delete" size="mini"
                                    type="text" @click="handleAlertSceneRemove(scope.row)">{{
                                        $t('alert.index.236501-26') }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane :label="$t('alert.index.236501-27')" name="notify">
                    <el-table :border="false" v-loading="notifyLoading" :data="form.notifyTemplateList" border
                        size="mini">
                        <el-table-column :label="$t('alert.index.236501-28')" align="center"
                            prop="name"></el-table-column>
                        <el-table-column :label="$t('alert.index.236501-44')" align="center" prop="status">
                            <template slot-scope="scope">
                                <el-tag v-if="scope.row.status == '1'" size="small" type="success">{{
                                    $t('alert.index.236501-45') }}</el-tag>
                                <el-tag v-if="scope.row.status == '0'" size="small" type="danger">{{
                                    $t('alert.index.236501-46') }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('alert.index.236501-29')" align="center" prop="channelType">
                            <template slot-scope="scope">
                                <dict-tag :options="dict.type.notify_channel_type" :value="scope.row.channelType" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('alert.index.236501-30')" align="center"
                            prop="channelName"></el-table-column>
                        <el-table-column :label="$t('alert.index.236501-31')" align="center"
                            prop="provider"></el-table-column>
                        <el-table-column :label="$t('opation')" align="center" width="120">
                            <template slot-scope="scope">
                                <el-button icon="el-icon-delete" size="mini" type="text"
                                    @click="handleAlertNotifyTempRemove(scope.row)">{{ $t('alert.index.236501-26')
                                    }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 用于设置间距 -->
                <el-tab-pane v-if="(this.$i18n.locale || defaultSettings.language) == 'en-US'" disabled>
                    <span slot="label">
                        <div style="margin-left: 260px"></div>
                    </span>
                </el-tab-pane>
                <el-tab-pane v-else disabled>
                    <span slot="label">
                        <div style="margin-left: 460px"></div>
                    </span>
                </el-tab-pane>
                <el-tab-pane v-if="activeName == 'relateScene'" disabled name="sceneButton">
                    <span slot="label">
                        <el-button type="" plain size="mini" @click="getScenesByAlertId"
                            v-hasPermi="['iot:alert:add']">{{
                                $t('refresh') }}</el-button>
                        <el-button type="" plain size="mini" @click="addAlertScenes" v-hasPermi="['iot:alert:add']">{{
                            $t('alert.index.236501-33') }}</el-button>
                    </span>
                </el-tab-pane>
                <el-tab-pane v-else disabled name="notifyButton">
                    <span slot="label">
                        <el-button type="" plain size="mini" @click="getNotifyTempsByAlertId"
                            v-hasPermi="['iot:alert:add']">{{
                                $t('refresh') }}</el-button>
                        <el-button type="" plain size="mini" @click="addAlertNotifyTemp"
                            v-hasPermi="['iot:alert:add']">{{
                                $t('alert.index.236501-34') }}</el-button>
                    </span>
                </el-tab-pane>
            </el-tabs>

            <div slot="footer" class="dialog-footer">
                <el-button v-show="form.alertId" v-hasPermi="['iot:alert:edit']" :disabled="updateBtnDisabled"
                    :loading="confirmLoading" type="primary" @click="handleSubmitForm">{{ $t('update') }}</el-button>
                <el-button v-show="!form.alertId" v-hasPermi="['iot:alert:add']" :disabled="updateBtnDisabled"
                    :loading="confirmLoading" type="primary" @click="handleSubmitForm">{{ $t('add') }}</el-button>
                <el-button @click="handleCancel">{{ $t('cancel') }}</el-button>
            </div>
        </el-dialog>

        <!-- 选择场景对话框 -->
        <scene-list ref="sceneList" @sceneEvent="getSceneData($event)" />
        <!-- 选择通知模板 -->
        <notify-temp-list ref="notifyTempList" @notifyEvent="getNotifyTempData($event)" />
    </div>
</template>

<script>
import { listAlert, getAlert, delAlert, addAlert, updateAlert, getScenesByAlertId, listNotifyTemplate } from '@/api/iot/alert';
import sceneList from './scene-list';
import notifyTempList from './notify-temp-list.vue';

export default {
    name: 'alert',
    dicts: ['iot_alert_level', 'sys_job_status', 'notify_channel_type'],
    props: {},
    watch: {},
    components: { sceneList, notifyTempList },
    data() {
        return {
            // 选中的选项卡
            activeName: 'relateScene',
            // 通知模板列表加载
            notifyLoading: false,
            updateBtnDisabled: false,
            // 确认按钮加载
            confirmLoading: false,
            // 告警列表加载
            sceneLoading: false,
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 设备告警表格数据
            alertList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                alertName: null,
                alertLevel: null,
            },
            form: {},
            // 表单校验
            rules: {
                alertName: [
                    {
                        required: true,
                        message: this.$t('alert.index.236501-39'),
                        trigger: 'blur',
                    },
                ],
                alertLevel: [
                    {
                        required: true,
                        message: this.$t('alert.index.236501-40'),
                        trigger: 'change',
                    },
                ],
            },
        };
    },

    created() {
        this.getList();
    },
    methods: {
        /** 移除告警通知项*/
        handleAlertNotifyTempRemove(row) {
            for (let i = 0; i < this.form.notifyTemplateList.length; i++) {
                if (row.id == this.form.notifyTemplateList[i].id) {
                    this.form.notifyTemplateList.splice(i, 1);
                }
            }
        },
        /**获取告警通知模板列表*/
        getNotifyTempsByAlertId() {
            if (this.form.alertId) {
                this.notifyLoading = true;
                listNotifyTemplate(this.form.alertId).then((response) => {
                    this.form.notifyTemplateList = response.rows;
                    this.notifyLoading = false;
                });
            }
        },
        /**添加通知模板*/
        addAlertNotifyTemp() {
            this.$refs.notifyTempList.open = true;
            if (this.form.notifyTemplateList) {
                let list = JSON.parse(JSON.stringify(this.form.notifyTemplateList));
                this.$refs.notifyTempList.selectNotifyTemps = list;
                this.$refs.notifyTempList.ids = list.map((item) => item.id);
            }
            this.$refs.notifyTempList.getList();
        },
        /**获取通知模板数据*/
        getNotifyTempData(data) {
            this.form.notifyTemplateList = data;
        },
        /** 移除告警场景项*/
        handleAlertSceneRemove(row) {
            for (let i = 0; i < this.form.scenes.length; i++) {
                if (row.sceneId == this.form.scenes[i].sceneId) {
                    this.form.scenes.splice(i, 1);
                }
            }
        },
        /**获取告警关联场景列表*/
        getScenesByAlertId() {
            if (this.form.alertId) {
                this.sceneLoading = true;
                getScenesByAlertId(this.form.alertId).then((response) => {
                    this.form.scenes = response.rows;
                    this.sceneLoading = false;
                });
            }
        },
        /**添加场景*/
        addAlertScenes() {
            this.$refs.sceneList.openScene = true;
            if (this.form.scenes) {
                let sceneList = JSON.parse(JSON.stringify(this.form.scenes));
                this.$refs.sceneList.selectScenes = sceneList;
                this.$refs.sceneList.ids = sceneList.map((item) => item.sceneId);
            }
            this.$refs.sceneList.getList();
        },
        /**获取场景数据*/
        getSceneData(data) {
            this.form.scenes = data;
        },
        // 查询设备告警列表
        getList() {
            this.loading = true;
            listAlert(this.queryParams).then((response) => {
                this.alertList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 表单重置
        reset() {
            this.form = {
                alertId: null,
                alertName: null,
                alertLevel: 1,
                productId: null,
                productName: null,
                remark: null,
                status: 1,
                scenes: [], // 场景列表
                notifyTemplateList: [], // 通知模板列表
            };
            this.activeName = 'relateScene';
            this.resetForm('form');
        },
        // 新增按钮操作
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = this.$t('alert.index.236501-41');
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm');
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.alertId);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        // 修改按钮操作
        handleUpdate(row) {
            this.reset();
            const alertId = row.alertId || this.ids;
            getAlert(alertId).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = this.$t('alert.index.236501-42');
            });
        },
        // 删除按钮操作
        handleDelete(row) {
            const alertIds = row.alertId || this.ids;
            this.$modal
                .confirm(this.$t('alert.index.236501-42', [alertIds]))
                .then(function () {
                    return delAlert(alertIds);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess(this.$t('delSuccess'));
                })
                .catch(() => { });
        },
        // 取消按钮
        handleCancel() {
            this.open = false;
            this.reset();
        },
        // 提交按钮
        handleSubmitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.form.alertId != null) {
                        updateAlert(this.form).then((res) => {
                            this.$modal.msgSuccess(this.$t('updateSuccess'));
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addAlert(this.form).then((res) => {
                            this.$modal.msgSuccess(this.$t('addSuccess'));
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
    },
};
</script>

<style lang="scss" scoped></style>
