<template>
	<div class="datasub">
		<div class="left">
			<div class="left-title">
				<img src="./assets/icon01.png" alt="" />
				<div class="tit">各类型合作限制政策对比</div>
				<el-select v-model="value" placeholder="Select" class="select" @change="getCoopRestrictionCompareData">
					<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</div>
            <div class="left-main">
                <div class="left-main-echarts" ref="leftChartRef"></div>
            </div>
		</div>
		<div class="right">
			<div class="right-title">
				<img src="./assets/icon02.png" alt="" />
				<div class="tit">各领域规则分布情况</div>
                <el-select v-model="value1" placeholder="Select" class="select" @change="getCoopRestrictionDomainData">
					<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</div>
            <div class="right-main">
                <div class="right-main-echarts" ref="rightChartRef"></div>
            </div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import * as echarts from "echarts";
import { getCoopRestrictionCompare, getCoopRestrictionDomain } from "@/api/coopRestriction/coopRestriction";

// 合作限制-各领域规则分布情况接口
const coopRestrictionDomain = ref([]);
const getCoopRestrictionDomainData = async () => {
	try {
		const res = await getCoopRestrictionDomain({
			year: value1.value
		});
		if (res && res.code === 200) {
			coopRestrictionDomain.value = res.data || [];
		}
	} catch (error) {
		console.error("获取合作限制各领域规则分布情况数据失败:", error);
	} 
};


// 合作限制-各类型合作限制政策对比接口
const coopRestrictionCompare = ref([]);
const getCoopRestrictionCompareData = async () => {
	try {
		const res = await getCoopRestrictionCompare({
			years: value.value
		});
		if (res && res.code === 200) {
			coopRestrictionCompare.value = res.data || [];
		}
	} catch (error) {
		console.error("获取合作限制各类型合作限制政策对比数据失败:", error);
	} 
};

watch(() => coopRestrictionCompare.value, () => {
    initLeftChart();
}, { deep: true });

watch(() => coopRestrictionDomain.value, () => {
    initRightChart();
}, { deep: true });

const value = ref(10);
const value1 = ref("2026");
const options = [
	{ value: 1, label: "近一年" },
	{ value: 2, label: "近两年" },
	{ value: 3, label: "近三年" },
	{ value: 4, label: "近四年" },
	{ value: 5, label: "近五年" },
	{ value: 10, label: "近十年" },
	{ value: 15, label: "近十五年" },
	{ value: 20, label: "近二十年" }
];
const options1 = [
    {
        value: "2026",
        label: "2026年"
    },
	{
		value: "2025",
		label: "2025年"
	},
	{
		value: "2024",
		label: "2024年"
	},
    {
        value: "2023",
        label: "2023年"
    },
    {
        value: "2022",
        label: "2022年"
    },
    {
        value: "2021",
        label: "2021年"
    },
    {
        value: "2020",
        label: "2020年"
    },
    {
        value: "2019",
        label: "2019年"
    },
    {
        value: "2018",
        label: "2018年"
    },
    {
        value: "2017",
        label: "2017年"
    },
    {
        value: "2016",
        label: "2016年"
    },
    {
        value: "2015",
        label: "2015年"
    },
    {
        value: "2014",
        label: "2014年"
    },
    {
        value: "2013",
        label: "2013年"
    },
    {
        value: "2012",
        label: "2012年"
    },
    {
        value: "2011",
        label: "2011年"
    },
    {
        value: "2010",
        label: "2010年"
    }
];

const leftChartRef = ref(null);
let leftChart;
const rightChartRef = ref(null);
let rightChart;

