/**
 * Created by Zhang Haijun on 2018/6/8.
 */

import echarts from './echarts'
import { onMounted, onUnmounted, ref, watch } from '@vue/composition-api'

export default function (props, updateChart) {
  const chart = ref(null)
  function initChart () {
    const target = document.getElementById(props.id)
    // 目标节点存在
    if (target) {
      chart.value = echarts.init(target)
      window.addEventListener('resize', resize)
      updateChart()
    }
  }
  function resize () {
    setTimeout(() => {
      if (chart.value) chart.value.resize()
    })
  }
  watch(() => props.data, () => {
    if (!chart.value) {
      setTimeout(initChart)
    } else {
      updateChart()
    }
  })
  watch(() => props.setting, updateChart)
  onMounted(() => {
    initChart()
  })
  onUnmounted(() => {
    if (!chart.value) {
      return
    }
    chart.value.dispose()
    chart.value = null
    window.removeEventListener('resize', resize)
  })
  return {
    chart
  }
}
export const commonProps = {
  data: {
    type: null
  },
  setting: {
    type: Object,
    default: function () {
      return {
        fixed: 0
      }
    }
  },
  unit: {
    type: String
  },
  id: {
    type: String,
    default: () => {
      return new Date().getTime().toString() + Math.random()
    }
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '300px'
  },
  options: {
    type: Object
  }
}
export function getLinerColor (startColor, endColor) {
  // 只有一种颜色返回单色
  if (!endColor) return startColor
  return new echarts.graphic.LinearGradient(
    0, 0, 1, 1, [{
      offset: 0,
      color: startColor
    },
    {
      offset: 1,
      color: endColor
    }
    ]
  )
}
