<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-if="visible"
      :visible.sync="visible"
      width="75%"
      destroy-on-close>
      <div  v-loading="dataListLoading" >

        <el-row :gutter="20">
          <el-col :span="24">
            <el-card>
              <div v-show="!showCiyun" id="jobresultshow" style="min-height: 400px;">
                暂无数据
              </div>
              <div  v-show="showCiyun" id="jobresultshowCiYun" style="min-height: 400px;">
                暂无数据
              </div>
            </el-card>
          </el-col>
          <el-col :span="24">
              <div style="text-align: center;margin-top: 20px">
                <span style="">{{title  }} :    </span><el-select v-model="selectValue" placeholder="请选择" size="mini">
                <el-option
                  v-for="item in tableClo"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
              </div>
          </el-col>
        </el-row>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import echarts from 'echarts'
// cnpm install echarts-wordcloud@1.1.3 --save
import 'echarts-wordcloud/dist/echarts-wordcloud.min'
export default {
  name: 'jobResult',
  data () {
    return {
      dataList: [],
      visiDataMap: {},
      tableClo: [],
      visible: true,
      info: null,
      title: '',
      selectValue: '-1',
      dataListLoading: false,
      showCiyun: false,
      chartLine: null,
      charWordCloud: null
    }
  },
  watch: {
    selectValue:
    {
      immediate: false, // 初始化时让handler调用一下
      handler (newValue, oldValue) {
        if (oldValue !== '-1') {
          this.dataListLoading = true
          this.charDecisionTree(newValue)
          this.dataListLoading = false
        }
      }
    }
  },
  methods: {
    init (info) {
      this.visible = true
      this.info = info
      this.title = info.jobName
      this.dataList = []
      this.tableClo = []
      this.visiDataMap = {}
      this.getJobRes()
      // console.log(info)
    },
    getJobRes () {
      this.dataListLoading = true
      this.visiDataMap = {}
      var visiData = {}
      this.$http({
        url: this.$http.snoopUrl('/v1/metrics/values'),
        methods: 'get',
        params: this.$http.adornParams({
          'offset': 0,
          'size': 100,
          'metricName': this.info.jobName
        })
      }).then((data) => {
        if (data.data.length && data.status === 200) {
          this.dataList = data.data
          let fristSign = true
          for (const item of this.dataList) {
            let time = this.timeFormater(item.tmst)
            for (let key in item.value) {
              if (fristSign) {
                this.visiDataMap[key] = []
              }
              if (typeof (item.value[key]) !== 'object') {
                visiData = {
                  'time': time,
                  'value': item.value[key].toString()
                }
                this.visiDataMap[key].push(visiData)
              } else {
                for (const i in item.value[key]) {
                  let name, count
                  for (const category in item.value[key][i]) {
                    if (category !== 'count') {
                      name = item.value[key][i][category]
                      count = item.value[key][i].count
                    }
                  }
                  visiData = {
                    'time': time,
                    'name': name,
                    'value': count
                  }

                  this.visiDataMap[key].push(visiData)
                }
              }
            }
            fristSign = false
          }
          this.tableClo = Object.keys(this.dataList[0].value)
          this.selectValue = this.tableClo[0]
          this.dataListLoading = false
          // console.log(this.tableClo)
        } else {
          this.tableClo = []
          this.dataListLoading = false
        }
        this.$nextTick(() => {
          this.charDecisionTree(this.selectValue)
        })
      })
    },
    timeFormater (value) {
      // console.log('@', value)
      var date = new Date(value)
      // let years = date.getFullYear()
      // let month = (date.getMonth() + 1) > 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)
      // let day = (date.getDate() >= 10) ? date.getDate() : '0' + date.getDate()
      let hours = (date.getHours() >= 10) ? date.getHours() : '0' + date.getHours()
      let minutes = (date.getMinutes() >= 10) ? date.getMinutes() : '0' + date.getMinutes()
      let seconds = (date.getSeconds() >= 10) ? date.getSeconds() : '0' + date.getSeconds()
      if (value) {
        // return years + '-' + month + '-' + day + '' + hours + ':' + minutes + ':' + seconds
        return hours + ':' + minutes + ':' + seconds
      } else {
        return 'N/A'
      }
    },
    charDecisionTree (cloum) {
      if (cloum.search('top10') === -1) {
        this.showCiyun = false
        this.initChartLine(cloum)
      } else {
        this.showCiyun = true
        this.$nextTick(() => {
          this.initCharWordCloud(cloum)
        })
      }
    },
    // 折线图
    initChartLine (cloum) {
      let datas = this.visiDataMap[cloum]
      // console.log(datas)
      if (datas && cloum !== '-1') {
        let xdata = []
        let ydata = []
        datas.map((data) => {
          xdata.push(data['time'])
          ydata.push(data['value'])
        })
        var option = {
          title: {
            text: this.title + ':' + this.selectValue
          },
          tooltip: {
            trigger: 'axis'
          },
          // legend: {
          //   data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
          // },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          toolbox: {
            feature: {
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: xdata.reverse()
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: 'value',
              type: 'line',
              stack: '总量',
              data: ydata.reverse()
            }
          ]
        }
        this.chartLine = echarts.init(document.getElementById('jobresultshow'))
        this.chartLine.setOption(option)
        // window.addEventListener('resize', () => {
        //   this.chartLine.resize()
        // })
      }
    },
    // 词云
    initCharWordCloud (cloum) {
      let datas = this.visiDataMap[cloum]
      if (datas && cloum !== '-1') {
        var option = {
          title: {
            text: this.title + ':' + this.selectValue
          },
          tooltip: {
            show: true,
            position: 'top',
            textStyle: {
              fontSize: 30
            }
          },
          series: [{
            type: 'wordCloud',
           // 用来调整词之间的距离
            gridSize: 30,
           // 用来调整字的大小范围

            sizeRange: [14, 60],
           // 用来调整词的旋转方向，，[0,0]--代表着没有角度，也就是词为水平方向，需要设置角度参考注释内容
           // rotationRange: [-45, 0, 45, 90],
           // rotationRange: [ 0,90],
            rotationRange: [0, 0],
           // 随机生成字体颜色
            textStyle: {
              normal: {
                color: function () {
                  return (
                   'rgb(' +
                   Math.round(Math.random() * 255) +
                   ', ' +
                   Math.round(Math.random() * 255) +
                   ', ' +
                   Math.round(Math.random() * 255) +
                   ')'
                  )
                }
              }
            },
           // 位置相关设置
            left: 'center',
            top: 'center',
            right: null,
            bottom: null,
            width: '200%',
            height: '200%',
           // 数据
            data: datas.slice(0, 10)
          }]
        }
        this.charWordCloud = echarts.init(document.getElementById('jobresultshowCiYun'))
        this.charWordCloud.setOption(option)
      }

      // window.addEventListener('resize', () => {
      //   this.charWordCloud.resize()
      // })
    }
  }
}
</script>

<style scoped>

</style>
