<template>
  <div :id="elId"  :style='style'></div>
</template>

<script>
  import uuidv1 from 'uuid/v1'
  export default {
    name: 'eachart-line-bar-pie',
    props: {
      height: {// 图表高度
        type: String,
        default: '400px'
      },
      width: {// 图表宽度
        type: String,
        default: '100%'
      },
      backgroundColor: {
        type: String,
        default() {
          return ''
        }
      },
      color: {
        default() {
          return ['#FFA500', '#FF69B4', '#DA70D6', '#B3EE3A', '#B22222', '#98FB98', '#8B4C39']
        }
      },
      textStyle: {
        type: Object,
        default() {
          return {}
        }
      },
      legend: {
        type: Object,
        default() {
          return { data: [], bottom: '-5px' }
        }
      },
      title: {
        type: Object,
        default() {
          return {
            text: '',
            x: 'center',
            y: 'top',
            subtextStyle: {
              align: 'center'
            }
          }
        }
      },
      // 提示栏
      tooltip: {
        type: [Array, Object],
        default() {
          return {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              lable: {
                backgroundColor: '#6a7985'
              },
              animation: true
            }
          }
        }
      },
      tooltip_pie: {
        default() {
          return {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          }
        }
      },
      // 工具栏
      toolbox: {
        type: Object,
        default() {
          return {
            show: false,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false },
              magicType: {
                type: ['line', 'bar']
              },
              restore: {},
              saveAsImage: {}
            }
          }
        }
      },
      grid: {
        type: Object,
        default() {
          return {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          }
        }
      },
      // x轴
      xAxis: {
        type: [Array, Object],
        default() {
          return {
            type: 'category',
            boundaryGap: true
          }
        }
      },
      // y轴
      yAxis: {
        type: [Array, Object],
        default() {
          return [
            {
              type: 'value'
            }
          ]
        }
      },
      series_config: {
        type: Object,
        default() {
          return {}
        }
      },
      series_config_pie: {
        type: Object,
        default() {
          return {
            radius: '50%',
            center: ['50%', '60%'],
            avoidLabelOverlap: false
          }
        }
      },
      // 原始数据
      option_data: {
        default() {
          return {
            title: '',
            data: []
          }
        }
      },
      // 所有完整的配置
      complate_options: {
        type: Object,
        default() {
          return {}
        }
      },
      config_object: {
        type: Object,
        default() {
          return {
          }
        }
      },
      barWidth: {
        type: [Number, String],
        default() {
          return 20
        }
      }
    },
    computed: {
      style() {
        return {
          height: this.height,
          width: this.width
        }
      }
    },
    watch: {
      option_data: {
        handler(newVal, oldVal) {
          newVal ? this.drawing(newVal) : this.drawing(oldVal)
        },
        deep: true // 对象内部属性的监听，关键。
      },
      // 这种情况就是传全部的配置项进来
      complate_options: {
        handler(newVal, oldVal) {
          newVal ? this.draw_complate_options(newVal) : this.draw_complate_options(oldVal)
        }
      }
    },
    data() {
      return {
        elId: '',
        chart: null
      }
    },
    created() {
      this.elId = uuidv1() // 获取随机id
    },
    mounted() {
      this.$nextTick(() => {
        this.drawing(this.option_data)
      })
    },
    methods: {
      // 传入完整的配置
      draw_complate_options(options) {
        this.chart = this.$echarts.init(document.getElementById(this.elId))
        this.chart.setOption(options)
      },
      // 根据某个字段来分组
      grup_by_key(key, list) {
        const parms = {}
        parms.name = key
        const data = []
        list.forEach(item => {
          data.push(item[key])
        })
        parms.data = data
        return parms
      },
      // 转化y轴配置
      tran_y_unit_config(data) {
        if (!data) {
          return
        }
        const y_axis_com = []
        if (typeof data === 'string') {
          y_axis_com[0] = {
            type: 'value',
            axisLabel: {
              show: true,
              interval: 'auto',
              formatter: `{value}${data}`
            }
          }
          return y_axis_com
        }
        const y_unit_config_keys = Object.keys(data)
        if (y_unit_config_keys.length > 1) {
          y_axis_com[0] = {
            type: 'value',
            axisLabel: {
              show: true,
              interval: 'auto',
              formatter: `{value}${data.yAxisIndex0}`
            }
          }
          y_axis_com[1] = {
            type: 'value',
            axisLabel: {
              show: true,
              interval: 'auto',
              formatter: `{value}${data.yAxisIndex1}`
            }
          }
        } else if (y_unit_config_keys.length === 1) {
          const k = y_unit_config_keys[0]
          if (k === 'yAxisIndex0') {
            y_axis_com[0] = {
              type: 'value',
              axisLabel: {
                show: true,
                interval: 'auto',
                formatter: `{value}${data.yAxisIndex0}`
              }
            }
          }
          if (k === 'yAxisIndex1') {
            y_axis_com[0] = this.yAxis
            y_axis_com[1] = {
              type: 'value',
              axisLabel: {
                show: true,
                interval: 'auto',
                formatter: `{value}${data.yAxisIndex1}`
              }
            }
          }
        }
        return y_axis_com
      },
      diy_line_bar_data(data) {
        // 如果没数据就不继续往下走了
        if (!data.data || !data.data.length) return
        const { title: title_config, legend: legend_config, textStyle, backgroundColor, tooltip, grid, yAxis, xAxis: xAxis_config, series_config, color, barWidth } = this.transConfigOption(this.config_object)
        const title = Object.assign(title_config, {
          text: data.title
        })
        const list = data.data
        const x_axis = data.x_axis // x轴对应的哪个字段
        const y_axis = data.y_axis
        const x_axis_data = []
        const series_data = []
        y_axis.forEach(key => {
          series_data.push(this.grup_by_key(key, list))
        })
        // 组装数据
        series_data.forEach(item => {
          Object.assign(item, series_config)
          const prop = item.name
          item.type = data.y_axis_config[prop].type
          const yAxisIndex = data.y_axis_config[prop].yAxisIndex
          item.yAxisIndex = !yAxisIndex ? 0 : 1
          if (item.type === 'bar') {
            item.barWidth = barWidth
          }
        })
        list.forEach(item => {
          x_axis_data.push(item[x_axis])
        })
        const legend = Object.assign(legend_config, {
          data: y_axis
        })
        const xAxis = Object.assign(xAxis_config, {
          data: x_axis_data
        })
        // 配置y轴
        const y_unit_config = this.tran_y_unit_config(data.y_unit_config)
        y_unit_config.forEach(item => {
          Object.assign(item, yAxis)
        })
        return {
          title, // 标题
          color,
          textStyle: textStyle, // 全局字体样式
          backgroundColor: backgroundColor, // 背景颜色
          tooltip: tooltip, // 提示
          grid: grid, // 网格
          legend: legend, // 图例
          xAxis: xAxis, // x轴
          yAxis: y_unit_config || yAxis, // y轴
          series: series_data // 展示的数据
        }
      },
      // 转换line bar的数据
      tran_line_bar_data(data) {
        const data_copy = data
        const { x_axis: x_axis_, series_prop, y_axis: y_axis_, y_axis_config } = data_copy
        const grup_box = {}
        const return_data = []
        data_copy.data.forEach(item => {
          if (!grup_box[item[x_axis_]]) {
            grup_box[item[x_axis_]] = item[x_axis_]
            const parm = {}
            parm[x_axis_] = item[x_axis_]
            return_data.push(parm)
          }
          return_data.forEach(item_ => {
            if (item_[x_axis_] === item[x_axis_]) {
              item_[item[series_prop] ] = item[y_axis_]
            }
          })
        })
        const legend = Object.keys(y_axis_config)
        data_copy.data = return_data
        data_copy.y_axis = legend
        return data_copy
      },
      transConfigOption(config) {
        const { title, textStyle, backgroundColor, tooltip, tooltip_pie, legend, grid, yAxis, xAxis, series_config, series_config_pie, color, barWidth } = config
        return {
          title: title || this.title,
          textStyle: textStyle || this.textStyle,
          backgroundColor: backgroundColor || this.backgroundColor,
          tooltip: tooltip || this.tooltip,
          tooltip_pie: tooltip_pie || this.tooltip_pie,
          grid: grid || this.grid,
          yAxis: yAxis || this.yAxis,
          series_config: series_config || this.series_config,
          series_config_pie: series_config_pie || this.series_config_pie,
          xAxis: xAxis || this.xAxis,
          legend: legend || this.legend,
          color: color || this.color,
          barWidth: barWidth || this.barWidth

        }
      },
      // 转化饼状图数据
      tran_pie_data(data) {
        const datas = []
        const lengend = []
        for (const [key, value] of Object.entries(data.data)) {
          datas.push({ name: key, value })
          lengend.push(key)
        }
        data.data = datas
        data.legend = lengend
        return data
      },
      // 组装饼状图的配置
      diy_pie_data(data) {
        if (!data.data || !data.data.length) return
        const { title: title_config, legend: legend_config, textStyle, backgroundColor, tooltip_pie: tooltip, grid, series_config_pie, color } = this.transConfigOption(this.config_object)
        const title = Object.assign(title_config, {
          text: data.title
        })
        const legend_data = data.legend
        const series_data = [{ data: data.data }]
        // 组装数据
        series_data.forEach(item => {
          Object.assign(item, series_config_pie)
          item.type = 'pie'
        })
        const legend = Object.assign(legend_config, {
          data: legend_data
        })

        var option = {
          title, // 标题
          color,
          textStyle: textStyle, // 全局字体样式
          backgroundColor: backgroundColor, // 背景颜色
          tooltip: tooltip, // 提示
          grid: grid, // 网格
          legend: legend, // 图例
          series: series_data // 展示的数据
        }
        console.log(option)
        return option
      },
      // 画图
      drawing(data) {
        var options = {}
        const copy_data = JSON.parse(JSON.stringify(data))
        if (data.type === 'pie') { // 饼状图
          options = this.diy_pie_data(this.tran_pie_data(copy_data))
        } else { // 无系列字段且是折线图或者柱状图
          const datas = data.series_prop ? this.tran_line_bar_data(copy_data) : copy_data
          options = this.diy_line_bar_data(datas)
        }
        this.chart = this.$echarts.init(document.getElementById(this.elId))
        this.chart.setOption(options)
      }
    }
  }
</script>
