<template>
    <div class="chart-list">
        <div class="chart-item weather-item">
            <chart-box name="气象预警">
                <template #title-right>
                    <div class="button-group">
                        <div class="button" @click="handlePlay">直播</div>
                        <div class="button" @click="gybg">果园报告</div>
                        <div class="button" @click="fightTask">一键飞巡</div>
                    </div>
                </template>
                <div class="base-wrap">
                    <div class="base-item" v-for="(item, index) in baseData.labels || []" :key="index">
                        <div class="label">{{ item }}风险</div>
                        <div class="value">
                            {{
                                baseData.valueMaxList && baseData.valueMaxList[index]
                                    ? baseData.valueMaxList[index].toFixed(0)
                                    : 0
                            }}<span>%</span>
                        </div>
                    </div>
                </div>
                <weatherChart class="line-chart"></weatherChart>
            </chart-box>
        </div>
        <div class="chart-item phenology">
            <chart-box :name="ecologyObj.name || '生态指标'">
                <template #title-right>
                    <tabs
                        :list="ecologyObj.btnGroup || []"
                        :keyStr="ecologyObj.name || '生态指标'"
                        :active="activeKey"
                        @handleActive="handleActiveTab"
                    ></tabs>
                </template>
                <bar-chart
                    class="bar-chart"
                    styleName="styleName1"
                    :xData="ecologyObj.xData || []"
                    :yData="ecologyObj.yData || []"
                ></bar-chart>
                <div class="tips box-bg">
                    <span v-html="ecologyObj.text || '暂无数据'"></span>
                    <!-- <div class="text" v-for="(item, index) in ecologyObj.text" :key="index">
                      {{ item.key }}：<span>{{ item.val }}</span>
                  </div> -->
                </div>
            </chart-box>
        </div>
        <div class="chart-item evaluate">
            <chart-box :name="growObj.name || '生长指标'">
                <template #title-right>
                    <tabs
                        :list="growObj.btnGroup || []"
                        :keyStr="growObj.name || '生长指标'"
                        :active="activeKey"
                        @handleActive="handleActiveTab"
                    ></tabs>
                </template>
                <div class="content">
                    <bar-chart
                        style="width: 57%"
                        styleName="styleName1"
                        :xData="growObj.xData || []"
                        :yData="growObj.yData || []"
                    ></bar-chart>
                    <div class="box-bg">
                        <span v-html="growObj.text || '暂无数据'"></span>
                    </div>
                </div>
            </chart-box>
        </div>
        <div class="chart-item phenology">
            <chart-box :name="diseasesObj.name || '病虫指标'">
                <template #title-right>
                    <tabs
                        :list="diseasesObj.btnGroup || []"
                        :keyStr="diseasesObj.name || '病虫指标'"
                        :active="activeKey"
                        @handleActive="handleActiveTab"
                    ></tabs>
                </template>
                <bar-chart
                    class="bar-chart"
                    styleName="styleName1"
                    :xData="diseasesObj.xData || []"
                    :yData="diseasesObj.yData || []"
                ></bar-chart>
                <div class="tips box-bg">
                    <span v-html="diseasesObj.text || '暂无数据'"></span>
                </div>
            </chart-box>
        </div>
    </div>
    <popup class="popup-video" v-model:show="showVideo" :close-on-click-overlay="false">
        <div class="video-cont">
            <div class="video-header">
                <el-select class="video-select" v-model="selectValue" @change="handleSelectChange">
                    <el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <div class="close" @click="handleClose">
                    <el-icon size="28" color="#000"><Close /></el-icon>
                </div>
            </div>
            <LivePlayer class="video" ref="player" :videoUrl="flvURL" live loop autoplay />
        </div>
    </popup>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import chartBox from "@/components/chartBox.vue";
import tabs from "./tabs.vue";
import weatherChart from "./weatherChart.vue";
import barChart from "@/components/charts/barChart.vue";
import { Popup } from "vant";
import LivePlayer from "@liveqing/liveplayer-v3";
import eventBus from "@/api/eventBus";
const baseData = ref({});

const connectionBtn = ref([]);

