<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import Page from '@/components/Pagination/page.vue'
import { ElMessageBox, ElMessage, ElTable, FormRules, ElTree } from 'element-plus'
import { getDeviceTree, queryDeviceSignal, addDeviceSignal, updateDeviceSignal, deleteDeviceSignalById, deleteDeviceByIds, getMeterDeviceByCode } from '@/api/equipmentsignal';
import { publicTree } from '@/utils/validate';
import { useUserStore } from '@/store/modules/user';
import Eldialog from '@/components/seccmsdialog/eldialog.vue'
import { getDeviceByType } from '@/api/device'
import Alarmset from '@/views/ledgermanagement/equipmentsignal/alarmset.vue'
const userStore = useUserStore();
const typeoptions: any = ref([])
//树形控件类型定义
interface Tree {
    [x: string]: any;
    label: string;
    children?: Tree[];
}
const rules = reactive<FormRules>({
    signalName: [{ required: true, message: "请输入信号名称", trigger: "blur" }],
    signalCode: [{ required: true, message: "请输入信号编号", trigger: "blur" }],
    systemcode: [{ required: true, message: "选择所属系统", trigger: "blur" }],
    meterDeviceId: [{ required: true, message: "选择辅控设备", trigger: "blur" }],
});
const signalform: any = ref({})
const ruleFormRef: any = ref(null);
const signalrangestart = ref('')
const signalrangeend = ref('')
const queryInfo: any = ref({
    current: 1,
    size: 15,
    total: 0
})
const multipleSelection = ref([])
const loading = ref(false)
const tableData: any = ref([])
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val
}
const dialogVisible = ref(false)
const dialogtitle = ref('新增信号设备')
const currentNodeid = ref("")
const defaultProps = { label: "name" };
const signalName = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData: any = ref([])
const treeloading = ref(false)
const handleNodeClick = (data: any, node: any) => {
    // 有子元素的节点，不能选中
    if (data.children.length > 0) {
        nextTick(() => {
            treeRef.value?.setCurrentKey(currentNodeid.value);
        });
    } else {
        queryInfo.value.current = 1
        queryInfo.value.size = 15
        signalName.value = ''
        currentNodeid.value = data.id
        getData();
    }
};
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;
            };
        };
    }
}

const dialogVisibles = ref(false)
const dialogtitles = ref('新增信号设备')
const alarmquerylist: any = ref({})
const temDeviceData: any = ref([]) // 系统设备列表
onMounted(() => {
    getDeviceByType({ dictcode: 'ykytType' }).then((ress: any) => {
        typeoptions.value = ress.data
    })
    gettype()
    getmeterDeviceId()
    init()
})
const CameraName = ref('')
function init() {
    treeloading.value = true
    getDeviceTree({ componentName: CameraName.value, stationCode: userStore.stationCode }).then((res: any) => {
        treeData.value = publicTree(res.data, '')
        treeloading.value = false
        currentNodeid.value = res.data[0].children[0].children[0].children[0].id
        queryInfo.value.current = 1
        queryInfo.value.size = 15
        signalName.value = ''
        getData();
        nextTick(() => {
            treeRef.value?.setCurrentKey(currentNodeid.value);
        });
    })
}
function isykyttype(val: any) {
    let name: any = ''
    for (let i = 0; i < typeoptions.value.length; i++) {
        if (typeoptions.value[i].itemcode === val) {
            name = typeoptions.value[i].dictname
            break
        }
    }
    return name
}
const systemcode = ref('')
const meterDeviceId = ref('')
function getData() {
    loading.value = true
    const params = {
        current: queryInfo.value.current,
        size: queryInfo.value.size,
        signalName: signalName.value,
        mainComponentId: currentNodeid.value,
        systemcode: systemcode.value,
        meterDeviceId:meterDeviceId.value
    }
    queryDeviceSignal(params).then((res: any) => {
        tableData.value = res.data.records
        queryInfo.value.total = res.data.total
        loading.value = false
    })
}
function editclick(row: any) {
    signalform.value = JSON.parse(JSON.stringify(row))
    getmeterDeviceId()
    if (signalform.value.normalRange !== '' && signalform.value.normalRange !== undefined && signalform.value.normalRange !== null) {
        signalrangestart.value = signalform.value.normalRange.match(/(\S*)~/)[1]
        signalrangeend.value = signalform.value.normalRange.match(/~(\S*)/)[1]
    }
    dialogtitle.value = '修改信号设备'
    isSwitch.value = false
    dialogVisible.value = true
}
function delclick(row: any) {
    ElMessageBox.confirm("确定删除此信号信息吗?", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        let params = {
            id: row.signalId
        };
        deleteDeviceSignalById(params).then((res: any) => {
            ElMessage({
                message: "删除成功",
                type: "success",
            });
            getData()
        })
    }).catch(() => { })
}
function delclicks() {
    ElMessageBox.confirm("确定删除选择信号信息吗?", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        let id = [] as any[];
        multipleSelection.value.forEach((item: any) => {
            id.push(item.signalId)
        })
        let params = {
            ids: id.join(','),
        };
        deleteDeviceByIds(params).then(() => {
            getData();
            ElMessage({
                message: "删除成功",
                type: "success",
            });
        });
    }).catch(() => { })
}
const belonging: any = ref([])
function gettype() {
    const params = {
        dictcode: 'system'
    }
    getDeviceByType(params).then((res: any) => {
        if (res.data.length !== 0 && res.data !== null) {
            belonging.value = res.data
        }
    })
}
const eterDevice: any = ref([])
function getmeterDeviceId() {
    getMeterDeviceByCode({ stationId: userStore.stationId, systemCode: signalform.value.systemcode }).then((res: any) => {
        eterDevice.value = res.data
    })
}
function getmeterDeviceId1(){
    if(!systemcode.value){
        meterDeviceId.value = ''
    }
    getmeterDeviceId()
    getData()
}

