<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 { useRouter } from "vue-router";
import { onMounted, onUnmounted, ref, computed } from "vue";
import { useStore } from "vuex";
import eventBus from "@/api/eventBus";
const router = useRouter();
const store = useStore();

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 = "果园总览"
}

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

onMounted(()=>{
    gardenOrganId(sessionStorage.getItem('farmId')*1)
    eventBus.on('handleActive',handleActive)
    eventBus.on('quitCompare', handleQuitCompare)
})
const mainMenuArr = computed(() => store.state.home.mainMenu);

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

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

const checkedChildren = ref([]);
const childrenData = ref([]);
const handleCheckedChange = (e) => {
    if(e.length){
        const monitorIndicatorId = [e[e.length -1]][0]
        const legendConfig = monitorData.value.filter(item => item.id === monitorIndicatorId)
        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)
        })
    }
};

// 根据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;
        }
        
        // 遍历legend配置中的每个分类
        legendList.forEach((legendItem) => {
            // 获取list数组
            const itemList = legendItem.list || legendItem.items || [legendItem];
            
            // 遍历每个分类下的具体项
            itemList.forEach((configItem) => {
                // 检查val是否在range区间内
                if (configItem.range && Array.isArray(configItem.range) && configItem.range.length === 2) {
                    const [min, max] = configItem.range
                    
                    if (sampleVal >= min && sampleVal < max) {
                        matchedResults.push({
                            ...sample, // 保留原始样本数据
                            key: legendItem.key || legendItem.name || 'unknown',
                            color: configItem.color,
                            label: configItem.label,
                            name: configItem.name,
                        })
                    }
                }
            })
        })
    })
    
    return matchedResults
}

function handleActive({name,key}){
    childrenData.value = []
    const menuItem = mainMenuArr.value.find(item =>item.name===key)
    active.value = menuItem.name;
    childrenData.value = menuItem.btnGroup
    checkedChildren.value = [name]

    emit('handleTab',{name:menuItem.name,id:active.value,isUpdate:true,params:name, legend: menuItem?.legend, colorObj: menuItem?.colorObj})
}

const active = ref("果园总览");
const monitorData = ref([]);
const handleHomeTab = ({ id, name , monitorItems}) => {
    active.value = name;
    childrenData.value = []
    monitorData.value = monitorItems || []
    checkedChildren.value = [] // 清空选中的值
    
    emit('handleTab',{name,id, legend: menuItem?.legend, colorObj: menuItem?.colorObj})
    // eventBus.emit("changePointType", {legend: menuItem?.legend, colorObj: menuItem?.colorObj})
    eventBus.emit('handleTab',name)
};

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>
