<template>
    <div class="container">
        <!-- 使用 v-for 遍历四个角落 -->
        <div v-for="corner in corners" v-show="corner.show" :key="corner.id" :class="['corner', corner.className]">
            <div class="content">
                <div class="title">{{ corner.title }}</div>
                <el-descriptions :column="1" size="small" label-width="70px" border>
                    <el-descriptions-item label="指标数据">
                        <div style="height: 200px; overflow-y: auto">
                            <div
                                v-for="item in props.steadyState?.filter(k => k.lineId === corner.elementId)"
                                :key="item.id"
                            >
                                {{ item.statisticalName.replace(/\//g, '_') }}:
                                {{ item.value === 3.1415926 ? '/' : item.value + item.unit }}
                            </div>
                        </div>
                    </el-descriptions-item>
                </el-descriptions>
            </div>
            <span class="close-btn" @click="closeCorner(corner.id)">
                <Close />
            </span>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { Close } from '@element-plus/icons-vue'

// 定义 emits
const emit = defineEmits(['lineListChange'])

// 定义接收的 props
const props = defineProps<{
    steadyState?: any[]
}>()

// 定义四个角落的数据
const corners = ref([
    {
        id: 'topLeft',
        title: '左上',
        className: 'top-left',
        show: false,
        data: [] as { label: string; value: string }[],
        elementId: '' // 记录该角落对应的元素ID
    },
    {
        id: 'topRight',
        title: '右上',
        className: 'top-right',
        show: false,
        data: [] as { label: string; value: string }[],
        elementId: ''
    }
])

const displayOrder = ref<number[]>([])

// 截取名称的最后一部分作为标题
const extractTitleFromLineName = (lineName: string): string => {
    if (!lineName) return '未知监测点'

    // 按照 "/" 分割字符串，取最后一部分
    const parts = lineName.split('/')
    return parts.length > 0 ? parts[parts.length - 1].trim() : lineName
}

// 更新指定角落数据的函数
const updateCornerData = (cornerIndex: number, elementId: string, lineName: string) => {
    // closeCorner(corners.value[cornerIndex].elementId)
    corners.value[cornerIndex].show = false
    setTimeout(() => {
        // 更新标题为传入的 lineName 的最后一部分
        corners.value[cornerIndex].title = extractTitleFromLineName(lineName)

        // 格式化数据（只保留稳态指标一项）
        corners.value[cornerIndex].data = [
            {
                label: '稳态指标',
                value: '正在加载...'
            }
        ]

        // 记录该角落对应的元素ID
        corners.value[cornerIndex].elementId = elementId
        corners.value[cornerIndex].show = true
    }, 500)
}

// 显示下一个角落的函数
const showNextCorner = (elementId: string, lineName: string) => {
    // 检查该元素ID是否已经显示过
    const existingCornerIndex = corners.value.findIndex(corner => corner.elementId === elementId && corner.show)

    if (existingCornerIndex !== -1) {
        // 如果该元素已经显示过，更新标题
        corners.value[existingCornerIndex].title = extractTitleFromLineName(lineName)
        return
    }

    // 查找一个未显示的角落
    const availableCornerIndex = corners.value.findIndex(corner => !corner.show)

    if (availableCornerIndex !== -1) {
        // 有空闲角落，显示在该角落
        updateCornerData(availableCornerIndex, elementId, lineName)

        // 记录显示顺序
        displayOrder.value.push(availableCornerIndex)
    } else {
        // 没有空闲角落，按顺序替换角落
        // 获取需要替换的角落索引（循环替换）
        const replaceIndex = displayOrder.value.shift() || 0
        updateCornerData(replaceIndex, elementId, lineName)
        // 将替换的索引重新加入队列末尾
        displayOrder.value.push(replaceIndex)
    }

    // updateLineList()
}
const timer = ref<any>(null)
// 更新 lineList，根据 corners 的 show 状态来维护
const updateLineList = () => {
    const newLineList = corners.value.filter(corner => corner.show && corner.elementId).map(corner => corner.elementId)
    if (timer.value) {
        clearInterval(timer.value)
        timer.value = null
    }
    if (newLineList.length > 0) {
        emit('lineListChange', newLineList)
        timer.value = setInterval(
            () => {
                emit('lineListChange', newLineList)
            },
            3 * 60 * 1000
        )
    }
}

// 关闭指定角落的函数
const closeCorner = (id: string) => {
    const cornerIndex = corners.value.findIndex(c => c.id === id)
    if (cornerIndex !== -1) {
        corners.value[cornerIndex].show = false
        corners.value[cornerIndex].elementId = '' // 清空元素ID记录

        // 从显示顺序中移除该角落索引
        const orderIndex = displayOrder.value.indexOf(cornerIndex)
        if (orderIndex !== -1) {
            displayOrder.value.splice(orderIndex, 1)
        }
    }
}

// 关闭所有角落的函数
const closeAllCorners = () => {
    corners.value.forEach(corner => {
        corner.show = false
        corner.elementId = ''
    })
    displayOrder.value = []

    updateLineList()
}

// 监听 corners 的变化，特别是 show 状态的变化
watch(
    () => corners.value.map(corner => ({ id: corner.id, show: corner.show, elementId: corner.elementId })),
    (newCorners, oldCorners) => {
        // 检查是否有 show 状态的变化
        const showStateChanged = newCorners.some((corner, index) => corner.show !== oldCorners[index]?.show)

        if (showStateChanged) {
            updateLineList()
        }
    },
    { deep: true }
)

// 暴露方法给父组件使用
defineExpose({
    showNextCorner,
    closeCorner,
    closeAllCorners
})
</script>

<style scoped lang="less">
.corner {
    width: 260px;
    position: absolute;
}

.top-left {
    top: 10px;
    left: 10px;
}

.top-right {
    top: 10px;
    right: 10px;
}

.bottom-left {
    top: 170px;
    left: 10px;
}

.bottom-right {
    top: 170px;
    right: 10px;
}

.content {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
}

.title {
    font-size: 16px;
    padding: 8px;
    border-bottom: 1px solid #ccc;

    background-color: #fff;
}

.data-item {
    display: flex;
    margin-bottom: 4px;
    font-size: 14px;
}

.label {
    width: 55px;
    flex-shrink: 0;
}

.value {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 关闭按钮样式 */
.close-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 14px;
    color: #000;
    font-size: 14px;
    font-weight: bold;
    cursor: pointer;
}

.indicator {
    display: flex;
}
</style>
