<template>
  <div style='width:100%;height:100%;'>
    <div class="xbox-title"
         :style="xboxTitle">
      {{currentXboxTitle}}
    </div>
    <div :id="elId"
         :style="xboxChart"></div>
    <jsoneditor v-model='jsoneditorVisible'
                :elInfo='params'
                :complatData='complatData'
                :initStyle='initStyle'
                :clickFunc="clickFunc"
                :dblclickFunc="dblclickFunc"
                :saveConfigDataFun='saveConfigDataFun'
                :jsoneditorData='jsoneditorData'
                :dealWithSourceFun='dealWithSource'>
    </jsoneditor>
  </div>
</template>
<script>
import groupBy from 'lodash/groupBy'
import values from 'lodash/values'
import uuidv1 from 'uuid/v1'
import jsoneditor from '../commonC/jsoneditor'
import mockData from '../commonC/initDbConfigDataJson'
import axios from 'axios'
export default {
  components: {
    jsoneditor
  },
  name: 'hsLineBar',
  props: {
    xboxTitle: {//
      type: Object,
      default() {
        return {}
      }
    },
    xboxChart: {//
      type: Object,
      default() {
        return {}
      }
    },
    height: {// 图表高度
      type: String,
      default: '100%'
    },
    width: {// 图表宽度
      type: String,
      default: '100%'
    },
    allSourceData: {
      type: Object,
      default() {
        return {}
      }
    },
    saveConfigDataFun: {
      type: Function
    },
    clickFunc: {
      type: Function
    },
    dblclickFunc: {
      type: Function
    },
    initStyle: {
      type: Object,
      default() {
        return {}
      }
    },
    complatData: {
      type: Array,
      default() {
        return []
      }
    },
    mock: {
      type: Boolean,
      default: false
    },
    echartType: {
      type: String,
      default: 'lineBar'
    },
    params: {
      type: Object,
      default() {
        return {
          el: 'hsLine',
          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 && newVal.config.hs && newVal.config.hs.hs_group_time !== 0) {
          const { config, sourceData } = newVal
          if (config && sourceData) {
            this.drowEchart(newVal)
          } else {
            this.initMockData()
          }
          // this.drowEchart(newVal)
          var that = this
          this.timer = setInterval(function() {
            that.setRanderDataTime++
          }, newVal.config.hs.hs_group_time)
        } else {
          this.drowEchart(newVal)
        }
        // }
      },
      deep: true
    },
    editData: {
      handler: function(newVal, oldVal) {
        this.jsoneditorData = newVal
      },
      deep: true
    }
  },
  computed: {
    style() {
      return {
        height: this.height,
        width: this.width
      }
    },
    title() {
      const title = this.params.page + '页面' + this.params.position + '配置'
      return title
    }
  },
  data() {
    return {
      currentXboxTitle: '',
      timer: null, // 计时器
      setRanderDataTime: 0, // 计数器
      randerData: [], // 分组后的数组
      pageSourceData: [],
      elId: '',
      chart: null,
      jsoneditorVisible: false, // 是否显示动态配置的弹框
      jsoneditorConfig: {}, // 配置
      jsoneditorSource: [], // 原始数据
      editOptions: {},
      itemLabel: {
        color: 'white',
        fontSize: 14,
        position: 'top',
        show: true,
        formatter: '{a}:{c}'
      },
      editData: {
        config: {},
        sourceData: [],
        sql: ''
      },
      jsoneditorData: {},
      outBoxDom: null
    }
  },
  created() {
    this.elId = uuidv1() // 获取随机id
  },
  mounted() {
    this.$nextTick(_ => {
      this.showEditJsonDialog()
    })
  },
  destroyed() {
    this.outBoxDom.removeEventListener('mousedown', this.boxEventMouse)
    this.chart = null
  },
  beforeDestroy() {
    clearInterval(this.timer)// 清除定时器
    if (this.chart) {
      this.chart.dispose()
    }
    this.chart = null
    this.timer = null
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    clearInterval() {
      clearInterval(this.timer)
    },
    initMockData() {
      this.initMockLineBar(this.params.el)
    },
    // 折线图的模拟数据
    initMockLineBar(type) {
      if (!type) return
      const mockData_ = mockData[type]
      const data = {
        config: mockData_.config,
        sourceData: mockData_.sourceData
      }
      this.editData.config = mockData_.config
      this.editData.sourceData = mockData_.sourceData
      this.editData.sql = mockData_.sql
      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))
      if (!source.sourceData.length) return
      this.editData.config = source.config
      this.editData.sourceData = source.sourceData
      this.editData.sql = source.sql
      const { config, sourceData } = JSON.parse(JSON.stringify(data))
      if (!Object.keys(config).length) return
      this.dealWithSource(config, sourceData)
      if (this.params.el === 'hsPie') {
        console.log(JSON.stringify(config))
      }

      this.draw_complate_options(config)
    },
    // 传入完整的配置
    draw_complate_options(options) {
      if (this.params.el === 'hsPie') {
        console.log(this.chart)
      }
      // 重新绘制的情况
      if (this.chart) {
        this.chart.clear()
        this.chart.setOption(options, true)
        return
      }
      this.chart = this.$drawEcharts(
        this.elId,
        options,
        params => { this.clickFunc(params) },
        params => { this.dblclickFunc(params) },
      )

      // // 新增双击事件
      // this.chart.on('dblclick', (parm) => {
      //   this.$emit('echartDbClick', parm)
      // })
      // // 单击事件
      // this.chart.on('click', (parm) => {
      //   this.$emit('echartClick', parm)
      // })
    },
    // 模拟数据
    get_echart_config() {
      const time = new Date()
      const configP = axios.get(`/static/config-line-bar.json?time=${time}`)
      const sourceDataP = axios.get(`/static/line-bar-source-data.json?time=${time}`)
      Promise.all([configP, sourceDataP])
        .then(res => {
          const config = res[0].data
          const sourceData = res[1].data
          this.jsoneditorConfig = config
          this.jsoneditorSource = sourceData
          const configs = this.dealWithSource(config, sourceData)
          this.draw_complate_options(configs)
        })
    },

    // 处理配置和原始数据
    dealWithSource(config, sourceData) {
      if (this.params.el === 'hsLineBar') {
        return this.dealWithSource_lineBar(config, sourceData)
      } else if (this.params.el === 'hsPie') {
        return this.dealWithSource_pie(config, sourceData)
      } else if (this.params.el === 'hsRadar') {
        return this.dealWithSource_radar(config, sourceData)
      }
    },
    // 处理配置和原始数据
    dealWithSource_lineBar(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[0].dataIndex]._formatter
              if (obj) {
                const value = Object.values(obj)
                const key = Object.keys(obj)
                var str = ''
                for (let i = 0; i < key.length; i++) {
                  str = '<div>' + key[i] + ':' + value[i] + '</div>' + str
                }
                return '<div>' + str + '</div>'
              } else {
                return ''
              }
            }
          }
        }
      }
      const isTransverse = config.isTransverse
      const series = config.series
      if (!series) {
        return
      }
      series.forEach(item => {
        const targetList = this.randerData.filter(jtem => {
          return jtem.sSeries === item.name
        })
        const seriesData = []
        const xData = []
        targetList.forEach(ftem => {
          seriesData.push(ftem.dValue)
          xData.push(ftem.sName)
          this.currentXboxTitle = ftem._sTitle
        })
        item.data = seriesData
        item.xData = xData
        // 支持渐变色
        if (item.itemStyle && item.itemStyle.hsColor) {
          var flage = false
          if (isTransverse) {
            flage = true
          }
          item.itemStyle.color = new this.$echarts.graphic.LinearGradient(
            flage ? 1 : 0, 0, 0, flage ? 0 : 1,
            [
              { offset: 0, color: item.itemStyle.hsColor[0] },
              { offset: 1, color: item.itemStyle.hsColor[1] }
            ]
          )
        }
        // 支持区域填充样式。
        if (item.areaStyle && item.areaStyle.hsColor) {
          item.areaStyle.color = new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: item.areaStyle.hsColor[0] },
            { offset: 1, color: item.areaStyle.hsColor[1] }
          ])
        }
        // 这里显示showValue
        if (!item.label) {
          item.label = this.itemLabel
        }
        item.label.formatter = function(params) {
          const { seriesName, data, name } = params
          const target = sourceData.find(jtem => {
            return jtem.sSeries === seriesName && jtem.dValue === data && jtem.sName === name
          })
          return target.sShowValue
        }
      })
      // 如果要横向显示的话 就得设置yAxis
      if (config.isTransverse) {
        config.yAxis[0].data = series[0].xData
      } else {
        config.xAxis.data = series[0].xData
      }
      return config
    },
    dealWithSource_pie(config, sourceData) {
      this.pageSourceData = values(groupBy(sourceData, '_iPage'))
      if (this.setRanderDataTime === this.pageSourceData.length) {
        this.setRanderDataTime = 0
      }
      this.randerData = this.pageSourceData[this.setRanderDataTime]
      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)
          if (config.title) {
            config.title.text = ftem._sTitle
          } else {
            config.title = ''
          }
        })
        item.data = seriesData
      })
      config.legend.data = legendDatas
      return config
    },
    dealWithSource_radar(config, sourceData) {
      const series = config.series
      if (!series) {
        return
      }
      series.forEach(item => {
        const targetList = sourceData.filter(jtem => {
          return jtem.sSeries === item.name
        })
        const seriesData = []
        targetList.forEach(ftem => {
          seriesData.push(ftem.dValue)
        })
        item.data = seriesData
      })
      return config
    }

  }
}
</script>