const initLeftChart = () => {
    if (!leftChartRef.value) return;
    if (leftChart) leftChart.dispose();
    leftChart = echarts.init(leftChartRef.value);
    
    // 处理动态数据
    const rawData = coopRestrictionCompare.value;
    const yearsSet = new Set();
    const typesSet = new Set();
    
    rawData.forEach(item => {
        yearsSet.add(item.LIMITDATE);
        typesSet.add(item.TYPENAME);
    });
    
    const years = Array.from(yearsSet).sort();
    const types = Array.from(typesSet);
    
    // 如果没有数据，给一些默认年份展示
    const finalYears = years.length > 0 ? years : ["2020", "2021", "2022", "2023", "2024", "2025"];
    
    // 定义颜色配置，确保线条色与阴影色对应
    const colorMap = [
        { line: "#2f7ae5", start: "rgba(47, 122, 229, 0.3)", end: "rgba(47, 122, 229, 0.05)" },
        { line: "#29c0b1", start: "rgba(41, 192, 177, 0.3)", end: "rgba(41, 192, 177, 0.05)" },
        { line: "#e45f5f", start: "rgba(228, 95, 95, 0.3)", end: "rgba(228, 95, 95, 0.05)" },
        { line: "#7b5de6", start: "rgba(123, 93, 230, 0.3)", end: "rgba(123, 93, 230, 0.05)" }
    ];
    
    const series = types.map((type, index) => {
        const data = finalYears.map(year => {
            const found = rawData.find(item => item.TYPENAME === type && item.LIMITDATE === year);
            return found ? found.TYPECOUNT : 0;
        });
        
        // 根据索引获取颜色配置，超出范围则循环使用
        const colorConfig = colorMap[index % colorMap.length];

        return {
            name: type,
            type: "line",
            smooth: false,
            data: data,
            symbol: "circle",
            symbolSize: 6,
            lineStyle: {
                color: colorConfig.line,
                width: 2
            },
            itemStyle: {
                color: colorConfig.line
            },
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: colorConfig.start },
                    { offset: 1, color: colorConfig.end }
                ])
            }
        };
    });

    const option = {
        color: colorMap.map(c => c.line),
        grid: { left: 40, right: 24, top: 46, bottom: 36 },
        tooltip: { trigger: "axis", axisPointer: { type: "line" } },
        legend: { 
            top: 8, 
            icon: "circle", 
            itemWidth: 12, 
            itemHeight: 12, 
            itemGap: 24, 
            textStyle: { 
                color: "rgb(95, 101, 108)", 
                fontSize: 16, 
                fontFamily: "Microsoft YaHei", 
                fontWeight: 400, 
                lineHeight: 24 
            }, 
            data: types 
        },
        xAxis: { 
            type: "category", 
            boundaryGap: false, 
            data: finalYears, 
            axisLine: { show: false }, 
            axisTick: { show: false }, 
            axisLabel: { 
                color: "rgba(132, 136, 142, 1)", 
                fontSize: 14, 
                lineHeight: 22, 
                fontFamily: "Microsoft YaHei", 
                fontWeight: 400 
            } 
        },
        yAxis: { 
            type: "value", 
            min: 0, 
            splitLine: { show: true, lineStyle: { color: "#e6e6e6", type: "dashed" } }, 
            axisLine: { show: false }, 
            axisTick: { show: false }, 
            axisLabel: { 
                color: "rgba(132, 136, 142, 1)", 
                fontSize: 14, 
                fontFamily: "Microsoft YaHei", 
                fontWeight: 400, 
                lineHeight: 22 
            } 
        },
        series: series
    };
    leftChart.setOption(option);
    window.addEventListener("resize", handleResize);
};

const handleResize = () => { if (leftChart) leftChart.resize(); if (rightChart) rightChart.resize(); };

