<template>
    <div class="home-index" :style="{ height: `calc(100vh - ${tabBarHeight}px)` }">
        <div class="banner-wrap" @click="handleBannerClick">
            <img class="banner-img" :src="bannerObj?.media?.[0]" alt="" />
            <div class="banner-title">  
                <span class="van-multi-ellipsis--l2">{{ bannerObj?.title }}</span>
            </div>
        </div>
        <!-- 天气遮罩 -->
        <div class="weather-mask" v-show="isExpanded" @click="handleMaskClick"></div>
        <!-- 天气 -->
        <weather-info
            ref="weatherInfoRef"
            class="weather-info"
            @weatherExpanded="weatherExpanded"
            :isGarden="false"
            @changeGarden="changeGarden"
        ></weather-info>
        <div class="farm-monitor-container" :class="{ 'farmer-role': userType == 2 }">
            <div class="farm-monitor-left" @click="handleCardClick(monitorCards.left)">
                <div class="title">
                    <span>{{ monitorCards.left.title }}</span>
                    <el-icon class="icon" v-if="userType == 2"><ArrowRightBold /></el-icon>
                </div>
                <div class="content">{{ monitorCards.left.content }}</div>
                <div class="arrow" v-if="userType != 2">
                    <el-icon class="icon"><ArrowRightBold /></el-icon>
                </div>
            </div>
            <div class="farm-monitor-right">
                <div
                    v-for="(item, index) in monitorCards.right"
                    :key="index"
                    class="right-item"
                    :class="{ expert: index === 1 }"
                    @click="handleCardClick(item)"
                >
                    <div class="title">
                        <span>{{ item.title }}</span>
                        <el-icon class="icon"><ArrowRightBold /></el-icon>
                    </div>
                    <div class="content">{{ item.content }}</div>
                </div>
            </div>
        </div>
        <template v-if="userType == 2">
            <knowledge-card />
        </template>
        <template v-else>
            <AgriculturalDynamics />
        </template>
    </div>
    <tip-popup
        v-model:show="showTipPopup"
        type="warning"
        text="请设置"
        highlightText="种植方案"
        buttonText="去设置"
        @confirm="handleBtn"
        :closeOnClickOverlay="false"
        :zIndex="9999"
    />
</template>

<script setup>
import { ref, computed, onActivated, onMounted } from "vue";
import { useStore } from "vuex";
import weatherInfo from "@/components/weatherInfo.vue";
import AgriculturalDynamics from "./components/AgriculturalDynamics.vue";
import { useRouter, useRoute } from "vue-router";
import wx from "weixin-js-sdk";
import tipPopup from "@/components/popup/tipPopup.vue";
import knowledgeCard from "./components/knowledgeCard.vue";

const store = useStore();
const tabBarHeight = computed(() => store.state.home.tabBarHeight);
const router = useRouter();
const route = useRoute();

const showTipPopup = ref(false);
const handleBtn = () => {
    router.push("/plan?pageType=plant&headerTitle=请设置您的种植方案");
};

//判断是否存在可用方案
async function checkExistsEnabledScheme() {
    const { data } = await VE_API.home.existsEnabledScheme({containerId:null});
    if(!data && localStorage.getItem("SET_USER_CUR_ROLE") == 2) {
        showTipPopup.value = true;
    }
}

const gardenId = ref(null);
const isGarden = ref(false);
const changeGarden = ({ id }) => {
    gardenId.value = id;
    getExpertByFarmId();
};

const expertInfo = ref({});
const getExpertByFarmId = () => {
    VE_API.home.getExpertByFarmId({ farmId: gardenId.value }).then(({ data }) => {
        expertInfo.value = data || {};
        sessionStorage.setItem("expertId", data.appUserId);
    });
};

// 监测卡片数据
const monitorCards = ref({
    left: {
        title: "农情采集",
        content: "精准监测  科学决策",
        route: "/pest",
    },
    right: [
        {
            title: "病虫识别",
            content: "智能识别  快速诊断",
            route: "/pest",
        },
        // {
        //     title: "新增客户",
        //     content: "农情先知  高效管理",
        //     route: "/create_farm?type=client&isReload=true&from=home",
        // },
    ],
});

// 卡片点击事件
const handleCardClick = (card) => {
    const dropdownGardenItem = ref({
        organId: 766,
        periodId: 1,
        name: "荔博园",
    });
    if (card.title === "农情采集") {
        dropdownGardenItem.value.page = "create_farm";
        wx.miniProgram.navigateTo({
            url: `/pages/subPages/new_recognize/index?gardenData=${JSON.stringify(dropdownGardenItem.value)}`,
        });
    } else if (card.title === "病虫识别") {
        dropdownGardenItem.value.page = "album_recognize";
        wx.miniProgram.navigateTo({
            url: `/pages/subPages/new_recognize/index?gardenData=${JSON.stringify(dropdownGardenItem.value)}`,
        });
    } else {
        router.push(card.route);
    }
};

