<template>
    <div class="linkMonitor">
        <el-container class="containerPart">
            <el-aside class="asidePart">
                <el-header class="asideHeader">
                    <el-input
                        v-model="searchLinkTreeInputValue"
                        :suffix-icon="Search"
                        clearable
                        @input="debounceSearchLinkTree"
                        placeholder="搜索"
                        class="searchLinkTreeInput"
                    ></el-input>
                </el-header>
                <el-main class="treeMain">
                    <el-tree
                        ref="linkTreeRef"
                        node-key="id"
                        :data="treeData"
                        @node-click="linkTreeNodeClick"
                        @node-expand="linkTreeNodeExpand"
                        @node-collapse="linkTreeNodeCollapse"
                        :props="LinkTreePropReplace"
                        class="treePart"
                        highlight-current
                        :render-content="renderContent"
                        :default-expanded-keys="linkTreeNodeExpandKeys"
                    >
                        <!-- <template #default="{ node, data }">
                            <span>{{ node.label }}</span>
                        </template> -->
                    </el-tree>
                </el-main>
            </el-aside>
            <el-container class="mainContainer">
                <el-header class="mainHeader">
                    <div class="mainHeaderCenter">
                        <el-input clearable placeholder="请输入链路名称" class="linkMonitorInput" v-model="linkMonitorInputValue"></el-input>
                        <el-button :icon="Search" type="primary" @click="searchLinkMonitor">查询</el-button>
                    </div>
                </el-header>
                <el-main class="mainMain">
                    <div class="tabsPart">
                        <el-table :data="linkMonitorTableData" class="tablePart" highlight-current-row>
                            <el-table-column prop="linkName" :label="LinkMonitorFieldsEnums['linkName']" align="left"> </el-table-column>
                            <el-table-column prop="status" :label="LinkMonitorFieldsEnums['status']" align="center" width="80">
                                <template #default="scope">
                                    <div class="status-container">
                                        <span
                                            :class="{
                                                'status-dot-online': !scope.row.status,
                                                'status-dot-offline': scope.row.status,
                                            }"
                                        ></span>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="protocolName" :label="LinkMonitorFieldsEnums['protocolName']" align="center">
                                <template #default="scope"> </template>
                            </el-table-column>
                            <!-- <el-table-column prop="remoteRegulation" :label="LinkMonitorFieldsEnums['remoteRegulation']" align="center">
                                <template #default="scope">
                                    <span style="cursor: pointer; color: #0064aa; font-weight: 600">查看参数</span>
                                </template>
                            </el-table-column> -->
                            <el-table-column label="操作" width="200" align="center">
                                <template #default="scope">
                                    <div class="tableOperate">
                                        <a @click="opneLog(scope.row)">日志</a>
                                        <a>|</a>
                                        <a @click="startLink(scope.row)">启动</a>
                                        <a>|</a>
                                        <el-popconfirm title="确定停止么？" @confirm="stopLink(scope.row)">
                                            <template #reference>
                                                <a style="color: red">停止</a>
                                            </template>
                                        </el-popconfirm>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="mainFooter">
                        <el-pagination
                            v-model:current-page="paginationOptions.current"
                            v-model:page-size="paginationOptions.pageSize"
                            :total="paginationOptions.total"
                            :page-sizes="paginationOptions.pageSizes"
                            background
                            :pager-count="7"
                            layout="prev, pager, next, jumper,sizes,total"
                            @change="getcurrentPage"
                        ></el-pagination>
                    </div>
                </el-main>
            </el-container>
        </el-container>
        <el-dialog v-model="linkLogVisible" title="日志" @close="closeLinklog" :width="900">
            <template #footer> </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue'
import { ElContainer, ElAside, ElHeader, ElMain, ElTree, ElInput, ElMessage, ElButton, ElTable, TreeInstance } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { LinkMonitorFieldsEnums, LinkMonitorTreeType, LinkMonitorTableType } from './type'
import { getNodeListReq, getLinkListReq } from '/@/api/backend/linkMonitor/request'
import { debounce, cloneDeep } from 'lodash'

