<template>
  <div class="line-content">
    <div id="golden-chart1" v-loading="loading1" class="line-chart" />
    <div id="golden-chart2" v-loading="loading2" class="line-chart" />
    <div id="golden-chart3" v-loading="loading3" class="line-chart" />
  </div>
</template>
<script>
import moment from 'moment'
import storage from '@/utils/storage'
export default {
  data() {
    return {
      subListQuery: {},
      loading1: false,
      loading2: false,
      loading3: false,
      myChartScale1: null,
      myChartScale2: null,
      myChartScale3: null
    }
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.subListQuery.start_time = newValue.startTime
          this.subListQuery.end_time = newValue.endTime
          this.drawEchartsScale()
        }
      }
    }
  },
  created() {
    const appItem = storage.get('appsItem')
    const start_time = this.$store.state.time.globalTimes.startTime
    const end_time = this.$store.state.time.globalTimes.endTime
    this.subListQuery.start_time = start_time
    this.subListQuery.end_time = end_time
    if (JSON.stringify(appItem) !== '{}') {
      this.subListQuery.app_alias = appItem.alias
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.drawEchartsScale()
    })
  },
  methods: {
    getOption(data, type) {
      const option = {
        color: [ // 图例的颜色
          '#00C7F2',
          '#0FCA7A',
          '#F7A23B',
          '#F75D5F'
        ],
        legend: {
          top: '20%',
          left: 0, // 设置水平位置为居中
          orient: 'horizontal' // 设置图例水平排布
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const axisValueLabel = params[0].axisValueLabel
            let str0 = ''
            params.forEach((item, idx) => {
              str0 += `${item.marker}${item.seriesName}<span style='margin-left:30px;text-align:right;font-weight:400'>${item.data}</span>`
              switch (idx) {
                case 0:
                  str0
                  break
                case 1:
                  str0
                  break
                default:
                  str0
              }
              str0 += idx === params.length - 1 ? '' : '<br/>'
            })
            return axisValueLabel + '<br>' + str0
          }
        },
        grid: {
          left: '4%',
          right: '8%',
          bottom: 0,
          top: '40%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.times,
          axisLabel: {
            interval: 'auto', // 每间隔显示一个坐标
            formatter: function(params) {
              const newParams = moment(params).format('MM-DD HH:mm')
              const newArr = newParams.split(' ')
              const time = newArr[0] + '\n' + newArr[1]
              return time
            }
          }
        },
        yAxis: {
          type: 'value',
          scale: true,
          gridIndex: 0,
          axisLabel: {
            formatter: '{value}'
          },
          axisLine: {
            show: true
          },
          axisTick: {
            show: true
          },
          splitLine: {
            show: true
          }
        },
        series: []
      }
      for (const key in data.values) {
        const obj = {
          name: key,
          type: 'line',
          data: data.values[key]
        }
        option.series.push(obj)
      }

      return option
    },
    async drawEchartsScale() {
      // 绘制趋势echarts

      const obj = {
        1: '请求趋势(QPS)',
        2: '延迟分位(ms)',
        3: '状态码占比'
        // 4: 'HTTP Bandwidth(KB)'
        // 5: 'HTTP Status 4xx Percent Per Minute(%)',
        // 6: 'HTTP Status 5xx Percent Per Minute(%)',
      }

      for (let i = 1; i <= 3; i++) {
        this[`loading${i}`] = true
        if (this[`myChartScale${i}`] == null) {
          this[`myChartScale${i}`] = this.$echarts5.init(document.getElementById(`golden-chart${i}`))
          this[`myChartScale${i}`].resize()
        }
        const res = await this.getChartDataFn(obj[i])
        if (res.code === 200) {
          this[`loading${i}`] = false
          const data = res.data
          const option = this.getOption(data, obj[i])
          this[`myChartScale${i}`].setOption(option)
          // this[`myChartScale${i}`].getZr().on('click', params => {
          //   const data = storage.get('paramsValue')
          //   const timestamp = moment(data[0].name).unix()
          //   this.$emit('chartClick', timestamp)
          // })
          // 分别设置每个实例的 group id
          this[`myChartScale${i}`].group = 'group1'
          this.$echarts5.connect('group1')
        }
      }
    },
    getChartDataFn(i) {
      return new Promise((resolve, reject) => {
        const rowItem = storage.get('row')
        const obj = {
          '请求趋势(QPS)': 'request_trend',
          '延迟分位(ms)': 'latency',
          '状态码占比': 'status_trend'
        }
        const par = {
          start_time: this.subListQuery.start_time, // 开始时间
          end_time: this.subListQuery.end_time, // 结束时间
          app_alias: this.subListQuery.app_alias, // 应用别名
          type: obj[i], // 类型，request_trend（默认）、status_trend、latency
          service_name: rowItem.service_name, // 服务名
          method: rowItem.method, // 请求方法
          route: rowItem.route || rowItem.value // 请求路由
        }
        getChartData(par).then(res => {
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.line-content{
  width: 100%;
  min-height: 600px;
}
</style>
