<template>
  <div class="line-content">
    <div class="line-box">
      <div class="h6">请求趋势(QPS)</div>
      <div id="chart1" class="line-chart" />
      <!-- <div class="line-chart">
        <div class="line-tilte">请求趋势(QPS)</div>
        <div class="line-des">暂无数据</div>
      </div> -->
    </div>
    <div class="line-box">
      <div class="h6">延迟分位(ms)</div>
      <div id="chart2" class="line-chart" />
    </div>
    <div class="line-box">
      <div class="h6">状态码占比</div>
      <div id="chart3" class="line-chart" />
    </div>
  </div>
</template>
<script>
import moment from 'moment'
// import resize from '../../service/mixins/resize'
import storage from '@/utils/storage'
import { getChartData } from '@/api/service'
export default {
  data() {
    return {
      myChartScale1: null,
      myChartScale2: null,
      myChartScale3: null,
      subListQuery: {
        start_time: 0,
        end_time: 0,
        app_alias: ''
      },
      // loading1: false,
      // loading2: false,
      // loading3: false,
      // display1: false,
      // display2: false,
      // display3: false,
      chartData1: {
        times: []
      },
      chartData2: {
        times: []
      },
      chartData3: {
        times: []
      }
    }
  },
  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.drawEchartsScale()
  },
  methods: {
    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)
        })
      })
    },
    async drawEchartsScale() {
      // 绘制趋势echarts

      const obj = {
        1: '请求趋势(QPS)',
        2: '延迟分位(ms)',
        3: '状态码占比'
      }
      this.$nextTick(() => {
        for (let i = 1; i <= 3; i++) {
          if (this[`myChartScale${i}`] == null) {
            this[`myChartScale${i}`] = this.$echarts5.init(document.getElementById(`chart${i}`))
            this[`myChartScale${i}`].resize()
          }
          this[`myChartScale${i}`].showLoading({
            text: ''
          })
          this.getChartDataFn(obj[i]).then((res) => {
            this[`myChartScale${i}`].hideLoading()
            if (res.code === 200) {
              const data = res.data
              data.text = obj[i]
              // this[`display${i}`] = data.times.length > 0
              this[`chartData${i}`] = data
              if (data.times.length > 0) {
                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')
              } else {
                this[`myChartScale${i}`].setOption({
                  title: {
                    text: '暂无数据',
                    x: 'center',
                    y: 'center',
                    textStyle: {
                      color: '#999',
                      fontSize: 14
                    }
                  }
                })
              }
            }
          })
        }
      })
    },
    getOption(data, type) {
      const option = {
        color: [ // 图例的颜色
          '#00C7F2',
          '#0FCA7A',
          '#F7A23B',
          '#F75D5F'
        ],
        // title: {
        //   top: 0,
        //   text: data.text,
        //   textStyle: {
        //     fontSize: 16,
        //     fontWeight: 'bold', // 标题字体粗细
        //     color: '#1a2233'
        //   }
        // },
        legend: {
          top: '5%',
          left: 0, // 设置水平位置为居中
          orient: 'horizontal' // 设置图例水平排布
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            storage.set('paramsValue', 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
          }
        },
        // toolbox: {
        //     show: true,
        //     top: '8%',
        //     feature: {
        //         dataZoom: { //数据区域缩放。目前只支持直角坐标系的缩放
        //             show: false, //是否显示该工具。
        //         },
        //         dataView: {  //数据视图工具，可以展现当前图表所用的数据，编辑后可以动态更新
        //             show: false
        //         },
        //         magicType: { type: ['line', 'bar'] },
        //         restore: {},//配置项还原。
        //         saveAsImage: { // 保存为图片。
        //            show: false, //是否显示该工具。
        //         }
        //     }
        // },
        grid: {
          left: '4%',
          right: '8%',
          bottom: 20,
          top: '20%',
          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 tempType = type === '状态码占比' ? 'bar' : 'line'
        const obj = {
          name: key,
          type: tempType,
          smooth: true,
          data: data.values[key]
        }
        option.series.push(obj)
      }

      return option
    }
  }
}
</script>
<style lang="scss" scoped>

.line-content{
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  flex-flow:row wrap;
  .h6{
    font-size: 16px;
    font-weight: bold;
    color: #1a2233;
  }
  .line-box{
    width: 33%;
    height:100%;
    .line-chart{
      width: 100%;
      height: 100%;
    }
    .line-tilte {
      text-align: left;
      font-size: 16px;
      font-weight: bold;
      color:#1a2233;
    }
    .line-des {
      text-align: center;
      font-size: 14px;
      height: calc(100% - 30px);
      display: flex;
      align-items: center;
      justify-content: center;
      color: #606266;
    }
  }
}
</style>
