import 'echarts-liquidfill/src/liquidFill.js';
import { cloneDeep } from 'lodash';
import { useAppStore } from '@/store';
const appStore = useAppStore();

const getTotal = (data) => {
  return data.reduce((num, item) => {
    return num + (Number(item.value) || 0);
  }, 0);
};

//mergeParams方法
//调用生成对应图表的方法时，extend参数可以对本文件里的基础配置里的字段进行覆盖，
//如果extend里的配置项里的字段为空，说明需要删除本文件里的配置项字段
//例如 options为{ legend :{top:'center',right:'3%'} } , extend参数为 { legend: { top:null,right:null,bottom:'3%',left:'center' } }
//那么合并后的结果对象就是  { legend: {bottom:'3%' ,left:'center' } }
const mergeParams = (options, obj) => {
  let keys = Object.keys(obj);
  keys.forEach((key) => {
    let optionsSubObj = options[key];
    if (optionsSubObj) {
      let subObj = obj[key];
      Object.entries(subObj).forEach((arr) => {
        if (arr[1] === null) {
          delete optionsSubObj[arr[0]];
        } else {
          optionsSubObj[arr[0]] = arr[1];
        }
      });
    }
  });
  return options;
};
export const colorList = [
  '#4080FF',
  '#23C343',
  '#F76560',
  '#FF9A2E',
  '#86909C',
  '#ffdb5c',
  '#ff9f7f',
  '#fb7293',
  '#e7bcf3',
  '#8378ea',
  '#47A2FF ',
  '#53C8D1',
  '#59CB74',
  '#FBD444',
  '#7F6AAD',
  '#585247',
  '#ff0000',
];

//堆叠柱状图
export const createStackingBarOption = ({ xData, seriesData }, extend = {}) => {
  return mergeParams(
    {
      customType: 'NORMAL',
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      legend: [
        {
          icon: 'react',
          right: '0%',
          top: '1%',
          textStyle: {
            color: '#595959',
            fontSize: 12,
          },
          itemWidth: 8,
          itemHeight: 8,
          data: seriesData.map((item) => item.name),
        },
      ],
      grid: {
        left: '1%',
        right: '1%',
        bottom: '1%',
        containLabel: true,
        show: true,
        // borderColor: appStore.isFullscreen ? '#0A3367' : '#e5e5e5',
        borderColor: 'transparent',
      },
      xAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value}',
          color: '#8c8c8c',
          textStyle: {
            fontSize: 12,
          },
        },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#e5e5e5',
          },
        },
      },
      yAxis: {
        type: 'category',
        data: xData,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          margin: 6,
          color: '#8c8c8c',
          textStyle: {
            fontSize: 12,
          },
        },
      },
      series: seriesData.map((item, index) => ({
        name: item.name,
        type: 'bar',
        data: item.data,
        // barWidth: item.barWidth ?? '8px',
        stack: '总量',
        label: {
          // show: true,
          normal: {
            show: true,
            // position: 'insideRight',
            color: '#fff',
            formatter: (obj) => {
              return obj.value > 0 ? obj.value : '';
            },
          },
        },
        itemStyle: {
          normal: {
            color: colorList[index % colorList.length],
          },
        },
      })),
    },
    extend
  );
};

