<template>
  <div class="ui-chart" :style="style">
    <div ref="control" class="ui-chart__control"></div>
    <div v-if="!ready" class="ui-chart__loading">
      <ui-loading :visible="true"></ui-loading>
    </div>
    <slot></slot>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import Loading from '@huntianning/components/packages/loading'

export default {
  name: 'UiChart',
  components: {
    UiLoading: Loading
  },
  provide() {
    return {
      UiChart: this
    }
  },
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    },
    color: {
      type: [Array, String],
      default: () => ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
    }
  },
  data() {
    return {
      ready: false,
      series: [],
      options: {
        color: Array.isArray(this.color) ? this.color : [this.color],
        xAxis: {},
        yAxis: {},
        grid: {}
      }
    }
  },
  computed: {
    style() {
      return {
        width: this.width,
        height: this.height
      }
    }
  },
  mounted() {
    this.chart = echarts.init(this.$refs.control)
    this.$nextTick(() => {
      this.ready = true
      this.init()
    })
  },
  methods: {
    init() {
      this.inited = true
      this.chart.setOption(this.options)
    },
    setOption(name, value) {
      if (!name || typeof name !== 'string') {
        return
      }
      this.$set(this.options, name, value)
      if (this.inited) {
        this.chart.setOption(this.options)
      }
    },
    addSeries(series) {
      if (!series || !series.id) {
        return
      }
      if (this.series.some(v => v.id === series.id)) {
        return
      }
      this.series.push(series)
      this.setOption('series', this.series)
    },
    updateSeries(id, series) {
      const index = this.getSeriesIndex(id)
      if (index < 0) {
        return
      }
      const nextSeries = Object.assign({}, this.series[index], series)
      this.series.splice(index, 1, nextSeries)
    },
    removeSeries(id) {
      const index = this.getSeriesIndex(id)
      if (index < 0) {
        return
      }
      this.series.splice(index, 1)
    },
    getSeriesIndex(id) {
      let index = -1
      this.series.some((v, i) => {
        if (v.id === id) {
          index = i
          return true
        }
      })
      return index
    },
    doLayout() {
      if (!this.chart) {
        return
      }
      this.chart.resize && this.chart.resize()
    }
  }
}
</script>
<style lang="less">
.ui-chart{
  position: relative;
}
.ui-chart__control{
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.ui-chart__loading{
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 100;
}
</style>