const LinkTreePropReplace = {
    label: 'nodeName',
    children: 'children',
}
const linkTreeRef = ref<TreeInstance>()
const treeData = ref<LinkMonitorTreeType[]>([])
const originTreeData = ref<LinkMonitorTreeType[]>([])
const curContextMenuTreeData = ref<LinkMonitorTreeType>()
const searchLinkTreeInputValue = ref('')
const getlinkTreeList = () => {
    return new Promise((resolve) => {
        getNodeListReq()
            .then((res) => {
                if (res.success) {
                    originTreeData.value = res.data!
                    treeData.value = res.data!
                    // originTreeData.value = res.data!
                    // const other = [
                    //     {
                    //         id: '5555',
                    //         nodeName: '鱼丸吃人111112222222222222222222222222222222',
                    //         nodeIp: '',
                    //         orgName: '',
                    //         orgId: '',
                    //         revision: 0,
                    //         children: [
                    //             {
                    //                 id: '1111',
                    //                 nodeName: '鱼丸吃人22222',
                    //                 nodeIp: '',
                    //                 orgName: '',
                    //                 orgId: '',
                    //                 revision: 0,
                    //                 children: [],
                    //             },
                    //         ],
                    //     },
                    // ]
                    // originTreeData.value[0].children = [...other]
                    // originTreeData.value[1] = {
                    //     id: '55654',
                    //     nodeName: '鱼丸吃人33',
                    //     nodeIp: '',
                    //     orgName: '',
                    //     orgId: '',
                    //     revision: 0,
                    //     children: [
                    //         {
                    //             id: '324232',
                    //             nodeName: '鱼丸吃人11',
                    //             nodeIp: '',
                    //             orgName: '',
                    //             orgId: '',
                    //             revision: 0,
                    //             children: [],
                    //         },
                    //     ],
                    // }
                    // const tree: LinkMonitorTreeType[] = [...originTreeData.value]
                    // treeData.value = tree

                    resolve(res.data![0])
                } else {
                    ElMessage.error(res.msg)
                }
            })
            .catch((err) => {
                ElMessage.error(err?.response?.data?.msg ?? '查询失败')
            })
    })
}

getlinkTreeList().then((res) => {
    curContextMenuTreeData.value = cloneDeep(res as LinkMonitorTreeType)
    linkTreeRef.value?.setCurrentKey(curContextMenuTreeData.value!.id!)
    getlinkMonitorList(curContextMenuTreeData.value!.id!, linkMonitorInputValue.value)
})

const searchLinkTree = () => {
    if (searchLinkTreeInputValue.value === '') {
        treeData.value = originTreeData.value
        nextTick(() => {
            linkTreeRef.value?.setCurrentKey(curContextMenuTreeData.value!.id!)
        })
        return
    }
    treeData.value = filterAndHighlightTreeArray(cloneDeep(originTreeData.value), searchLinkTreeInputValue.value) as LinkMonitorTreeType[]
    linkTreeNodeExpandKeys.value = Array.from(new Set([...linkTreeNodeExpandKeys.value, ...getAllIds(treeData.value)]))
    nextTick(() => {
        linkTreeRef.value?.setCurrentKey(curContextMenuTreeData.value!.id!)
    })
}
const getAllIds = (nodes: LinkMonitorTreeType[]) => {
    let ids: any = []
    nodes.forEach((node) => {
        ids.push(node.id)
        if (node.children && node.children.length > 0) {
            ids = ids.concat(getAllIds(node.children))
        }
    })
    return ids
}
const filterAndHighlightTreeArray = (treeArray: LinkMonitorTreeType[], searchQuery: string) => {
    return treeArray.map((tree: LinkMonitorTreeType) => filterAndHighlightTree(tree, searchQuery)).filter(Boolean)
}
const filterAndHighlightTree = (tree: LinkMonitorTreeType, searchQuery: string): (LinkMonitorTreeType & { isMatch?: boolean }) | null => {
    const isMatch = tree.nodeName.toLowerCase().includes(searchQuery.toLowerCase())
    if (isMatch) {
        return {
            ...tree,
            children: tree?.children?.map((child) => filterAndHighlightTree(child, searchQuery)).filter(Boolean) as LinkMonitorTreeType[],
            isMatch: true,
        }
    }
    if (tree.children && tree.children.length > 0) {
        const filteredChildren = tree.children.map((child) => filterAndHighlightTree(child, searchQuery)).filter(Boolean) as LinkMonitorTreeType[]

        if (filteredChildren.length > 0) {
            return { ...tree, children: filteredChildren }
        }
    }
    return null
}

const debounceSearchLinkTree = debounce(searchLinkTree, 200)

const linkTreeNodeExpandKeys = ref([] as any)
const linkTreeNodeExpand = (node: any) => {
    if (!linkTreeNodeExpandKeys.value.includes(node.id)) {
        linkTreeNodeExpandKeys.value.push(node.id)
    }
}
const linkTreeNodeCollapse = (node: any) => {
    const index = linkTreeNodeExpandKeys.value.indexOf(node.id)
    if (index > -1) {
        linkTreeNodeExpandKeys.value.splice(index, 1)
    }
}
const linkTreeNodeClick = (target: LinkMonitorTreeType) => {
    curContextMenuTreeData.value = cloneDeep(target)
    getlinkMonitorList(curContextMenuTreeData.value!.id!, linkMonitorInputValue.value)
}
const renderContent = (h: any, { node, data }: any) => {
    const label = node.label || ''
    const searchTerm = searchLinkTreeInputValue.value.toLowerCase()
    const startIndex = label.toLowerCase().indexOf(searchTerm)
    if (startIndex === -1) {
        return h('span', {}, label)
    }
    const beforeMatch = label.substring(0, startIndex)
    const matchText = label.substring(startIndex, startIndex + searchLinkTreeInputValue.value.length)
    const afterMatch = label.substring(startIndex + searchLinkTreeInputValue.value.length)
    return h('span', {}, [beforeMatch, h('span', { style: { color: '#f14c4c', fontWeight: 'bold' } }, matchText), afterMatch])
}
const linkMonitorInputValue = ref('')
const searchLinkMonitor = () => {
    if (linkMonitorInputValue.value === '') {
        getlinkMonitorList(curContextMenuTreeData.value!.id!)
        return
    }
    getlinkMonitorList(curContextMenuTreeData.value!.id!, linkMonitorInputValue.value)
}

