<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="value1" placeholder="Select" class="select">
					<el-option v-for="item in options1" :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="value2" placeholder="Select" class="select1">
					<el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
				<el-select v-model="value" placeholder="Select" class="select">
					<el-option v-for="item in options" :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 { getAreaDistribution, getEntityChangeTrend } from '@/api/ruleRestriction/index.js'

const value = ref(10);
const value1 = ref("2025");
const value2 = ref("01");
const options = [
  {
    value: 10,
    label: "近十年"
  },
  {
    value: 5,
    label: "近五年"
  }
];
const options1 = [
  {
    value: "2025",
    label: "2025年"
  },
  {
    value: "2024",
    label: "2024年"
  }
];
const options2 = [
  {
    value: "01",
    label: "行政令"
  },
  {
    value: "02",
    label: "法案"
  }
];

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


const colors = [
  {
    name: '集成电路',
    value: "rgba(105, 177, 255, 1)",
  },
  {
    name: '新一代通信网络',
    value: "rgba(135, 232, 222, 1)",
  },
  {
    name: '人工智能',
    value: "rgba(255, 192, 105, 1)",
  },
  {
    name: '能源',
    value: "rgba(89, 126, 247, 1)",
  },
  {
    name: '先进制造',
    value: "rgba(214, 228, 255, 1)",
  },
  {
    name: '生物科技',
    value: "rgba(255, 120, 117, 1)",
  },
  {
    name: '航空航天',
    value: "rgba(179, 127, 235, 1)",
  },
  {
    name: '新材料',
    value: "rgba(255, 163, 158, 1)",
  }
];
const initLeftDonut = async () => {
  if (!leftChartRef.value) return;
  if (leftChart) leftChart.dispose();
  leftChart = echarts.init(leftChartRef.value);
  let data = []

  try {
    const params = {
      year: value1.value
    }
    const res = await getAreaDistribution(params);
    if (res && res.code === 200) {
      console.log('----getAreaDistribution', res.data)
      for (let i = 0; i < res.data.length; i++) {
        let item = {
          name: '',
          value: 0
        }

        item.name = res.data[i].AREANAME
        item.value = res.data[i].AREACOUNT
        item.itemStyle = {
          color: getColor(colors, item.name)
        }
        data.push(item)
      }
    }
  } catch (error) {
    console.error("获取限制领域分布情况接口失败:", error);
  }
  // console.log('----data', data)
  // const data = [
  //     { name: "集成电路", value: 50 },
  //     { name: "人工智能", value: 46 },
  //     { name: "通信网络", value: 40 },
  //     { name: "能源", value: 32 },
  //     { name: "先进制造", value: 31 },
  //     { name: "生物科技", value: 31 },
  //     { name: "航空航天", value: 30 },
  //     { name: "新材料", value: 24 }
  // ];

  const option = {
    tooltip: { trigger: "item", formatter: ({ name, value, percent }) => `${name}<br/>${value}项 ${percent}%` },
    series: [{
      type: "pie",
      radius: [96, 120],
      center: ["50%", "50%"],
      avoidLabelOverlap: true,
      itemStyle: { borderWidth: 0 },
      label: {
        show: true,
        position: "outside",
        alignTo: 'edge',
        formatter: ({ name, value, percent }) => `{name|${name}}  {value|${value}项}  {percent|${percent}%}`,
        minMargin: 5,
        edgeDistance: 10,
        lineHeight: 15,
        rich: {
          name: { fontSize: 16, fontFamily: "Microsoft YaHei", fontWeight: 700, lineHeight: 24, color: "rgb(59, 65, 75)" },
          value: { fontSize: 14, fontFamily: "Microsoft YaHei", fontWeight: 400, lineHeight: 22, color: "rgb(95, 101, 108)" },
          percent: { fontSize: 14, fontFamily: "Microsoft YaHei", fontWeight: 400, lineHeight: 22, color: "rgb(95, 101, 108)" }
        }
      },
      labelLine: {
        show: true,
        length: 30,
        length2: 0,
        maxSurfaceAngle: 80
      },
      labelLayout: function (params) {
        const isLeft = params.labelRect.x < leftChart.getWidth() / 2;
        const points = params.labelLinePoints;
        // 导航线终点在标签下方
        const lineY = params.labelRect.y + params.labelRect.height;
        points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
        points[2][1] = lineY;
        points[1][1] = lineY;
        return {
          labelLinePoints: points
        };
      },
      data: data.map((d, i) => ({
        ...d,
        labelLine: { lineStyle: { color: getColor(colors, d.name), width: 1 } }
      }))
    }]
  };
  leftChart.setOption(option);
};

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

  // 首先根据现在的年份，然后再根据所选的年限生成years
  const currentYear = new Date().getFullYear()
  // 再根据年限往前倒退
  const years = []
  for (let i = value.value - 1; i >= 0; i--) {
    const year = currentYear - i + ''
    years.push(year)
  }

  console.log('----years', years)

  // 根据后端生成的数据然后填充数据
  const seriesData = []
  let maxValue = 0
  try {
    const params = {
      year: value.value,
      type: value2.value
    }
    const res = await getEntityChangeTrend(params);
    console.log('-----getEntityChangeTrendList res', res)
    if (res && res.code === 200) {
      console.log('----getEntityChangeTrendList', res.data)
      // 对查询到的数据进行分类
      for (let i = 0; i < res.data.length; i++) {
        const item = res.data[i]
        maxValue = Math.max(item.ENTITYCOUNT, maxValue)
        // 优先遍历seriesData中是否已经存在name对象
        const index = seriesData.findIndex((ele) => ele.name === item.AREANAME)
        // console.log('---seriesData', i, JSON.stringify(seriesData), index)
        if (index !== -1) {
          const yearIndex = years.findIndex((y) => y === item.YEAR)
          seriesData[index].data[yearIndex] = item.ENTITYCOUNT
        } else {
          const data = new Array(value.value).fill(0)
          const yearIndex = years.findIndex((y) => y === item.YEAR)
          data[yearIndex] = item.ENTITYCOUNT
          // 新建
          const color_ = getColor(colors, item.AREANAME)
          // 以逗号划分为数组并修改最后一部分的值
          const colorArray = color_.split(',')
          const colorArray1 = JSON.parse(JSON.stringify(colorArray))
          const colorArray2 = JSON.parse(JSON.stringify(colorArray))
          colorArray1[colorArray1.length - 1] = '0.5)'
          colorArray2[colorArray2.length - 1] = '0.1)'
          const color1 = colorArray1.join(',')
          const color2 = colorArray2.join(',')
          console.log(item.AREANAME, '----color1 color2', color1, color2)
          const options = {
            name: item.AREANAME,
            type: 'line',
            data: data,
            smooth: false,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: { width: 2 },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: color1 },
                { offset: 1, color: color2 }
              ])
            },
            itemStyle: {
              color: color_
            }
          }

          seriesData.push(options)
        }

      }
    }
  } catch (error) {
    console.error("获取受限实体数量变化趋势接口失败:", error);
  }

  const option = {
    color: colors.map((item) => {
      return item.value
    }),
    legend: {
      top: 10,
      left: 'center',
      itemWidth: 12,
      itemHeight: 12,
      itemGap: 20,
      icon: 'circle',
      textStyle: {
        fontSize: 16,
        fontWeight: 400,
        lineHeight: 24,
        fontFamily: 'Microsoft YaHei',
        color: 'rgb(95, 101, 108)'
      }
    },
    grid: {
      top: 60,
      left: 50,
      right: 40,
      bottom: 40
    },
    xAxis: {
      type: 'category',
      data: years,
      boundaryGap: false,
      axisLine: {
        lineStyle: { color: '#E5E7EB' }
      },
      axisLabel: {
        color: 'rgba(132, 136, 142, 1)',
        fontSize: 14,
        fontWeight: 400,
        lineHeight: 22,
        fontFamily: 'Microsoft YaHei'
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: maxValue * 1.5,
      interval: maxValue * 0.5,
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: {
        color: 'rgba(132, 136, 142, 1)',
        fontSize: 14,
        fontWeight: 400,
        lineHeight: 22,
        fontFamily: 'Microsoft YaHei'
      },
      splitLine: {
        lineStyle: { color: '#E5E7EB' }
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line'
      }
    },
    series: seriesData
  };

  rightChart.setOption(option);
};

