<template>
  <!-- <div id='Latency' v-loading="loading" :style="{ height: height + 'px' }"></div> -->
  <div id="Latency" v-loading="loading" />
</template>

<script>
import resize from './mixins/resize'
import { analyst } from '@/api/apps'
import storage from '@/utils/storage'
import moment from 'moment'

let tmpData = {}

export default {
  mixins: [resize],
  props: {
    percentile: {
      type: Number
    },
    height: {
      type: Number
    },
    serviceName: {
      type: String
    }
  },
  data() {
    return {
      latencyTimer: null,
      loading: true,
      timer: null,
      chart: null,
      LatencyData: {},
      analystQuery: {
        start_time: 0,
        end_time: 0,
        percentile: 0.95,
        service_name: ''
      },
      AnalystData: {},
      app_alias: '',
      appsItem: {},
      option: {
        title: {
          text: '延迟分位图(ms)',
          textStyle: {
            fontSize: 14
          }
          // triggerEvent: true,
        },
        grid: {
          left: '3%',
          right: '7%',
          bottom: '7%',
          containLabel: true
        },
        tooltip: {
          // trigger: 'axis',
          showDelay: 0,
          formatter: function(params) {
            const newParams = moment(params.data[0]).format('YYYY-MM-DD HH:mm:ss')
            const time = newParams + '<br/>' + params.data[1] + 'ms'
            return time
          },
          axisPointer: {
            show: true,
            type: 'cross',
            lineStyle: {
              type: 'dashed',
              width: 1
            }
          }
        },
        toolbox: {
          show: true,
          // feature: {
          // dataZoom: {},
          // brush: {
          //   type: ['rect', 'clear']
          // }

          // },
          showTitle: true,
          feature: {
            rect: {
              show: true,
              title: 'Trace选择'
            }
          },
          left: '57%', // 组件离容器左侧的距离,'left', 'center', 'right','20%'
          top: '3%', // 组件离容器上侧的距离,'top', 'middle', 'bottom','20%'
          right: 'auto', // 组件离容器右侧的距离,'20%'
          bottom: 'auto'
        },
        brush: {
          // toolbox: ['rect'],
          xAxisIndex: 0,
          throttleType: 'debounce',
          throttleDelay: 600
        },
        legend: {
          data: ['Success', 'Failed'],
          left: 'center',
          bottom: -2,
          itemGap: 100,
          textStyle: { // 文字颜色
            fontSize: 12,
            padding: [0, 3], // 文字与图形之间的左右间距
            rich: {
              labelName: {
                fontSize: 14,
                color: '#333',
                fontWeight: 500
              }
            }
          },
          formatter: function(params) {
            // 获取legend显示内容
            const data = tmpData
            let sl, fl
            if (data.success != null) {
              sl = tmpData.success.length
            } else {
              sl = 0
            }
            if (data.failed != null) {
              fl = tmpData.failed.length
            } else {
              fl = 0
            }
            var target
            if (params == 'Success') {
              target = sl
            } else if (params == 'Failed') {
              target = fl
            }
            return target != undefined ? params + ' ' + `{labelName|${target}}` : params
          }
        },
        xAxis: [
          {
            // type: 'category',
            type: 'time',
            scale: true,
            gridIndex: 0,
            axisLabel: {
              textStyle: {
                fontSize: 12,
                textAlign: 'center'
              },
              formatter: function(params) {
                const newParams = moment(params).format('YYYY-MM-DD HH:mm:ss')
                const newArr = newParams.split(' ')
                const time = newArr[0] + '\n' + newArr[1]
                return time
              }
            },
            splitLine: {
              show: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            scale: true,
            gridIndex: 0,
            axisLabel: {
              formatter: '{value}'
            },
            axisLine: {
              show: true
            },
            axisTick: {
              show: true
            },
            splitLine: {
              show: true
            },
            data: [0, 2500, 5000, 7500, 10000]
          }
        ],
        series: [
          {
            name: 'Success',
            type: 'scatter',
            emphasis: {
              focus: 'series'
            },
            // 设置散点图样式
            itemStyle: {
              color: '#13ce66'
            },
            symbolSize: 10, // 设置散点的大小
            // symbolSize: function(arg) {
            //     //  arg表示每个点的横纵坐标
            //     var height = arg[0] / 100.0
            //     var weight = arg[1]
            //     return weight / (height * height)
            // },
            // prettier-ignore
            // data:this.LatencyData.success,
            data: tmpData.success,
            markArea: {
              silent: true,
              itemStyle: {
                color: 'transparent',
                borderWidth: 0,
                borderType: 'dashed'
              }
            }
          },
          {
            name: 'Failed',
            type: 'scatter',
            emphasis: {
              focus: 'series'
            },
            itemStyle: {
              color: '#ff4949'
            },
            // prettier-ignore
            data: tmpData.failed,
            // data:[],
            markArea: {
              silent: true,
              itemStyle: {
                color: 'transparent',
                borderWidth: 0,
                borderType: 'dashed'
              }
            }
          }
        ]
      }
    }
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.analystQuery.start_time = newValue.startTime
          this.analystQuery.end_time = newValue.endTime
          if (this.app_alias != '' || this.app_alias != undefined) {
            this.getAnalyst()
          }

          if (newValue.timeOut) {
            if (newValue.timeOut == 1) {
              clearInterval(this.latencyTimer)
            } else {
              clearInterval(this.latencyTimer)
              this.Refresh(newValue.timeOut)
            }
          }
        }
      },
      // immediate: true,
      deep: true
    },
    option: {
      handler(newVal, oldVal) {
        if (this.chart) {
          if (newVal) {
            this.chart.setOption(newVal)
          } else {
            this.chart.setOption(oldVal)
          }
        } else {
          if (this.app_alias != '' || this.app_alias != undefined) {
            this.getAnalyst()
          }
        }
      },
      deep: true
    },
    percentile: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.analystQuery.percentile = newVal
          this.getAnalyst()
          // this.initChart();
        }
      }
    },
    serviceName: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.analystQuery.serviceName = newVal
          this.getAnalyst()
          // this.initChart();
        }
      }
    }
  },
  created() {
    this.analystQuery.percentile = this.percentile
    this.analystQuery.service_name = this.serviceName
    this.appItem = storage.get('appsItem')
    const start_time = this.$store.state.time.globalTimes.startTime
    const end_time = this.$store.state.time.globalTimes.endTime
    if (JSON.stringify(this.appItem) != '{}') {
      this.app_alias = this.appItem.alias
      this.appId = this.appItem.id
      this.analystQuery.start_time = start_time
      this.analystQuery.end_time = end_time
      this.getAnalyst()
    }

    // if(this.app_alias!=''||this.app_alias!=undefined){
    //   this.getAnalyst();
    // }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  destroyed() {
    clearTimeout(this.timer)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
    clearInterval(this.latencyTimer)
  },
  methods: {
    Refresh(timeOut) {
      this.latencyTimer = setInterval(() => {
        this.getAnalyst()
      }, timeOut)
    },
    // 定时器的执行
    setTime(time) {
      this.timer = setTimeout(() => {
        this.getAnalyst()
      }, time)
    },
    initChart() {
      this.chart = this.$echarts5.init(document.getElementById('Latency'))
      this.chart.clear()
      this.chart.setOption(this.option, true)
      // 默认开启框选
      this.chart.dispatchAction({
        type: 'takeGlobalCursor',
        key: 'brush',
        brushOption: {
          brushType: 'rect' // 指定选框类型
        }
      })
      this.chart.off('brushSelected')
      // 框选选择数据
      this.chart.on('brushSelected', (params) => {
        var brushComponent = params.batch[0]

        let successIndexList = []
        let failIndexList = []
        const successList = []
        const failList = []
        if (brushComponent.selected.length > 1) {
          successIndexList = brushComponent.selected[0].dataIndex
          failIndexList = brushComponent.selected[1].dataIndex
        } else {
          if (brushComponent.selected[0].seriesName != undefined) {
            if (brushComponent.selected[0].seriesName == 'Failed') {
              failIndexList = brushComponent.selected[0].dataIndex
            } else {
              successIndexList = brushComponent.selected[0].dataIndex
            }
          }
        }

        if (successIndexList.length > 0) {
          for (let i = 0; i < this.AnalystData.success.length; i++) {
            for (let j = 0; j < successIndexList.length; j++) {
              if (successIndexList[j] == i) {
                successList.push(this.AnalystData.success[i])
              }
            }
          }
        }

        if (failIndexList.length > 0) {
          for (let k = 0; k < this.AnalystData.failed.length; k++) {
            for (let l = 0; l < failIndexList.length; l++) {
              if (failIndexList[l] == k) {
                failList.push(this.AnalystData.failed[k])
              }
            }
          }
        }

        const arr = successList.concat(failList)
        let dataRange = {}
        if (arr.length > 0) {
          const timeArr = []
          const valueArr = []
          for (let m = 0; m < arr.length; m++) {
            timeArr.push(Math.round(Date.parse(arr[m][0]) / 1000))
            valueArr.push(arr[m][1])
          }

          let minTime = Math.min(...timeArr)
          let maxTime = Math.max(...timeArr)

          let minValue = Math.min(...valueArr)
          let maxValue = Math.max(...valueArr)

          if (minTime == maxTime) {
            minTime = minTime - 1
            maxTime = maxTime + 1
          }

          if (minValue == maxValue) {
            minValue = minValue - 1
            maxValue = maxValue + 1
          }

          // 看是否有成功节点
          if (successIndexList.length > 0) {
            dataRange = {
              start_time: minTime,
              end_time: maxTime,
              min_duration: minValue,
              max_duration: maxValue,
              app_alias: this.app_alias,
              failed: false
            }
          } else {
            dataRange = {
              start_time: minTime,
              end_time: maxTime,
              min_duration: minValue,
              max_duration: maxValue,
              failed: true,
              app_alias: this.app_alias
            }
          }

          const href = this.$router.resolve({
            path: '/latency/index',
            query: dataRange
          })
          window.open(window.location.origin + '/' + href.href, '_blank')
          this.chart.dispatchAction({
            type: 'brush', // 选择action行为
            areas: []// areas表示选框的集合，此时为空即可。
          })
        }
      })
    },
    // 获取latency数据
    getAnalyst() {
      this.loading = true
      analyst(this.analystQuery, this.app_alias).then(res => {
        if (res.code == 200) {
          this.loading = false
          this.AnalystData = res.data
          tmpData = res.data
          this.option.series[0].data = res.data.success
          this.option.series[1].data = res.data.failed
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
#Latency{
  width: 100%;
  height:288px;
  box-sizing: border-box;
}
</style>
