import * as echarts from "echarts";


// 计算总和
function getTotal(data) {
  return data.reduce((sum, item) => sum + item.value, 0);
};
export const pieOption = (data) => {
  console.log(data, 'datadatadata')
  // 颜色数组
  const colors = [
    'rgba(105, 177, 255, 1)',
    'rgba(255, 236, 61, 1)',
    'rgba(135, 232, 222, 1)',
    'rgba(133, 165, 255, 1)',
    'rgba(255, 120, 117, 1)',
    'rgba(179, 127, 235, 1)',
    'rgba(255, 187, 120, 1)',
    'rgba(120, 255, 180, 1)',
    'rgba(255, 150, 150, 1)'
  ];
  const seriesData = data.names.map((name, index) => ({
    name,
    value: data.values[index],
    itemStyle: { color: colors[index % colors.length] }
  }));
  const option = {
    tooltip: {
      trigger: 'item'
    },
    grid: {
      left: '5%',
      right: '5%',
      top: '5%',
      bottom: '5%',
      containLabel: true
    },
    legend: {
      orient: 'vertical',
      x: 'right',
      y: 'center',
      align: 'left',
      left: '52%',
      data: data.names,
      textStyle: {
        color: "rgba(59, 65, 75, 1)",
        fontSize: 14
      },
      formatter: function (name) {
        const index = data.names.indexOf(name)
        if (index === -1) return name
        const value = data.values[index]
        const total = data.total || data.values.reduce((sum, v) => sum + v, 0)
        const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : '0.0'
        return `${name}  ${percentage}%`
      }
    },
    series: [
      {
        name: '频度',
        type: 'pie',
        center: ['28%', '50%'],
        radius: ['35%', '55%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        labelLine: {
          show: false
        },
        data: seriesData,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1
        }
      }
    ]
  };
  return option
}

var data1 = [
  {
    name: "捐赠基金",
    value: 27
  },
  {
    name: "政府拨款",
    value: 22
  },
  {
    name: "企业合作",
    value: 18
  },
  {
    name: "学费收入",
    value: 15
  },
  {
    name: "其他来源",
    value: 12
  }
];

export const pieOption1 = (data) => {
  // 提取部门名称和对应的金额 
  const colors = [
    'rgba(105, 177, 255, 1)',
    'rgba(255, 236, 61, 1)',
    'rgba(135, 232, 222, 1)',
    'rgba(133, 165, 255, 1)',
    'rgba(255, 120, 117, 1)'
  ];
  // 提取部门名称和对应的金额
  const departmentNames = data.map(item => item.departmentName);
  const amounts = data.map(item => item.amount);

  // 计算总金额
  const getTotal = (data) => {
    return data.reduce((total, item) => total + item.amount, 0);
  };

  // 饼图配置
  const option = {
    legend: {
      orient: 'vertical',
      x: 'right',
      y: 'center',
      align: 'left',
      left: '60%',
      data: departmentNames,
      textStyle: { // 图例字体样式
        color: "rgba(59, 65, 75, 1)",
        fontSize: 16
      },
      formatter: function (name) {
        var total = getTotal(data);
        var item = data.find(item => item.departmentName === name);
        var percentage = ((item.amount / total) * 100).toFixed(2);
        return `${name} ${percentage}%`;
      }
    },
    series: [
      {
        name: '频度',
        type: 'pie',
        center: ['30%', '50%'],
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        labelLine: {
          show: false
        },
        data: data.map((item, index) => ({
          name: item.departmentName,
          value: item.amount,
          itemStyle: { color: colors[index % colors.length] } // 使用颜色列表
        }))
      }
    ]
  };
  return option;
}