const getBaseData = () => {
    connectionBtn.value = ["孢子监测", "虫情监测"];
    const point = sessionStorage.getItem("point");
    const farmId = sessionStorage.getItem("farmId");

    if (!farmId) {
        console.warn("farmId not found in sessionStorage");
        return;
    }

    VE_API.mini_farm
        .weather_warning_land_check({ farmId, point })
        .then((res) => {
            if (res && res.data) {
                baseData.value = res.data;
            } else {
                // 设置默认数据
                baseData.value = {
                    labels: ["温度", "湿度", "风速"],
                    valueMaxList: [0, 0, 0],
                };
            }
        })
        .catch((error) => {
            // 设置默认数据
            baseData.value = {
                labels: ["温度", "湿度", "风速"],
                valueMaxList: [0, 0, 0],
            };
        });

    // 获取气象图表数据
    //   VE_API.mini_farm.gardenItemChart({point}).then(res =>{
    //     minData.value = res.data.weatherData.map(item =>item.tempMin)
    //     lineYdata.value = res.data.weatherData.map(item =>item.tempMax)
    //   })
};

onMounted(() => {
    //选项子项监听事件
    eventBus.on("handleTabItem", handleTabItem);
    eventBus.on("area:id", areaId);
    // 监听组件激活事件
    eventBus.on("component:activated", handleComponentActivated);

    // 初始化数据
    initializeData();
});

// 组件激活处理函数
const handleComponentActivated = (componentName) => {
    if (componentName === "homePage") {
        // 重新初始化数据
        initializeData();
    }
};

// 初始化数据函数
const initializeData = () => {
    const farmId = sessionStorage.getItem("farmId");
    const areaId = sessionStorage.getItem("areaId");

    if (farmId) {
        // 设置 farmIdVal 和 regionId，确保后续 API 调用有正确的参数
        farmIdVal.value = farmId;
        regionId.value = areaId;

        getBaseData();
        getListByFarmId(farmId, areaId);
    } else {
        console.warn("farmId 不存在，无法初始化数据");
        // 设置默认数据
        baseData.value = {
            labels: ["温度", "湿度", "风速"],
            valueMaxList: [0, 0, 0],
        };
    }
};

onUnmounted(() => {
    eventBus.off("handleTabItem", handleTabItem);
    eventBus.off("area:id", areaId);
    eventBus.off("component:activated", handleComponentActivated);
});

const reportData = ref([]);
const lastActiveTab = ref({ id: null, name: null });

const handleActiveTab = ({ name, id }) => {
    // 防止重复调用相同的指标
    if (lastActiveTab.value.id === id && lastActiveTab.value.name === name) {
        return;
    }

    lastActiveTab.value = { id, name };
    getIndicatorReport(id, name);
};

const menuList = ref([]);

const regionId = ref(null);
const farmIdVal = ref(null);
function areaId({ areaId, farmId }) {
    regionId.value = areaId;
    farmIdVal.value = farmId;
    menuList.value = [];
    getBaseData();
    getListByFarmId(farmId, areaId);
}

const getListByFarmId = (farmId, areaId) => {
    VE_API.home
        .listByFarmId({ farmId })
        .then((res) => {
            if (res.data?.length) {
                // 过滤掉果园总览，获取其他数据
                const filteredData = res.data.filter((item) => item.name !== "果园总览");

                // 批量处理指标数据
                filteredData.forEach((item) => {
                    // 更新指标对象的基本信息
                    updateIndicatorObj(item.name, {
                        name: item.name,
                        btnGroup: item.monitorItems,
                    });

                    // 请求详细数据
                    if (item.monitorItems && item.monitorItems.length > 0) {
                        getIndicatorReport(item.monitorItems[0].id, item.name);
                    }
                });
            } else {
                console.warn("没有获取到指标数据");
            }
        })
        .catch((error) => {
            console.error("获取指标列表失败:", error);
        });
};

const getIndicatorReport = (id, indicatorName) => {
    // 验证必需参数
    if (!farmIdVal.value) {
        console.error(`获取 ${indicatorName} 指标数据失败: farmId 为空`);
        updateIndicatorObj(indicatorName, {
            xData: [],
            yData: [],
            text: "farmId 参数缺失",
        });
        return;
    }

    if (!id) {
        console.error(`获取 ${indicatorName} 指标数据失败: monitorIndicatorId 为空`);
        updateIndicatorObj(indicatorName, {
            xData: [],
            yData: [],
            text: "指标ID 参数缺失",
        });
        return;
    }

    VE_API.home
        .statByLegendRanges({
            farmId: farmIdVal.value,
            regionId: regionId.value || null,
            monitorIndicatorId: id,
        })
        .then((res) => {
            if (res && res.data) {
                processIndicatorData(indicatorName, res.data);
            } else {
                console.warn(`${indicatorName} 指标数据为空`);
                // 设置默认数据
                updateIndicatorObj(indicatorName, {
                    xData: [],
                    yData: [],
                    text: "暂无数据",
                });
            }
        })
        .catch((error) => {
            console.error(`获取 ${indicatorName} 指标数据失败:`, error);
            // 设置默认数据
            updateIndicatorObj(indicatorName, {
                xData: [],
                yData: [],
                text: "数据获取失败",
            });
        });
};

