<template>
  <div class="echart_content" style="overflow: hidden;">
    <div class="is_show_all" v-if="showCheckBox">
      <el-checkbox v-model="allSeriesSelected" :indeterminate="isIndeterminate">
        显示全部
      </el-checkbox>
    </div>
    <!-- 雷达图 -->
    <div ref="radarChart" class="chart_box" :style="{ height: reportHeight || `${height}px` }"></div>
  </div>
</template>
<script>

export default {
  name: "radarCharts",//雷达图
  props: {
    showCheckBox: {
      type: Boolean,
      default: true
    },//是否显示全部
    height: {
        type: Number,
        default: 400
    },//高度
    reportHeight: {
        type: [Number,String],
        default: ''
    },//高度
    showLegend: {
      type: Boolean,
      default: true
    },//是否显示图例
    legengAlign: { // left center right 100px
      type: String,
      default: '110px'
    },
    showTooltip:{
        type: Boolean,
        default: true
    },
    showDataLabel:{//是否显示标签
        type: Boolean,
        default: false
    },
    unit:{//单位
        type: String,
        default: '%'
    },
    legendList:{
      type:Array,
      default:()=>[],
    },//默认显示的图例数据
    legendLeft:{
        type:String,
        default: '110px'
    },
    colorType:{ 
        type:String,
        default: 'colors'
    },
    color:{
      type:Array,
      default:()=>[],
    },
    data: {
      type: Array,
      default: ()=>[
        // ['group', '年级', 'G10', 'G9', 'G8', 'G7', 'G6', 'G5', 'G4', 'G3', 'G2', 'G1'],
        // ['阅读理解', '96.52', '90.23', '80.22', '78.22', '70.32', '60.43', '60.42', '50.52', '40.63', '40.55', '36.44'],
        // ['完形填空', '98.32', '92.15', '82.34', '79.45', '71.56', '62.67', '61.78', '52.89', '42.91', '41.82', '37.73'],
        // ['知识理解', '97.72', '89.87', '79.76', '77.65', '69.54', '59.43', '58.32', '49.21', '39.12', '38.23', '35.34'],
        // ['阅读表达', '94.52', '91.45', '81.34', '78.23', '70.12', '61.23', '60.34', '51.45', '41.56', '40.67', '36.78'],
        // ['七选五', '94.23', '93.56', '83.45', '80.34', '72.23', '63.34', '62.45', '53.56', '43.67', '42.78', '38.89'],
        // ['作文', '91.52', '88.76', '78.65', '76.54', '68.43', '58.32', '57.21', '48.12', '38.23', '37.34', '34.45'],
        // ['听口', '94.52', '90.34', '80.23', '77.12', '69.01', '60.12', '59.23', '50.34', '40.45', '39.56', '35.67'],
      ],
      require: true
    },
    isClick:{
      type:Boolean,
      default:false
    },//是否可以点击事件
    showRadiusAxis:{//是否显示
      type:Boolean,
      default:true
    },
    fontSize:{
      type:[Number,String],
      default:''
    },
    fontColor:{
      type:String,
      default:''
    }
  },
  components: {},
  data() {
    return {
      myChart: null,
      allSeriesSelected: false,
      isIndeterminate: false,
      gColors: this.$global.getGGroupColor(), //g1-g10颜色值固定
      colors: this.$global.getScorePerformanceAnalysis(),//按顺序显示的20个颜色值
      legendSelected:{},//图例选中状态
      legenSelectList:this.data[0],//选中的图例数据 默认选中年级和G10 //修改图例默认全选中
    };
  },
  watch: {
    allSeriesSelected(newVal) {
      this.toggleChangeAll(newVal);
    },
    data: {
      handler() {
        this.initChart();
      },
      deep: true,
    },
  },
  computed: {

  },
  created() 
  {

  },
  mounted() 
  {
    this.initChart();
  },
  methods: {
    //加载图表
    initChart() {
      if (this.myChart) {
        this.myChart.dispose();
      }
      this.myChart = this.$echarts.init(this.$refs.radarChart, null, {
        devicePixelRatio: 2,
      });
      if(this.legendList&&this.legendList.length>0){
        this.legenSelectList = this.legendList;
      }else{
        this.legenSelectList = this.data[0].slice(1);
      }
      //提取指示器数据  每行的第一个字段
      console.log("打印legendSelected",this.legendSelected);
      console.log("打印data1111",this.data);
      const indicators = this.data.slice(1).map((row,index) => {
        const name = row[0];
        return {
          name: name,
          max: this.unit == '%' ? 100 : null,
          min: this.unit == '%' ? 0 : null,
          axisLabel: this.showRadiusAxis && index ==0 ? {
            show: true,
            formatter: (val) => `${val}${this.unit}`,
            textStyle: {
              fontSize: this.fontSize?this.fontSize:12,
              color: '#666'
            }
          } : {
            show: false
          },
          color:this.isClick && index == 0?'#2e64fa':(this.fontColor?this.fontColor:'#666666'),
          nameTextStyle: { fontSize: this.fontSize?this.fontSize:14, fontWeight: this.isClick && index==0?'bold':'normal' }
        };
      });
      console.log("打印indicators数据",indicators);
      // if(indicators.length<2)
      // {
      //   for(let i=0;i<30;i++)
      //   {
      //     indicators.push({
      //       name: '',
      //       max: 100,
      //     })
      //     indicators.push({
      //       name: '',
      //       max: 100,
      //     })
      //   }
      // }
      //提取图例数据
      const legendData=this.data[0].slice(1);
      //colors
      let colorList = [];  
      if(this.colorType=='gColors'){//G组
        colorList = legendData.map(item=>{
            const gColor = this.gColors.find(gg=>gg.name==item);
            return gColor?gColor.color:'#848BDC'
        })
      }else{
        colorList = this.color && this.color.length > 0?this.color:this.colors;
      }
      // 初始化 legendSelected 为所有图例项显示
      this.legendSelected = legendData.reduce((acc, dim,index) => {
        acc[dim] = false; // 默认不显示
        return acc;
      }, {});
      this.legenSelectList.forEach(item=>{
        this.legendSelected[item] = true;//修改图例默认全选中
      })
      this.checkAll = this.legenSelectList.length === legendData.length;
      
      this.isIndeterminate = this.legenSelectList.length > 0 && this.legenSelectList.length < legendData.length;
      this.allSeriesSelected = this.legenSelectList.length === legendData.length;
      console.log('this.legenSelectList.length == legendData.length',this.legenSelectList , legendData,this.data)
      // console.log("legendSelected",this.legendSelected);
      // 提取每个年级的数据
      const seriesData = legendData.map((grade, gradeIndex) => {
        const values = this.data.slice(1).map((row) => Number(row[gradeIndex + 1])); // 获取对应年级的数据
        return {
          name: grade,
          value: values,
          label: {
            show: this.showDataLabel,
            position: 'outside',
            formatter:(params)=> {
              return `${params.value}${this.unit}`;
            }
          }
        };
      });
      console.log("打印indicators数据",indicators);
      console.log("打印seriesData数据",seriesData);

      if (this.unit != '%') {
        let maxValue = -Infinity;
        let minValue = Infinity;
        // 遍历外层数组
        seriesData.forEach(item => {
          // 遍历当前item的value数组
          item.value.forEach(num => {
            // 更新最大值
            if (num > maxValue) {
              maxValue = num;
            }
            // 更新最小值
            if (num < minValue) {
              minValue = num;
            }
          });
        });
        indicators.map(item => {
          item.max = Math.ceil(maxValue);
          item.min = Math.floor(minValue);
        })
      }
      let option = {
        grid: {
        //   top: 50,
        //   left: 20,
        //   right: 40,
        //   bottom: 30,
        //   containLabel: true,
        },
        emphasis: {
          blurScope: 'global'
        },

        legend: {
          show: this.showLegend,
          data: legendData,
        //   left: 'center',
          left: this.legendLeft,
          itemGap: 20,
          itemHeight: 10,
          itemWidth: 20,
          textStyle: { fontSize: 12, color: "#333" },
          icon: 'path://M352.64 526.336a158.272 158.272 0 0 0 2.56 17.664H96v-64h259.2a161.952 161.952 0 0 0-2.336 15.232A160 160 0 0 1 672 512a160.992 160.992 0 0 0-3.2-32H928v64h-259.2q1.12-5.504 1.824-11.104a160 160 0 0 1-318.016-6.4zM416 512a96 96 0 1 0 96-96 96 96 0 0 0-96 96z m254.72 20.224v-0.576z m-318.08-5.888v-1.664q-0.064 0.832 0 1.664z m-0.16-2.08v-1.248a5.44 5.44 0 0 0 0 1.248z m0-2.08v-0.928z m0-2.048zM352 518.08z m0-2.048zM352 512v-4.096V512z m0-5.344v-0.736 0.736z m0-2.56z m0.256-4.128z m0-1.664z m0-1.6v-0.992z',
          // icon: "roundRect",
          selectedMode: true,
          selected: this.legendSelected,
          type:'scroll',//启用图例滚动  翻页功能
          pageButtonItemGap: 5, // 分页按钮与图例的间距
          pageButtonPosition: 'end', // 分页按钮显示在右侧
          orient: 'horizontal', // 图例横向排列（也可以设为 'vertical'）
          alignTo: 'none',//不进行额外对齐处理（比如不强制靠左或靠右）；
          pageIconColor: '#999', // 翻页按钮默认颜色
          pageIconInactiveColor: '#ccc', // 翻页按钮禁用状态颜色
        },
       
        tooltip: {
          show: this.showTooltip,
          // trigger: "axis",
          triggerOn: "mousemove | click",
          renderModel:'html',//使用html渲染模式
          confine:true,//是否将 tooltip 框限制在图表的区域内。
          extraCssText: 'border-radius: 4px;white-space:normal;word-warp:break-word;max-width: 400px;', // 设置最大宽度和高度
          enterable:true,
          formatter: (params) => {
            const chart = this.myChart.getOption();
            let indicator=chart.radar[0].indicator;
            let tooltipContent = `<div class='tooltip_content'>`;
            
            let title = params.name

            tooltipContent += `<div class='tooltip_title'>${title}</div>`
            indicator.forEach((item, index) => {
              
              //不显示虚拟维度
              if(item.name)
              {
                let name=item.name;
                let value =params.value[index];
                let unit=this.unit;
                tooltipContent += `<div class='tooltip_student'>${name}：${value}${unit}</div>`
              }
              
            })
            return tooltipContent
            
          },
        },
      
        color: colorList,
        radar: {
          indicator: indicators,//指示器顺时针显示
          shape: indicators.length < 3 ? 'circle' : '',
          splitNumber: 5,
          startAngle:90,//第一个指示器轴的角度
          splitLine:{
            show:true,
            // lineStyle:{
            //   color:'#666',
            //   width:1,
            //   type:'dashed'
            // },
          },
          axisLabel: {
              show: false,
              
              
          },//维度刻度值显示设置
          splitArea: {
            show: true,
            areaStyle: {
              opacity: 0.1, // 设置背景透明度
              color: ['#f0f8ff', '#e0f7fa', '#fff3e0', '#efebe9', '#f5f5f5'] // 设置交替的圆环背景色，按需自定义
            }
          },
          polar: {}, // 强制使用极坐标系
          
          radiusAxis: {
            type: 'value',
            min: 0,
            max: 100, // 设置最大值范围，根据你的数据调整
            interval: 20, // 分割间隔
            splitLine: {
              show: true,
              lineStyle: {
                color: '#eee'
              }
            },
            splitArea: {
              show: false,
              areaStyle: {
                color: ['#f0f8ff', '#e0f7fa', '#fff3e0', '#efebe9', '#f5f5f5']
              }
            }
          },
          axisLine: {
            show: this.data.length<3?false:true,//维度小于3的时候 显示圆环 不显示刻度线
            lineStyle: {
              color: '#999' // 设置轴线颜色
            }
          },
          center: this.reportHeight?['50%', '50%']:(this.showLegend?['50%', '55%']:['50%', '55%'])//位置调整
        },
        triggerEvent: true,//坐标轴的标签是否响应和触发鼠标事件，默认不响应。
        series: [
          {
            type: "radar",
            symbol: 'circle', // 空心圆
            // symbol: 'none',  // 不显示symbol
            symbolSize: 7,
            data: seriesData,
            itemStyle: { opacity: 1 },
            // emphasis: {
            //   itemStyle: { opacity: 1 }
            // },
            emphasis: {
              symbol: 'none',  // 不显示symbol
              focus: "self",//只聚焦当前系列
              itemStyle: {
                opacity: 1, // 强调状态下保持可见
                // borderColor: '#fff',
                borderWidth: 2
              },
              areaStyle: {
                opacity:0.1
              }
            },
            blur:{
              symbol: 'none',  // 不显示symbol
              itemStyle: {
                opacity: 0.2, // 圆点消失或者设置为 0.1 弱化
                color:'red',
                show: false  // 其他系列模糊时不显示symbol
              },//都不生效
              lineStyle: {
                opacity: 0.2
              }
            },
            // emphasis: {
            //     focus: 'self'
            // }
            
          },
        ],
        
      }

      this.myChart.setOption(option);
      console.log(option,'option')
      this.myChart.on("legendselectchanged", this.handleLegendSelectChanged);
      // 监听点击事件
      if(this.isClick){
        this.bindChartNameEvents(indicators);
      }
      window.addEventListener("resize", this.resizeFn);
    },
    //绑定点击事件
    bindChartNameEvents(indicators){
      if(!this.myChart){
        return false
      }
      const _that = this;
      this.myChart.on('click', function(params) {
        // 判断是否点击的是雷达图指示器（可选：也可去掉判断，点击任何区域都隐藏）
        if (params.componentType === 'radar' && params.targetType == 'axisName') {
          let name = params.name;
          const data = _that.data.slice(1);
          const  list = data.map(item=>item[0]);
          const index = list.indexOf(name);
          let indicatorList = [...indicators];
          indicatorList.forEach((item,key)=>{
            if(key==index){
              item.color = '#2e64fa'
            }else{
              item.color = '#666666'
            }
            item.nameTextStyle.fontWeight = key==index?'bold':'normal'
          })
          // 更新图表配置
          _that.myChart.setOption({
            radar: {
              indicator: indicatorList,
              
            }
          });
          _that.$emit('HandleChartClick', index,name);//返回点击的柱子索引和x轴名称
        }
      });
    },
    // 图例与显示全部按钮联动 事件
    handleLegendSelectChanged(params) {
      
      const legendData = this.myChart.getOption().legend[0].data;
      const selected = params.selected;
      // 检查是否有任何图例项被隐藏
      this.legendSelected=selected;
      const allSelected = legendData.every(
        (seriesName) => selected[seriesName]
      );
      const noneSelected = legendData.every(
        (seriesName) => !selected[seriesName]
      );
      const someSelected = !allSelected && !noneSelected;
      // 更新“显示全部”按钮的状态
      if (noneSelected) {
        this.allSeriesSelected = false;
      }
      if (allSelected) {
        this.allSeriesSelected = true;
      }
      this.isIndeterminate = someSelected;
    },
    resizeFn() {
      this.myChart.resize();
    },
    // 显示全部按钮
    toggleChangeAll(show) {
      if (!this.showCheckBox) return false
      const legendData = this.myChart.getOption().legend[0].data;
      legendData.forEach((seriesName) => {
        this.myChart.dispatchAction({
          type: show ? "legendSelect" : "legendUnSelect",
          name: seriesName,
        });
      });
      this.allSeriesSelected = show;
      this.isIndeterminate = false;
    },
    // resizeFn() {
    //   this.myChart.resize();
    // },
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.resizeFn);
  },
};
</script>
<style lang="scss" scoped>
.chart_box {
  width: 100%;
  height: 400px;
}
</style>
