<template>
    <div class="weather-info" :class="{ expanded: isExpanded, 'is-garden': isGarden ,'bg-white': isWhite}">
        <div class="header flex-center">
            <div class="header-left">
                <div class="address-select flex-center" v-if="isGarden">
                    <el-dropdown class="select-garden" trigger="click" popper-class="select-garden-popper">
                        <div class="el-dropdown-link flex-center">
                            <span class="ellipsis-l1">{{ farmName }}</span>
                            <div class="default-text" v-show="isDefaultFarm">默认</div>
                            <el-icon class="el-icon--right"><arrow-down /></el-icon>
                        </div>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item
                                    @click="handleCommand(item)"
                                    v-for="item in farmList"
                                    :key="item.id"
                                    :class="{ 'selected-active-garden': farmId === item.id }"
                                >
                                    <span>{{ item.name }}</span>
                                    <span v-if="item.defaultOption" class="dropdown-default-text">默认</span>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <div class="add-garden" @click="handleAddGarden">新增农场</div>
                </div>
                <div class="temperature flex-center">
                    <div class="temperature-number">{{ currentWeather.temp || '--' }}</div>
                    <div class="temperature-text">
                        <span>{{ locationName || '--' }}</span>
                        <div class="temperature-text-time">
                            <span>{{ currentWeather.text }}-</span>
                            <span>{{ currentDateText }}</span>
                            <span v-show="!isExpanded" class="temperature-text-more" @click="toggleExpand">
                                展开更多天气
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="weather-icon" v-if="currentWeather.iconDay">
                <i :class="'qi-'+currentWeather.iconDay + '-fill'"></i>
            </div>
            <!-- <div class="weather-icon" v-else>
                <img :src="`https://birdseye-img.sysuimars.com/weather/${currentWeather.iconDay}.svg`" alt="" />
            </div> -->
        </div>
        <div class="weather-chart-container">
            <div class="weather-chart-title">
                <span>未来七天天气</span>
                <div class="weather-chart-title-more" @click="toggleExpand">收起</div>
            </div>
            <weather-chart class="weather-chart" :weather-data="weatherData"></weather-chart>
        </div>
    </div>
</template>

<script setup>
import { ref, onActivated, computed, watch, onMounted } from "vue";
import weatherChart from "./weatherChart.vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
const store = useStore();

const props = defineProps({
    isGarden: {
        type: Boolean,
        default: false
    },
    gardenId: {
        type: [Number, String],
        default: null
    }
});

// 定义emit事件
const emit = defineEmits(['weatherExpanded','changeGarden']);
const router = useRouter();
const handleCommand = ({id, name}) => {
    farmName.value = name;
    farmId.value = id;
    // 更新默认农场标识
    const selectedFarm = farmList.value.find(farm => farm.id === id);
    isDefaultFarm.value = selectedFarm ? selectedFarm.defaultOption || false : false;
    // 保存用户选择的农场到 localStorage
    localStorage.setItem('selectedFarmId', id);
    localStorage.setItem('selectedFarmName', name);
    emit('changeGarden',{id, name});
};

const isExpanded = ref(false);
const isWhite = ref(false);
const toggleExpand = () => {
    if(props.isGarden){
        isWhite.value = !isWhite.value;
    }
    isExpanded.value = !isExpanded.value;
    emit('weatherExpanded',isExpanded.value);
};

const farmId = ref(null);
const farmName = ref("");
const farmList = ref([]);
const isDefaultFarm = ref(false); // 添加默认农场标识

// 根据传入的gardenId设置农场（先刷新列表再设置）
async function setFarmByGardenId(gardenIdValue) {
    if (!gardenIdValue) {
        return false;
    }
    
    // 先刷新农场列表，确保数据是最新的
    return new Promise((resolve) => {
        VE_API.farm.userFarmSelectOption().then(({data}) => {
            farmList.value = data || [];
            if (data && data.length > 0) {
                const targetFarm = data.find(farm => farm.id == gardenIdValue);
                if (targetFarm) {
                    farmName.value = targetFarm.name;
                    farmId.value = Number(gardenIdValue);
                    isDefaultFarm.value = targetFarm.defaultOption || false;
                    // 保存到 localStorage
                    localStorage.setItem('selectedFarmId', farmId.value);
                    localStorage.setItem('selectedFarmName', farmName.value);
                    emit('changeGarden', { id: farmId.value, name: farmName.value });
                    resolve(true);
                } else {
                    resolve(false);
                }
            } else {
                resolve(false);
            }
        }).catch(() => {
            resolve(false);
        });
    });
}