const activeKey = ref("");
function handleTabItem(e) {
    activeKey.value = e;
}

// 病虫测报
const diseasesObj = ref({});

// 生长指标
const growObj = ref({});

//生态指标
const ecologyObj = ref({});

// 指标对象映射 - 必须在所有指标对象定义之后
const indicatorObjMap = {
    生态指标: ecologyObj,
    生长指标: growObj,
    病虫指标: diseasesObj,
};

// 通用的指标对象数据更新方法
const updateIndicatorObj = (indicatorName, data) => {
    const targetObj = indicatorObjMap[indicatorName];
    if (targetObj) {
        // 使用Object.assign确保响应式更新
        Object.assign(targetObj.value, data);
    }
};

// 通用的接口数据处理方法
const processIndicatorData = (indicatorName, apiData) => {
    const processedData = {
        xData: apiData?.data?.map((item) => item.name) || [],
        yData: apiData?.data?.map((item) => item.count) || [],
        text: apiData?.description,
    };

    updateIndicatorObj(indicatorName, processedData);

    // 将数据添加到reportData中，如果已存在则更新
    const existingIndex = reportData.value.findIndex((item) => item.key === indicatorName);
    if (existingIndex !== -1) {
        reportData.value[existingIndex] = {
            key: indicatorName,
            obj: apiData,
        };
    } else {
        reportData.value.push({
            key: indicatorName,
            obj: apiData,
        });
    }
};

const gybg = () => {
    VE_API.farm_files.last({ farmId: sessionStorage.getItem("farmId"), key: "pdf_report" }).then(({ data }) => {
        eventBus.emit("homePage:gybg", { filename: data.path, title: "果园报告" });
    });
};

const fightTask = () => {
    ElMessageBox.confirm("是否确认执行一键飞巡任务?", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            VE_API.home.startFightTask({ farmId: sessionStorage.getItem("farmId") }).then((res) => {
                if (res.code === 0) {
                    ElMessage.success("一键飞巡成功");
                } else {
                    ElMessage.error(res.msg);
                }
            });
        })
        .catch(() => {});
};

const selectValue = ref(1)
const selectOptions = [
  {
    value: 1,
    label: '机库',
  },
  {
    value: 0,
    label: '无人机',
  },
]
const handleSelectChange = () => {
    flvURL.value = "";
    VE_API.home.closeStreamConverters({ farmId: sessionStorage.getItem("farmId"), converterId: converterId.value }).then(() => {
        handlePlay();
    });
};

const showVideo = ref(false);
const flvURL = ref("");
const converterId = ref("");
const handlePlay = () => {
    VE_API.home.startStreamConverters({ farmId: sessionStorage.getItem("farmId"),isDock:selectValue.value }).then((res) => {
        if (res.code === 0) {
            if (res.data.url.length) {
                showVideo.value = true;
                flvURL.value = res.data.url[0];
                converterId.value = res.data.converterId;
            } else {
                ElMessage.warning("暂无直播");
            }
        }
    });
};

const handleClose = () => {
    showVideo.value = false;
    flvURL.value = "";
    VE_API.home.closeStreamConverters({ farmId: sessionStorage.getItem("farmId"), converterId: converterId.value,isDock:selectValue.value });
};
</script>

