<template>
    <div class="chart-list">
        <div class="chart-item">
            <chart-box :name="`三门坡镇${selectedCategory.category}占比统计`">
                <div class="box-content">
                    <div class="chart-dom">
                        <pie-chart :chartData="pieChartData" :totalArea="totalArea"></pie-chart>
                    </div>
                    <div class="box-bg">
                        <div class="legend-list">
                            <div class="legend-item" v-for="(item, index) in legendData" :key="index">
                                <span class="dot" :style="{ background: item.color }"></span>
                                <span class="text">
                                    {{ item.name }}
                                    <span class="percent">{{ item.percent }}%</span>
                                    <span class="line">|</span>
                                    <span class="value">{{ item.value }}亩</span>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </chart-box>
        </div>
        <div class="chart-item">
            <chart-box :name="`三门坡镇物候进程分布`">
                <template #title-right>
                    <el-select
                        v-model="selectedPieItem"
                        size="small"
                        style="width: 100px"
                        @change="fetchStatPhenologyAreaRatioForGrain"
                    >
                        <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </template>
                <div class="box-content">
                    <div class="chart-dom">
                        <bar-chart :key="`region-${activeBaseTab}`" :chartData="regionChartData"></bar-chart>
                    </div>
                    <div class="box-bg">{{ regionSummaryText }}</div>
                </div>
            </chart-box>
        </div>
        <div class="chart-item">
            <chart-box :name="`三门坡镇农事调度规划`">
                <template #title-right>
                  <el-select
                      v-model="selectedPieItem"
                      size="small"
                      style="width: 100px"
                      @change="handleSpeciesChange"
                  >
                    <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </template>
                <div class="box-content">
                    <div class="farm-work-list">
                        <div v-if="farmWorkList.length === 0" class="farm-work-empty">暂无数据</div>
                        <div v-else class="farm-work-item" v-for="item in farmWorkList" :key="item.farmWorkId">
                            <div class="farm-work-title">{{ item.title || "-" }}</div>
                            <div class="farm-work-desc">{{ item.description || "-" }}</div>
                        </div>
                    </div>
                    <div class="box-bg">{{ farmWorkSummaryText }}</div>
                </div>
            </chart-box>
        </div>
    </div>
</template>

<script setup>
import chartBox from "@/components/chartBox.vue";
import pieChart from "./pieChart.vue";
import { computed, ref, onMounted, onUnmounted } from "vue";
import barChart from "./barChart.vue";
import eventBus from "@/api/eventBus";

const props = defineProps({
    activeBaseTab: {
        type: String,
        default: "作物分布",
    },
    areaCode: {
        type: String,
        default: "156440000",
    },
    areaName: {
        type: String,
        default: "广东省",
    },
});

// 图表数据
const pieChartData = ref([]);
const totalArea = ref(0);

// 饼图颜色数组（与 chartOption.js 保持一致）
const pieColors = ["#2199F8", "#14C9C9", "#FFCC4B", "#8F46F4", "#FF7878", "#9FDB1D"];

// 图例数据（基于饼图数据计算）
const legendData = computed(() => {
    if (!pieChartData.value || pieChartData.value.length === 0 || totalArea.value === 0) {
        return [];
    }

    return pieChartData.value.map((item, index) => {
        const percent = ((item.value / totalArea.value) * 100).toFixed(2);
        // 从饼图数据中获取颜色（优先使用 itemStyle.color，如果没有则使用默认颜色）
        const color = item.itemStyle?.color || pieColors[index % pieColors.length];
        return {
            color: color,
            name: item.name,
            percent: parseFloat(percent),
            value: Math.round(item.value),
        };
    });
});

// 物候进程分布标题右侧下拉框选中项（来自饼图数据）
const selectedPieItem = ref(null);

// 区域占比图表数据
const regionChartData = ref({
    categories: [], // 区域名称数组
    values: [], // 占比百分比数组
});

// 区域占比摘要文字
const regionSummaryText = ref("暂无数据");

// 农事调度文本列表
const farmWorkList = ref([]);
const farmWorkSummaryText = ref("暂无数据");

onMounted(() => {
    // 监听图例组件的变化事件
    eventBus.on("landUseLegend:change", handleLandUseLegendChange);
});

onUnmounted(() => {
    // 移除事件监听
    eventBus.off("landUseLegend:change", handleLandUseLegendChange);
});

// 处理图例组件变化
const handleLandUseLegendChange = (data) => {
    if (data.category === "作物类型" || data.nonGrain == null) {
        options.value = data.children;
        selectedPieItem.value = data.children[0].id;
    }
    // 更新选中的类别信息
    selectedCategory.value = {
        category: data.category,
        nonGrain: data.nonGrain,
    };
    // 使用新的 nonGrain 重新获取饼图数据
    fetchStatRegionAreaRatio(data.nonGrain);
    handleSpeciesChange();
};

const options = ref([]);
// 当前选中的类别信息
const selectedCategory = ref({
    category: null,
    nonGrain: null,
});