const getColor = (colors, name) => {
  const index = colors.findIndex((i) => i.name === name)
  if (index !== -1) {
    return colors[index].value
  } else {
    return "rgba(105, 177, 255, 1)"
  }
}

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

const getEntityChangeTrendList = async () => {
  try {
    const params = {
      year: value.value,
      type: value2.value
    }
    const res = await getEntityChangeTrend(params);
    console.log('-----getEntityChangeTrendList res', res)
    if (res && res.code === 200) {
      console.log('----getEntityChangeTrendList', res.data)
    }
  } catch (error) {
    console.error("获取受限实体数量变化趋势接口失败:", error);
  }
}

watch(value1, () => {
  initLeftDonut()
})

watch([value, value2], () => {
  initRightLine()
})

onMounted(async () => {
  await initLeftDonut();
  await initRightLine();
  window.addEventListener("resize", handleResize);
});
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: 792px;
		height: 460px;
		margin-right: 16px;
		border-radius: 10px;
		box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
		background-color: #fff;
		.left-title {
			width: 792px;
			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: 120px;
				height: 28px;
				padding: 0px 12px;
				position: absolute;
				top: 11px;
				right: 31px;
			}
		}
		.left-main {
			width: 792px;
			height: 412px;
			padding: 52px 60px 78px 61px;
			.left-main-echarts {
				width: 100%;
				height: 100%;
			}
		}
	}
	.right {
		width: 792px;
		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: 792px;
			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);
			}
			.select1 {
				width: 155px;
				height: 28px;
				padding: 0px 12px;
				position: absolute;
				top: 11px;
				right: 163px;
			}
			.select {
				width: 120px;
				height: 28px;
				padding: 0px 12px;
				position: absolute;
				top: 11px;
				right: 31px;
			}
		}
		.right-main {
			width: 792px;
			height: 421px;
			padding: 15px 37px 25px 46px;
			.right-main-echarts {
				width: 100%;
				height: 100%;
			}
		}
	}
}
</style>