//基础柱状图
export const createBarOption = ({ xData, seriesData }, extend = {}) => {
  return mergeParams(
    {
      customType: 'NORMAL',
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      legend: [
        {
          icon: 'react',
          right: '0%',
          top: '1%',
          textStyle: {
            color: appStore.isFullscreen ? '#e5e5e5' : '#8c8c8c',
            fontSize: 12,
          },
          itemWidth: 8,
          itemHeight: 8,
          data: seriesData.map((item) => item.name),
        },
      ],
      grid: {
        left: '1%',
        right: '1%',
        bottom: '1%',
        top: '35',
        containLabel: true,
      },
      xAxis: [
        {
          type: 'category',
          data: xData,
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            margin: 6,
            color: appStore.isFullscreen ? '#BFBFBF' : '#8c8c8c',
            textStyle: {
              fontSize: 12,
            },
          },
        },
      ],
      yAxis: [
        {
          axisLabel: {
            formatter: '{value}',
            color: appStore.isFullscreen ? '#BFBFBF' : '#8c8c8c',
            textStyle: {
              fontSize: 12,
            },
          },
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
      ],
      series: seriesData.map((item, index) => ({
        name: item.name,
        type: 'bar',
        data: item.data,
        // barWidth: '12px',
        itemStyle: {
          normal: {
            color: colorList[index % colorList.length],
          },
        },
      })),
    },
    extend
  );
};
//创建圆环状的基础饼图
export const createRingPieOption = (
  {
    data,
    title = '',
    center = ['50%', '50%'],
    seriesName = '',
    radius = [40, 60],
  },
  extend = {}
) => {
  const total = getTotal(data);
  return mergeParams(
    {
      customType: 'NORMAL',
      tooltip: {
        trigger: 'item',
      },
      legend: {
        orient: 'vertical',
        right: '0%',
        top: 'center',
        icon: 'circle',
        data: data.map((item) => item.name),
        textStyle: {
          color: appStore.isFullscreen ? '#fff' : '#595959',
        },
        itemWidth: 10,
        itemHeight: 10,
        formatter: (name) => {
          let target = data.find((item) => item.name == name);
          let float = ((target.value * 100) / total).toFixed(1);
          return target.value ? `${name} ${Number(float) + '%'}` : `${name}`;
          //   return `{a|${name}}{b|${Number(float) * 100 + '%'}}`;
        },
      },
      color: colorList,
      series: [
        {
          name: seriesName,
          type: 'pie',
          radius: radius,
          center: center,
          label: {
            position: 'center',
            formatter: () => {
              return `${title}\n{total|${total}}`;
            },
            rich: {
              total: {
                fontSize: 16,
                color: appStore.isFullscreen ? '#fff' : '#262626',
              },
            },
            color: appStore.isFullscreen ? '#bfbfbf' : '#595959',
            fontSize: 12,
            lineHeight: 24,
          },
          labelLine: {
            show: false,
          },
          itemStyle: {
            borderWidth: 2,
            borderColor: '#fff',
          },
          data: data,
        },
      ],
    },
    extend
  );
};
//创建蛋糕试的饼图
export const createCakePieOption = (
  {
    data,
    title = '',
    center = ['35%', '50%'],
    seriesName = '',
    radius = [0, 60],
    showLegendValue = true,
    showLegendPercent = true,
  },
  extend = {}
) => {
  const total = getTotal(data);
  return mergeParams(
    {
      color: colorList,
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)',
      },
      toolbox: {
        show: true,
      },
      legend: {
        orient: 'vertical',
        right: '1%',
        top: 'center',
        icon: 'circle',
        textStyle: {
          color: appStore.isFullscreen ? '#E5E5E5' : '#8C8C8C',
        },
        itemWidth: 10,
        itemHeight: 10,
        formatter: function (name) {
          let item = data.find((item) => item.name == name);
          let percent =
            total == 0 ? 0 : ((item?.value / total) * 100).toFixed(2);
          return item?.value
            ? `${name}${showLegendValue ? ' ' + item?.value : ''}${
                showLegendPercent ? '(' + percent + '%' + ')' : ''
              }`
            : `${name}`;
        },
      },
      series: [
        {
          name: seriesName,
          type: 'pie',
          radius: radius,
          center: center,
          data: data,
          label: {
            show: true,
            position: 'inside',
            textStyle: {
              fontSize: '14',
              color: '#FFFFFF',
            },
            // formatter: '{d}%',
            formatter: (obj) => {
              return obj.value == 0
                ? ''
                : ((obj.value / total) * 100).toFixed(2) + '%';
            },
          },
        },
      ],
    },
    extend
  );
};
//基础水球图
export const createWaterBallOption = (
  { data, title, center, radius = '90%', color = '64,128,255' },
  extend = {}
) => {
  return mergeParams(
    {
      // backgroundColor: "#0e2147",
      // title: {
      //   show: true,
      //   text: title,
      //   x: 'center',
      //   y: '50%',
      //   z: 10,
      //   textStyle: {
      //     color: '#666',
      //     fontSize: 12,
      //     // fontWeight: 500,
      //   },
      // },
      // title: {
      //   //   text: (value * 100).toFixed(0) + '{a|%}',
      //   text: 30 + '{a|%}',
      //   textStyle: {
      //     fontSize: 50,
      //     fontFamily: 'Microsoft Yahei',
      //     fontWeight: 'normal',
      //     color: '#bcb8fb',
      //     rich: {
      //       a: {
      //         fontSize: 28,
      //       },
      //     },
      //   },
      //   x: 'center',
      //   y: '35%',
      // },
      graphic: [
        {
          type: 'group',
          left: 'center',
          top: '34%',
          children: [
            {
              type: 'text',
              z: 100,
              left: '10',
              top: 'middle',
              style: {
                fill: appStore.isFullscreen ? '#BFBFBF' : '#fff',
                text: title,
                font: '12px Microsoft YaHei',
              },
            },
          ],
        },
      ],
      series: [
        {
          name: 'test',
          type: 'liquidFill',
          radius: radius,
          center: center || ['50%', '50%'],
          data: [data],
          label: {
            normal: {
              // formatter: '',
              position: ['50%', '66%'],
              textStyle: {
                color: appStore.isFullscreen ? '#BFBFBF' : '#333',
                fontSize: 18,
              },
            },
          },
          color: [`rgba(${color},1)`],
          backgroundStyle: {
            color: `rgba(${color},0.26)`,
          },
          outline: {
            borderDistance: 0,
            itemStyle: {
              borderWidth: 5,
              borderColor: `rgba(${color},0.5)`,
            },
            // show: false,
          },
          // amplitude: 0,
        },
      ],
    },
    extend
  );
};

