<template>
    <div class="param_config_page">
        <!-- 固定在顶部的头部区域 -->
        <div class="fixed_header" ref="fixedHeader">
            <HeaderComponent title="硫酸钠-参数配置" backTo="/controlPage/flowSelect" />
            <PageNav :items="paramItems_Na2SO4" :currentCode="paramPageCode" />
        </div>

        <!-- 主内容区（包含设备导航） -->
        <div class="main_container">
            <div class="main_content">
                <!-- 设备列表区域 -->
                <div class="content_area">
                    <!-- 加载状态 -->
                    <div v-if="isLoading" class="loading">正在加载参数配置...</div>

                    <!-- 错误状态 -->
                    <div v-if="hasError" class="error">
                        <p>加载配置失败: {{ errorMessage }}</p>
                        <button @click="loadConfigData">重试</button>
                    </div>

                    <div v-else class="config_container">
                        <!-- 按罐体分组 -->
                        <div v-for="(equipments, tankName) in filteredDeviceConfigGroup" :key="tankName"
                            class="tank_section" :id="`tank_${tankName}`">
                            <h2 class="tank_title">{{ tankName }}</h2>
                            <div class="params_grid">
                                <!-- 显示参数加载状态 -->
                                <div v-if="!isInitialParamsLoaded" class="loading">加载参数中...</div>

                                <!-- 确保初始参数加载完成后再渲染组件 -->
                                <ParamConfigComponent v-if="isInitialParamsLoaded" v-for="equipment in equipments"
                                    :key="equipment.code" :title="equipment.title + '-' + equipment.equipmentName"
                                    :code="equipment.code" :initial-params="getInitialParams(equipment.code)"
                                    :id="`device_${equipment.code}`" />
                            </div>
                        </div>

                        <!-- 无数据提示 -->
                        <div v-if="isEmptyData" class="no_data">未获取到设备配置信息</div>
                    </div>
                </div>

                <!-- 右侧罐体导航（使用导航组件） -->
                <TankNavigation :tanks="tankNavList" :current-index="currentNavIndex" :header-height="headerHeight"
                    @tankClick="scrollToTank" @scrollPositionChange="handleScrollPositionChange" />
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, watchEffect, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import HeaderComponent from '@/components/DCS/HeaderComponent.vue'
import PageNav from '@/components/GeneralComponents/control/PageNavComponent.vue'
import { getPageEquipmentGroupByTankByFlowCode } from '@/api/hnyz/equipment'
import { paramItems_Na2SO4 } from '@/config'
import ParamConfigComponent from '@/components/GeneralComponents/control/paramConfigComponent.vue'
import TankNavigation from '@/components/GeneralComponents/control/TankNavigationComponent.vue'
import { getAllParamConfigDataByCodeList } from '@/api/hnyz/param'
const route = useRoute()

// 状态变量
const isLoading = ref(true)
const hasError = ref(false)
const errorMessage = ref('')
const isEmptyData = ref(false)
const flowCode = ref(route.name.replace(/_.+$/, '_Control'))
const paramPageCode = ref(route.name)
const fixedHeader = ref(null)
const headerHeight = ref(0)

// 新增：标记初始参数是否加载完成
const isInitialParamsLoaded = ref(false)

// 导航相关变量 - 只处理最外层罐体
const tankNavList = ref([])  // 罐体导航列表数据
const currentNavIndex = ref(-1)  // 当前激活的导航项索引

// 设备配置和初始参数数据
const deviceConfigGroup = ref({})
const initialParamData = ref({})

// 过滤后的设备配置（排除阀门）
const filteredDeviceConfigGroup = computed(() => {
    const filtered = {}
    Object.entries(deviceConfigGroup.value).forEach(([tankName, equipments]) => {
        const validEquipments = equipments.filter(equip =>
            ![1, 5].includes(Number(equip.equipmentType))
        )
        if (validEquipments.length > 0) {
            filtered[tankName] = validEquipments
        }
    })
    isEmptyData.value = Object.keys(filtered).length === 0
    return filtered
})

// 生成罐体导航列表（只包含最外层罐体，不包含子设备）
const generateTankNavList = computed(() => {
    const navList = []
    // 直接遍历罐体名称，不处理子设备
    Object.keys(filteredDeviceConfigGroup.value).forEach(tankName => {
        // 生成简短名称用于导航显示
        const shortName = tankName.length > 18
            ? tankName.substring(0, 17) + '...'
            : tankName

        navList.push({
            uniqueId: `tank_${tankName}`,  // 与罐体DOM元素ID对应
            tankName,
            shortName,
            fullName: tankName
        })
    })
    return navList
})

// 计算固定头部高度
const calculateHeaderHeight = () => {
    if (fixedHeader.value) {
        headerHeight.value = fixedHeader.value.offsetHeight
    }
}

// 处理滚动位置变化事件
function handleScrollPositionChange(index) {
    currentNavIndex.value = index
}

// 加载设备配置和初始参数
async function loadConfigData() {
    try {
        isLoading.value = true
        hasError.value = false
        // 重置参数加载状态
        isInitialParamsLoaded.value = false

        // 1. 获取设备列表（按罐体分组）
        const res = await getPageEquipmentGroupByTankByFlowCode(flowCode.value)
        deviceConfigGroup.value = Object.fromEntries(
            Object.entries(res.data || {}).filter(([_, equipments]) => equipments?.length > 0)
        )
        // 2. 加载初始参数值（若有设备）
        if (Object.keys(filteredDeviceConfigGroup.value).length > 0) {
            await loadInitialParamValues()
        } else {
            // 没有设备时也标记参数加载完成
            isInitialParamsLoaded.value = true
        }

    } catch (err) {
        hasError.value = true
        errorMessage.value = err.message || '加载配置失败'
        console.error('加载配置失败', err)
        // 错误时也标记参数加载完成，避免一直显示加载状态
        isInitialParamsLoaded.value = true
    } finally {
        isLoading.value = false
    }
}