//种植面积占比
const fetchStatRegionAreaRatio = (nonGrain = null) => {
    const params = { statType: nonGrain || 0 };
    VE_API.warning
        .fetchStatAreaRatioByType(params)
        .then((res) => {
            if (res.code === 0 && res.data && res.data.length > 0) {
                // 转换接口数据为饼图格式
                // 饼图数据格式：{ value: 种植面积, name: 物种名称, itemStyle: { color: 颜色 } }
                const chartData = res.data.map((item, index) => ({
                    value: item.plantArea,
                    name: item.name,
                    itemStyle: {
                        color: item.color || pieColors[index % pieColors.length], // 使用接口返回的 color，如果没有则使用默认颜色
                    },
                }));

                if (chartData.length > 0) {
                    // 计算总种植面积
                    const total = chartData.reduce((sum, item) => sum + (item.value || 0), 0);

                    // 更新饼图数据
                    pieChartData.value = chartData;
                    totalArea.value = total;
                } else {
                    // 数据过滤后为空
                    pieChartData.value = [];
                    totalArea.value = 0;
                }
            } else {
                // 接口返回空数据时，清空饼图数据
                pieChartData.value = [];
                totalArea.value = 0;
            }
        })
        .catch((error) => {
            console.error("获取种植面积占比数据失败:", error);
            // 错误时清空数据
            pieChartData.value = [];
            totalArea.value = 0;
        });
};

const fetchFarmWorkDesc = () => {
    if (!selectedPieItem.value) {
        farmWorkList.value = [];
        farmWorkSummaryText.value = "暂无数据";
        return;
    }

    VE_API.warning
        .fetchFarmWorkDesc({ speciesId: selectedPieItem.value })
        .then((res) => {
            if (res.code === 0 && res.data && res.data.length > 0) {
                farmWorkList.value = res.data;
                farmWorkSummaryText.value = `共${res.data.length}条农事调度`;
            } else {
                farmWorkList.value = [];
                farmWorkSummaryText.value = "暂无数据";
            }
        })
        .catch((error) => {
            console.error("获取农事调度描述失败:", error);
            farmWorkList.value = [];
            farmWorkSummaryText.value = "暂无数据";
        });
};

const fetchStatPhenologyAreaRatioForGrain = () => {
    VE_API.warning
        .fetchStatPhenologyAreaRatioForGrain({ speciesId: selectedPieItem.value })
        .then((res) => {
            if (res.code === 0 && res.data && res.data.length > 0) {
                // 转换接口数据为图表格式（物候进程分布）
                // 横轴：作物名称（有物候期则为“作物名(物候期)”），纵轴：面积占比（百分比）
                const categories = res.data.map((item) => item.phenologyName);
                const values = res.data.map((item) => parseFloat((item.areaRatio * 100).toFixed(2)));

                // 更新区域图表数据
                regionChartData.value = {
                    categories,
                    values,
                };

                // 找到最大占比的物候期
                let maxRatio = 0;
                let maxPhenology = "";
                let maxPhenologyName = "";
                res.data.forEach((item) => {
                    if (item.areaRatio > maxRatio) {
                        maxRatio = item.areaRatio;
                        maxPhenology = item.speciesName;
                        maxPhenologyName = item.phenologyName;
                    }
                });

                // 更新摘要文字
                if (maxPhenology) {
                    const maxPercent = (maxRatio * 100).toFixed(1);
                    regionSummaryText.value = `当前有${maxPercent}%的${maxPhenology}进入${maxPhenologyName}`;
                } else {
                    regionSummaryText.value = "暂无数据";
                }
            } else {
                // 接口返回空数据时，清空区域图表数据
                regionChartData.value = {
                    categories: [],
                    values: [],
                };
                regionSummaryText.value = "暂无数据";
            }
        })
        .catch(() => {
            // 错误时也清空数据
            regionChartData.value = {
                categories: [],
                values: [],
            };
            regionSummaryText.value = "暂无数据";
        });
};

const handleSpeciesChange = () => {
    fetchStatPhenologyAreaRatioForGrain();
    fetchFarmWorkDesc();
};
</script>

<style lang="scss" scoped>
.chart-list {
    width: 100%;
    height: 100%;
    .chart-item {
        width: 100%;
        height: 285px;
        box-sizing: border-box;
        margin-bottom: 10px;
        background: rgba(35, 35, 35, 1);
        border: 1px solid #444444;
        border-radius: 4px;
        .box-content {
            width: 100%;
            height: 100%;
        }
        .chart-dom {
            height: calc(100% - 61px);
            width: 100%;
        }
        .farm-work-list {
            height: calc(100% - 61px);
            width: 100%;
            overflow-y: auto;
            padding: 8px;
            box-sizing: border-box;
            color: #fff;
            font-size: 12px;
            line-height: 1.5;

            .farm-work-empty {
                color: rgba(255, 255, 255, 0.6);
            }

            .farm-work-item {
                padding-bottom: 8px;
                margin-bottom: 8px;
                border-bottom: 1px dashed rgba(255, 255, 255, 0.15);

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

            .farm-work-title {
                font-weight: 600;
                margin-bottom: 2px;
            }

            .farm-work-desc {
                color: rgba(255, 255, 255, 0.8);
                white-space: pre-wrap;
            }
        }
        .box-bg {
            border-radius: 2px 2px 0 0;
            font-size: 12px;
            padding: 6px 8px;
            box-sizing: border-box;
            height: 61px;
            overflow-y: auto;
            background: linear-gradient(180deg, rgb(85, 85, 85, 0.4) 0%, rgb(35, 35, 35, 1) 100%);

            .legend-list {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 8px 12px;
                height: 100%;
                font-size: 12px;

                .legend-item {
                    display: flex;
                    align-items: center;
                    gap: 6px;
                    line-height: 12px;

                    .dot {
                        width: 5px;
                        height: 5px;
                        border-radius: 50%;
                        flex-shrink: 0;
                    }

                    .text {
                        color: rgba(255, 255, 255, 1);
                        font-size: 12px;
                        white-space: nowrap;
                        .percent {
                            padding: 0 10px;
                        }
                        .line {
                            color: rgba(255, 255, 255, 0.2);
                            padding-right: 10px;
                        }
                    }
                }
            }
        }
    }
}
</style>
