<template>
    <div class="monitor-index" :style="{ height: `calc(100vh - ${tabBarHeight}px)` }">
        <!-- 天气遮罩 -->
        <div class="weather-mask" v-show="isExpanded"></div>
        <!-- 天气 -->
        <weather-info
            ref="weatherInfoRef"
            class="weather-info"
            @weatherExpanded="weatherExpanded"
            @changeGarden="changeGarden"
            :isGarden="true"
        ></weather-info>
        <!-- 操作按钮 -->
        <div class="operation-button">
            <div class="button-group">
                <div class="button-item" @click="toFarmInfo">
                    <img class="button-icon" src="@/assets/img/tab_bar/home-active.png" alt="" />
                    <span>基本信息</span>
                </div>
                <div class="button-item" @click="handlePage('/farm_photo')">
                    <img class="button-icon" src="@/assets/img/home/photo-icon.png" alt="" />
                    <span>农场相册</span>
                </div>
            </div>
            <badge dot :offset="[-4, 5]" @click="handlePage('/message_list')">
                <div class="add-farm-button">
                    <img class="icon" src="@/assets/img/monitor/notice.png" alt="" />
                    <span>农场消息</span>
                </div>
            </badge>
        </div>
        <!-- 功能卡片网格 -->
        <div class="function-cards">
            <div
                v-for="(card, index) in functionCards"
                :key="index"
                class="function-card"
                @click="handleCardClick(card)"
            >
                <div class="card-title">{{ card.title }}</div>
                <img :src="require(`@/assets/img/monitor/grid-${index + 1}.png`)" :alt="card.title" />
                <div class="card-status" :class="card.className" v-if="card.status">
                    {{ card.status }}
                </div>
            </div>
        </div>

        <!-- 实时播报 -->
        <div class="realtime-broadcast">
            <div class="broadcast-header">
                <div class="header-left">
                    <span class="broadcast-title">实时播报</span>
                    <!-- <div class="broadcast-action" :class="{ speaking: isSpeaking }" @click="handleBroadcast">
                        <img class="speaker-icon" src="@/assets/img/monitor/speaker.png" alt="播报" />
                        <span class="broadcast-text">{{ isSpeaking ? '停止播报' : '点击播报' }}</span>
                    </div> -->
                </div>
            </div>

            <list
                v-model:loading="loading"
                :finished="finished"
                finished-text="暂无更多播报"
                @load="onLoad"
                class="broadcast-list"
            >
                <div
                    v-for="(item, index) in broadcastList"
                    :key="index"
                    class="broadcast-item"
                >
                    <div class="item-content">
                        <div class="content-top">
                            <div class="item-icon">
                                <img src="@/assets/img/monitor/bell.png" alt="通知" />
                            </div>
                            <div class="item-title">{{ item.title }}</div>
                        </div>
                        <div class="item-status van-multi-ellipsis--l2">{{ item.content }}</div>
                    </div>
                    <div class="item-zone" v-if="item.regionId">
                        <div class="point"></div>
                        <span>{{ item.regionId }}</span>
                    </div>
                </div>
            </list>
        </div>
    </div>
    <!-- 农场信息 -->
    <farm-info-popup ref="farmInfoRef" :farmId="gardenId"></farm-info-popup>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, onActivated } 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";

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

