<template>
  <div ref="chartRef" :style="{ height, width }"></div>
</template>
<script lang="ts" setup>
  import { onMounted, PropType, ref, Ref } from 'vue';
  import { useECharts } from '@/hooks/web/useECharts';

  defineProps({
    width: {
      type: String as PropType<string>,
      default: '100%',
    },
    height: {
      type: String as PropType<string>,
      default: '209px',
    },
  });
  const chartRef = ref<HTMLDivElement | null>(null);
  const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

  let color = ['#0E7CE2', '#FF8352', '#E271DE', '#F8456B', '#00FFFF', '#4AEAB0'];
  let echartData = [
    {
      name: '互联网',
      value: 525,
    },
    {
      name: '实体门店',
      value: 305,
    },
    {
      name: '境外',
      value: 134,
    },
    {
      name: '其他',
      value: 60,
    },
  ];

  let total = echartData.reduce((a, b) => {
    return a + b.value * 1;
  }, 0);
  let maxObj = echartData.reduce((prev, cur) => {
    return prev.value > cur.value ? prev : cur;
  });
  let maxPerNum = Math.floor((maxObj.value / total) * 100) + '%';
  const option = {
    color: color,
    title: [
      {
        text: maxPerNum,
        x: '50%',
        y: '40%',
        textAlign: 'center',
        textStyle: {
          fontSize: '24',
          fontWeight: '500',
          color: '#000000',
          textAlign: 'center',
        },
      },
      {
        text: '最大来源占比',
        left: '50%',
        top: '52%',
        textAlign: 'center',
        textStyle: {
          fontSize: '12',
          fontWeight: '400',
          color: '#5c5a68',
          textAlign: 'center',
        },
      },
    ],
    series: [
      {
        type: 'pie',
        radius: ['45%', '60%'],
        center: ['50%', '50%'],
        data: echartData,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2,
        },
      },
    ],
  };

  onMounted(() => {
    setOptions(option as any);
  });
</script>
