<template>
    <div class="weather-info is-garden"
        :class="{ expanded: isExpanded, 'no-farm': !hasFarm, 'no-weather': !hasWeather, 'farm-list': activeGarden === 'list' }">
        <div class="header flex-center">
            <div class="header-left">
                <div class="address-select flex-center" v-if="hasFarm">
                    <div class="garden-tabs">
                        <div class="garden-item left-item" @click="handleGardenClick('current')"
                            :class="{ 'active': activeGarden === 'current' }">
                            <img class="current-icon"
                                :src="activeGarden === 'current' ? require('@/assets/img/common/farm-active.png') : require('@/assets/img/common/farm.png')"
                                alt="">
                            <span class="current-name van-ellipsis">{{ farmName }}</span>
                            <el-icon
                                @click="handleFarmInfo"
                                v-if="activeGarden === 'current'"
                                class="farm-edit-icon"
                            >
                                <Edit />
                            </el-icon>
                        </div>
                        <img class="title-block" v-show="activeGarden === 'current'"
                            src="@/assets/img/common/title-block.png" alt="">
                        <img class="title-block" v-show="activeGarden !== 'current'"
                            src="@/assets/img/common/title-block-active.png" alt="">
                        <div class="garden-item right-item" @click="handleGardenClick('list')"
                            :class="{ 'active': activeGarden === 'list' }">
                            <img class="current-icon"
                                :src="activeGarden === 'list' ? require('@/assets/img/common/menu-active.png') : require('@/assets/img/common/menu.png')"
                                alt="">
                            <span class="current-name">{{ t("weather.farmList") }}</span>
                        </div>

                        <div class="mask-wrap" v-if="props.showTabMask" @click="emit('closeTabMask')">
                            <div class="mask-content">
                                <div class="mask-text">
                                    {{ t("weather.farmListGuide") }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="address-select flex-center farm-name" v-else>
                    {{ t("common.demoFarm") }}
                </div>
                <div class="farm-l" v-show="activeGarden === 'current' && hasWeather">
                    <div class="temperature flex-center">

                        <div class="weather-icon" v-if="currentWeather.iconDay">
                            <i :class="'qi-' + currentWeather.iconDay + '-fill'"></i>
                        </div>
                        <div class="temperature-number">{{ currentWeather.temp || '--' }}</div>
                        <div class="temperature-text">
                            <span>{{ currentWeather.text }}</span>
                            <div class="temperature-text-time">
                                <span>{{ currentDateText }}</span>
                                <span class="temperature-text-date">{{ currentWeekText }}</span>
                                <span v-show="!isExpanded" class="temperature-text-more" @click="toggleExpand">
                                    {{ t("weather.expandMore") }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div v-if="!hasWeather" class="report-tabs">
                    <div
                        v-for="(item, index) in reportTabs"
                        :key="item.key"
                        class="report-tab-item"
                        @click="emit('reportTabClick', item)"
                    >
                        <img class="report-tab-icon" :src="getReportTabIcon(index)" alt="" />
                        <span class="report-tab-label">{{ getReportTabLabel(item) }}</span>
                    </div>
                </div>
            </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" v-show="activeGarden === 'current' && hasWeather">
            <div class="weather-chart-title">
                <span>{{ t("weather.future7Days") }}</span>
                <div class="weather-chart-title-more" @click="toggleExpand">{{ t("weather.collapse") }}</div>
            </div>
            <weather-chart class="weather-chart" :weather-data="weatherData"></weather-chart>
        </div>
        <!-- 农场筛选 -->
        <div class="farm-filter" v-show="activeGarden === 'list'">
            <div class="filter-l">
                <el-input v-model="searchFarm" style="width: 96px" :placeholder="t('weather.searchFarm')" :prefix-icon="Search" />
            </div>
            <div class="filter-r">
                <el-select v-model="regionVal" :placeholder="t('weather.selectRegion')" style="width: 92px">
                    <el-option v-for="item in regionOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
                <el-select v-model="typeVal" :placeholder="t('weather.selectCategory')" style="width: 92px">
                    <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
        </div>
    </div>

</template>

<script setup>
import { ref, onActivated, computed } from "vue";
import weatherChart from "./weatherChart.vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { Edit, Search } from '@element-plus/icons-vue';
import { convertPointToArray } from "@/utils/index";
import { useI18n } from "@/i18n";

const { t } = useI18n();
const store = useStore();

const props = defineProps({
    showTabMask: {
        type: Boolean,
        default: false
    },
    gardenId: {
        type: [Number, String],
        default: null
    },
    hasWeather: {
        type: Boolean,
        default: true
    },
    reportTabs: {
        type: Array,
        default: () => [
            { key: "historyRisk" },
            { key: "soilImprovement" },
            { key: "rotationAdvice" },
        ],
    },
    from: {
        type: String,
        default: null
    }
});

const regionVal = ref('');
const typeVal = ref('');
const searchFarm = ref('');
const regionOptions = ref([{
    label: '地区1',
    value: '1'
}, {
    label: '地区2',
    value: '2'
}]);
const typeOptions = ref([{
    label: '品类1',
    value: '1'
}]);

const REPORT_TAB_ICONS = [
    require("@/assets/img/common/header-icon-1.png"),
    require("@/assets/img/common/header-icon-2.png"),
    require("@/assets/img/common/header-icon-3.png"),
];

const getReportTabIcon = (index) => REPORT_TAB_ICONS[index] || REPORT_TAB_ICONS[0];

const getReportTabLabel = (item) => {
    if (!item?.key) return item?.label || "";
    const i18nKey = `weather.reportTab.${item.key}`;
    const translated = t(i18nKey);
    if (translated !== i18nKey) return translated;
    return item.label || item.key;
};

// 定义emit事件
const emit = defineEmits(['weatherExpanded', 'changeGarden', 'changeGardenTab', 'closeTabMask', 'reportTabClick']);
const router = useRouter();

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

const farmId = ref(null);
const farmName = ref("");
const hasFarm = ref(false)
const activeGarden = ref('current');

onActivated(() => {
    handleGardenClick('current');
});

function setGardenLoaded(hasFarmData) {
    hasFarm.value = !!hasFarmData;
    if (!hasFarm.value) {
        farmId.value = null;
        farmName.value = "";
    }
}

function setSelectedGarden(payload) {
    if (!payload?.id) {
        setGardenLoaded(false);
        getLocationName();
        getWeatherData();
        return;
    }

    hasFarm.value = true;
    farmId.value = Number(payload.id);
    farmName.value = payload.name || "";
    getLocationName();
    getWeatherData();
    emit('changeGarden', payload);
}

const handleGardenClick = (type) => {
    activeGarden.value = type;
    emit("changeGardenTab", type);
};

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 locationPoint = localStorage.getItem('selectedFarmPoint') || store.state.home.miniUserLocationPoint;
    const farmLocation = convertPointToArray(locationPoint);
    let formattedLocation = `${farmLocation[1]},${farmLocation[0]}`;
    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 handleFarmInfo = () => {
    router.push(`/farm_info?subjectId=${farmId.value}`);
}

// 获取天气数据
function getWeatherData() {
    const point = localStorage.getItem('selectedFarmPoint') || 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 || t("weather.sunny"),
                iconDay: today.iconDay,
                fxDate: today.fxDate
            };
        }
    }).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}`;
});

const currentWeekText = computed(() => {
    if (!currentWeather.value?.fxDate) {
        return "";
    }

    // 兼容 "YYYY-MM-DD" 格式，避免部分环境下直接 new Date() 解析异常
    const date = new Date(currentWeather.value.fxDate.replace(/-/g, "/"));
    if (Number.isNaN(date.getTime())) {
        return "";
    }

    return t(`week.${date.getDay()}`);
});


// 暴露方法供父页面（如长势报告）同步农场列表状态
defineExpose({
    setGardenLoaded,
    setSelectedGarden,
    toggleExpand,
    handleGardenClick
});
</script>

<style lang="scss" scoped>
.mask-wrap {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: calc(100% - 300px);
    background-color: rgba(0, 0, 0, 0.52);
    z-index: 99999;
    color: rgba(0, 0, 0, 0.9);
    .mask-content {
        position: absolute;
        right: 51px;
        top: 58px;
        .mask-text {
            background: #fff;
            padding: 6px 16px;
            border-radius: 10px;
            font-size: 14px;
            line-height: 22px;
            text-align: center;
            width: fit-content;
            box-sizing: border-box;
            border: 1px solid #DCDCDC;
            position: relative;
            z-index: 10px;
            &::after {
                content: '';
                position: absolute;
                right: 24px;
                top: -10px;
                width: 0;
                height: 0;
                border-right: 5px solid transparent;
                border-top: 5px solid transparent;
                border-left: 5px solid transparent;
                border-bottom: 5px solid #fff;
            }
        }
    }
}
.weather-info {
    width: 100%;
    // height: 58px;
    height: 80px;
    border-radius: 14px;
    border: 0.5px solid #ffffff;
    background: linear-gradient(180deg, #89CBFF 0%, #2199F8 100%);
    box-sizing: border-box;
    transition: height 0.3s ease-in-out;
    overflow: hidden;

    &.is-garden {
        border-radius: 8px;
        box-shadow: 0px -2px 4px 0px #0000000D;
        // height: 130px;
        height: 96px;
    }

    &.no-weather {
        height: auto;
        position: relative;
    }

    &.no-farm {
        height: 80px;

        &.expanded {
            height: 312px;
        }
    }

    &.expanded {
        height: 362px;
    }

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

    &.farm-list {
        height: 94px;
    }

    .flex-center {
        display: flex;
        align-items: center;
    }

    .header {
        display: flex;
        align-items: flex-end;
        justify-content: space-between;

        .header-left {
            width: 100%;

            .address-select {
                .select-garden {
                    width: fit-content;
                    max-width: 170px;
                    margin-right: 8px;
                    margin-bottom: 10px;

                    .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;
                        }
                    }
                }

                .btn-wrap {
                    position: absolute;
                    right: 10px;
                    top: 8px;
                    display: flex;
                    gap: 8px;
                }

                .add-garden {
                    font-size: 12px;
                    color: #2199f8;
                    padding: 3px 10px;
                    border: 1px solid rgba(33, 153, 248, 0.5);
                    border-radius: 25px;
                    display: flex;
                    align-items: center;
                }

                .gray-btn {
                    color: #919191;
                    border: 1px solid rgba(145, 145, 145, 0.5);
                }
            }

            .farm-name {
                font-size: 16px;
                color: #1D2129;
                background: #fff;
                padding: 2px 0 4px 12px;
            }

            .temperature {
                padding-left: 10px;
                width: 100%;
                box-sizing: border-box;
                position: relative;
                background: #fff;

                .temperature-number {
                    font-size: 38px;
                    position: relative;
                    margin: 0 8px;

                    &::after {
                        content: "°";
                        font-size: 10px;
                        position: absolute;
                        right: -6px;
                        top: 2px;
                    }
                }

                .temperature-text {
                    .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;
                    }

                    .temperature-text-date {
                        color: #1D2129;
                        margin-left: 4px;
                    }
                }
            }

            .report-tabs {
                width: 100%;
                display: flex;
                align-items: center;
                gap: 7px;
                padding: 8px 10px 10px;
                background: #fff;
                box-sizing: border-box;

                .report-tab-item {
                    flex: 1;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    gap: 5px;
                    padding: 5px 8px;
                    font-size: 12px;
                    color: #5A5A5A;
                    border: 0.5px solid rgba(180, 180, 180, 0.4);
                    border-radius: 4px;

                    .report-tab-icon {
                        width: 14px;
                        height: 14px;
                    }

                    .report-tab-label {
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                }
            }
        }

        .header-right {
            width: 84px;
            height: 73px;
        }

        .weather-icon {
            i {
                font-size: 40px;
                color: #a7cffb;
            }
        }
    }

    .garden-tabs {
        width: 100%;
        display: flex;
        align-items: center;

        .garden-item {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            height: 40px;
            width: calc(50% - 17px);

            // width:100px;
            // background: linear-gradient(180deg, #89CBFF 0%, #2199F8 100%);
            &.left-item {
                padding-left: 10px;
                justify-content: flex-start;

                .farm-edit-icon {
                    width: 16px;
                    height: 16px;
                    color: #2199F8;
                    flex-shrink: 0;
                    margin-left: 2px;
                }
            }

            &.right-item {
                padding-right: 10px;
                z-index: 9999999;
            }

            &.active {
                background: #fff;

                // background: linear-gradient(360deg, #FFFFFF 30.18%, #FFFFFF 82.87%, #D3ECFF 106.69%);
                .current-name {
                    color: #2199F8;
                }
            }

            .current-name {
                font-size: 18px;
                color: #fff;
                font-family: "PangMenZhengDao";
            }

            .current-icon {
                width: 16px;
            }
        }

        .title-block {
            width: 34px;
            height: 40px;
        }
    }

    .farm-filter {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 7px 8px 7px;
        height: 53px;
        box-sizing: border-box;
        background: #ffffff;

        .filter-l {
            ::v-deep {
                .el-input__wrapper {
                    border-radius: 20px;
                }

                .el-input .el-input__icon {
                    margin-right: 3px;
                }
            }
        }

        .filter-r {
            display: flex;
            align-items: center;
            gap: 10px;

            ::v-deep {
                .el-select__wrapper {
                    border-radius: 20px;
                    padding: 4px 6px 4px 10px;
                }
            }
        }
    }

    .weather-chart-container {
        width: 100%;
        height: 100%;
        overflow: hidden;
        padding: 8px 10px 0 10px;
        box-sizing: border-box;
        background: #ffffff;

        .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>