const initRightChart = () => {
    if (!rightChartRef.value) return;
    if (rightChart) rightChart.dispose();
    rightChart = echarts.init(rightChartRef.value);

    const rawData = coopRestrictionDomain.value;

    // 数据为空处理
    if (!rawData || rawData.length === 0) {
        rightChart.setOption({
            graphic: {
                type: 'text',
                left: 'center',
                top: 'middle',
                style: {
                    text: '暂无数据',
                    fill: '#999',
                    fontSize: 16
                }
            }
        });
        return;
    }
    
    // 1. 动态提取所有领域（雷达图的维度）
    const domainsSet = new Set();
    const typesSet = new Set();
    rawData.forEach(item => {
        domainsSet.add(item.AREA);
        typesSet.add(item.COOPERTYPE);
    });

    const domains = Array.from(domainsSet);
    const types = Array.from(typesSet);

    // 2. 构造指示器（Indicator），自动计算 Max 值
    const indicators = domains.map(domain => {
        const domainData = rawData.filter(item => item.AREA === domain);
        const maxVal = Math.max(...domainData.map(d => d.COOPERTYPECOUNT), 5); // 最小给个5
        return { name: domain, max: Math.ceil(maxVal * 1.2) }; // 留 20% 的余量
    });

    // 3. 构造 Series 数据
    const colorMap = ["#2f7ae5", "#29c0b1", "#e45f5f", "#7b5de6"];
    const seriesData = types.map((type, index) => {
        const dataValues = domains.map(domain => {
            const found = rawData.find(item => item.COOPERTYPE === type && item.AREA === domain);
            return found ? found.COOPERTYPECOUNT : 0;
        });

        return {
            name: type,
            value: dataValues,
            itemStyle: { color: colorMap[index % colorMap.length] },
            areaStyle: { color: colorMap[index % colorMap.length], opacity: 0.1 }
        };
    });

    const option = {
        color: colorMap,
        legend: { 
            top: 8, 
            icon: "circle", 
            itemWidth: 12, 
            itemHeight: 12, 
            itemGap: 24, 
            textStyle: {
                color: "rgb(95, 101, 108)",
                fontSize: 16,
                fontFamily: "Microsoft YaHei",
                fontWeight: 400,
                lineHeight: 24
            },
            data: types
        },
        radar: {
            center: ["50%", "55%"],
            radius: "65%",
            indicator: indicators.length > 0 ? indicators : [
                { name: "暂无数据", max: 100 },
                { name: "暂无数据", max: 100 },
                { name: "暂无数据", max: 100 }
            ],
            axisName: {
                color: "rgba(132, 136, 142, 1)",
                fontSize: 14,
                fontWeight: 400
            },
            splitLine: { lineStyle: { color: ["#e6e6e6"] } },
            splitArea: { show: false }
        },
        series: [{
            type: "radar",
            data: seriesData
        }]
    };
    rightChart.setOption(option);
    window.addEventListener("resize", handleResize);
};

onMounted(() => { 
    // 合作限制-各类型合作限制政策对比接口
    getCoopRestrictionCompareData();
    // 合作限制-各领域规则分布情况接口
    getCoopRestrictionDomainData();
    initLeftChart();
    initRightChart();
});
onBeforeUnmount(() => { window.removeEventListener("resize", handleResize); if (leftChart) { leftChart.dispose(); leftChart = null; } if (rightChart) { rightChart.dispose(); rightChart = null; } });
</script>

<style lang="scss" scoped>
* {
	margin: 0;
	padding: 0;
}
.datasub {
	width: 1600px;
	height: 460px;
	display: flex;
	justify-content: space-between;
	.left {
		width: 1063px;
		height: 460px;
		margin-right: 16px;
		border-radius: 10px;
		// border: 1px solid rgb(234, 236, 238);
		box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
		background-color: #fff;
		.left-title {
			width: 1063px;
			height: 48px;
			border-bottom: 1px solid rgb(234, 236, 238);
			position: relative;
			img {
				width: 19px;
				height: 19px;
				position: absolute;
				top: 16px;
				left: 21px;
			}
			.tit {
				margin-left: 60px;
				height: 48px;
				padding: 11px 0;
				font-size: 20px;
				font-weight: 700;
				font-family: "Microsoft YaHei";
				line-height: 26px;
				color: rgb(5, 95, 194);
			}
            .select {
                width: 150px;
                height: 28px;
                padding: 0px 12px;
                position: absolute;
                top: 11px;
                right: 31px;
            }
		}
        .left-main {
            width: 1063px;
            height: 412px;
            padding: 15px 23px 25px 38px;
            .left-main-echarts {
                width: 1002px;
                height: 372px;
            }
        }
	}
	.right {
		width: 521px;
		height: 460px;
		border-radius: 10px;
		// border: 1px solid rgb(234, 236, 238);
		box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
		background-color: #fff;
		.right-title {
			width: 521px;
			height: 48px;
			border-bottom: 1px solid rgb(234, 236, 238);
			position: relative;
			img {
				width: 19px;
				height: 19px;
				position: absolute;
				top: 16px;
				left: 21px;
			}
			.tit {
				margin-left: 60px;
				height: 48px;
				padding: 11px 0;
				font-size: 20px;
				font-weight: 700;
				font-family: "Microsoft YaHei";
				line-height: 26px;
				color: rgb(5, 95, 194);
			}
            .select {
                width: 150px;
                height: 28px;
                padding: 0px 12px;
                position: absolute;
                top: 11px;
                right: 31px;
            }
		}
        .right-main {
            width: 521px;
            height: 421px;
            padding: 15px 50px 25px 50px;
            .right-main-echarts {
                width: 420px;
                height: 372px;
            }
        }
	}
}
</style>