// 获取农场列表
function getFarmList() {
    // 如果传入了 gardenId，优先使用 setFarmByGardenId（它会刷新列表并设置）
    if (props.gardenId) {
        setFarmByGardenId(props.gardenId).then((setSuccess) => {
            // 如果设置失败，使用已获取的列表数据执行默认逻辑（避免重复请求）
            if (!setSuccess && farmList.value && farmList.value.length > 0) {
                selectFarmFromList(farmList.value);
            } else if (!setSuccess) {
                // 如果列表为空，再次获取列表
                getFarmListWithoutGardenId();
            }
        });
        return;
    }
    
    // 如果没有传入 gardenId，执行正常逻辑
    getFarmListWithoutGardenId();
}

// 从列表中选择农场（使用已有列表数据）
function selectFarmFromList(data) {
    // 使用 localStorage 中保存的农场选择
    const savedFarmId = localStorage.getItem('selectedFarmId');
    const savedFarmName = localStorage.getItem('selectedFarmName');
    if (savedFarmId && savedFarmName) {
        // 检查保存的农场是否还在当前列表中
        const savedFarm = data.find(farm => farm.id == savedFarmId);
        if (savedFarm) {
            farmName.value = savedFarmName;
            farmId.value = Number(savedFarmId);
            isDefaultFarm.value = savedFarm.defaultOption || false;
        } else {
            // 如果保存的农场不在列表中，按优先级选择
            selectDefaultFarm(data);
        }
    } else {
        // 如果没有保存的选择，按优先级选择
        selectDefaultFarm(data);
    }
    emit('changeGarden',{id: farmId.value, name: farmName.value});
}

// 获取农场列表（不处理传入的gardenId）
function getFarmListWithoutGardenId() {
    VE_API.farm.userFarmSelectOption().then(({data}) => {
        farmList.value = data || []
        if (data && data.length > 0) {
            selectFarmFromList(data);
        }
    })
}

// 监听父组件传入的gardenId变化
watch(() => props.gardenId, (newGardenId) => {
    if (newGardenId) {
        // 直接调用 setFarmByGardenId，它会刷新列表并设置
        setFarmByGardenId(newGardenId);
    }
}, { immediate: false });

// 选择默认农场的逻辑
function selectDefaultFarm(data) {
    // 首先查找 defaultOption 为 true 的农场
    const defaultFarm = data.find(farm => farm.defaultOption === true);
    
    if (defaultFarm) {
        // 如果有默认农场，选择它
        farmName.value = defaultFarm.name;
        farmId.value = defaultFarm.id;
        isDefaultFarm.value = true;
    } else {
        // 如果没有默认农场，选择第一个
        farmName.value = data[0].name;
        farmId.value = data[0].id;
        isDefaultFarm.value = data[0].defaultOption || false;
    }
    
    // 保存到 localStorage
    localStorage.setItem('selectedFarmId', farmId.value);
    localStorage.setItem('selectedFarmName', farmName.value);
}

onMounted(() => {
    getLocationName();
    getWeatherData();
})

onActivated(() => {
    getFarmList();
    getWeatherData();
});

// 暴露刷新方法供父组件调用
defineExpose({
    refreshFarmList: getFarmList,
    toggleExpand
});

const locationName = ref("");
const weatherData = ref(null);
const currentWeather = ref({ temp: "--", text: "--", iconDay: "" });
const MAP_KEY = "CZLBZ-LJICQ-R4A5J-BN62X-YXCRJ-GNBUT";
function getLocationName() {
    const location = store.state.home.miniUserLocation;
    // 将 location 从"经度,纬度"格式转换为"纬度,经度"格式
    let formattedLocation = location;
    if (typeof location === 'string' && location.includes(',')) {
        const [lng, lat] = location.split(',');
        formattedLocation = `${lat},${lng}`;
    }
    const params = {
            key: MAP_KEY,
            location: formattedLocation,
        };
        VE_API.old_mini_map.location(params).then(({ result }) => {
            // locationVal.value = result.formatted_addresses.recommend;
            locationName.value = result.address_component
                ? result.address_component.city + result.address_component.district
                : result.address + "";
        });
}

const handleAddGarden = () => {
    router.push(`/create_farm?isReload=true&from=monitor`)
}

