<script lang="ts">
export default {
    name: 'alarmset' // 告警设置
};
</script>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick, reactive } from 'vue'
import Page from '@/components/Pagination/page.vue'
import { ElMessageBox, ElMessage, ElTable, FormRules, ElTree } from 'element-plus'
import { DeviceAlarmParameter, addDeviceAlarmParameter, updateDeviceAlarmParameter, deleteDeviceAlarmParameterById, deleteDeviceAlarmParameterByIds } from '@/api/equipmentsignal';
import { getDeviceByType } from '@/api/device';
import { listDeviceLinkagePlan, listDeviceLinkageOperate } from '@/api/linkageplan'
import { useDark } from '@vueuse/core'
import Eldialog from '@/components/seccmsdialog/eldialog.vue'
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/silver'
import 'tinymce/models/dom/model'
import 'tinymce/icons/default/icons'
import "tinymce/themes/silver/theme.min.js";
import 'tinymce/plugins/table'// 插入表格插件
import 'tinymce/plugins/lists'// 列表插件
import 'tinymce/plugins/wordcount'// 字数统计插件
import 'tinymce/plugins/advlist'// 高级列表插件
import 'tinymce/plugins/autosave'// 字数统计插件


const props: any = defineProps({
    alarmquerylist: {
        required: true,
        type: Object
    }
})
//树形控件类型定义
interface Tree {
    [x: string]: any;
    label: string;
}
const produrl = ref('')
const contentstyleval = ref('body { background-color: #001e55;color:#fff;border:none;}')
const initlist = ref({
    selector: 'textarea',
    language_url: produrl.value + '/tinymce/langs/zh_CN.js',
    language: 'zh_CN',
    skin_url: produrl.value + '/tinymce/skins/ui/oxide',
    content_css: produrl.value + '/tinymce/skins/content/default/content.css',
    height: 300, // 编辑器高度
    content_style: contentstyleval,
    body_class: 'panel-body',
    toolbar: 'fontfamily fontsize lineheight bold italic underline strikethrough forecolor | outdent indent alignleft aligncenter alignright alignjustify bullist numlist',
    menubar: false,
    plugins: 'advlist autosave lists table wordcount',
    end_container_on_empty_block: true,
    powerpaste_word_import: 'clean',
    code_dialog_height: 450,
    code_dialog_width: 1000,
    advlist_bullet_styles: 'square',
    advlist_number_styles: 'default',
    imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
    default_link_target: '_blank',
    link_title: false,
    fontsize_formats: '12px 14px 16px 18px 20px 24px 28px 30px 36px 40px 48px',
    font_formats: '微软雅黑=微软雅黑;宋体=宋体;黑体=黑体;',
    nonbreaking_force_tab: true,
    convert_urls: false,
    branding: false,
})
let isDark: any = '1'
watch(useDark(), () => {
    isDark = '1'
    if (useDark().value == true) {
        initlist.value.skin_url = produrl.value + '/tinymce/skins/ui/oxide-dark'
        contentstyleval.value = 'body { background-color: #001e55;color:#fff;border:none;}'
    } else {
        initlist.value.skin_url = produrl.value + '/tinymce/skins/ui/oxide'
        contentstyleval.value = 'body { background-color: #fff;color:#000;border:none;}'
    }
})
// 告警设置
const content = ref('')
const dialogVisible = ref(false)
const dialogtitle = ref('新增告警设置')
watch(dialogVisible, () => {
    if (dialogVisible.value) {
        nextTick(() => {
            if (isDark === '1') {
                //深色
                initlist.value.skin_url = produrl.value + '/tinymce/skins/ui/oxide-dark'
                contentstyleval.value = 'body { background-color: #001e55;color:#fff;border:none;}'
            } else {
                initlist.value.skin_url = produrl.value + '/tinymce/skins/ui/oxide'
                contentstyleval.value = 'body { background-color: #fff;color:#000;border:none;}'
            }
            tinymce.init(initlist.value)
            if (alarmform.value.messageTemplate !== '') {
                if (tinymce.activeEditor) {
                    tinymce.activeEditor.setContent(alarmform.value.messageTemplate)
                }
            }
        })
    } else {
        tinymce.remove()
    }
})
const alarmform: any = ref({})
const rules = reactive<FormRules>({
    alarmType: [{ required: true, message: "请选择报警类型", trigger: "change" }],
    alarmLevel: [{ required: true, message: "请选择报警等级", trigger: "change" }]
});
const ruleFormRef: any = ref(null);
const queryInfo: any = ref({
    current: 1,
    size: 10,
    total: 0
})
const alarmType = ref('')
const alarmLevel = ref('')
const multipleSelection = ref([])
const loading = ref(false)
const tableData: any = ref([])
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val
}
const typeoptions: any = ref([])
const leveloptions: any = ref([])
const noticeoptions: any = ref([])
const checkList: any = ref(['01'])
const emaillist: any = ref([{ name: '', email: '' }])
// 联动方案配置
const dialogVisibles = ref(false)
const planData: any = ref([])
const planloading = ref(false)
const treeData = ref([])
const treeInfo: any = ref({})
const treeRef = ref<InstanceType<typeof ElTree>>()
const handleNodeClick = (data: Tree) => {
    treeInfo.value = data
    getplanData();
};
const checkplanData: any = ref([])
const defaultProps = { label: 'schemeName' };
const defaultchecknode: any = ref([])
const schemelabel = ref('')
const vMove = {
    mounted(el: any) {
        el.onmousedown = function (e: any) {
            var init = e.clientX;
            var parent: any = document.getElementById("silderLeft");
            const initWidth: any = parent.offsetWidth;
            document.onmousemove = function (e) {
                var end = e.clientX;
                var newWidth = end - init + initWidth;
                parent.style.width = newWidth + "px";
            };
            document.onmouseup = function () {
                document.onmousemove = document.onmouseup = null;
            };
        };
    }
}
onMounted(() => {

    if (import.meta.env.VITE_USER_NODE_ENV !== 'development') {
        produrl.value = '/monitor'
        initlist.value.language_url = produrl.value + '/tinymce/langs/zh_CN.js'
        initlist.value.content_css = produrl.value + '/tinymce/skins/content/default/content.css'
    } else {
        produrl.value = ''
        initlist.value.language_url = produrl.value + '/tinymce/langs/zh_CN.js'
        initlist.value.content_css = produrl.value + '/tinymce/skins/content/default/content.css'
    }
    queryselect()
    getData()
})
function queryselect() {
    const levelparams = {
        dictcode: 'fk_alarmLevel'
    }
    getDeviceByType(levelparams).then((levelres: any) => {
        // debugger
        leveloptions.value = levelres.data
    })
    const typeparams = {
        dictcode: 'fk_alarmType'
    }
    getDeviceByType(typeparams).then((typeres: any) => {
        typeoptions.value = typeres.data
    })
    const noticeparams = {
        dictcode: 'noticeType'
    }
    getDeviceByType(noticeparams).then((noticeres: any) => {
        noticeoptions.value = noticeres.data
    })
}
function getplanData() {
    const params = {
        schemeName: treeInfo.value.schemeName,
        size: 9999,
        current: 1
    }
    listDeviceLinkageOperate(params).then((res: any) => {
        planData.value = res.data
        if (planData.value.length > 0) {
            const arr = []
            for (let i in checkplanData.value) {
                for (let j in planData.value) {
                    if (checkplanData.value[i] === planData.value[j].schemeName) {
                        arr.push(planData.value[j].schemeName)
                    }
                }
            }
            checkplanData.value = arr
        }
    })
}
function handleClose() {
    dialogVisible.value = false
}

