<template>
  <div
    :style="{ width: '100%', height: '100%' }"
    ref="chartDom"
  ></div>
  <!--     :style="{ width: props.option.width, height: props.option.height }" -->
</template>

<script>
export default {
  name: 'HsLineChart',
}
</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: [],
  },
})
console.log(props.option, '-----')
// 横坐标
// eslint-disable-next-line vue/no-setup-props-destructure
let keyName = props.data.columns[0]
let xData = reactive([])
props.data.rows.map((item) => {
  xData.push(item[keyName])
})

// series
let series = reactive([])
for (let i = 1; i < props.data.columns.length; i++) {
  series[i - 1] = {
    name: props.data.columns[i],
    type: 'line',
    stack: 'Total',
    smooth: true,
    data: [],
  }
  props.data.rows.map((item) => {
    series[i - 1].data.push(item[props.data.columns[i]])
  })
}

const defalutOption = reactive({
  color: [
    '#1890FF',
    '#13C2C2',
    '#2EC25B',
    '#FACC14',
    '#EF4864',
    '#8543E0',
    '#d87a80',
    '#9cbbff',
    '#d9d0c7',
    '#87a997',
    '#d49ea2',
    '#5b4947',
    '#1890FF',
  ],
  grid: {
    containLabel: true,
    left: 10,
    right: 10,
  },
  tooltip: {
    trigger: 'axis',
    backgroundColor: '#6f6f6f',
    textStyle: {
      color: '#fff',
    },
  },
  toolbox: {
    feature: {
      saveAsImage: {},
    },
  },
  legend: {},
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: xData,
  },
  yAxis: {
    type: 'value',
  },
  series: series,
})
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>