// 加载所有设备的初始参数值
async function loadInitialParamValues() {
    try {
        const allCodes = []
        Object.values(filteredDeviceConfigGroup.value).forEach(equipments => {
            equipments.forEach(equip => allCodes.push(equip.code))
        })
        const res = await getAllParamConfigDataByCodeList(allCodes)
        // console.log('加载初始参数结果', res)
        initialParamData.value = res.data || {}
    } catch (err) {
        console.error('加载初始参数失败', err)
        initialParamData.value = {}
    } finally {
        // 无论成功失败，都标记参数加载完成
        isInitialParamsLoaded.value = true
    }
}

// 获取设备的初始参数
function getInitialParams(code) {
    const paramCount = getParamCountByCode(code)
    // console.log('获取初始参数', code, paramCount, initialParamData.value)
    return initialParamData.value[code] || new Array(paramCount).fill(0)
}

// 辅助函数：根据设备code获取参数数量
function getParamCountByCode(code) {
    const type = getDeviceTypeByCode(code)
    const paramCount = paramTemplates[type] || 0
    return paramCount
}

// 辅助函数：根据设备code判断类型
function getDeviceTypeByCode(code) {
    const upperType = code.toUpperCase()
    if (upperType.startsWith('PH')) return 'ph'
    if (upperType.startsWith('PT')) return 'pressuregauge'
    if (upperType.startsWith('TT')) return 'thermometer'
    if (upperType.startsWith('FIT')) return 'flowmeter'
    if (upperType.startsWith('P') || upperType.startsWith('M')) return 'pump'
    if (upperType.startsWith('LT')) return 'levelmeter'
    return 'unknown'
}

// 滚动到指定罐体（而非子设备）
function scrollToTank(tank, index) {
    currentNavIndex.value = index
    const element = document.getElementById(`tank_${tank.tankName}`)
    if (element) {
        // 平滑滚动到罐体位置，考虑头部高度
        window.scrollTo({
            top: element.offsetTop - headerHeight.value - 20,
            behavior: 'smooth'
        })
    }
}

// 参数模板定义（不同设备类型的参数数量）
const paramTemplates = {
    pump: 3,
    flowmeter: 5,
    thermometer: 2,
    ph: 3,
    levelmeter: 5,
    pressuregauge: 3,
    unknown: 0
}

// 初始化
onMounted(() => {
    // 计算头部高度
    calculateHeaderHeight()
    // 监听窗口大小变化，重新计算头部高度
    window.addEventListener('resize', calculateHeaderHeight)
    loadConfigData()

    // 当罐体列表变化时更新导航
    watchEffect(() => {
        tankNavList.value = generateTankNavList.value
        currentNavIndex.value = -1
    })
})

onBeforeUnmount(() => {
    window.removeEventListener('resize', calculateHeaderHeight)
})
</script>

<style scoped>
.param_config_page {
    width: 100%;
    min-height: 100vh;
    padding: 0;
    background-color: #252525;
}

/* 固定头部样式 */
.fixed_header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1000;
    background-color: #252525;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

/* 主容器样式（避免被固定头部遮挡） */
.main_container {
    padding: 140px 20px 24px;
    box-sizing: border-box;
}

/* 主内容区布局 */
.main_content {
    display: flex;
    gap: 20px;
    max-width: 1700px;
    margin: 0 auto;
}

.content_area {
    flex: 1;
    min-width: 1350px;
}

.config_container {
    width: 100%;
    padding: 20px 0;
}

.tank_section {
    margin-bottom: 30px;
    background: #1a1a1a;
    border-radius: 8px;
    padding: 20px;
    border: 1px solid #72E0FF;
    scroll-margin-top: 160px;
    /* 滚动定位预留空间 */
}

.tank_title {
    margin: 0 0 20px 0;
    padding-bottom: 10px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    font-size: 18px;
    color: #76E1FF;
}

.params_grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
}

/* 状态提示样式 */
.loading,
.error,
.no_data {
    width: 100%;
    margin: 20px auto;
    padding: 20px;
    border-radius: 8px;
    text-align: center;
    background-color: rgba(255, 255, 255, 0.1);
    color: #fff;
}

.loading {
    color: #1890ff;
}

.error {
    color: #f5222d;
}

.error button {
    padding: 8px 16px;
    background: #f5222d;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-top: 10px;
}

.error button:hover {
    background: #d91111;
}

/* 响应式调整 */
@media (max-width: 1400px) {
    .params_grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 20px;
    }
}

@media (max-width: 1200px) {
    .main_container {
        padding: 140px 15px 16px;
    }

    .main_content {
        max-width: 100%;
    }

    .content_area {
        min-width: auto;
    }
}

@media (max-width: 992px) {
    .main_content {
        flex-direction: column;
    }

    .params_grid {
        grid-template-columns: 1fr;
        gap: 16px;
    }

    .main_container {
        padding: 120px 15px 16px;
    }
}

@media (max-width: 768px) {
    .tank_section {
        padding: 15px;
        margin-bottom: 20px;
    }

    .params_grid {
        gap: 14px;
    }
}
</style>