//基础百分比堆叠柱状图
//originData：原始数据二维数组，每个子元素数组的内容累加和可能会不相等，会导致整体柱状集的尾部不对齐，所以要二次处理
export const createPercentBarOption = (
  { xData = [], originData = [], legendData = [], xName = '' },
  extend = {}
) => {
  const oData = cloneDeep(originData);
  let newData = [];
  if (originData.length) {
    newData = originData.map(() => {
      return [];
    });
    for (let i = 0; i < originData.length; i++) {
      let row = originData[i];
      let rowTotal = row.reduce((num, item) => {
        return num + item;
      }, 0);
      for (let j = 0; j < row.length; j++) {
        if (j != row.length - 1) {
          newData[i].push(Math.round((row[j] / rowTotal) * 100));
        } else {
          let prevTotal = newData[i].reduce((num, v) => {
            return v + num;
          }, 0);
          newData[i].push(100 - prevTotal < 0 ? 0 : 100 - prevTotal);
        }
      }
    }
  }
  let sData = [];
  if (newData.length) {
    sData = newData[0].map(() => []);
    for (let i = 0; i < newData[0].length; i++) {
      for (let j = 0; j < newData.length; j++) {
        sData[i].push(newData[j][i]);
      }
    }
  }
  return mergeParams(
    {
      customType: 'NORMAL',
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
        formatter: function (obj, b, c) {
          let total = 0;
          let str = '';
          for (let i = 0; i < obj.length; i++) {
            total += obj[i]['value'];
          }
          for (let i = 0; i < obj.length; i++) {
            let name = obj[i].name;
            let dataIndex = xData.findIndex((item) => item == name);
            let val = originData[dataIndex][obj[i].seriesIndex];

            str =
              str +
              '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:' +
              obj[i]['color'] +
              ';"></span>' +
              ' ' +
              obj[i]['seriesName'] +
              ' : ' +
              val +
              ' (' +
              (total == 0 ? 0 : (obj[i]['value'] / total) * 100).toFixed(1) +
              ' %)' +
              '</br>';
          }
          return str;
        },
      },
      color: colorList,
      legend: {
        data: legendData,
        top: '1%',
        left: 'center',
        icon: 'circle',
        textStyle: {
          color: appStore.isFullscreen ? '#E5E5E5' : '#8C8C8C',
        },
        itemWidth: 10,
        itemHeight: 10,
      },
      calculable: true,
      grid: {
        left: '1%',
        right: '5%',
        bottom: '1%',
        containLabel: true,
      },
      yAxis: [
        {
          type: 'category',
          data: xData,
          axisLabel: {
            formatter: '{value}',
            color: '#8c8c8c',
            textStyle: {
              fontSize: 12,
            },
          },
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
      ],
      xAxis: {
        type: 'value',
        splitArea: { show: true },
        axisLabel: {
          formatter: '{value}%',
          color: '#8c8c8c',
          textStyle: {
            fontSize: 12,
          },
        },
      },
      series: sData.map((item, index) => {
        return {
          name: legendData[index],
          type: 'bar',
          stack: '百分比',
          data: item,
          label: {
            // show: true,
            normal: {
              show: true,
              // position: 'insideRight',
              color: '#fff',
              formatter: (obj) => {
                return obj.value == 0 ? '' : obj.value + '%';
              },
            },
          },
        };
      }),
    },
    extend
  );
};

export const createLineOption = ({ sData = [], xData = [] }, extend = {}) => {
  return mergeParams(
    {
      customType: 'NORMAL',
      grid: {
        top: 50,
        bottom: 15,
        left: 30,
        right: 30,
        containLabel: true,
      },
      legend: {
        top: 10,
        right: 0,
        itemWidth: 10,
        data: sData.map((item) => item.name),
        textStyle: {
          color: appStore.isFullscreen ? '#E5E5E5' : '#8C8C8C',
        },
      },
      tooltip: {
        trigger: 'axis',
      },
      xAxis: {
        axisLine: { show: false },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: {
          align: 'right',
        },
        data: xData,
      },
      yAxis: {
        type: 'value',
      },
      series: sData.map((item, index) => ({
        name: item.name,
        type: 'line',
        itemStyle: {
          color: colorList[index],
        },
        data: item.data,
      })),
    },
    extend
  );
};

// 雷达图
export const createRadarOption = ({ names, sData = [] }, extend = {}) => {
  return mergeParams(
    {
      color: colorList,
      tooltip: {
        show: true,
      },
      legend: {
        data: sData.map((item) => item.name),
        bottom: 0,
        itemWidth: 10,
        itemHeight: 10,
        textStyle: {
          color: '#595959',
          fontSize: 12,
        },
      },
      radar: {
        radius: '65%',
        indicator: names.map((item) => ({ name: item })),
        axisName: {
          color: '#8c8c8c',
          fontSize: 10,
        },
        axisLine: {
          lineStyle: {
            color: '#e5e5e5',
          },
        },
        splitLine: {
          lineStyle: {
            color: '#e5e5e5',
          },
        },
        splitNumber: 4,
        splitArea: {
          show: false,
        },
      },
      series: [
        {
          type: 'radar',
          data: sData.map((item) => ({
            value: item.data,
            name: item.name,
            areaStyle: {
              opacity: 0.2,
            },
          })),
        },
      ],
    },
    extend
  );
};
