// 生成Excel表格的头部标题栏
// const tHeader = ['名称', '数量']
// 生成Excel表格的内容栏（根据自己的数据内容属性填写）
// const filterVal = ['name', 'value']
// 引入 ECharts 主模块
import { export_json_to_excel } from '@/utils/Export2Excel'
import * as echarts from 'echarts'
import elementResize from 'element-resize-detector' // 尺寸监听组件
export default {
  props: {
    showBtns: {
      //  控制操作按钮操作集合
      type: String,
      default: ''
    }
  },
  watch: {
    datas: {
      // echart 数据
      handler(n, o) {
        this.init()
      },
      deep: true
    },
    options: {
      // echart 配置
      handler(n, o) {
        this.init()
      },
      deep: true
    }
  },
  data() {
    return {
      themeEC4: {
        color: [
          '#c23531',
          '#2f4554',
          '#61a0a8',
          '#d48265',
          '#91c7ae',
          '#749f83',
          '#ca8622',
          '#bda29a',
          '#6e7074',
          '#546570',
          '#c4ccd3'
        ]
      },
      icon:
        'image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAYAAABWzo5XAAAAAXNSR0IArs4c6QAAAcxJREFUOBGlVD9PFFEQn5nd5U4iED4BFZFcZUOhsdDK2PABLEiOiqMwfg07YmNhcQlfglhpQyi1IhBDQW1BQGIOd3eG93vL3O4tRC/HK/bNzv+Z38xjuue8+WiL10LLafl3QZkzqIhZXiRzvztK5/vv+LJtxk3Gy6F1+eJ6hVgeN/l3aNMrW+qcfevzyGXixMaHXwvZn3ztv05gEAJBFzZuHzNCJhAUBSUumOZOUyrz+ewYmaUwQDkFy4QTE3lqhW6yaQ86xnLEqeyx6g/84yBwbAXRCaOxI8tXK1H1NZI+me6Q2UQPmVhDgE9MOmzqdzn7mQIdKms2MuFCB4kY958n9LpXtfHLkdLwsJRSdWCpfG9mFhEGxDnVgVFOKET6zxJ6u15X6/Tng1JiyULjEuFDfE48J++JZ+J83M5zHZfBxxh+Z856Cya2aQx08I+etI/zXMfl8JFi7MM0dJwZIS70BRoLnpdz2+zQTVYKY0BaB4KPe+FXoy0x2rbQdA+A+1/wR7he7Y6etFdjmoGMQcLefX3fPYmTjQVsrwjmhCPEVVIxYqMcOKlWpHMGOmphVx5dXZxCAOY0B7qw8RegnsRg/ZBnZMKRZzLLw3YDmyf57R/BliMAAAAASUVORK5CYII=',
      id: Math.floor(Math.random() * (100000 - 1)), // 组件添加唯一标识,
      chart: null,
      isShowZoom: false, // 放大
      isShowTable: false, // 是否显示表格
      tooltipOptions: {
        extraCssText: 'background: rgba(0,0,0,.6);', // 渐变颜色
        borderWidth: 0,
        textStyle: {
          color: '#fff' // 设置文字颜色
        }
      }
    }
  },
  mounted() {
    // echart初次渲染
    this.$nextTick(() => {
      this.init()
    })
    // 全局监听浏览器大小
    window.addEventListener(
      'resize',
      () => {
        this.chart && this.chart.resize()
        this.$emit('chart', this.chart)
      },
      false
    )
    // 全局监听事件组件销毁生命周期移除
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener('resize', null)
      this.chart && this.chart.clear()
    })
  },
  methods: {
    // 初始化
    init() {
      const _this = this
      try {
        _this.$nextTick(() => {
          // 使用 ref 访问 DOM, 也可以使用 document.getElementById('chart')
          const canvas = _this.isShowZoom
            ? document.getElementById(this.id + 1)
            : document.getElementById(this.id)
          _this.chart = echarts.init(canvas, this.themeEC4)
          if (_this.chart) {
            console.log(this.options)
            _this.chart.setOption(this.options, true)
            // 初始化element-resize-detector组件
            const er = elementResize({
              strategy: 'scroll', // <- 推荐监听滚动，提升性能
              callOnAdd: true // 添加侦听器时是否应调用,默认true
            })
            er.listenTo(canvas, function() {
              echarts.init(canvas).resize() // 当元素尺寸发生改变是会触发此事件，刷新图表
            })
            _this.chart.off('click')
            _this.chart.on('click', params => {
              _this.callback && _this.callback(params)
            })
            // echart 渲染完成之后 抛出echart实例
            _this.chart.on('finished', params => {
              _this.$emit('chart', _this.chart)
            })
          }
        })
      } catch (error) {
        console.log(error)
      }
    },

    // 点击外部
    handlerClickout() {
      this.isShowZoom = false
    },
    // 点击堆积图
    handlerArea() {
      this.isShowTable = false
      this.init()
      this.$emit('handlerArea')
    },
    // 点击折线图
    handlerLine() {
      this.isShowTable = false
      this.init()
      this.$emit('handlerLine')
    },
    // 点击条形图
    handlerBar() {
      this.isShowTable = false
      this.init()
      this.$emit('handlerBar')
    },
    // 点击表格
    handlerTable() {
      this.isShowTable = true
      this.$emit('handlerTable')
    },
    // 点击饼图
    handlerPie() {
      this.isShowTable = false
      this.init()
      this.$emit('handlerPie')
    },
    // 词云图
    handlerCloud() {
      this.isShowTable = false
      this.init()
      this.$emit('handlerCloud')
    },
    // 重播
    handlerRepeat() {
      this.isShowTable = false
      console.log('点击了重播')
      this.chart.clear()
      this.init()
      this.$emit('handlerRepeat')
    },
    // 缩放
    handlerZoom() {
      this.isShowTable = false
      this.isShowZoom = !this.isShowZoom
      console.log('zoom', this.isShowZoom)
      this.chart && this.init()
    },
    // 点击下载
    handlerDownload() {
      const aEle = document.createElement('a')
      if (this.isShowTable) {
        // 导出excel表格
        this.exportExcel()
      } else {
        // 根据主题色设置不同下载图片背景
        this.$nextTick(() => {
          let bgColor = '#fff'
          if (this.$store.state.theme === '0') {
            bgColor = '#1D2432'
          }
          const chartImgUrl = this.chart.getDataURL({
            pixelRatio: 2,
            backgroundColor: bgColor
          })
          aEle.setAttribute('href', chartImgUrl)
          const echartName = this.downloadEchartName ? this.downloadEchartName : 'echart'
          aEle.setAttribute('download', `${echartName}.png`)
          aEle.click()
          aEle.remove()
        })
      }
    },
    // 导出excel
    exportExcel() {
      require.ensure([], () => {
        const tableData = this.tableData ? this.tableData : this.datas
        let data = []
        if (this.tableHeaders.filterVal.length) {
          data = this.formatJson(this.tableHeaders.filterVal, tableData)
        } else {
          data = tableData
        }
        export_json_to_excel(
          this.tableHeaders.tHeader,
          data,
          this.downloadName
        ) // 这里可以定义你的Excel表的默认名称
      })
    },
    // 格式化数据
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    // 表格点击事件
    handlerCellClick(row, column) {
      this.$emit('cellClick', row, column)
    }
  }
}
