<script lang="ts">
export default {
    name: "alarminterval",
};
</script>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { getAlarm, getSubstation, setAlgorithmModel, getAlgorithmModelById } from "@/api/alarminterval";
import { getDeviceByType, getaccType, getMainEquipment } from "@/api/device";
import { ElMessage } from "element-plus";
import Eldialog from '@/components/seccmsdialog/eldialog.vue';
import Page from '@/components/Pagination/page.vue'
// 右侧表格
const tableData: any = ref()
const loading = ref(false)
const deviceName = ref()
const params = ref({
    size: 10,
    current: 1,
    stationId: '',
    areaId: '',
    bayId: '',
    componentId: '',
    mainDeviceId: '',
    deviceName: '',
    metertype: '',
    recognitionType: ''
})
const total = ref()
function getData() {
    loading.value = true
    params.value.deviceName = deviceName.value
    getAlarm(params.value).then((res: any) => {
        loading.value = false
        tableData.value = res.data.records
        total.value = res.data.total
        params.value.size = res.data.size
        params.value.current = res.data.current
        loading.value = false
        notification()
    })
}
//获取变电站树
const treeAll = ref([])
function notification() {
    getSubstation().then((res: any) => {
        treeAll.value = res.data
    })

}
//获取变电站
const stationAll: any = ref([])
const areaAll: any = ref([])
const bayAll: any = ref([])
function getStation() {
    const terrlist: any = ref([])
    const terrarealist: any = ref([])
    const terrbaylist: any = ref([])
    treeAll.value.forEach((element: any) => {
        terrlist.value.push(element)
        if (element.stationId == params.value.stationId) {
            element.children.forEach((res: any) => {
                terrarealist.value.push(res)
                if (res.areaId == params.value.areaId) {
                    if (res.children) {
                        res.children.forEach((row: any) => {
                            terrbaylist.value.push(row)
                        })
                    }
                }
            });
        }

    });
    stationAll.value = [...new Set(terrlist.value)];
    areaAll.value = [...new Set(terrarealist.value)];
    bayAll.value = [...new Set(terrbaylist.value)];
}
//获取间隔下主设备
const Masterdata: any = ref([])
function gatMain() {
    const paramsall = {
        bayId: params.value.bayId
    }
    getMainEquipment(paramsall).then((res: any) => {
        Masterdata.value = res.data
    });
}
//获取主设备下部件
const getacaType = ref()
function getCompont() {
    const paramsall = {
        mainDeviceId: params.value.mainDeviceId
    }
    getaccType(paramsall).then((res: any) => {
        getacaType.value = res.data
    })
}
//识别类型&&表计类型
const recognitionTypeList: any = ref([])
const meterType: any = ref([])
const EquipmentType: any = ref([])
function getType() {
    const paramsall = {
        dictcode: 'recognition_type'
    }
    getDeviceByType(paramsall).then((res: any) => {
        recognitionTypeList.value = res.data
    })
    const paramsid = {
        dictcode: 'meterType'
    }
    getDeviceByType(paramsid).then((res: any) => {
        meterType.value = res.data
    })
    getDeviceByType({ dictcode: 'EquipmentType' }).then((res: any) => {
        EquipmentType.value = res.data
    })
}
//重置
function resetting() {
    params.value = {
        size: 10,
        current: 1,
        stationId: '',
        areaId: '',
        bayId: '',
        componentId: '',
        mainDeviceId: '',
        deviceName: '',
        metertype: '',
        recognitionType: ''
    }
    deviceName.value = ''
    getData()
}
//表格多选
const deviceInfos: any = ref([])
function handleSelectionChange(val: any) {
    deviceInfos.value = val
}
//设置阈值
const dialogVisible = ref(false)
//表单数据
const info: any = ref({
    commonLower: '',
    commonUpper: '',
    seriousLower: '',
    seriousUpper: '',
    dangerLower: '',
    dangerUpper: '',
    alarmClass: '1',
    isLastContrast: '1',
    baseValue: '',
    isenable: '1',
    alarmType: '',
})
function isAllEqual(array: any) {
    let is = true
    for (let i = 0; i < array.length; i++) {
        if (array.every((item: any) => item.recognitionTypeList === array[i].recognitionTypeList) === false) {
            is = false
            break
        }

    }
    return is
}
const alarmTypeList: any = ref([])
function setClick() {
    if (deviceInfos.value.length == 1) {
        getAlgorithmModelById({ id: deviceInfos.value[0].deviceId }).then((res: any) => {
            if (res.data) {
                info.value = res.data
               
            } else {
                info.value = {
                    commonLower: '',
                    commonUpper: '',
                    seriousLower: '',
                    seriousUpper: '',
                    dangerLower: '',
                    dangerUpper: '',
                    alarmClass: '1',
                    isLastContrast: '1',
                    baseValue: '',
                    isenable: '1',
                    alarmType: '',
                    unit: deviceInfos.value[0].unit
                }
            }


        })

    } else {
        if (isAllEqual(deviceInfos.value) == false) {
            ElMessage({
                type: "warning",
                message: "请选择相同单位的点位进行设置阈值！",
            });
            return
        }
        info.value = {
            commonLower: '',
            commonUpper: '',
            seriousLower: '',
            seriousUpper: '',
            dangerLower: '',
            dangerUpper: '',
            unit: '',
            alarmClass: '1',
            isLastContrast: '1',
            baseValue: '',
            isenable: '1',
            alarmType: '',
        }
    }
    const paramsall = {
        dictcode: 'AlarmType'
    }
    getDeviceByType(paramsall).then((res: any) => {
        alarmTypeList.value = res.data
    })
    dialogVisible.value = true
}
//弹窗
function confirmClick() {

    if (((info.value.commonLower && info.value.commonUpper == '') || (info.value.commonUpper && info.value.commonLower == ''))) {
        ElMessage({
            type: "warning",
            message: "一般阈值下限和上限不能有一方为空！",
        });
        return
    }
    if (((info.value.seriousLower && info.value.seriousUpper == '') || (info.value.seriousUpper && info.value.seriousLower == ''))) {
        ElMessage({
            type: "warning",
            message: "严重阈值下限和上限不能有一方为空！",
        });
        return
    }
    if (((info.value.dangerLower && info.value.dangerUpper == '') || (info.value.dangerUpper && info.value.dangerLower == ''))) {
        ElMessage({
            type: "warning",
            message: "危急阈值下限和上限不能有一方为空！",
        });
        return
    }
    if (info.value.commonLower) {
        if (Number(info.value.commonLower) > Number(info.value.commonUpper)) {
            ElMessage({
                type: "warning",
                message: "一般阈值下限不能大于上限！",
            });
            return
        }
    }
    if (info.value.seriousLower) {
        if (Number(info.value.seriousLower) > Number(info.value.seriousUpper)) {
            ElMessage({
                type: "warning",
                message: "严重阈值下限不能大于上限！",
            });
            return
        }
    }
    if (info.value.dangerLower) {
        if (Number(info.value.dangerLower) > Number(info.value.dangerUpper)) {
            ElMessage({
                type: "warning",
                message: "危急阈值下限不能大于上限！",
            });
            return
        }
    }
    if (info.value.seriousLower && info.value.dangerLower) {
        if (isRangeNotInOtherRange([Number(info.value.seriousLower), Number(info.value.seriousUpper)], [Number(info.value.dangerLower), Number(info.value.dangerUpper)]) == false) {
            ElMessage({
                type: "warning",
                message: "阈值不能有交叉！",
            });
            return
        }
    }
    if (info.value.commonLower && info.value.dangerLower) {
        if (isRangeNotInOtherRange([Number(info.value.commonLower), Number(info.value.commonUpper)], [Number(info.value.dangerLower), Number(info.value.dangerUpper)]) == false) {
            ElMessage({
                type: "warning",
                message: "阈值不能有交叉！",
            });
            return
        }
    }
    if (info.value.commonLower && info.value.seriousLower) {
        if (isRangeNotInOtherRange([Number(info.value.commonLower), Number(info.value.commonUpper)], [Number(info.value.seriousLower), Number(info.value.seriousUpper)]) == false) {
            ElMessage({
                type: "warning",
                message: "阈值不能有交叉！",
            });
            return
        }
    }

    const infoAll: any = ref({})
    const infoAllList: any = ref([])
    infoAll.value = JSON.parse(JSON.stringify(info.value))
    if (infoAll.value.commonLower) infoAll.value.commonLower = Number(infoAll.value.commonLower).toFixed(2);
    if (infoAll.value.commonUpper) infoAll.value.commonUpper = Number(infoAll.value.commonUpper).toFixed(2);
    if (infoAll.value.seriousLower) infoAll.value.seriousLower = Number(infoAll.value.seriousLower).toFixed(2);
    if (infoAll.value.seriousUpper) infoAll.value.seriousUpper = Number(infoAll.value.seriousUpper).toFixed(2);
    if (infoAll.value.dangerLower) infoAll.value.dangerLower = Number(infoAll.value.dangerLower).toFixed(2);
    if (infoAll.value.dangerUpper) infoAll.value.dangerUpper = Number(infoAll.value.dangerUpper).toFixed(2);
   
    deviceInfos.value.forEach((element: any) => {
        const infoAllOne:any = ref({})
        infoAllOne.value = JSON.parse(JSON.stringify(infoAll.value))
        infoAllOne.value['stationName'] = element.stationName
        infoAllOne.value['deviceName'] = element.deviceName
        infoAllOne.value['stationCode'] = element.stationCode
        infoAllOne.value.deviceId = element.deviceId
        infoAllOne.value.alarmThresholdId = element.stationId + element.deviceId + JSON.parse(element.pictureAnalysisTypeList).PictureDefectAnalysisType + infoAll.value.alarmType
        if (JSON.parse(element.pictureAnalysisTypeList).PictureDefectAnalysisType) {
            infoAllOne.value['defectType'] = JSON.parse(element.pictureAnalysisTypeList).PictureDefectAnalysisType
        }
       
        infoAllList.value.push(infoAllOne.value)

    });
    const infoList: any = ref([])
    const newinfo: any = ref({
        deviceId: '',
        deviceName: '',
        defectType: '',
        stationCode: '',
        stationName: '',
        decideRule: '',
        decisionValueClass: '',
        alarmDesc: '',
        alarmType: '',
        baseValue: '',
        alarmLevel: '',
        alarmClass: '',
        isenable: '',
    })
  
    infoAllList.value.forEach((element: any) => {
        newinfo.value.alarmClass = element.alarmClass
        newinfo.value.isenable = element.isenable
        newinfo.value.defectType = element.defectType
        newinfo.value.stationCode = element.stationCode
        newinfo.value.stationName = element.stationName
        newinfo.value.alarmType = element.alarmType
        newinfo.value.isLastContrast = element.isLastContrast
        newinfo.value.baseValue = element.baseValue
        if (element.alarmClass == 2) {
            const inallList = JSON.parse(JSON.stringify(newinfo.value))
            inallList.deviceId = element.deviceId
            inallList.deviceName = element.deviceName
            infoList.value.push(inallList)
        } else {
            if (element.commonLower) {
                const inallList = JSON.parse(JSON.stringify(newinfo.value))
                inallList.deviceId = element.deviceId
                inallList.deviceName = element.deviceName
                inallList.decideRule = '6'//判定规则
                inallList.decisionValueClass = '1'
                inallList.alarmDesc = ''//告警描述
                inallList.baseLineValue = element.commonLower
                inallList.alarmLevel = '1'
                infoList.value.push(inallList)
            }
            if (element.commonUpper) {
                const inallList = JSON.parse(JSON.stringify(newinfo.value))
                inallList.deviceId = element.deviceId
                inallList.deviceName = element.deviceName
                inallList.decideRule = '7'//判定规则
                inallList.decisionValueClass = '1'
                inallList.alarmDesc = ''//告警描述
                inallList.baseLineValue = element.commonUpper
                inallList.alarmLevel = '1'
                infoList.value.push(inallList)
            }

            if (element.seriousLower) {
                const inallList = JSON.parse(JSON.stringify(newinfo.value))
                inallList.deviceId = element.deviceId
                inallList.deviceName = element.deviceName
                inallList.decideRule = '6'//判定规则
                inallList.decisionValueClass = '1'
                inallList.alarmDesc = ''//告警描述
                inallList.baseLineValue = element.seriousLower
                inallList.alarmLevel = '2'
                infoList.value.push(inallList)
            }
            if (element.seriousUpper) {
                const inallList = JSON.parse(JSON.stringify(newinfo.value))
                inallList.deviceId = element.deviceId
                inallList.deviceName = element.deviceName
                inallList.decideRule = '7'//判定规则
                inallList.decisionValueClass = '1'
                inallList.alarmDesc = ''//告警描述
                inallList.baseLineValue = element.seriousUpper
                inallList.alarmLevel = '2'
                infoList.value.push(inallList)
            }

            if (element.dangerLower) {
                const inallList = JSON.parse(JSON.stringify(newinfo.value))
                inallList.deviceId = element.deviceId
                inallList.deviceName = element.deviceName
                inallList.decideRule = '6'//判定规则
                inallList.decisionValueClass = '1'
                inallList.alarmDesc = ''//告警描述
                inallList.baseLineValue = element.dangerLower
                inallList.alarmLevel = '3'
                infoList.value.push(inallList)
            }
            if (element.dangerUpper) {
                const inallList = JSON.parse(JSON.stringify(newinfo.value))
                inallList.deviceId = element.deviceId
                inallList.deviceName = element.deviceName
                inallList.decideRule = '7'//判定规则
                inallList.decisionValueClass = '1'
                inallList.alarmDesc = ''//告警描述
                inallList.baseLineValue = element.dangerUpper
                inallList.alarmLevel = '3'
                infoList.value.push(inallList)
            }

        }

    })
    setAlgorithmModel(JSON.stringify(infoList.value)).then((res: any) => {
        if (res.code != 1) {
            ElMessage({
                type: "success",
                message: "修改成功",
            });
            dialogVisible.value = false
            getData()
        }
    })

}
// 判断1-2不在3-9内
function isRangeNotInOtherRange([start1, end1]: any, [start2, end2]: any) {
    // 解析两个范围  
    // 检查范围1是否完全在范围2之外  
    // 即，范围1的结束数字小于范围2的开始数字，或者范围1的开始数字大于范围2的结束数字  
    return end1 <= start2 || start1 >= end2;
}
// 判断1-2不在3-9和9-12内
//关闭弹窗
function handleClose() {
    dialogVisible.value = false
}



