<template>
    <div class="navigation yes-events">
        <el-select class="select" v-model="areaId" size="large" @change="changeSelect" popper-class="focus-farm-select">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <div class="tabs" v-if="list.length">
            <template v-for="(item, index) in list" :key="index">
                <div
                    class="tab-item"
                    @click="handleHomeTab(item)"
                    :class="{ active: active === item.name }"
                    
                >
                    {{ item.name }}
                </div>
                <el-checkbox-group
                    v-show="item.monitorItems && item.name == active"
                    class="checkbox-group"
                    v-model="checkedChildren"
                    @change="handleCheckedChange"
                    :min="1"
                >
                    <el-checkbox v-for="ele in item.monitorItems" :key="ele.id" :label="ele.indicatorName" :value="ele.id">
                        {{ ele.indicatorName }}
                    </el-checkbox>
                </el-checkbox-group>
            </template>
        </div>
        <!-- 对比 -->
        <el-checkbox-group
            class="checkbox-group compare-btn"
            v-model="checkedCompareChildren"
            @change="handleCompareChange"
        >
            <el-checkbox label="指标对比" value="1">
                指标对比
            </el-checkbox>
        </el-checkbox-group>

        <div class="compare-tips" v-show="checkedCompareChildren.length && !checkedCompareChildren.includes('2')">
            <span>提示：</span>请在底图上点选 <span>两棵树</span>，才可以进行对比
        </div>
    </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import eventBus from "@/api/eventBus";

const areaId = ref("");
const options = ref([]);
eventBus.off('garden:organId', gardenOrganId)
eventBus.on('garden:organId',gardenOrganId)

const organId = ref()
function gardenOrganId(farmId){
    organId.value = farmId
    getListByFarmId()
    VE_API.region.list({farmId}).then(res =>{
        options.value = res.data
        options.value.unshift({
            id:0,
            name:'全部区域'
        })
        areaId.value = res.data[0].id
        eventBus.emit('area:id',{areaId:areaId.value,farmId})
        sessionStorage.setItem('regionId',areaId.value)
    })
}

const changeSelect = (e) =>{
    eventBus.emit('area:id',{areaId:areaId.value,farmId:organId.value})
    sessionStorage.setItem('regionId',e)
    eventBus.emit('handleTab',)
    active.value = "果园总览"
    handleCheckedChange(checkedChildren.value,true)
}

const getListByFarmId = () =>{
    VE_API.home.listByFarmId({farmId:organId.value}).then(res =>{
        list.value = res.data || []
        monitorData.value = res.data[0].monitorItems || []
        checkedChildren.value = [res.data[0].monitorItems[0].id]
        handleCheckedChange(checkedChildren.value,true)
    })
}

onMounted(()=>{
    gardenOrganId(sessionStorage.getItem('farmId')*1)
    eventBus.on('handleActive',handleActiveTab)
    eventBus.on('quitCompare', handleQuitCompare)
})

onUnmounted(()=>{
    eventBus.off('handleActive',handleActiveTab)
    eventBus.off('quitCompare', handleQuitCompare)
})

const emit = defineEmits(["handleTab","updateLegend"])

const checkedChildren = ref([]);
const handleCheckedChange = (e,isInit = false) => {
    if(e.length){
        checkedChildren.value = [e[e.length -1]];
        const monitorIndicatorId = [e[e.length -1]][0]
        const legendConfig = monitorData.value.filter(item => item.id === monitorIndicatorId)
        
        // 发射事件通知 tabs 组件更新高亮状态
        if (legendConfig.length > 0) {
            eventBus.emit('updateTabActive', {
                indicatorId: monitorIndicatorId,
                indicatorName: active.value
            });
        }
        
        VE_API.home.queryWorkCodeSampleParams({monitorIndicatorId,farmId:organId.value,regionId:areaId.value || null}).then(res =>{
            // 解析legendConfig
            const parsedLegendConfig = JSON.parse(legendConfig[0].legendConfig)
            // 根据接口返回的val字段匹配range区间
            let matchedData = matchDataByVal(res.data, parsedLegendConfig)
            emit('updateLegend',matchedData,parsedLegendConfig,isInit)
        })
    }
};