// 获取天气数据
function getWeatherData() {
    const point = store.state.home.miniUserLocationPoint;
    if (!point) {
        return;
    }
    VE_API.old_mini_map.get7d({ point }).then(({ data }) => {
        if (data && data.daily && data.daily.length > 0) {
            weatherData.value = data;
            // 设置当前天气（第一天的数据）
            const today = data.daily[0];
            currentWeather.value = {
                temp: today.tempMax || today.tempMin || 26,
                text: today.textDay || "晴天",
                iconDay: today.iconDay
            };
        }
    }).catch(() => {
        // 获取天气数据失败，使用默认值
    });
}

// 获取当前日期和星期
const currentDateText = computed(() => {
    const now = new Date();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    return `${month}/${day}`;
});
</script>

<style lang="scss" scoped>
.weather-info {
    width: 100%;
    height: 58px;
    border-radius: 14px;
    background-color: #ffffff;
    padding: 0 12px;
    box-sizing: border-box;
    transition: height 0.3s ease-in-out;
    overflow: hidden;

    &.expanded {
        height: 312px;
    }

    &.is-garden {
        border-radius: 0;
        background-image: none;
    }

    &.bg-white{
        border-radius: 14px;
        background-image: linear-gradient(90deg, #e2f1fe 0%, #ffffff 80%);
    }

    .flex-center {
        display: flex;
        align-items: center;
    }
    .header {
        display: flex;
        justify-content: space-between;
        .header-left {
            .address-select {
                .select-garden {
                    width: fit-content;
                    max-width: 170px;
                    margin-right: 8px;
                    .el-dropdown-link {
                        font-size: 15px;
                        font-weight: 500;
                        color: #000000;
                        span {
                            width: fit-content;
                            max-width: 95%;
                            margin-right: 4px;
                        }

                        .default-text {
                            font-size: 12px;
                            color: #fff;
                            padding: 2px 4px;
                            width: 44px;
                            text-align: center;
                            box-sizing: border-box;
                            font-weight: 400;
                            background-color: #2199f8;
                            border-radius: 25px;
                        }
                    }
                }
                .add-garden {
                    font-size: 12px;
                    color: #2199f8;
                    padding: 3px 10px;
                    border: 1px solid rgba(33, 153, 248, 0.5);
                    border-radius: 25px;
                }
            }
            .temperature {
                .temperature-number {
                    font-size: 40px;
                    position: relative;
                    margin-right: 14px;
                    &::after {
                        content: "°";
                        font-size: 18px;
                        position: absolute;
                        right: -6px;
                        top: 2px;
                    }
                }
                .temperature-text {
                    font-weight: 500;
                    .temperature-text-time {
                        font-size: 12px;
                        font-weight: 400;
                    }
                    .temperature-text-more {
                        font-size: 12px;
                        color: #2199f8;
                        margin-left: 10px;
                        font-weight: 500;
                        cursor: pointer;
                    }
                }
            }
        }
        .header-right {
            width: 84px;
            height: 73px;
        }
        .weather-icon {
            i {
                font-size: 47px;
                color: #a7cffb;
            }
        }
    }
    .weather-chart-container {
        width: 100%;
        height: 100%;
        overflow: hidden;
        margin-top: 8px;
        .weather-chart-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
            font-weight: 500;
            .weather-chart-title-more {
                color: #828282;
                cursor: pointer;
                padding: 3px 10px;
                border-radius: 25px;
                font-weight: 400;
                border: 1px solid rgba(130, 130, 130, 0.5);
            }
        }
        .weather-chart {
            margin-top: 5px;
            width: 100%;
            height: 180px;
        }
    }
}
</style>
<style lang="scss">
.select-garden-popper {
    max-height: calc(100vh - 200px);
    overflow-y: auto;
    &.el-dropdown__popper {
        .el-dropdown__list {
            max-width: 250px;
        }
        .el-dropdown-menu__item{
            background-color: transparent !important;
            color: #606266 !important;
        }
        .selected-active-garden {
            color: #2199f8 !important;
            background-color: rgba(33, 153, 248, 0.1) !important;
            font-weight: 500;
        }
    }
    .dropdown-default-text {
        font-size: 11px;
        color: #2199f8;
        margin-left: 8px;
        padding: 0 5px;
        background-color: rgba(33, 153, 248, 0.1);
        border-radius: 10px;
        font-weight: 400;
    }
}
</style>
