<template>
  <div ref="dom" class="charts chart-bar"></div>
</template>

<script>
import echarts from 'echarts'
import tdTheme from './theme.json'
import { on, off } from '@/libs/tools'

echarts.registerTheme('tdTheme', tdTheme)
export default {
  name: 'ChartBar',
  props: {
    // 单列柱状图，列name为x轴，value为y轴
    value: {
      type: Array,
      default: function () {
        return []
      }
    },
    text: String,
    subtext: String,
    color: {
      type: Array,
      default: function () {
        return []
      }
    },
    // 当有多列柱状图展示时的X轴坐标数据
    xAxisData: {
      type: Array,
      default: function () {
        return []
      }
    },
    // y轴坐标单位
    yUnit: {
      type: String,
      default: ''
    },
    // 当有多列柱状图展示时的y轴坐标数据
    seriesData: {
      type: Array,
      default: function () {
        return []
      }
    },
    // x轴标签旋转角度
    xAxisRotate: {
      type: Number,
      default: 0
    }
  },
  watch: {
    xAxisData: {
      handler (nVal, oVal) {
        // console.log(nVal, 'nnnnnnnn')
        if (nVal) {
          // 根据x轴时间长度控制滚动条位置及显示状态 x轴长度大于25时，显示滚动条并且滚动条结束位置在80%
          if (nVal.length > 25) {
            this.isShowZoom = true
            this.xZoomEnd = 80
          } else {
            this.isShowZoom = false
            this.xZoomEnd = 100
          }
          if (nVal.length > 30) {
            this.xZoomEnd = 70
          }
          if (nVal.length > 35) {
            this.xZoomEnd = 60
          }
          if (nVal.length > 40) {
            this.xZoomEnd = 50
          }
          if (nVal.length > 45) {
            this.xZoomEnd = 40
          }
          if (nVal.length > 50) {
            this.xZoomEnd = 30
          }
          this.pageInit()
        }
      },
      deep: true,
      immediate: true // 代表如果在 wacth 里声明了 xAxisData 之后，就会立即先去执行里面的handler方法，如果为 false就跟我们以前的效果一样，不会在绑定的时候就执行
    },
    xAxisRotate: {
      handler (nVal, oVal) {
        if (nVal !== '') {
          this.pageInit()
        }
      },
      deep: true,
      immediate: true
    },
    value: {
      handler (nVal, oVal) {
        if (nVal) {
          this.pageInit()
        }
      },
      deep: true,
      immediate: true
    }
  },
  data () {
    return {
      dom: null,
      isShowZoom: false, // 是否展示滚动条
      xZoomEnd: 100 // x轴滚动条结束位置
    }
  },
  methods: {
    resize () {
      this.dom.resize()
    },
    pageInit () {
      const that = this
      const legend = this.seriesData.map(_ => _.name)
      this.$nextTick(() => {
        const keys = this.value.map(item => (item = item.name))
        const values = this.value.map(item => (item = item.value))
        const xAxisData = this.value.length ? keys : this.xAxisData
        const seriesData = this.value.length ? values : this.seriesData
        const yMax = this.getYMax(this.seriesData) // 计算最大值
        const option = {
          color: this.color,
          title: {
            text: this.text,
            subtext: this.subtext,
            x: 'left'
          },
          legend: {
            data: legend
          },
          tooltip: {
            trigger: 'axis'
          },
          dataZoom: [
            {
              type: 'slider',
              show: this.isShowZoom, // flase直接隐藏图形
              xAxisIndex: [0],
              left: '9%', // 滚动条靠左侧的百分比
              bottom: -5,
              start: 0, // 滚动条的起始位置
              end: this.xZoomEnd, // 滚动条的截止位置（按比例分割你的柱状图x轴长度）
              zoomLock: true // 锁定区域禁止缩放(鼠标滚动会缩放,所以禁止)
            }
          ],
          xAxis: {
            type: 'category',
            data: xAxisData,
            axisLabel: {
              interval: 0,
              rotate: this.xAxisRotate // 刻度标签旋转的角度，在类目轴的类目标签显示不下的时候可以通过旋转防止标签之间重叠。旋转的角度从 -90 度到 90 度。
            }
          },
          yAxis: {
            type: 'value',
            min: 0,
            max: yMax,
            axisLabel: {
              formatter: `{value} ${this.yUnit}`
            },
            // interval: 2,
            position: 'left'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          }
        }
        // 单柱图
        if (this.value.length) {
          option.series = [
            {
              data: seriesData,
              type: 'bar',
              barWidth: 35,
              label: {
                normal: {
                  show: true,
                  position: 'top'
                }
              }
            }
          ]
        } else {
          option.series = this.seriesData
        }
        // 已创建的先销毁
        if (this.dom) {
          this.dom.dispose()
        }
        this.dom = echarts.init(this.$refs.dom, 'tdTheme')
        this.dom.setOption(option)
        // 更新y轴最大值
        this.dom.on('legendselectchanged', function (params) {
          // console.log(params, that.seriesData, 'legendselectchanged')
          const data = that.seriesData.filter(item => params.selected[item.name])
          option.yAxis.max = that.getYMax(data)
          that.dom.setOption(option)
        })
        // 解决首次加载宽度超出容器bug
        this.dom.resize()
        on(window, 'resize', this.resize)
      })
    },
    // 计算y轴最大值
    getYMax (data) {
      let max = []
      data.map(item => {
        max = max.concat(item.data)
      })
      return Math.max.apply(null, max)
    }
  },
  mounted () {
    this.pageInit()
  },
  beforeDestroy () {
    off(window, 'resize', this.resize)
  }
}
</script>
