<template>
  <div
    :id="id"
    :class="className"
    :style="{height: height, width: width}"
  />
</template>

<script lang="ts">
import {defineComponent, onActivated, onBeforeUnmount, onDeactivated, onMounted, nextTick, watch} from 'vue'
import resize from './mixins/resize'
import {init} from 'echarts'

export default defineComponent({
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'lineChartsCompoents'
    },
    width: {
      type: String,
      default: '200px',
      required: true
    },
    height: {
      type: String,
      default: '200px',
      required: true
    },
    options: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props) {
    const {
      mounted,
      chart,
      beforeDestroy,
      activated,
      deactivated
    } = resize()
    const initChart = () => {
      const barChart = init(document.getElementById(props.id) as HTMLDivElement)
      barChart.setOption(props.options)
      chart.value = barChart
    }
    watch(
      props,
      (newProps: any) => {
        if (newProps.options) {   // 空间id改变的重新获取值调用接口
          if (chart.value) {
            chart.value.setOption(newProps.options)
          }
        }
      }
    )
    onMounted(() => {
      mounted()
      nextTick(() => {
        initChart()
      })
    })

    onBeforeUnmount(() => {
      beforeDestroy()
    })

    onActivated(() => {
      activated()
    })

    onDeactivated(() => {
      deactivated()
    })

    return {}
  }
})
</script>