function addclick() {
    if (ruleFormRef.value != null) ruleFormRef.value.resetFields();
    isSwitch.value = false
    signalform.value = {}
    signalform.value.signalType = 0
    dialogtitle.value = '新增信号设备'
    signalrangeend.value = ''
    signalrangestart.value = ''
    dialogVisible.value = true
}
const isSwitch = ref(false)
function formsubmit(formEl: any) {
    formEl.validate((valid: any) => {
        if (valid) {
            if (signalrangestart.value !== '') {
                if (signalrangeend.value === '') {
                    ElMessage({
                        message: "请填写完整范围！",
                        type: "warning",
                    });
                    return
                }
            }
            if (signalrangeend.value !== '') {
                if (signalrangestart.value === '') {
                    ElMessage({
                        message: "请填写完整范围！",
                        type: "warning",
                    });
                    return
                }
            }
            if (signalrangestart.value !== '' && signalrangeend.value !== '') {
                if (signalform.value.signalUnit === '') {
                    ElMessage({
                        message: "请填写信号单位！",
                        type: "warning",
                    });
                    return
                }
            }
            if (isSwitch.value == true) {
                return
            }
            isSwitch.value = true
            loading.value = true
            signalform.value.mainComponentId = currentNodeid.value
            if (signalform.value.signalId) {
                if (signalrangestart.value !== '' && signalrangeend.value !== '' && signalform.value.signalUnit !== '') {
                    signalform.value.normalRange = signalrangestart.value + '~' + signalrangeend.value
                }
                updateDeviceSignal(signalform.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 {
                if (signalrangestart.value !== '' && signalrangeend.value !== '' && signalform.value.signalUnit !== '') {
                    signalform.value.normalRange = signalrangestart.value + '~' + signalrangeend.value
                }
                addDeviceSignal(signalform.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 handleClose() {
    dialogVisible.value = false
}
function setclick(row: any) {
    alarmquerylist.value = {
        signalId: row.signalId,
        deviceId: row.meterDeviceId,
        signalName: row.signalName
    }
    dialogtitles.value = row.signalName + '信号告警设置'
    dialogVisibles.value = true
}
function handleCloses() {
    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 ''
}
function currency(list: any, itemcode: any) {
    let dictname = ''
    list.forEach((element: any) => {
        if (element.itemcode == itemcode) {
            dictname = element.dictname
        }
    })
    return dictname
}
function currency1(list: any, itemcode: any) {
    let dictname = ''
    list.forEach((element: any) => {
        if (element. deviceId== itemcode) {
            dictname = element.deviceName
        }
    })
    return dictname
}
</script>
<template>
    <div class="faulttemplate-box">
        <aside id="silderLeft">
            <el-input v-model="CameraName" clearable placeholder="请输入部件名称" @clear="getData()" @keyup.enter="getData()"
                style="width:100%;margin-top: 10px;" class="videomonitor-input">
                <template #suffix>
                    <img src="@/assets/videoimg/u2937.png" style="cursor:pointer ;" @click="getData">
                </template>
            </el-input>
            <el-scrollbar height="calc(83vh)">
                <el-tree v-loading="treeloading" ref="treeRef" node-key="id" :data="treeData" :highlight-current="true"
                    :props="defaultProps" :expand-on-click-node="false" default-expand-all @node-click="handleNodeClick"
                    style="margin-top: 10px;">
                </el-tree>
            </el-scrollbar>

            <div class="moveBtn" v-move>
                <div class="moveBtn-line"></div>
            </div>
        </aside>
        <section class="silderRight">
            <el-row>
                <el-col :span="24">
                    <div
                        style="margin-bottom:10px;display: flex;display: -webkit-flex; justify-content: space-between;-webkit-justify-content: space-between; width: 100%;">
                        <div style="display: flex;align-items: center;">
                            <el-input v-model="signalName" placeholder="请输入信号名称" @change="getData" style="width: 220px;margin-right: 10px;" clearable />
                            <el-select v-model="systemcode" placeholder="请选择所属系统" clearable 
                                style="width: 220px;margin-right: 10px;" @change="getmeterDeviceId1">
                                <el-option v-for="item in belonging" :key="item.itemcode" :label="item.dictname"
                                    :value="item.itemcode" />
                            </el-select>
                            <el-select v-model="meterDeviceId" placeholder="请选择辅控设备" clearable  @change="getData"
                                style="width: 220px;" :disabled="!systemcode">
                                <el-option v-for="item in eterDevice" :key="item.deviceId" :label="item.deviceName"
                                    :value="item.deviceId" />
                            </el-select>
                            <el-button class="searchButton" type="primary" style="margin-left: 10px;"
                                @click="getData">搜索</el-button>
                        </div>
                        <div>
                            <el-button class="searchButton" type="primary" style="margin-left: 10px;"
                                :disabled="currentNodeid !== '' ? false : true" @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>
                </el-col>
            </el-row>
            <el-table ref="multipleTableRef" :data="tableData" style="width: 100%;margin-bottom: 20px;height: calc(78vh);
                      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="序号" align="center" type="index" width="50" />
                <el-table-column label="信号编号" align="center" prop="signalCode" width="100" />
                <el-table-column label="信号名称" align="left" prop="signalName" width="140" />
                <el-table-column label="信号单位" align="center" prop="signalUnit" width="80" />
                <el-table-column label="遥控遥调类型" align="center" prop="ykytType" width="150">
                    <template #default="scope">
                        <span>{{ isykyttype(scope.row.ykytType) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="是否告警信号" align="center" prop="signalType" width="100">
                    <template #default="scope">
                        <span v-if="scope.row.signalType === '1'">是</span>
                        <span v-else>否</span>
                    </template>
                </el-table-column>
                <el-table-column label="所属系统" align="center" prop="systemcode" width="80">
                    <template #default="scope">
                        <span>{{ currency(belonging,scope.row.systemcode) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="辅控设备" align="center" prop="meterDeviceId" width="80">
                    <template #default="scope">
                        <span>{{ currency1(eterDevice,scope.row.meterDeviceId) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="遥信地址(yx)" align="left" prop="yxAddr" />
                <el-table-column label="遥测地址(yc)" align="left" prop="ycAddr" />
                <el-table-column label="遥控地址(yk)" align="left" prop="ykAddr" />
                <el-table-column label="遥调地址(yt)" align="left" prop="ytAddr" />
                <!-- <el-table-column label="数据地址" prop="reportAddr" /> -->
                <el-table-column fixed="right" label="操作" width="100">
                    <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" v-hasPerm="['update:devicesignal']" title="修改"
                                style="cursor: pointer;" @click="editclick(scope.row)">
                            <img src="@/assets/newimg/gjsz.png" title="告警设置" style="cursor: pointer;"
                                @click="setclick(scope.row)">
                            <img src="@/assets/newimg/ht_sc.png" v-hasPerm="['del:devicesignal']" title="删除"
                                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" />
        </section>
        <Eldialog v-if="dialogVisible" :title="dialogtitle" :zIndex="2000" :width="'40%'" @before-close="handleClose">
            <template v-slot:PopFrameContent>
                <el-form ref="ruleFormRef" :model="signalform" label-width="100px" :rules="rules"
                    style="margin-top: 15px;">
                    <el-form-item label="信号编号" prop="signalCode">
                        <el-input v-model="signalform.signalCode" maxlength="40" show-word-limit placeholder="请输入信号编号"
                            clearable />
                    </el-form-item>
                    <el-form-item label="信号名称" prop="signalName">
                        <el-input v-model="signalform.signalName" maxlength="100" show-word-limit placeholder="请输入信号名称"
                            clearable />
                    </el-form-item>
                    <el-form-item label="所属系统" prop="systemcode">
                        <el-select v-model="signalform.systemcode" placeholder="请选择所属系统" clearable style="width: 100%;"
                            @change="getmeterDeviceId">
                            <el-option v-for="item in belonging" :key="item.itemcode" :label="item.dictname"
                                :value="item.itemcode" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="辅控设备" prop="meterDeviceId">
                        <el-select v-model="signalform.meterDeviceId" placeholder="请选择辅控设备" clearable
                            style="width: 100%;" :disabled="!signalform.systemcode">
                            <el-option v-for="item in eterDevice" :key="item.deviceId" :label="item.deviceName"
                                :value="item.deviceId" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="信号单位">
                        <el-input v-model="signalform.signalUnit" maxlength="40" show-word-limit placeholder="请输入信号单位"
                            clearable />
                    </el-form-item>
                    <div style="display: flex;justify-content: space-between;">
                        <div style="width: calc(100% - 100px);">
                            <el-form-item label="遥控遥调类型">
                                <el-select v-model="signalform.ykytType" placeholder="请选择遥控遥调类型" clearable
                                    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="padding-left: 10px;">
                            <el-checkbox v-model="signalform.signalType" true-label="1"
                                false-label="0">是否告警信号</el-checkbox>
                        </div>
                    </div>
                    <div style="display: flex;justify-content: space-between;">
                        <div style="width: 57%;">
                            <el-form-item label="正常范围">
                                <el-input v-model="signalrangestart" maxlength="50" show-word-limit placeholder="请输入范围"
                                    clearable />
                            </el-form-item>
                        </div>
                        <div style="margin: 6px 10px 0px;">~</div>
                        <div style="width: 43%;">
                            <el-input v-model="signalrangeend" maxlength="50" show-word-limit placeholder="请输入范围"
                                clearable />
                        </div>
                    </div>
                    <el-form-item label="遥信地址">
                        <el-input v-model="signalform.yxAddr" placeholder="请输入遥信地址" maxlength="600" show-word-limit
                            clearable />
                    </el-form-item>
                    <el-form-item label="遥测地址">
                        <el-input v-model="signalform.ycAddr" placeholder="请输入遥测地址" maxlength="600" show-word-limit
                            clearable />
                    </el-form-item>
                    <el-form-item label="遥控地址">
                        <el-input v-model="signalform.ykAddr" placeholder="请输入遥控地址" maxlength="600" show-word-limit
                            clearable />
                    </el-form-item>
                    <el-form-item label="遥调地址">
                        <el-input v-model="signalform.ytAddr" placeholder="请输入遥调地址" maxlength="600" show-word-limit
                            clearable />
                    </el-form-item>
                    <!-- <el-form-item label="数据地址">
          <el-input v-model="signalform.reportAddr" maxlength="600" show-word-limit placeholder="请输入数据地址" clearable />
        </el-form-item> -->
                </el-form>
                <span class="dialog-footer" style="display: flex;justify-content: flex-end;">
                    <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="dialogtitles" :zIndex="2000" :width="'65%'"
            @before-close="handleCloses">
            <template v-slot:PopFrameContent>
                <Alarmset v-if="dialogVisibles" :alarmquerylist="alarmquerylist" />
            </template>
        </Eldialog>
    </div>
</template>

<style scoped lang="scss">
.looknum {
    cursor: pointer;
}

.silderLeft-default {
    :deep(.el-tree-node__label) {
        font-size: 16px !important;
    }
}

.faulttemplate-box {
    height: 100%;
    display: flex;
    display: -webkit-flex;
    background-color: #f2f4f900;
    padding: 15px 15px 0px 15px;

}

#silderLeft {
    width: 300px;
    padding: 5px 10px 10px;
    box-sizing: border-box;
    border-radius: 3px;
    position: relative;
    background: url(@/assets/navigation/ty_260x988.png);
    background-size: 100% 100%;

    &: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;
    background-color: #60bfff;
}

.silderRight {
    flex: 1;
    width: 100%;
    height: calc(100vh - 160px);
    overflow: auto;
    background-color: rgba(255, 255, 255, 0);
    border-radius: 3px;
    padding: 15px;
    padding-bottom: 0px;
    box-sizing: border-box;
    margin-left: 15px;
    background: url(@/assets/newimg/cjrw_1890.png);
    background-size: 100% 100%;
}

.avatar {
    width: 86px;
    height: 86px;
    display: block;
}

:deep(.el-tree-node.is-current>.el-tree-node__content) {
    width: 100%;
    height: 40px;
    // color: #fff !important;
}

:deep(.el-tree) {
    background-color: #ffffff00 !important;
    --el-tree-node-hover-bg-color: #0099ff09;
}



:deep(.el-tree-node__content) {
    width: 100% !important;
    height: 40px !important;
    margin: auto !important;
}

.el-message-box {
    width: 300px !important;
}

:deep(.el-table:not(.el-table--border) .el-table__cell) {
    border: none;
    color: #fff;
}

:deep(.el-tree) {
    background-color: #ffffff00 !important;
    --el-tree-node-hover-bg-color: #0099ff09;
}

:deep(.el-input) {
    --el-input-bg-color: #ffffff00 !important;
}

:deep(.el-input-group__append) {
    background: #ffffff00 !important;
}

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

</style>