// 根据val字段匹配range区间的函数
const matchDataByVal = (sampleData, legendConfig) => {
    if (!sampleData || !legendConfig) {
        return []
    }
    
    // 检查不同的数据结构可能性
    let legendList = null;
    if (legendConfig.legendList) {
        legendList = legendConfig.legendList;
    } else if (Array.isArray(legendConfig)) {
        legendList = legendConfig;
    } else if (legendConfig.list) {
        legendList = [legendConfig];
    }
    
    if (!legendList) {
        return []
    }
    
    const matchedResults = []
    
    // 遍历样本数据
    sampleData.forEach((sample) => {
        const sampleVal = sample.val || sample.value || sample.data
        
        if (sampleVal === undefined || sampleVal === null) {
            return;
        }
        
        let foundMatch = false; // 标记是否找到匹配项
        
        // 遍历legend配置中的每个分类
        for (const legendItem of legendList) {
            if (foundMatch) break; // 如果已找到匹配项，跳出循环
            
            // 获取list数组
            const itemList = legendItem.list || legendItem.items || [legendItem];
            
            // 遍历每个分类下的具体项
            for (const configItem of itemList) {
                if (foundMatch) break; // 如果已找到匹配项，跳出内层循环
                
                // 检查val是否在range区间内
                if (configItem.range && Array.isArray(configItem.range) && configItem.range.length === 2) {
                    const [min, max] = configItem.range
                    
                    // 兼容区间判断：如果min和max相等，则精确匹配；否则使用范围匹配
                    let isMatch = false;
                    if (min === max) {
                        // 精确匹配：当区间为[0,0]时，兼容浮点数，将sampleVal转换为整数进行比较
                        isMatch = Math.floor(sampleVal) === min;
                    } else {
                        // 范围匹配：当区间为[0,1]时，值在[0,1)范围内匹配
                        isMatch = Number(sampleVal) >= min && Number(sampleVal) <= max;
                    }
                    
                    if (isMatch) {
                        matchedResults.push({
                            ...sample, // 保留原始样本数据
                            key: legendItem.key || legendItem.name || 'unknown',
                            color: configItem.color,
                            label: configItem.label,
                            name: configItem.name,
                        })
                        foundMatch = true; // 标记已找到匹配项
                        break; // 跳出内层循环
                    }
                }
            }
        }
    })
    
    return matchedResults
}

function handleActiveTab({id,key,monitorItems}){
    checkedChildren.value = []
    active.value = key
    checkedChildren.value = [id]
    monitorData.value = monitorItems || []
    handleCheckedChange(checkedChildren.value)
}

const active = ref("果园总览");
const monitorData = ref([]);
const handleHomeTab = ({ name , monitorItems}) => {
    active.value = name;
    checkedChildren.value = []
    monitorData.value = monitorItems || []
    
    // 默认勾选第一项
    if (monitorItems && monitorItems.length > 0) {
        checkedChildren.value = [monitorItems[0].id]
        handleCheckedChange(checkedChildren.value)
    }
};

const list = ref([]);

// 对比
const checkedCompareChildren = ref([]);
function handleCompareChange(v) {
    if(v == 2){
      eventBus.emit("showGspgjdfbt", v == 2)
      return
    }
    eventBus.emit("showGspgjdfbt", false)
    eventBus.emit("compareTree", checkedCompareChildren.value.length > 0 ? true : false)
}

// 退出对比
function handleQuitCompare() {
    checkedCompareChildren.value = []
}
</script>

<style lang="scss" scoped>
.navigation {
    position: fixed;
    top: 34px;
    left: calc(50% - 70px);
    // left: 50%;
    transform: translateX(-50%);
    width: calc(100% - 430px * 2);
    display: flex;
    justify-content: center;
    align-items: center;
    .select{
        // width: 120px;
        width: 166px;
        height: 50px;
        margin-right: 21px;
        ::v-deep{
            .el-select__wrapper{
                height: 100%;
                background: rgba(0, 0, 0, 0.3);
                box-shadow: 0 0 0 1px #F7BE5A;
                border-radius: 2px;
                text-align: center;
            }
            .el-select__placeholder{
                color: #F7BE5A;
                font-size: 20px;
                font-family: "PangMenZhengDao";
            }
            .el-select__caret{
                color: #F7BE5A;
                font-size: 20px;
            }
        }
    }
    .tabs {
        background: rgba(35, 35, 35, 0.8);
        border: 1px solid #555555;
        padding: 8px;
        border-radius: 8px;
        display: flex;
        justify-content: center;
        .tab-item {
            font-size: 16px;
            color: rgba(255, 255, 255, 0.8);
            padding: 7px 12px 9px 12px;
            font-family: "PangMenZhengDao";
            cursor: pointer;
            &.active {
                background: #ffd489;
                color: #1d1d1d;
                border-radius: 4px;
            }
        }
        .tab-item + .tab-item {
            margin-left: 25px;
        }
    }
    .tabs + .tabs {
        margin-left: 12px;
    }

    .checkbox-group {
        position: absolute;
        top: 65px;
        right: 36px;
        background: rgba(35, 35, 35, 0.8);
        border-radius: 8px;
        border: 1px solid #555555;
        padding: 10px 20px;
        display: flex;
        flex-direction: column;
        &.compare-btn {
            right: 40px;
            top: 0px;
        }
        ::v-deep {
            .el-checkbox {
                margin-right: 0;
            }
            .el-checkbox__input.is-checked + .el-checkbox__label {
                color: #ffd489;
            }
            .el-checkbox__input.is-checked .el-checkbox__inner {
                background-color: #ffd489;
                border-color: #ffd489;
                &::after {
                    border-color: #1d1d1d;
                }
            }
            .el-checkbox__label {
                color: #fff;
            }
        }
    }

    .compare-tips {
        position: absolute;
        top: 96px;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(4, 3, 0, 0.6);
        width: max-content;
        border-radius: 40px;
        padding: 6px 34px;
        font-family: 'PangMenZhengDao';
        font-size: 20px;
        span {
            color: #F3C11D;
        }
    }

    .btn {
        width: 80px;
        height: 30px;
        text-align: center;
        line-height: 28px;
        border-radius: 5px;
        cursor: pointer;
        background: rgba(255, 255, 255, 0.5);
    }
}
</style>
