<template>
  <div
    :style="{ width: '100%', height: '100%' }"
    ref="chartDom"
  ></div>
</template>

<script>
export default {
  name: 'HsPieChart',
}
</script>

<script setup>
import {
  ref,
  // inject,
  onMounted,
  onBeforeUnmount,
  defineProps,
  watch,
  reactive,
} from 'vue'
import merge from 'deepmerge'
import * as echarts from 'echarts'
// const echarts = inject("echarts");

//获取 dom 和 父组件数据 并定义"myChart"用于初始化图表
const chartDom = ref()
let myChart = null

const props = defineProps({
  option: Object,
  data: {
    columns: [],
    rows: [],
  },
})

// seriesData

// eslint-disable-next-line vue/no-setup-props-destructure
let len = props.data.columns.length - 1
// eslint-disable-next-line vue/no-setup-props-destructure
let keyValue = props.data.columns[len]
// eslint-disable-next-line vue/no-setup-props-destructure
let nameValue = reactive(props.data.columns[0])

let seriesData = reactive([])
for (let i = 0; i < props.data.rows.length; i++) {
  seriesData[i] = {
    name: props.data.rows[i][nameValue],
    value: props.data.rows[i][keyValue],
  }
}

const defalutOption = reactive({
  color: [
    '#1890FF',
    '#13C2C2',
    '#2EC25B',
    '#FACC14',
    '#EF4864',
    '#8543E0',
    '#d87a80',
    '#9cbbff',
    '#d9d0c7',
    '#87a997',
    '#d49ea2',
    '#5b4947',
    '#1890FF',
  ],
  title: {
    // text: "Referer of a Website",
    // subtext: "Fake Data",
    // left: "center",
  },
  tooltip: {
    trigger: 'item',
  },
  legend: {},
  series: [
    {
      // name: "Access From",
      type: 'pie',
      radius: '50%',
      data: seriesData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
        },
      },
    },
  ],
})

let option = merge(defalutOption, props.option || {})

const resizeHandler = () => {
  myChart.resize()
}

const debounce = (fn, delay) => {
  let timer = null
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.call(this)
    }, delay)
  }
}
const cancalDebounce = debounce(resizeHandler, 0)

onMounted(() => {
  //配置为 svg 形式，预防页面缩放而出现模糊问题；图表过于复杂时建议使用 Canvas
  myChart = echarts.init(chartDom.value, null, { renderer: 'svg' })
  // myChart = echarts.init(chartDom.value);
  myChart.setOption(option, true)
  window.addEventListener('resize', cancalDebounce)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', cancalDebounce)
  myChart.dispose()
})

watch(
  () => option,
  () => {
    myChart.setOption(option, true)
  },
  { deep: true }
)
</script>

<style scoped>
.echart {
  width: 100%;
  height: 100%;
}
</style>