const farmInfoRef = ref(null);
const weatherInfoRef = 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 = (page = 1, isLoadMore = false) => {
    loading.value = true;
    VE_API.monitor
        .broadcastPage({
            farmId: gardenId.value,
            limit: pageSize.value,
            page: page,
        })
        .then((res) => {
            const newData = res.data || [];
            if (isLoadMore) {
                broadcastList.value = [...broadcastList.value, ...newData];
            } else {
                broadcastList.value = newData;
            }

            // 判断是否还有更多数据
            if (newData.length < pageSize.value) {
                finished.value = true;
            }

            loading.value = false;
        })
        .catch(() => {
            loading.value = false;
        });
};

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

    currentPage.value += 1;
    getBroadcastList(currentPage.value, true);
};
// 卡片点击事件
const handleCardClick = (card) => {
    const params = {
        farmId: gardenId.value,
        containerId: card.containerId,
    };
    router.push({
        path: card.route,
        query: 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);
};

// 组件激活时检查是否需要刷新农场列表
onActivated(() => {
    weatherInfoRef.value.getFarmList();
});

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

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

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

function handlePage(url) {
    router.push({
        path: url,
    });
}
</script>

<style scoped lang="scss">
.monitor-index {
    width: 100%;
    height: 100%;
    padding: 13px 10px;
    box-sizing: border-box;
    background-image: linear-gradient(250deg, #cbebff 0%, #dceffd 50%, #e7f3fd 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;
    }
    .operation-button {
        position: absolute;
        top: 117px;
        left: 12px;
        width: calc(100% - 24px);
        z-index: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 12px;
        font-weight: 500;
        .button-group {
            display: flex;
            align-items: center;
            justify-content: space-between;
            .button-item {
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 4px;
                color: rgba(0, 0, 0, 0.8);
                background-color: #fff;
                border: 1px solid #f2f2f2;
                .button-icon {
                    width: 13px;
                    height: 13px;
                }
            }
            .button-item:first-child {
                margin-right: 10px;
            }
        }
        .add-farm-button {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 4px;
            color: rgba(0, 0, 0, 0.8);
            background: rgba(33, 153, 248, 0.1);
            border: 1px solid #fff;
            .icon {
                width: 14px;
                height: 14px;
            }
        }
        .button-item,
        .add-farm-button {
            border-radius: 25px;
            padding: 8px 12px;
        }
    }

    .function-cards {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 10px;
        margin-top: 155px;

        .function-card {
            background: #fff;
            border-radius: 12px;
            padding: 20px 0;
            box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            img {
                width: 40px;
                height: 40px;
            }
            .card-title {
                font-size: 16px;
                font-weight: 500;
                color: #1d2129;
            }
            .card-status {
                position: absolute;
                top: -5px;
                right: 0;
                padding: 1px 4px;
                border-radius: 6px 8px 8px 2px;
                font-size: 11px;
                background: #2199f8;
                color: #fff;
                &.yellow {
                    background: #fdcf4c;
                }
                &.blue {
                    background: #8a87ff;
                }
            }
        }
    }

    .realtime-broadcast {
        margin-top: 10px;
        background: #fff;
        border-radius: 8px;
        box-sizing: border-box;
        padding: 12px;

        .broadcast-header {
            display: flex;
            align-items: center;
            margin-bottom: 4px;

            .header-left {
                display: flex;
                align-items: center;
                gap: 12px;

                .broadcast-title {
                    font-size: 16px;
                    font-weight: 600;
                    color: #1d2129;
                }

                .broadcast-action {
                    display: flex;
                    align-items: center;
                    gap: 4px;
                    cursor: pointer;
                    transition: all 0.3s ease;

                    &:hover {
                        opacity: 0.8;
                    }

                    .speaker-icon {
                        width: 16px;
                        height: 14px;
                        transition: transform 0.3s ease;
                    }

                    .broadcast-text {
                        color: #2199f8;
                        font-size: 14px;
                    }

                    // 播放状态下的样式
                    &.speaking {
                        .speaker-icon {
                            animation: pulse 1s infinite;
                        }
                        .broadcast-text {
                            color: #ff4757;
                        }
                    }
                }

                @keyframes pulse {
                    0% { transform: scale(1); }
                    50% { transform: scale(1.1); }
                    100% { transform: scale(1); }
                }
            }
        }

        .broadcast-list {
            .broadcast-item {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 12px 0;
                border-bottom: 1px solid rgba(0, 0, 0, 0.1);

                &:last-child {
                    border-bottom: none;
                }

                .item-content {
                    width: calc(100% - 50px);
                    .content-top {
                        display: flex;
                        align-items: center;
                    }
                    .item-icon {
                        margin-right: 8px;
                        background: rgba(255, 0, 0, 0.05);
                        width: 26px;
                        height: 26px;
                        border-radius: 50%;
                        display: flex;
                        align-items: center;
                        justify-content: center;

                        img {
                            width: 18px;
                            height: 12px;
                        }
                    }

                    .item-title {
                        color: #1d2129;
                    }

                    .item-status {
                        margin-top: 3px;
                        font-size: 13px;
                        color: rgba(29, 33, 41, 0.5);

                        .countdown {
                            color: #ff7254;
                        }
                    }
                }

                .item-zone {
                    background: rgba(241, 243, 246, 0.5);
                    color: #7c7e81;
                    font-size: 12px;
                    padding: 3px 11px;
                    border-radius: 25px;
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    .point {
                        width: 6px;
                        height: 6px;
                        border-radius: 50%;
                        background: rgba(124, 126, 129, 0.5);
                    }
                }
            }
        }
    }
}
</style>
