import { reverse } from "d3";
import * as echarts from "echarts";

const getBarChart = (originalData) => {
  // 按 value 从大到小排序
  const sortedData = [...originalData].sort((a, b) => b.value - a.value);
  const option = {
    tooltip: {},
    grid: {
      top: '3%',
      right: '3%',
      bottom: '1%',
      left: '1%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      splitLine: {
        show: false
      },
      show: false
    },
    yAxis: {
      type: 'category',
      splitLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      },
      axisLabel: {
        show: true,
        formatter: function (value, index) {
          // index 是从 0 开始的
          const rank = index + 1;

          // 基础版本
          // return `${rank}. ${value}`;

          // 带样式的版本
          return `{rank|${rank}}  {name|${value}}`;
        },
        // 启用富文本
        rich: {
          rank: {
            color: 'rgba(5, 95, 194, 1)',      // 序号颜色
            fontFamily: 'Microsoft YaHei',
            fontSize: 12,          // 字体大小
            width: 24,
            height: 24,
            align: 'center',
            verticalAlign: 'middle',
            backgroundColor: 'rgba(231, 243, 255, 1)',
            borderRadius: 12,
            padding: [0, 0]
          },
          name: {
            color: '#333',         // 名称颜色
            fontSize: 12
          }
        }
      },
      data: sortedData.map(item => item.name),
      inverse: true,  // Y轴反向，使第一个在顶部
    },
    series: [{
      type: 'bar',
      data: sortedData.map(item => item.value),
      label: {
        show: true,
        position: [300, 0],
        formatter: function (params) {
          return params.value + ' 次'
        }
      },
      barWidth: 8,
      itemStyle: {
        color: function (params) {
          if (params.dataIndex === 0) {
            return new echarts.graphic.LinearGradient(0, 0, 1, 0,
              [{
                offset: 0,
                color: 'rgba(206, 79, 81, 0)'
              },
              {
                offset: 1,
                color: 'rgba(206, 79, 81, 1)'
              }
              ]);
          } else if (params.dataIndex < 3) {
            return new echarts.graphic.LinearGradient(0, 0, 1, 0,
              [{
                offset: 0,
                color: 'rgba(255, 172, 77, 0)'
              },
              {
                offset: 1,
                color: 'rgba(255, 172, 77, 1)'
              }
              ]);
          } else {
            return new echarts.graphic.LinearGradient(0, 0, 1, 0,
              [{
                offset: 0,
                color: 'rgba(5, 95, 194, 0)'
              },
              {
                offset: 1,
                color: 'rgba(5, 95, 194, 1)'
              }
              ]);
          }

        },
        barBorderRadius: 4,
      }
    }]
  }
  return option
}

export default getBarChart