<template>
    <custom-header v-if="isHeaderShow" name="农场详情"></custom-header>
    <div class="monitor-index" :style="{ height: `calc(100vh - ${tabBarHeight}px)` }">
        <!-- 天气遮罩 -->
        <div class="weather-mask" v-show="isExpanded" @click="handleMaskClick"></div>
        <!-- 天气 -->
        <weather-info ref="weatherInfoRef" class="weather-info" @weatherExpanded="weatherExpanded"
            @changeGarden="changeGarden" :isGarden="true" :gardenId="defaultGardenId"></weather-info>
        <!-- 作物档案 -->
        <div class="archives-time-line">
            <div class="archives-time-line-header" @click="handleJump">
                <div class="line-title">作物档案</div>
                <el-date-picker style="width: 110px" v-model="date" type="year" placeholder="全部日期" />
            </div>
            <div class="archives-time-line-content">
                <div class="report-box">
                    <div class="box-content">
                        <div class="box-title" @click="handleReportClick">
                            <span>农情互动报告</span>
                            <el-icon>
                                <CaretRight />
                            </el-icon>
                        </div>
                        <span class="box-text">当前处于蒂蛀虫高发期，请及时采集</span>
                    </div>
                    <img src="@/assets/img/monitor/report-icon.png" alt="" class="report-icon" />
                </div>
                <div class="time-line">
                    <archives-farm-time-line :farmId="gardenId"></archives-farm-time-line>
                </div>
            </div>
        </div>
    </div>

    <tip-popup v-model:show="showFarmPopup" type="success" text="农场领取成功"
        :overlay-style="{ 'backdrop-filter': 'blur(4px)' }" :closeOnClickOverlay="false" :zIndex="9999" />

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

<script setup>
import customHeader from "@/components/customHeader.vue";
import { ref, computed, onActivated, onDeactivated, onMounted } from "vue";
import { useStore } from "vuex";
import { Badge, List } from "vant";
import weatherInfo from "@/components/weatherInfo.vue";
import { useRouter, useRoute } from "vue-router";
import farmInfoPopup from "../home/components/farmInfoPopup.vue";
import tipPopup from "@/components/popup/tipPopup.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ArchivesFarmTimeLine from "@/components/pageComponents/ArchivesFarmTimeLine.vue";
import agriExecutePopup from "@/components/popup/agriExecutePopup.vue";

const handleJump = () =>{
    router.push('/create_farm?type=farmer&expertMiniUserId=81881')
}

const showAgriExecutePopup = ref(false); // 农事执行弹窗
const agriExecuteData = ref({});
const handleAgriExecuted = () => {
    showAgriExecutePopup.value = false;
    // router.push("/interaction_list?expertMiniUserId=81881&oldUser=true");
    router.push("/interaction_list?expertMiniUserId=81881");
};

const checkHasUnrepliedTriggeredInteraction = async () => {
    const { data } = await VE_API.home.hasUnrepliedTriggeredInteraction({ farmId: localStorage.getItem("selectedFarmId") });
    if (data && data.id != null) {
        agriExecuteData.value = {
            title: data.interactionTypeName,
            abnormalText: data.reason,
            exampleImg: JSON.parse(data.exampleImagesJson)[0],
            executedButtonText: '开始采集',
        };
        showAgriExecutePopup.value = true;
    }
};

const showFarmPopup = ref(false); // 农场领取成功弹窗
const date = ref(new Date());

const defaultGardenId = ref(null);
const isHeaderShow = ref(false);
const isDefaultFarm = ref(false);
const weatherInfoRef = ref(null);

onActivated(() => {
    // 用来接收我的农场跳转过来的农场详情逻辑
    if (route.query.isHeaderShow) {
        isHeaderShow.value = true;
        defaultGardenId.value = route.query.farmId;
        // 统一转换为布尔值
        isDefaultFarm.value = route.query.defaultFarm === "true" || route.query.defaultFarm === true;
    }
});

const receiveFarm = (json) => {
    VE_API.monitor
        .receiveFarm({
            agriculturalStoreId: json.agriculturalStoreId,
            farmId: json.farmId,
        })
        .then((res) => {
            if (res.code === 0) {
                showFarmPopup.value = true;
                defaultGardenId.value = json.farmId;
            } else {
                ElMessage.warning(res.msg);
            }
            // 清空路由参数
            router.replace({ path: route.path });
        });
};

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

const farmInfoRef = ref(null);

function toFarmInfo() {
    farmInfoRef.value.handleShow();
}

// 功能卡片数据
const functionCards = ref([
    {
        title: "农事规划",
        route: "/plan",
    },
    {
        title: "农场报告",
        status: "最新",
        route: "/farm_report",
        className: "blue",
    },
    {
        title: "农事方案",
        route: "/agricultural_plan",
    },
    {
        title: "复核成效",
        status: "最新",
        route: "/review-results",
        className: "yellow",
    },
]);

const getStayCount = () => {
    VE_API.monitor
        .getCountByStatusAndFarmId({
            farmId: gardenId.value,
            startStatus: 1,
            endStatus: 3,
        })
        .then((res) => {
            functionCards.value[0].status = null;
            if (res.data && res.data != 0) {
                functionCards.value[0].status = res.data + " 待完成";
            }
        });
};

// 实时播报数据
const broadcastList = ref([]);
const loading = ref(false);
const finished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

