<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="expert-home">
            <div class="expert-banner" @click="handleExpertBannerClick">
                <img class="expert-banner-img" src="@/assets/img/home/banner.png" alt="">
                <div class="expert-desc">
                    <img class="expert-desc-icon" src="@/assets/img/home/expert-text.png" alt="">
                    <div class="desc-text"><span class="dotted"></span>您有一条长势报告，请查看</div>
                </div>
            </div>
        </div>
        <knowledge-card />
        <!-- <template v-if="userType == 2">
        </template> -->
        <!-- <template v-else>
            <AgriculturalDynamics />
        </template> -->
    </div>
    <tip-popup
        v-model:show="showTipPopup"
        type="warning"
        text="请设置"
        highlightText="种植方案"
        buttonText="去设置"
        @confirm="handleBtn"
        :closeOnClickOverlay="false"
        :zIndex="9999"
    />

    <!-- 农事执行弹窗 -->
    <agri-execute-popup
        v-model:show="showAgriExecutePopup"
        :popupData="agriExecuteData"
        @later="handleAgriLater"
        @executed="handleAgriExecuted"
    />

    <!-- 提醒时间选择弹窗 -->
    <reminder-time-popup
        v-model:show="showReminderTimePopup"
        @confirm="handleReminderTimeConfirm"
    />

    <!-- 执行轨迹弹窗 -->
    <execute-trace-popup
        v-model:show="showExecuteTracePopup"
        @later="handleTraceLater"
        @confirm="handleTraceConfirm"
    />
</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 agriExecutePopup from "@/components/popup/agriExecutePopup.vue";
import reminderTimePopup from "@/components/popup/reminderTimePopup.vue";
import executeTracePopup from "@/components/popup/executeTracePopup.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=请设置您的种植方案");
};

// 农事执行弹窗相关
const showAgriExecutePopup = ref(false); // 农事执行弹窗
const agriExecuteData = ref({
    expertName: "韦帮稳",
    title: "梢期杀虫 农事执行",
    abnormalText: "由于***异常的出现,由于***异常的出现,由于***异常的出现,由于***异常的出现,",
    imageUrl: "",
    laterBtn:true,
});

// const agriExecuteData = ref({
//     expertName: "韦帮稳",
//     title: "农情互动任务采集",
//     abnormalText: "现在已处于 花芽分化期 ，上传照片反馈您的荔枝生长近况",
//     imageUrl: "",
//     executedButtonText:'查看任务',
// });

// 农事执行弹窗相关方法
const handleAgriLater = () => {
    console.log("稍后执行");
    // 可以在这里添加稍后执行的逻辑
    // 关闭当前弹窗
    showAgriExecutePopup.value = false;
    // 显示提醒时间选择弹窗
    showReminderTimePopup.value = true;
};

const handleAgriExecuted = () => {
    console.log("我已执行");
    // 关闭当前弹窗
    showAgriExecutePopup.value = false;
    // 显示执行轨迹弹窗
    showExecuteTracePopup.value = true;
};

// 提醒时间选择弹窗相关
const showReminderTimePopup = ref(false);

// 确认提醒时间
const handleReminderTimeConfirm = (time) => {
    console.log("选择的提醒时间:", time);
    // 可以在这里添加提交提醒时间的逻辑
};

// 执行轨迹弹窗相关
const showExecuteTracePopup = ref(false);

// 稍后上传
const handleTraceLater = () => {
    console.log("稍后上传");
    // 可以在这里添加稍后上传的逻辑
};

// 确认上传
const handleTraceConfirm = () => {
    console.log("确认上传");
    // 可以在这里添加确认上传的逻辑
};

// 显示农事执行弹窗的方法（可以在需要的地方调用）
const showAgriExecute = (data = {}) => {
    agriExecuteData.value = {
        expertName: data.expertName || "韦帮稳",
        expertAvatar: data.expertAvatar || "",
        title: data.title || "梢期杀虫 农事执行",
        abnormalText: data.abnormalText || "由于***异常的出现,由于***异常的出现,由于***异常的出现,由于***异常的出现,",
        imageUrl: data.imageUrl || "",
        showMarker: data.showMarker !== undefined ? data.showMarker : true,
    };
    showAgriExecutePopup.value = true;
};

//判断是否存在可用方案
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();
    if (userType.value != 2) {
        checkExistsEnabledScheme()
    }
    getBannerList();
    // 检测是否从创建农场页面成功返回
    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 handleExpertBannerClick = () => {
    router.push("/consult?userId=81881");
};

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%);
    background: linear-gradient(180deg, #F9F9F9 0%, #F0F8FF 31.47%, #F9F9F9 46.81%, #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);
        top: 8px;
        left: 10px;
        z-index: 3;
    }
    .expert-home {
        padding: 90px 10px 10px 10px;
        .expert-banner {
            position: relative;
            .expert-banner-img {
                width: 100%;
            }
            .expert-desc {
                position: absolute;
                bottom: 0;
                left: 0;
                width: 100%;
                border-radius: 0 0 8px 8px;
                padding: 6px 8px;
                box-sizing: border-box;
                background: rgba(0, 0, 0, 0.5);
                color: #fff;
                backdrop-filter: blur(4px);
                display: flex;
                align-items: center;
                justify-content: space-between;
                .expert-desc-icon {
                    width: 91px;
                }
                .desc-text {
                    font-family: "PangMenZhengDao";
                    font-size: 14px;
                    color: #fff;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    gap: 6px;
                    .dotted {
                        width: 5px;
                        height: 5px;
                        background: #fff;
                        border-radius: 50%;
                    }
                }
            }
        }
    }
}
</style>