function handleCloses() {
    dialogVisibles.value = false
}
function formsubmit(formEl: any) {
    formEl.validate((valid: any) => {
        if (valid) {
            if (isSwitch.value == true) {
                return
            }
            isSwitch.value = true
            loading.value = true
            if (tinymce.activeEditor !== null) {
                // 获取富文本内容
                alarmform.value.messageTemplate = tinymce.activeEditor.getContent()
            } else {
                alarmform.value.messageTemplate = ''
            }
            alarmform.value.noticeEmails = JSON.stringify(emaillist.value)
            if (checkList.value.length !== 0) {
                alarmform.value.noticeType = checkList.value.join()
            } else {
                alarmform.value.noticeType = ''
            }
            if (checkplanData.value.length > 0) {
                alarmform.value.noticeLinkages = checkplanData.value.join()
            } else {
                alarmform.value.noticeLinkages = ''
            }
            if (alarmform.value.paramId) {
                updateDeviceAlarmParameter(alarmform.value).then((res: any) => {
                    ElMessage({
                        message: "修改成功",
                        type: "success",
                    });
                    isSwitch.value = false
                    dialogVisible.value = false
                    loading.value = false
                    getData()
                }).catch(() => {
                    isSwitch.value = false
                    loading.value = false
                })
            } else {
                addDeviceAlarmParameter(alarmform.value).then((res: any) => {
                    ElMessage({
                        message: "新增成功",
                        type: "success",
                    });
                    isSwitch.value = false
                    dialogVisible.value = false
                    loading.value = false
                    getData()
                }).catch(() => {
                    isSwitch.value = false
                    loading.value = false
                })
            }
        }
    })
}
// 刷新告警信息
function getData() {
    loading.value = true
    const params = {
        signalId: props.alarmquerylist.signalId,
        meterDeviceId: props.alarmquerylist.deviceId,
        signalName: props.alarmquerylist.signalName,
        current: queryInfo.value.current,
        size: queryInfo.value.size,
        alarmType: alarmType.value,
        alarmLevel: alarmLevel.value
    }
    DeviceAlarmParameter(params).then((res: any) => {
        tableData.value = res.data.records
        queryInfo.value.total = res.data.total
        loading.value = false
    })
}
function resetData() {
    queryInfo.value.current = 1,
        queryInfo.value.size = 10
    alarmType.value = ''
    alarmLevel.value = ''
    getData()
}
const isSwitch = ref(false)
// 新增告警设置
function addclick() {
    checkplanData.value = []
    defaultchecknode.value = []
    schemelabel.value = ''
    isSwitch.value = false
    dialogtitle.value = '新增告警设置'
    alarmform.value = {}
    // alarmform.value.alarmLevel = '01'
    alarmform.value.signalId = props.alarmquerylist.signalId,
        alarmform.value.deviceId = props.alarmquerylist.deviceId,
        alarmform.value.signalName = props.alarmquerylist.signalName
    content.value = ''
    dialogVisible.value = true
}
// 批量删除告警信息
function delclicks() {
    ElMessageBox.confirm("确定删除选择告警信息吗?", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        let id = [] as any[];
        multipleSelection.value.forEach((item: any) => {
            id.push(item.paramId)
        })
        let params = {
            ids: id.join(','),
        };
        deleteDeviceAlarmParameterByIds(params).then(() => {
            getData();
            ElMessage({
                message: "删除成功",
                type: "success",
            });
        });
    }).catch(() => { })
}
function editclick(row: any) {
    dialogtitle.value = '修改告警设置'
    schemelabel.value = ''
    checkplanData.value = []
    defaultchecknode.value = []
    alarmform.value = {}
    checkList.value = []
    alarmform.value = JSON.parse(JSON.stringify(row))
    if (alarmform.value.noticeType !== undefined && alarmform.value.noticeType !== null && alarmform.value.noticeType !== '') {
        checkList.value = alarmform.value.noticeType.split(',')
    }
    if (alarmform.value.noticeEmails !== undefined && alarmform.value.noticeEmails !== null && alarmform.value.noticeEmails !== '') {
        emaillist.value = JSON.parse(alarmform.value.noticeEmails)
    }
    if (alarmform.value.noticeLinkages !== undefined && alarmform.value.noticeLinkages !== null && alarmform.value.noticeLinkages !== '') {
        const arr = alarmform.value.noticeLinkages.split(',')
        const namearr = []
        for (let i = 0; i < arr.length; i++) {
            checkplanData.value.push(arr[i])
            defaultchecknode.value.push(arr[i])
            namearr.push(arr[i])
        }
        schemelabel.value = namearr.join()
    }
    isSwitch.value = false
    dialogVisible.value = true
}
// 删除告警信息
function delclick(row: any) {
    ElMessageBox.confirm("确定删除此告警信息吗?", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        let params = {
            id: row.paramId
        };
        deleteDeviceAlarmParameterById(params).then((res: any) => {
            ElMessage({
                message: "删除成功",
                type: "success",
            });
            getData()
        })
    }).catch(() => { })
}
// 删除邮件人信息
function delemailclick(index: any) {
    emaillist.value.splice(index, 1);
}
//添加邮件人信息
function addemailclick() {
    emaillist.value.push({ name: '', address: '' })
}
// 方案配置
function plansetclick() {
    const params = {}
    listDeviceLinkagePlan(params).then((res: any) => {
        treeData.value = res.data
        if (res.data.length !== 0 && res.data !== null) {
            nextTick(() => {
                treeRef.value?.setCurrentKey(res.data[0].schemeName);
                treeInfo.value = res.data[0]
                getplanData();
            });
        }
    })
    dialogVisibles.value = true
}
const handleCheckChange = (
    data: Tree,
    checked: boolean,
    indeterminate: boolean
) => {
    if (checked) {
        checkplanData.value.push(data.schemeName)
    } else {
        checkplanData.value = checkplanData.value.filter((item: any) => item !== data.schemeName)
    }
}
function schemesubmit() {
    const namearr = []
    schemelabel.value = ''
    if (checkplanData.value.length > 0) {
        for (let i = 0; i < checkplanData.value.length; i++) {
            namearr.push(checkplanData.value[i])
        }
    }
    schemelabel.value = namearr.join()
    dialogVisibles.value = false
}
const tableRowClassName = ({
    row,
    rowIndex,
}: {
    row: any
    rowIndex: number
}) => {
    if (rowIndex % 2 === 0) {
        return 'warning-row'
    } else if (rowIndex % 2 === 1) {
        return 'success-row'
    }
    return ''
}
</script>
<template>
    <div class="alarmcontent">
        <div class="alarmcontent-content-top">
            <div>
                <el-select v-model="alarmType" placeholder="请选择告警类型" style="width: 220px;margin-left: 10px;" clearable>
                    <el-option v-for="item in typeoptions" :key="item.itemcode" :label="item.dictname"
                        :value="item.itemcode" />
                </el-select>
                <el-select v-model="alarmLevel" placeholder="请选择告警等级" style="width: 220px;margin-left: 10px;" clearable>
                    <el-option v-for="item in leveloptions" :key="item.itemcode" :label="item.dictname"
                        :value="item.itemcode" />
                </el-select>
                <el-button class="searchButton" type="primary" style="margin-left: 10px;"
                    @click="getData">搜索</el-button>
                <el-button class="searchButton" style="margin-left: 10px;" @click="resetData">重置</el-button>
            </div>
            <div>
                <el-button class="searchButton" type="primary" style="margin-left: 10px;"
                    @click="addclick">新增</el-button>
                <el-button class="searchButton" :type="multipleSelection.length <= 0 ? '' : 'primary'"
                    :disabled="multipleSelection.length <= 0 ? true : false" style="margin-left: 10px;"
                    @click="delclicks">删除</el-button>
            </div>
        </div>
        <div>
            <el-table ref="multipleTableRef" :data="tableData" style="width: 100%;margin-bottom: 20px;height: calc(100vh - 360px);
                      overflow: auto;" row-key="id" default-expand-all :v-loading="loading"
                @selection-change="handleSelectionChange" :row-class-name="tableRowClassName"
                :header-cell-style="{ background: '#002b6a', color: '#B5D7FF', height: '50px' }">
                <el-table-column type="selection" align="center" width="55" />
                <el-table-column label="序号" type="index" width="50" />
                <el-table-column label="告警类型" prop="alarmTypeName" width="240" />
                <el-table-column label="告警等级" prop="alarmLevelName" width="100" />
                <el-table-column label="告警条件" prop="alarmCondition" />
                <el-table-column label="联动方案" prop="noticeLinkages" min-width="100" />
                <el-table-column label="告警通知方式" prop="noticeTypeName" width="240" />
                <el-table-column fixed="right" label="操作" width="80">
                    <template #default="scope">
                        <span
                            style="display: flex;display: -webkit-flex;justify-content: space-around; -webkit-justify-content: space-around; ">
                            <img  src="@/assets/newimg/ht_xg.png" title="修改" v-hasPerm="['update:devicesignal']"
                                style="cursor: pointer;" @click="editclick(scope.row)">
                            <img src="@/assets/newimg/ht_sc.png" title="删除" v-hasPerm="['del:devicesignal']"
                                style="cursor: pointer;" @click="delclick(scope.row)">
                        </span>
                    </template>
                </el-table-column>
            </el-table>
            <Page class="mt-[20px]" :total="queryInfo.total" v-model:size="queryInfo.size"
                v-model:current="queryInfo.current" @pagination="getData" />
        </div>
        <Eldialog v-if="dialogVisible" :title="dialogtitle" :zIndex="2000" :width="'60%'" @before-close="handleClose">
            <template v-slot:PopFrameContent>
                <el-form :model="alarmform" ref="ruleFormRef" :rules="rules" label-width="120px"
                    style="height: calc(65vh);overflow: auto;padding:0px 10px;">
                    <div class="dialogcontent-title">基本信息</div>
                    <div style="display: flex;justify-content: space-between;">
                        <div style="width: 50%;">
                            <el-form-item label="告警类型" prop="alarmType">
                                <el-select v-model="alarmform.alarmType" placeholder="请选择告警类型" style="width: 100%;">
                                    <el-option v-for="item in typeoptions" :key="item.itemcode" :label="item.dictname"
                                        :value="item.itemcode" />
                                </el-select>
                            </el-form-item>
                        </div>
                        <div style="width: 50%;">
                            <el-form-item label="告警等级" prop="alarmLevel">
                                <el-radio-group v-model="alarmform.alarmLevel">
                                    <el-radio v-for="(levelitem, levelindex) in leveloptions" :key="levelindex"
                                        :value="levelitem.itemcode"  :label="levelitem.itemcode">{{ levelitem.dictname }}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </div>
                    </div>
                    <div style="display: flex;justify-content: space-between;">
                        <div style="width: 50%;">
                            <el-form-item label="告警条件">
                                <el-input v-model="alarmform.alarmCondition" maxlength="100" show-word-limit
                                    placeholder="请输入告警条件" clearable />
                            </el-form-item>
                        </div>
                        <div style="width: 50%;">
                            <el-form-item label="告警抑制条件">
                                <el-input v-model="alarmform.inhibitionCondition" maxlength="200" show-word-limit
                                    placeholder="请输入告警抑制条件" clearable />
                            </el-form-item>
                        </div>
                    </div>
                    <el-form-item label="告警描述模板">
                        <textarea v-model="alarmform.messageTemplate" maxlength="200" show-word-limit :init="initlist"
                            style="width: 100%;"></textarea>
                    </el-form-item>
                    <div class="dialogcontent-title" style="margin-top: 20px;">配置信息</div>
                    <el-form-item label="告警通知方式">
                        <el-checkbox-group v-model="checkList">
                            <el-checkbox v-for="(noticeitem, noticeindex) in noticeoptions" :key="noticeindex"
                                :label="noticeitem.dictname" :value="noticeitem.itemcode" />
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="邮件通知人">
                        <div v-for="(item, index) in emaillist" :key="index" class="tsalarcontent-input-box">
                            <div style="width:calc((100% - 50px)/2)">
                                <el-input v-model="item.name" placeholder="请输入收件人" maxlength="100" show-word-limit
                                    clearable />
                            </div>
                            <div style="margin-left: 10px;margin-right: 10px;width:calc((100% - 50px)/2)">
                                <el-input v-model="item.email" placeholder="请输入邮件地址" maxlength="300" show-word-limit
                                    clearable />
                            </div>
                            <div style="display: flex;width:50px;">
                                <img v-if="index !== 0" src="@/assets/configmanage/del.png"
                                    style="width: 16px;height:16px;cursor: pointer;" @click="delemailclick(index)"
                                    alt="">
                                <img src="@/assets/configmanage/add.png"
                                    style="width: 16px;height:16px;margin-left: 10px;cursor: pointer;"
                                    @click="addemailclick" alt="">
                            </div>
                        </div>
                    </el-form-item>

                </el-form>
                <span class="dialog-footer" style="display: flex;justify-content: flex-end;margin-top: 15px;">
                    <el-button class="searchButton" @click="handleClose">取消</el-button>
                    <el-button class="searchButton" type="primary" @click="formsubmit(ruleFormRef)">确定</el-button>
                </span>
            </template>
        </Eldialog>
        <Eldialog v-if="dialogVisibles" :title="'选择联动方案'" :zIndex="2000" :width="'60%'" @before-close="handleCloses">
            <template v-slot:PopFrameContent>
                <div style="display: flex;">
                    <aside id="silderLeft">
                        <el-tree ref="treeRef" node-key="schemeName" :data="treeData" :props="defaultProps"
                            :default-checked-keys="defaultchecknode" show-checkbox @check-change="handleCheckChange"
                            @node-click="handleNodeClick" style="width:100%;" />
                    </aside>
                    <div class="silderRight" style="height: calc(70vh) !important;">
                        <el-table ref="multipleTableRef" :data="planData" style="width: 100%;margin-bottom: 20px;height: calc(60vh);
                      overflow: auto;" row-key="id" default-expand-all :v-loading="planloading"
                            @selection-change="handleSelectionChange" :row-class-name="tableRowClassName"
                            :header-cell-style="{ background: '#002b6a', color: '#B5D7FF', height: '50px' }">
                            <el-table-column label="序号" type="index" width="50" align="center" />
                            <el-table-column label="联动设备名称" prop="linkDeviceName" />
                            <el-table-column label="联动信号名称" prop="linkSignalName" />
                            <el-table-column label="联动信号类型" prop="linkSignalType" />
                            <el-table-column label="联动控制指令" prop="linkSignalCommand" />
                            <el-table-column label="联动动作描述" prop="linkAction" />
                        </el-table>
                    </div>
                </div>
                <span class="dialog-footer" style="display: flex;justify-content: flex-end;margin-top: 10px;">
                    <el-button class="searchButton" type="primary" @click="schemesubmit">确定</el-button>
                </span>
            </template>
        </Eldialog>
    </div>