const getBroadcastList = async (page = 1, isLoadMore = false) => {
    if (!gardenId.value) {
        loading.value = false;
        return;
    }

    // 如果正在加载，直接返回（避免重复请求）
    if (loading.value) {
        return;
    }

    loading.value = true;
    try {
        const res = await VE_API.monitor.broadcastPage({
            farmId: gardenId.value,
            limit: pageSize.value,
            page: page,
        });

        const newData = res.data || [];
        if (isLoadMore) {
            broadcastList.value = [...broadcastList.value, ...newData];
        } else {
            broadcastList.value = newData;
        }

        // 判断是否还有更多数据
        if (newData.length < pageSize.value) {
            finished.value = true;
        } else {
            finished.value = false;
            // 如果未完成，页码+1，为下次加载做准备
            currentPage.value = page + 1;
        }
    } catch (error) {
        console.error("获取播报列表失败:", error);
        finished.value = true;
    } finally {
        // 确保 loading 状态被正确设置为 false
        loading.value = false;
    }
};

// 滚动加载更多
const onLoad = async () => {
    if (finished.value || loading.value) return;

    // 判断是否是首次加载（页码为1）
    const isLoadMore = currentPage.value > 1;
    const pageToLoad = currentPage.value;

    // 加载数据（页码会在 getBroadcastList 成功后自动更新）
    await getBroadcastList(pageToLoad, isLoadMore);
};

// 卡片点击事件
const handleCardClick = (card) => {
    const params = {
        farmId: gardenId.value,
    };
    router.push({
        path: card.route,
        query: { ...params, miniJson: JSON.stringify(params) },
    });
};

// 播报相关事件
const isSpeaking = ref(false);
const speechSynthesis = window.speechSynthesis;

const handleBroadcast = () => {
    if (isSpeaking.value) {
        // 如果正在播放，则停止
        speechSynthesis.cancel();
        isSpeaking.value = false;
        return;
    }

    // 构建播报文本
    let broadcastText = "实时播报：";

    if (broadcastList.value.length === 0) {
        broadcastText += "暂无更多播报";
    } else {
        broadcastList.value.forEach((item, index) => {
            broadcastText += `${index + 1}、${item.title}。${item.content}。`;
        });
    }

    // 创建语音合成对象
    const utterance = new SpeechSynthesisUtterance(broadcastText);

    // 设置语音参数
    utterance.lang = "zh-CN";
    utterance.rate = 0.8; // 语速
    utterance.pitch = 1; // 音调
    utterance.volume = 1; // 音量

    // 播放开始事件
    utterance.onstart = () => {
        isSpeaking.value = true;
    };

    // 播放结束事件
    utterance.onend = () => {
        isSpeaking.value = false;
    };

    // 播放错误事件
    utterance.onerror = (event) => {
        isSpeaking.value = false;
        console.error("播报错误:", event.error);
    };

    // 开始播报
    speechSynthesis.speak(utterance);
};

// 组件卸载时停止语音播放
onDeactivated(() => {
    showFarmPopup.value = false;
    isDefaultFarm.value = false;
    if (isSpeaking.value) {
        speechSynthesis.cancel();
        isSpeaking.value = false;
    }
});

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

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

const gardenId = ref(store.state.home.gardenId);

// 初始化加载数据
onMounted(() => {
    if (gardenId.value) {
        currentPage.value = 1;
        finished.value = false;
        broadcastList.value = [];
        getStayCount();
        checkHasUnrepliedTriggeredInteraction();
    }
});

const changeGarden = ({ id }) => {
    gardenId.value = id;
    // 更新 store 中的状态
    store.commit("home/SET_GARDEN_ID", id);
    // 重置分页状态
    currentPage.value = 1;
    finished.value = false;
    broadcastList.value = [];
    getStayCount();
    getBroadcastList(1, false);
    checkHasUnrepliedTriggeredInteraction();
};

function handlePage(url) {
    const query = {
        farmId: gardenId.value,
    };
    if (url === "/message_list") {
        query.from = "monitor";
    }
    router.push({
        path: url,
        query: query,
    });
}

function handleReportClick() {
    router.push({
        path: "/growth_report",
        query: { miniJson: JSON.stringify({ id: gardenId.value }) },
    });
}
</script>

<style scoped lang="scss">
.monitor-index {
    width: 100%;
    height: 100%;
    padding: 13px 10px;
    box-sizing: border-box;
    background: linear-gradient(180deg, #f9f9f9 0%, #f0f8ff 31.47%, #f9f9f9 46.81%, #f9f9f9 69.38%, #f9f9f9 100%);

    .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;
        z-index: 3;
    }

    .archives-time-line {
        position: relative;
        margin-top: 96px;
        height: calc(100% - 90px);

        .archives-time-line-header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .line-title {
                position: relative;
                padding-left: 14px;
                font-size: 16px;

                &::before {
                    content: "";
                    position: absolute;
                    left: 5px;
                    top: 50%;
                    transform: translateY(-50%);
                    width: 4px;
                    height: 15px;
                    background: #2199f8;
                    border-radius: 20px;
                }
            }
        }

        .archives-time-line-content {
            margin-top: 10px;
            height: calc(100% - 35px);
            background: #fff;
            border-radius: 8px;
            padding: 10px;
            box-sizing: border-box;

            .report-box {
                background: linear-gradient(120deg, #eef8ff, #bbe3ff);
                border-radius: 4px;
                padding: 6px 0 0 16px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 12px;

                .box-content {
                    .box-title {
                        font-size: 16px;
                        color: #2199f8;
                        font-weight: 500;
                        margin-bottom: 4px;
                        display: flex;
                        align-items: center;
                    }

                    .box-text {
                        color: #4e5969;
                    }
                }

                .report-icon {
                    width: 120px;
                    height: 85px;
                }
            }

            .time-line {
                height: calc(100% - 100px);
            }
        }
    }
}
</style>