onActivated(() => {
    getManagerList();
    checkExistsEnabledScheme()
    getBannerList();
    isGarden.value = Boolean(localStorage.getItem("isGarden"));
    // 检测是否从创建农场页面成功返回
    if (route.query.showSuccess === "true") {
        // 清除URL参数，避免刷新页面时再次显示弹窗
        router.replace({
            path: "/home",
            query: { reload: route.query.reload },
        });
    }
});

const userType = ref(localStorage.getItem("USER_TYPE"));
onMounted(() => {
    if (userType.value != 2) {
        monitorCards.value.right.push({
            title: "新增客户",
            content: "农情先知  高效管理",
            route: "/create_farm?type=client&isReload=true&from=home",
        });
    }
});


// 查询当前农资店的成员列表（只保留有"任务接单"权限的成员）
const getManagerList = async () => {
    const { data } = await VE_API.mine.listManagerList({ onlyExecutor: true });
    if (data && data.length > 0) {
        // 过滤 permissionList 中包含"任务接单"的成员，并过滤掉超管（role为1）
        const executorList = data.filter((item) => item.role !== 1);
        sessionStorage.setItem("executorList", JSON.stringify(executorList));
    }
};

const bannerObj = ref({});
const getBannerList = () => {
    const params = {
        page: 1,
        limit: 1,
        topicId: 5,
    };
    VE_API.home.warningPageList(params).then(({ data }) => {
        bannerObj.value = data[0] || {};
    });
};

const isExpanded = ref(false);
const weatherInfoRef = ref(null);
const weatherExpanded = (isExpandedValue) => {
    isExpanded.value = isExpandedValue;
};

// 点击遮罩时收起天气
const handleMaskClick = () => {
    if (weatherInfoRef.value && weatherInfoRef.value.toggleExpand) {
        weatherInfoRef.value.toggleExpand();
    }
};

const handleBannerClick = () => {
    router.push(`/warning_detail?id=${bannerObj.value.id}`);
};
</script>

<style scoped lang="scss">
.home-index {
    width: 100%;
    height: 100vh;
    overflow: auto;
    position: relative;
    background: linear-gradient(180deg, #f4f9fd 0%, #f9f9f9 100%);
    .banner-wrap {
        width: 100%;
        height: 200px;
        position: relative;
        z-index: 1;
        .banner-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .banner-title {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            padding: 10px 12px 34px 12px;
            box-sizing: border-box;
            background: linear-gradient(
                180deg,
                rgba(102, 102, 102, 0) -64.3%,
                rgba(0, 0, 0, 0.0074) -1.43%,
                rgba(0, 0, 0, 0.684747) 39.67%,
                rgba(0, 0, 0, 0.74) 40.09%,
                rgba(0, 0, 0, 0.74) 83.2%
            );
            color: #fff;
            font-weight: bold;
            backdrop-filter: blur(2px);
        }
    }
    .weather-mask {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.52);
        z-index: 2;
    }
    .weather-info {
        width: calc(100% - 20px);
        position: absolute;
        top: calc(200px - 28px);
        left: 10px;
        z-index: 3;
    }
    .farm-monitor-container {
        padding-top: 30px;
        display: flex;
        align-items: center;
        margin: 10px;
        gap: 6px;
        height: 134px;
        &.farmer-role {
            height: 104px;
            .farm-monitor-left {
                background: url("@/assets/img/home/farm-bg-4.png") no-repeat center center / 100% 100%;
            }
            .farm-monitor-right {
                .right-item {
                    background: url("@/assets/img/home/farm-bg-5.png") no-repeat center center / 100% 100%;
                }
            }
        }
        .farm-monitor-left,
        .farm-monitor-right {
            .title {
                font-size: 16px;
                color: #1d2129;
                font-weight: 500;
                .icon {
                    font-size: 12px;
                    margin-left: 2px;
                }
            }
            .content {
                margin-top: 6px;
                font-size: 12px;
                color: rgba(29, 33, 41, 0.5);
                line-height: 1.5;
            }
            .arrow {
                border-radius: 5px;
                background: #fff;
                display: flex;
                align-items: center;
                justify-content: center;
                width: 34px;
                height: 25px;
                margin-top: 10px;
                font-size: 11px;
            }
        }
        .farm-monitor-left {
            flex: 1;
            height: 100%;
            margin-top: 2px;
            padding: 25px 12px;
            box-sizing: border-box;
            max-width: 170px;
            background: url("@/assets/img/home/farm-bg-1.png") no-repeat center center / 105% 106%;
        }
        .farm-monitor-right {
            flex: 1;
            height: 100%;
            display: flex;
            flex-direction: column;
            .right-item {
                padding: 10px 12px;
                box-sizing: border-box;
                display: flex;
                flex-direction: column;
                justify-content: center;
                flex: 1;
                background: url("@/assets/img/home/farm-bg-2.png") no-repeat center center / 100% 100%;
            }
            .expert {
                background: url("@/assets/img/home/farm-bg-3.png") no-repeat center center / 100% 100%;
            }
        }
    }
}
</style>
