<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 flex-center" v-if="!isGarden">
                    <el-icon class="address-icon"><Location /></el-icon>
                    <span class="address-text">广州市番禺区</span>
                </div>
                <div class="address-select flex-center" v-else>
                    <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">26</div>
                    <div class="temperature-text">
                        <span>晴天</span>
                        <div class="temperature-text-time">
                            <span>{{ currentDateText }}</span>
                            <span v-show="!isExpanded" class="temperature-text-more" @click="toggleExpand">
                                展开更多天气
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <img class="header-right" src="@/assets/img/home/rain.png" alt="" />
        </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-chart>
        </div>
    </div>
</template>

<script setup>
import { ref, onActivated, computed } from "vue";
import weatherChart from "./weatherChart.vue";
import { useRouter } from "vue-router";
const props = defineProps({
    isGarden: {
        type: Boolean,
        default: false
    }
});
// 定义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); // 添加默认农场标识

// 获取农场列表
function getFarmList() {
    VE_API.farm.userFarmSelectOption().then(({data}) => {
        farmList.value = data || []
        if (data && data.length > 0) {
            // 优先使用 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});
        }
    })
}

// 选择默认农场的逻辑
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);
}

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

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

// 获取当前日期和星期
const currentDateText = computed(() => {
    const now = new Date();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const weekDay = weekDays[now.getDay()];
    return `${month}/${day} ${weekDay}`;
});
</script>

<style lang="scss" scoped>
.weather-info {
    width: 100%;
    height: 89px;
    border-radius: 14px;
    background-image: linear-gradient(90deg, #e2f1fe 0%, #ffffff 80%);
    padding: 10px;
    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: 100%;
                            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;
                }
            }
            .address-icon {
                margin-right: 4px;
                font-size: 16px;
            }
            .address-text {
                font-size: 16px;
                font-weight: 500;
                color: #000000;
            }
            .temperature {
                margin-top: 8px;
                .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-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 {
    &.el-dropdown__popper {
        .el-dropdown__list {
            max-width: 160px;
        }
        .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>