export const raderOption = (data) => {
  // 固定颜色数组，避免随机色
  const colors = [
    { line: 'rgba(91, 143, 249, 1)', area: 'rgba(91, 143, 249, 0.2)' },
    { line: 'rgba(255, 166, 77, 1)', area: 'rgba(255, 166, 77, 0.2)' },
    { line: 'rgba(100, 210, 180, 1)', area: 'rgba(100, 210, 180, 0.2)' },
    { line: 'rgba(168, 124, 255, 1)', area: 'rgba(168, 124, 255, 0.2)' },
    { line: 'rgba(255, 120, 117, 1)', area: 'rgba(255, 120, 117, 0.2)' }
  ];

  // 提取所有可能的 areaName
  const allAreaNames = new Set();
  data.forEach(subject => {
    subject.areaVoList.forEach(area => {
      allAreaNames.add(area.areaName);
    });
  });
  const indicatorNames = Array.from(allAreaNames);

  // 保存原始数据用于 tooltip 显示
  const originalData = {};
  data.forEach(subject => {
    originalData[subject.subjectTypeName] = {};
    indicatorNames.forEach(indicator => {
      const area = subject.areaVoList.find(a => a.areaName === indicator);
      originalData[subject.subjectTypeName][indicator] = area ? area.amount : 0;
    });
  });

  // 对数归一化函数：将原始值转换到 0-100 范围，保持相对差异可见
  const logNormalize = (value, maxVal) => {
    if (value <= 0) return 0;
    if (maxVal <= 0) return 0;
    // 使用对数变换：log(1+value) / log(1+max) * 100
    return (Math.log(1 + value) / Math.log(1 + maxVal)) * 100;
  };

  // 计算每个维度的全局最大值
  const globalMaxValues = {};
  indicatorNames.forEach(name => {
    let maxVal = 0;
    data.forEach(subject => {
      const area = subject.areaVoList.find(a => a.areaName === name);
      if (area && area.amount > maxVal) {
        maxVal = area.amount;
      }
    });
    globalMaxValues[name] = maxVal;
  });

  // 生成雷达图的 indicator 配置（统一使用 100 作为 max）
  const radarIndicators = indicatorNames.map(name => ({
    name,
    max: 100
  }));

  // 为每个 subjectTypeName 生成雷达图数据（归一化后的值）
  const radarSeriesData = data.map((subject, index) => {
    const values = indicatorNames.map(indicator => {
      const area = subject.areaVoList.find(a => a.areaName === indicator);
      const originalValue = area ? area.amount : 0;
      const maxVal = globalMaxValues[indicator];
      return logNormalize(originalValue, maxVal);
    });
    const colorIndex = index % colors.length;
    return {
      value: values,
      name: subject.subjectTypeName,
      lineStyle: {
        color: colors[colorIndex].line,
        width: 2
      },
      areaStyle: {
        color: colors[colorIndex].area
      },
      itemStyle: {
        color: colors[colorIndex].line
      },
      symbol: 'circle',
      symbolSize: 6
    };
  });

  // 雷达图配置
  const option = {
    tooltip: {
      trigger: 'item',
      confine: true,
      formatter: function(params) {
        if (!params.value) return '';
        const name = params.name;
        let html = `<div style="font-weight:bold;margin-bottom:8px;border-bottom:1px solid #eee;padding-bottom:4px;">${name}</div>`;
        indicatorNames.forEach((indicator) => {
          const originalValue = originalData[name] ? originalData[name][indicator] : 0;
          html += `<div style="padding:2px 0;">${indicator}: <span style="font-weight:bold;color:#333;">${originalValue}</span></div>`;
        });
        return html;
      }
    },
    legend: {
      icon: 'circle',
      orient: 'vertical',
      right: 30,
      top: 'center',
      align: 'left',
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 12,
      textStyle: {
        color: "rgba(59, 65, 75, 1)",
        fontSize: 14
      }
    },
    radar: {
      center: ['35%', '50%'],
      radius: '55%',
      indicator: radarIndicators,
      axisName: {
        formatter: '{value}',
        color: 'rgba(59, 65, 75, 1)',
        fontSize: 14,
        fontWeight: 700
      },
      splitArea: {
        areaStyle: {
          color: ['#fff', '#F5F7FA', '#fff', '#F5F7FA', '#fff']
        }
      },
      splitLine: {
        lineStyle: {
          color: '#E8E8E8'
        }
      },
      axisLine: {
        lineStyle: {
          color: '#E8E8E8'
        }
      }
    },
    series: [
      {
        name: '研究领域分布',
        type: 'radar',
        data: radarSeriesData
      }
    ]
  };
  return option;
}