</template>
<style scoped lang="scss">
.alarmcontent {
    width: 100%;
    height: calc(100vh - 260px);
    margin-top: 10px;

    .alarmcontent-content-top {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;
    }
}

.dialogcontent-title {
    font-family: 'Arial Negreta', 'Arial Normal', 'Arial';
    font-weight: 700;
    font-style: normal;
    font-size: 14px;
    color: #0099FF;
    padding-left: 15px;
    height: 14px;
    line-height: 14px;
    border-left: 4px solid #0099ff;
    margin-bottom: 20px;
}

.tsalarcontent-input-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    margin-bottom: 5px;
}

:deep() {
    .el-tree-node__content {
        height: 40px;
    }

    .el-tree .is-current .el-tree-node__content {
        background-color: rgb(17, 63, 93);
        color: #fff;
    }

    .el-tree-node__expand-icon {
        font-size: 0px;
    }

    .el-checkbox__inner {
        border-color: #787878;
    }
}

#silderLeft {
    width: 230px;
    box-sizing: border-box;
    border-radius: 3px;
    position: relative;
    height: calc(100vh - 330px);

    &:hover {
        .moveBtn {
            opacity: 1;
        }
    }
}

/* 拖动条 */
.moveBtn {
    height: 100%;
    width: 15px;
    padding: 0 6px;
    opacity: 0;
    position: absolute;
    right: -15px;
    top: 0;
}

.moveBtn-line {
    width: 100%;
    height: 100%;
    cursor: col-resize;
    user-select: none;
}

.silderRight {
    flex: 1;
    position: relative;
    width: 100%;
    overflow: auto;
    padding-bottom: 0px;
    margin-left: 15px;
    box-sizing: border-box;
    height: calc(100vh - 330px);
}

:deep(.el-input .el-input__count .el-input__count-inner) {
    background-color: rgba(240, 248, 255, 0);
}

</style>