<style lang="scss" scoped>
.chart-list {
    width: calc(100% - 54px - 10px);
    height: 100%;
    padding: 8px 8px 8px 0;
    box-sizing: border-box;
    position: relative;
    overflow-y: auto;

    .chart-item {
        width: 100%;
        // height: calc(100% / 4.15);
        height: 228px;
        box-sizing: border-box;
        margin-bottom: 10px;
        &.weather-item {
            height: 260px;
            .button-group {
                display: flex;
                // .button + .button{
                //     margin-left: 2px;
                // }
            }
        }
        .box-flex {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            .box-card {
                background: rgba(255, 255, 255, 0.1);
                border-radius: 5px;
                width: 292px;
                height: 92px;
                display: flex;
                align-items: center;
                justify-content: center;
                flex-direction: column;
                .box-desc {
                    font-size: 16px;
                    font-family: "PangMenZhengDao";
                    margin-bottom: 8px;
                }
                .box-button {
                    font-size: 13px;
                    border-radius: 20px;
                    padding: 3px 27px;
                    cursor: pointer;
                    border: 1px solid rgba(255, 255, 255, 0.45);
                    background: linear-gradient(180deg, #ffd887, #ed9e1e);
                }
            }
        }
        .button {
            border: 1px solid rgba(255, 255, 255, 0.4);
            border-radius: 4px;
            padding: 2px 10px;
            cursor: pointer;
        }
        &.chart-item:last-child {
            margin: 0;
        }
        .base-wrap {
            width: 100%;
            height: 56px;
            margin-top: 4px;
            display: flex;
            justify-content: space-evenly;
            .base-item {
                width: 110px;
                height: 100%;
                font-size: 12px;
                text-align: center;
                box-sizing: border-box;
                color: #f3c11d;
                display: flex;
                flex-direction: column;
                align-items: center;
                margin: 0 12px;
                background: url("@/assets/images/home/scale-bg.png") no-repeat center center / 100% 100%;
                .label {
                    width: 85px;
                    height: 16px;
                    line-height: 16px;
                    color: #fff;
                    background: url("@/assets/images/home/label-bg.png") no-repeat center center / 100% 100%;
                }
                .value {
                    font-size: 18px;
                    font-family: "PangMenZhengDao";
                    span {
                        font-size: 12px;
                    }
                }
            }
        }
        .line-chart {
            height: calc(100% - 56px);
        }
        .box-bg {
            border-radius: 2px 2px 0 0;
            font-size: 12px;
            padding: 3px 6px;
            box-sizing: border-box;
            font-family: Arial, Helvetica, sans-serif;
            overflow-y: auto;
            background: linear-gradient(180deg, rgb(85, 85, 85, 0.4) 0%, rgb(35, 35, 35, 1) 100%);
            .text {
                position: relative;
                padding-left: 10px;
                &::before {
                    content: "";
                    position: absolute;
                    left: 0;
                    top: 8px;
                    width: 3px;
                    height: 3px;
                    border-radius: 50%;
                    background: #fff;
                }
                span {
                    color: rgba(255, 255, 255, 0.4);
                    line-height: 1.7;
                }
            }
        }
        &.phenology {
            .bar-chart {
                width: 100%;
                height: calc(100% - 75px);
            }
            .tips {
                margin-top: 10px;
                width: 100%;
                height: 65px;
            }
        }
        &.evaluate {
            height: 220px;
            .content {
                width: 100%;
                height: calc(100% - 10px);
                display: flex;
                align-items: center;
                justify-content: space-between;
                .text {
                    font-weight: 400;
                    padding: 8px 0 4px 5px;
                    text-indent: 2em;
                    margin-left: 8px;
                    span {
                        color: #ffd489;
                    }
                }
            }
            .text-list {
                width: 100%;
                height: 33px;
                display: flex;
                align-items: flex-start;
                justify-content: space-between;
                .text-item {
                    display: flex;
                    align-items: center;

                    .circle {
                        width: 4px;
                        height: 4px;
                        background: rgba(255, 255, 255, 0.44);
                        border-radius: 50%;
                        margin-right: 6px;
                    }
                    .txt {
                        font-size: 12px;
                        span {
                            color: #ffd489;
                        }
                    }
                }
            }
        }
        &.connection {
            height: max-content;
            ::v-deep {
                .carousel-item {
                    img {
                        border-radius: 5px;
                    }
                    min-height: 250px;
                }
            }
            .stauts {
                position: absolute;
                left: 118px;
                top: -30px;
                background: rgba(255, 212, 137, 0.1);
                border-radius: 2px;
                padding: 5px;
                height: 19px;
                line-height: 19px;
                box-sizing: border-box;
                color: #f2d677;
                font-size: 10px;
                display: flex;
                align-items: center;
                span {
                    display: inline-block;
                    width: 5px;
                    height: 5px;
                    border-radius: 50%;
                    background: #f2d677;
                    margin-right: 5px;
                }
                &.off {
                    color: #bdbdbd;
                    span {
                        background: #bdbdbd;
                    }
                }
            }
        }
    }
}
.popup-video {
    width: 100%;
    background: transparent;
    .video-cont {
        width: 70%;
        margin: auto;
        background: #fff;
        padding: 10px;
        border-radius: 10px;
        .video-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 10px;
            .video-select{
                width: 200px;
            }
            .close {
                text-align: right;
            }
        }
        .video {
            width: 100%;
            height: 100%;
        }
    }
}
</style>