export const barOption = (data) => {
  // 提取年份和对应的专利数量
  const years = data.map(item => item.year.toString());
  const counts = data.map(item => item.countNum);
  // 柱状图配置
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      top: '3%',
      right: '3%',
      bottom: '1%',
      left: '1%',
      containLabel: true
    },
    xAxis: [{
      axisLine: {
        lineStyle: {
          width: 1,
          color: "rgba(231, 243, 255, 1)"
        }
      },
      axisTick: { show: false },
      type: "category",
      boundaryGap: [100, 100],
      axisLabel: {
        color: "rgba(95, 101, 108, 1)",
        // fontSize: 22,
        // fontWeight: 400
      },
      data: years, // 动态设置 xAxis 数据
    }],
    yAxis: {
      type: "value",
      axisLine: {
        lineStyle: {
          type: "dashed"
        }
      },
      axisLabel: {
        color: "rgba(95, 101, 108, 1)",
        // fontSize: 22,
        // fontWeight: 400
      },
      splitNumber: 5,
      splitLine: {
        lineStyle: {
          width: 1,
          type: "dashed",
          color: "rgba(231, 243, 255, 1)"
        },
      }
    },
    series: [
      {
        name: "专利数量",
        data: counts, // 动态设置 series 数据
        type: "bar",
        barWidth: 20,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(46, 165, 255, 1)" },
            { offset: 1, color: "rgba(46, 165, 255, 0)" }
          ])
        },
        label: {
          show: false,
          position: 'top',
          textStyle: {
            fontSize: '20px',
            fontWeight: 400,
            color: 'rgba(255, 255, 255, 1)'
          }
        }
      }
    ]
  };
  return option;
}
export const lineChart = (data) => {
  // 提取年份和对应的专利数量
  const years = data.map(item => item.year.toString());
  const counts = data.map(item => item.countNum);
  // 折线图配置
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: '2%',
      top: '8%',
      right: '2%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      splitLine: {
        show: false
      },
      axisLine: {
        show: false
      },
      data: years, // 动态设置 xAxis 数据
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: true,
        lineStyle: {
          type: "dashed",
          color: "#E7F3FF"
        }
      },
      axisLine: {
        show: false
      },
    },
    color: ['rgba(255, 149, 77, 1)'],
    series: [
      {
        data: counts, // 动态设置 series 数据
        type: 'line',
        emphasis: {
          focus: 'series'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(255, 149, 77, 0.5)' }, // 起始颜色：深色
            { offset: 1, color: 'rgba(255, 149, 77, 0)' } // 结束颜色：浅色且透明度降低
          ])
        },
      }
    ]
  };
  return option;
}
export const lineChart1 = (data) => {
  // 提取年份和对应的 fundAmount
  const years = data.map(item => item.year.toString());
  const fundAmounts = data.map(item => item.fundAmount);
  // 折线图配置
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: '2%',
      top: '8%',
      right: '2%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      splitLine: {
        show: false
      },
      axisLine: {
        show: false
      },
      data: years, // 动态设置 xAxis 数据
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: true,
        lineStyle: {
          type: "dashed",
          color: "#E7F3FF"
        }
      },
      axisLine: {
        show: false
      },
    },
    color: ['rgba(33, 129, 57, 1)'],
    series: [
      {
        data: fundAmounts, // 动态设置 series 数据
        type: 'line',
        emphasis: {
          focus: 'series'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(33, 129, 57, 0.5)' }, // 起始颜色：深色
            { offset: 1, color: 'rgba(33, 129, 57, 0)' } // 结束颜色：浅色且透明度降低
          ])
        },
      }
    ]
  };
  return option;
}


const nameList = ["教育学院", "文理学院", "法学院", "商学院", "工程学院", "医学院"];
const valueList = [21, 21, 25, 79, 95, 109];
export const horizontalBaroption = (data) => {
  // 提取部门名称和对应的金额
  const departmentNames = data.map(item => item.departmentName);
  const amounts = data.map(item => item.amount);

  // 水平柱状图配置
  const option = {
    grid: {
      top: '0',
      right: '3%',
      bottom: '1%',
      left: '1%',
      containLabel: true
    },
    color: ['#ce4f51', '#1778ff'],
    xAxis: {
      type: 'value',
      splitLine: {
        show: false
      },
      show: false
    },
    yAxis: {
      type: 'category',
      data: departmentNames, // 动态设置 yAxis 数据
      splitLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      },
      axisLabel: {
        show: true
      }
    },
    series: [{
      type: 'bar',
      data: amounts.map((item, index) => {
        return {
          value: item,
          label: {
            textStyle: {
              color: index < 3 ? '#1778ff' : '#ce4f51'
            }
          }
        };
      }),
      label: {
        show: true,
        position: [650, -2]
      },
      barWidth: 8,
      itemStyle: {
        color: function (params) {
          if (params.dataIndex < 3) {
            return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: 'rgba(22, 119, 255, 0)' },
              { offset: 1, color: '#1778ff' }
            ]);
          } else {
            return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: 'rgba(206, 79, 81, 0)' },
              { offset: 1, color: '#ce4f51' }
            ]);
          }
        },
        barBorderRadius: 4,
      }
    }]
  };
  return option;
}
export const raderOption1 = (data) => {
  // 提取指标名称和对应的值
  const indicatorNames = data.map(item => item.areaName);
  const indicatorValues = data.map(item => item.areaValue);

  //   indicator 配置
  const indicators = indicatorNames.map((name, index) => ({
    name,
    max: Math.max(...indicatorValues) * 1.2 // 设置最大值为所有值的最大值的1.2倍
  }));

  let radarData = {
    color:
      "rgba(215, 27, 56, 0.2)",
    name: '',
    value: indicatorValues
  }
  console.log(indicators, 'indicators', radarData, 'radarDataradarData')
  // 雷达图配置
  const option = {
    title: { text: '' },
    legend: {
      icon: 'circle',
      orient: 'vertical',
      right: 50,
      top: 'center',
      align: 'left',
      textStyle: {
        color: "rgba(59, 65, 75, 1)",
        fontSize: "16px"
      }
    },
    radar: {
      radius: '60%',
      indicator: indicators,
      axisName: {
        formatter: '{value}',
        color: 'rgba(59, 65, 75, 1)',
        fontSize: 16,
        fontWeight: 700
      }
    },
    series: [
      {
        name: 'Budget vs spending',
        type: 'radar',
        data: [radarData]
      }
    ]
  };
  return option;

}