//获取用户列表信息
onMounted(() => {
    getData()
    getType()
});

//表格多选样式
const tableRowClassName = ({
    row,
    rowIndex,
}: {
    row: any
    rowIndex: number
}) => {
    if (rowIndex % 2 === 0) {
        return 'warning-row'
    } else if (rowIndex % 2 === 1) {
        return 'success-row'
    }
    return ''
}

function currency(list: any, itemcode: any) {
    let dictname = ''
    list.forEach((element: any) => {
        if (element.itemcode == itemcode) {
            dictname = element.dictname
        }
    })
    return dictname
}
function radiochange(row: any) {
    if(row == 1){
        info.value.baseValue = ''
    }
}
</script>

<template>
    <div class="faulttemplate-box">
        <section class="silderRight">
            <div
                style="display: flex;display: -webkit-flex; justify-content: space-between; -webkit-justify-content: space-between;  margin:15px 0px">
                <div style="display: flex;display: -webkit-flex; align-items: center;width:90%">

                    <el-input v-model="deviceName" clearable placeholder="请输入巡视点位名称" @clear="getData()"
                        @keyup.enter="getData()" style="margin-right:5px ;width: 335px;" />
                    <el-select clearable v-model="params.stationId" placeholder="所属变电站"
                        style="margin-right:5px ;width: 25%;" @visible-change="getStation" @change="getData()">
                        <el-option v-for="item in stationAll" :key="item.stationId" :label="item.stationName"
                            :value="item.stationId" />
                    </el-select>
                    <el-select :disabled="params.stationId == ''" clearable v-model="params.areaId" placeholder="所属区域"
                        style="margin-right:5px ;width: 25%;" @visible-change="getStation" @change="getData()">
                        <el-option v-for="item in areaAll" :key="item.areaId" :label="item.areaName"
                            :value="item.areaId" />
                    </el-select>
                    <el-select :disabled="params.areaId == ''" clearable v-model="params.bayId" placeholder="所属间隔"
                        style="margin-right:5px ;width: 25%;" @visible-change="getStation" @change="getData()">
                        <el-option v-for="item in bayAll" :key="item.bayId" :label="item.bayName" :value="item.bayId" />
                    </el-select>
                    <el-select :disabled="params.bayId == ''" clearable v-model="params.mainDeviceId"
                        placeholder="所属主设备" style="margin-right:5px ;width: 25%;" @visible-change="gatMain"
                        @change="getData()">
                        <el-option v-for="item in Masterdata" :key="item.mainDeviceId" :label="item.mainDeviceName"
                            :value="item.mainDeviceId" />
                    </el-select>
                    <el-select :disabled="params.mainDeviceId == ''" clearable v-model="params.componentId"
                        placeholder="所属部件" style="margin-right:5px ;width: 25%;" @visible-change="getCompont"
                        @change="getData()">
                        <el-option v-for="item in getacaType" :key="item.componentId" :label="item.componentName"
                            :value="item.componentId" />
                    </el-select>
                    <el-select clearable v-model="params.recognitionType" placeholder="识别类型"
                        style="margin-right:5px ;width: 25%;" @visible-change="getType" @change="getData()">
                        <el-option v-for="item in recognitionTypeList" :key="item.itemcode" :label="item.dictname"
                            :value="item.dictname" />
                    </el-select>
                    <el-select clearable v-model="params.metertype" placeholder="表计类型"
                        style="margin-right:10px ;width: 25%;" @visible-change="getType" @change="getData()">
                        <el-option v-for="item in meterType" :key="item.itemcode" :label="item.dictname"
                            :value="item.itemcode" />
                    </el-select>
                    <el-button type="primary" @click="getData()">搜索</el-button>
                    <el-button @click="resetting()">重置</el-button>
                </div>
                <div>
                    <el-button @click="setClick" :disabled="deviceInfos.length == 0"  v-hasPerm="['update:alarminterval']"
                        :type="deviceInfos.length > 0 ? 'primary' : ''">
                        <img v-show="deviceInfos.length != 0" src="@/assets/MenuIcon/yvzhi1.png"
                            style="margin-right:5px;" alt="">
                        <img v-show="deviceInfos.length == 0" src="@/assets/MenuIcon/yvzhi2.png"
                            style="margin-right:5px;" alt="">
                        设置阈值</el-button>
                </div>
            </div>
            <div class="draggable">
               
                 
                   
                    
                <el-table v-loading="loading" :data="tableData" style="width: 100%;height: calc(100vh - 255px);
                overflow: auto;margin-bottom: 15px;" row-key="deviceId" border
                    @selection-change="handleSelectionChange" default-expand-all :row-class-name="tableRowClassName"
                    :header-cell-style="{ background: '#002b6a', color: '#B5D7FF', height: '50px'}">
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column type="index" label="序号" width="80px" align="center" />
                    <el-table-column label="巡视点位名称" prop="deviceName" width="140"
                        show-overflow-tooltip></el-table-column>
                    <el-table-column label="所属变电站" prop="stationName" width="140"
                        show-overflow-tooltip></el-table-column>
                    <el-table-column label="所属区域" prop="areaName" width="100" show-overflow-tooltip></el-table-column>
                    <el-table-column label="所属间隔" prop="bayName" width="110" show-overflow-tooltip></el-table-column>
                    <el-table-column label="所属主机设备" prop="mainDeviceName" width="140"
                        show-overflow-tooltip></el-table-column>
                    <el-table-column label="主设备类型" prop="deviceType" width="120" show-overflow-tooltip>
                        <template #default="scope">
                            <span>{{ currency(EquipmentType, scope.row.deviceType) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="所属部件" prop="componentName" show-overflow-tooltip></el-table-column>
                    <el-table-column label="表计类型" prop="meterType" show-overflow-tooltip>
                        <template #default="scope">
                            <span>{{ currency(meterType, scope.row.meterType) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="识别类型" prop="recognitionTypeNameList"
                        show-overflow-tooltip></el-table-column>

                    <el-table-column label="单位" prop="unit" show-overflow-tooltip></el-table-column>
                </el-table>
                <Page :total="total" v-model:size="params.size" v-model:current="params.current"
                    @pagination="getData()">
                </Page>
            </div>
        </section>
        <Eldialog v-if="dialogVisible" :title="'设置阈值'" class="AngleBox" :zIndex="2000" :width="'800px'" 
            @before-close="handleClose">
            <template v-slot:PopFrameContent>
                <div style="height:400px;" v-if="info">
                <div>
                    <span>规则类型：</span>
                    <el-radio-group v-model="info.alarmClass">
                        <el-radio :value="'1'" :label="'1'">阈值类</el-radio>
                        <el-radio :value="'2'" :label="'2'">状态类</el-radio>
                        <el-radio :value="'3'" :label="'3'">趋势类</el-radio>
                    </el-radio-group>
                </div>

                <div style="margin-top: 10px;">
                    <span>告警类型：</span>
                    <el-select clearable v-model="info.alarmType" placeholder="请选择"
                        style="margin-right:5px ;width:335px;">
                        <el-option v-for="item in alarmTypeList" :key="item.itemcode" :label="item.dictname"
                            :value="item.itemcode" />
                    </el-select>
                </div>
                <div v-if="info.alarmClass == 2 || info.alarmClass == 3">
                    <span>上次点位比较：</span>
                    <el-radio-group v-model="info.isLastContrast" @change="radiochange">
                        <el-radio value="1" :label="'1'" size="large">是</el-radio>
                        <el-radio value="0" :label="'0'" size="large">否</el-radio>
                    </el-radio-group>
                </div>
                <div style="margin-top: 10px;" v-if="info.alarmClass == 2 || info.alarmClass == 3">
                    <span v-if="info.alarmClass == 3">基准值A0：</span>
                    <span v-if="info.alarmClass == 2">基准值：</span>
                    <el-input v-model="info.baseValue" clearable placeholder="请输入基准值A0"
                        :disabled="info.isLastContrast == '1'" style="margin-right:5px ;width: 335px;" />
                    <span style="color: red;" v-if="info.alarmClass == 3">偏差率 = (A1-A0)/A0*100%</span>
                </div>

                <div v-if="info.alarmClass == 1 || info.alarmClass == 3" style="margin-top: 10px;">
                    <span>阈值范围：</span>
                    <div class="inputDiv">
                        <span>一般区间</span>
                        <el-input class="input" v-model="info.commonLower" placeholder="一般区间最小值" />
                        <span>~</span> <el-input class="input" v-model="info.commonUpper" placeholder="一般区间最大值" />
                        <span>{{ info.unit }}</span>
                    </div>
                    <div class="inputDiv">
                        <span>严重区间</span>
                        <el-input class="input" v-model="info.seriousLower" placeholder="严重区间最小值" />
                        <span>~</span>
                        <el-input class="input" v-model="info.seriousUpper" placeholder="严重区间最大值" />
                        <span>{{ info.unit }}</span>
                    </div>

                    <div class="inputDiv">
                        <span>危急区间</span>
                        <el-input class="input" v-model="info.dangerLower" placeholder="危急区间最小值" />
                        <span>~</span>
                        <el-input class="input" v-model="info.dangerUpper" placeholder="危急区间最大值" />
                        <span>{{ info.unit }}</span>
                    </div>
                </div>
                <div>
                    <span>是否启用：</span>
                    <el-radio-group v-model="info.isenable">
                        <el-radio value="1" :label="'1'" size="large">启用</el-radio>
                        <el-radio value="0" :label="'0'" size="large">禁用</el-radio>
                    </el-radio-group>
                </div>
            </div>


            <span class="dialog-footer"
                style="width: 100%;margin: auto; display: flex;display: -webkit-flex; justify-content: flex-end;-webkit-justify-content: flex-end;margin-top: 20px;">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="confirmClick">保存</el-button>
            </span>
            </template>
        </Eldialog>
       
    </div>
</template>

<style scoped lang="scss">
.silderRight {
    width: 100%;
    height: calc(100vh - 135px);
    overflow: auto;
    background-color: rgba(255, 255, 255, 1);
    border-radius: 3px;
    padding: 0px 15px 15px 15px;
    padding-bottom: 0px;
    box-sizing: border-box;
}

.inputDiv {
    text-align: center;
    margin-left: 40px;

    .input {
        width: 35%;
        margin: 10px;
    }
}
</style>
