<template>
  <div style='width:100%;height:100%;'>
    <div :id="elId"
         :style='style'></div>
    <jsoneditor v-model='jsoneditorVisible'
                :elInfo='params'
                :complatData='complatData'
                :saveConfigDataFun='saveConfigDataFun'
                :clickFunc="clickFunc"
                :dblclickFunc="dblclickFunc"
                :jsoneditorData='jsoneditorData'
                :dealWithSourceFun='dealWithSource'>
    </jsoneditor>
  </div>
</template>
<script>
import option from './pie-options.js'
import groupBy from 'lodash/groupBy'
import values from 'lodash/values'
import uuidv1 from 'uuid/v1'
import jsoneditor from '../commonC/jsoneditor'
export default {
  name: 'hsPie',
  components: {
    jsoneditor
  },
  props: {
    height: {
      type: String,
      default: '100%'
    },
    width: {
      type: String,
      default: '100%'
    },
    margin: {
      type: String,
      default: '0 auto'
    },
    allSourceData: {
      type: Object,
      default() {
        return {}
      }
    },
    saveConfigDataFun: {
      type: Function
    },
    clickFunc: {
      type: Function
    },
    dblclickFunc: {
      type: Function
    },
    complatData: {
      type: Array,
      default() {
        return []
      }
    },
    mock: {
      type: Boolean,
      default: false
    },
    params: {
      type: Object,
      default() {
        return {
          el: 'hsPie',
          page: 'page1',
          position: 'table1'
        }
      }
    }
  },
  watch: {
    setRanderDataTime: {
      handler: function(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.drowEchart(this.allSourceData)
        }
      },
      deep: true
    },
    allSourceData: {
      handler: function(newVal, oldVal) {
        if (newVal.config.hs.hs_group_time !== 0) {
          this.drowEchart(newVal)
          var that = this
          this.timer = setInterval(function() {
            that.setRanderDataTime++
          }, newVal.config.hs.hs_group_time)
        } else {
          this.drowEchart(newVal)
        }
      },
      deep: true
    }
  },
  computed: {
    style() {
      return {
        height: this.height,
        width: this.width,
        margin: this.margin
      }
    },
    jsoneditorData() {
      return {
        config: this.jsoneditorConfig,
        sourceData: this.jsoneditorSource
      }
    },
    title() {
      const title = this.params.page + '页面' + this.params.position + '配置'
      return title
    }
  },
  data() {
    return {
      allConfig: {},
      timer: null, // 计时器
      setRanderDataTime: 0, // 计数器
      randerData: [], // 分组后的数组
      pageSourceData: [],
      elId: 'el1',
      option: {},
      chart: null,
      jsoneditorVisible: false, // 是否显示动态配置的弹框
      jsoneditorConfig: {}, // 配置
      jsoneditorSource: [], // 原始数据
      editOptions: {},
      outBoxDom: null
    }
  },
  created() {
    this.elId = uuidv1() // 获取随机id
  },
  mounted() {
    this.initMockData()
    this.showEditJsonDialog()
  },
  destroyed() {
    this.outBoxDom.removeEventListener('mousedown', this.boxEventMouse)
    this.chart = null
  },
  beforeDestroy() {
    clearInterval(this.timer)// 清除定时器
    if (this.chart) {
      this.chart.dispose()
    }
    // if (this.chart) {
    //   this.chart.clear()
    // }
    this.chart = null
    this.timer = null
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    clearInterval() {
      clearInterval(this.timer)
    },
    initMockData() {
      if (this.mock) {
        this.initMockPie()
      } else {
        this.drowEchart(this.allSourceData)
      }
    },
    // pie图的模拟数据
    initMockPie() {
      const data = {
        config: option.config,
        sourceData: option.sourceData
      }
      this.drowEchart(data)
    },
    boxEventMouse(event) {
      const that = this
      event.stopPropagation()
      if (event.shiftKey && event.altKey && !event.ctrlKey) {
        that.jsoneditorVisible = true
      }
    },
    // 弹出可编辑的弹框
    showEditJsonDialog() {
      this.outBoxDom = document.getElementById(this.elId)
      this.outBoxDom.addEventListener('mousedown', this.boxEventMouse)
    },
    dialogClose() {
      this.jsoneditorVisible = false
    },
    drowEchart(data) {
      const source = JSON.parse(JSON.stringify(data))
      this.jsoneditorConfig = source.config
      this.jsoneditorSource = source.sourceData
      const { config, sourceData } = JSON.parse(JSON.stringify(data))
      if (!Object.keys(config).length) return
      this.dealWithSource(config, sourceData)
      this.editOptions = { config, sourceData }
      this.draw_complate_options(config)
    },
    // 传入完整的配置
    draw_complate_options(options) {
      // 重新绘制的情况
      if (this.chart) {
        this.chart.setOption(options, true)
        return
      }
      this.chart = this.$drawEcharts(
        this.elId,
        options,
        params => { this.clickFunc(params) },
        params => { this.dblclickFunc(params) },
      )
    },
    // 处理配置和原始数据
    dealWithSource(config, sourceData) {
      this.pageSourceData = values(groupBy(sourceData, '_iPage'))
      if (this.setRanderDataTime === this.pageSourceData.length) {
        this.setRanderDataTime = 0
      }
      this.randerData = this.pageSourceData[this.setRanderDataTime]
      if (config.hs) {
        if (config.hs.hs_formatter_type) {
          if (config.hs.hs_formatter_type === 1) {
            const _this = this
            config.tooltip.formatter = (a) => {
              const obj = _this.randerData[a.dataIndex]._formatter
              const key = Object.keys(obj)
              const value = Object.values(obj)
              var str = ''
              for (let i = 0; i < key.length; i++) {
                str = '<div>' + key[i] + ':' + value[i] + '</div>' + str
              }
              return '<div>' + str + '</div>'
            }
          }
        }
      }

      const series = config.series
      if (!series) {
        return
      }
      const legendDatas = []
      series.forEach(item => {
        const targetList = this.randerData.filter(jtem => {
          // const targetList = sourceData.filter(jtem => {
          return jtem.sSeries === item.name
        })
        const seriesData = []
        targetList.forEach(ftem => {
          // seriesData.push(ftem.dValue)
          seriesData.push({
            value: ftem.dValue,
            name: ftem.sName
          })
          legendDatas.push(ftem.sName)
          config.title.text = ftem._sTitle
        })
        item.data = seriesData
      })
      config.legend.data = legendDatas
      return config
    }

  }
}
</script>

<style>
</style>