const linkMonitorTableData = ref<LinkMonitorTableType[]>([])

// 链路监视列表
const paginationOptions = reactive({
    current: 1,
    pageSize: 20,
    total: 0,
    pageSizes: [20, 50, 100],
})
const getcurrentPage = () => {
    getlinkMonitorList(curContextMenuTreeData.value!.id!, linkMonitorInputValue.value)
}
const protocolList = [
    { label: 'IEC104主 *', value: 8 },
    { label: 'IEC104从 *', value: 9 },
    { label: 'MODBUSRTU主 *', value: 12 },
    { label: 'MODBUSTCP主 *', value: 16 },
]
const getlinkMonitorList = (nodeId: string, linkName?: string) => {
    getLinkListReq({ nodeId, linkName, pageNum: paginationOptions.current, pageSize: paginationOptions.pageSize })
        .then((res) => {
            if (res.rows) {
                linkMonitorTableData.value = res.rows.map((item) => {
                    return {
                        ...item,
                        protocolName: protocolList.find((i) => i.value === item.protocol)?.label,
                    }
                })
                paginationOptions.total = res.total
            } else {
                ElMessage.error(res.msg ?? '查询失败')
            }
        })
        .catch((err) => {
            ElMessage.error(err?.response?.data?.msg ?? '查询失败')
        })
}

const linkLogVisible = ref(false)
const closeLinklog = () => {
    linkLogVisible.value = false
}
const opneLog = (val: LinkMonitorTableType) => {
    // linkLogVisible.value = true
}
const startLink = (val: LinkMonitorTableType) => {
    console.log('startLink')
}
const stopLink = (val: LinkMonitorTableType) => {
    console.log('stopLink')
}
</script>

<style lang="scss" scoped>
$headerHeight: 60px;
$defaultBackgroundColor: #fff;
$defaultAsideWidth: 260px;
$paginationHeight: 32px;
.linkMonitor {
    position: relative;
    width: 100%;
    height: 100%;
    .containerPart {
        width: 100%;
        height: 100%;
        .asidePart {
            width: $defaultAsideWidth;
            height: 100%;
            border-right: 1px solid #eaebed;
            .asideHeader {
                display: flex;
                justify-content: center;
                align-items: center;
                .searchLinkTreeInput {
                    height: 40px;
                }
            }
            .treeMain {
                height: calc(100% - $headerHeight);
                overflow-y: auto;

                .treePart {
                    min-width: 100%;
                    overflow: auto;
                    display: inline-block;
                    background-color: $defaultBackgroundColor;
                }
            }
        }
        .mainContainer {
            width: calc(100% - $defaultAsideWidth);
            height: 100%;
            .mainHeader {
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: $headerHeight;
                padding: 0 20px;
                border-bottom: 1px solid #eaebed;
                .linkMonitorInput {
                    height: 40px;
                    width: 220px;
                }
                .mainHeaderCenter {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 320px;
                }
            }
            .mainMain {
                height: calc(100% - $headerHeight);
                .tabsPart {
                    height: calc(100% - $paginationHeight);
                    padding-bottom: 5px;
                    :deep(.el-tabs__content) {
                        height: calc(100% - 55px);
                        .el-tab-pane {
                            height: 100%;
                        }
                    }
                    .tablePart {
                        height: 100%;
                    }
                    .tableOperate {
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        a {
                            margin: 5px;
                            color: #0064aa;
                            font-weight: 600;
                            &:hover {
                                cursor: pointer;
                            }
                        }
                    }
                }
                .mainFooter {
                    display: flex;
                    justify-content: right;
                    background-color: #fff;
                }
            }
        }
    }
    .modelOperate {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;
        width: 80px;
        height: 150px;
        .el-button {
            margin: 0;
        }
    }
}

// 状态
.status-container {
    display: flex;
    justify-content: center;
    align-items: center;
}
.status-dot-online,
.status-dot-offline {
    width: 10px;
    height: 10px;
    border-radius: 50%;
}

.status-dot-online {
    background-color: #06b429;
}

.status-dot-offline {
    background-color: red;
}
.highlight {
    background-color: yellow; /* 高亮背景颜色 */
    color: red; /* 字体颜色 */
    font-weight: bold; /* 加粗字体 */
}
</style>
