<template>
  <div class="detail_box">
    <div v-if="AnalystData.grpc" style="border-bottom:1px dashed #eee;padding-bottom:20px">
      <div class="titlesty">grpc信息</div>
      <div style="text-indent: 18px">
        <div id="main1" v-loading="loading" class="echartsbox" style="width:100%;height:300px;" />
      </div>
    </div>
    <div v-if="AnalystData.http" style="border-bottom:1px dashed #eee;padding-bottom:20px">
      <div class="titlesty">https信息</div>
      <div style="text-indent: 18px">
        <div id="main2" class="echartsbox" style="width:100%;height:300px" />
      </div>
    </div>
    <div v-if="AnalystData.kafka" style="border-bottom:1px dashed #eee;padding-bottom:20px">
      <div class="titlesty">kafka信息</div>
      <div style="text-indent: 18px">
        <div id="main3" class="echartsbox" style="width:100%;height:300px" />
      </div>
    </div>
  </div>
</template>

<script>
import resize from './mixins/resize'
import moment from 'moment'
import { getToken } from '@/utils/auth'
export default {
  mixins: [resize],
  data() {
    return {
      queryParams: {
        start_time: 1699941690,
        end_time: 1699945290,
        // app_alias:'UNSET',
        // service_name:'frontend',
        app_alias: '',
        service_name: '',
        percentile: 0.95
      },
      AnalystData: {},
      // topoUrl:'http://observe-front.cestong.com.cn',
      topoUrl: '',
      httpChart: null,
      grpcChart: null,
      kafkaChart: null,
      app_alias: ''
    }
  },
  created() {
    this.queryParams.start_time = this.GetRequest().start_time // 点击应用拓扑节点获取到id
    this.queryParams.end_time = this.GetRequest().end_time // 点击应用拓扑节点获取到id
    this.queryParams.app_alias = this.GetRequest().app_alias // 点击应用拓扑节点获取到id
    this.app_alias = this.GetRequest().app_alias
    this.queryParams.service_name = this.GetRequest().service_name // 点击应用拓扑节点获取到id
    this.queryParams.percentile = this.GetRequest().percentile // 点击应用拓扑节点获取到id
  },
  mounted() {
    if (this.queryParams.app_alias != undefined) {
      this.getList()
    }
    setTimeout(() => {
      if (this.AnalystData.grpc != undefined) {
        this.grpcInitChart(this.AnalystData.grpc)
      }
      if (this.AnalystData.http != undefined) {
        this.httpInitChart(this.AnalystData.http)
      }
      if (this.AnalystData.kafka != undefined) {
        this.kafkaInitChart(this.AnalystData.kafka)
      }
    }, 2000)
  },
  methods: {
    getList() {
      this.loading = true
      // this.topoUrl = window.location.host;
      this.$http({
        // url: `${this.topoUrl}/re/api/v1/service/side`,
        url: '/re/api/v1/service/side',
        method: 'get',
        headers: {
          'Authorization': 'Bearer ' + getToken() // 特定请求的header
        },
        params: this.queryParams
      }).then(res => {
        if (res.data.code == 200) {
          this.loading = false
          this.AnalystData = res.data.data
        }
      })
    },
    GetRequest() {
      var url = window.location.href // 获取url中"?"符后的字串
      // var url = `http://123.56.75.55:8208/#/iframe/nodeDetail?endpoint_id=1&id=81&ip=5.3.4.5&cmdb_tag=1`;
      var theRequest = new Object()
      if (url.indexOf('?') != -1) {
        // var str = url.substring(1);
        var str = url.substring(url.indexOf('?') + 1, url.length)
        var strs = str.split('&')
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
        }
      }
      return theRequest
    },
    grpcInitChart(tmpData) {
      const _this = this
      this.grpcChart = this.$echarts5.init(document.getElementById('main1'))
      this.grpcChart.clear()
      const option = {
        title: {
          text: 'Latency',
          subtext: 'ms',
          textStyle: {
            fontSize: 14
          }
        },
        grid: {
          left: '5%',
          right: '7%',
          bottom: '7%',
          containLabel: true
        },
        tooltip: {
          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,
          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, // 设置散点的大小
            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'
              }
            }
          }
        ]
      }
      this.grpcChart.setOption(option, true)
      this.grpcChart.off('brushSelected')
      // 框选选择数据
      this.grpcChart.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 < tmpData.success.length; i++) {
            for (let j = 0; j < successIndexList.length; j++) {
              if (successIndexList[j] == i) {
                successList.push(tmpData.success[i])
              }
            }
          }
        }

        if (failIndexList.length > 0) {
          for (let k = 0; k < tmpData.failed.length; k++) {
            for (let l = 0; l < failIndexList.length; l++) {
              if (failIndexList[l] == k) {
                failList.push(tmpData.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
            }
          } else {
            dataRange = {
              start_time: minTime,
              end_time: maxTime,
              min_duration: minValue,
              max_duration: maxValue,
              failed: true,
              app_alias: this.app_alias
            }
          }

          const timeAndDuration = JSON.stringify(dataRange)
          const href = this.$router.resolve({
            path: '/latency/index',
            query: {
              data: timeAndDuration
            }
          })
          window.open(window.location.origin + '/' + href.href, '_blank')
          this.grpcChart.dispatchAction({
            type: 'brush', // 选择action行为
            areas: []// areas表示选框的集合，此时为空即可。
          })
        }
      })
    },
    httpInitChart(tmpData) {
      this.httpChart = this.$echarts5.init(document.getElementById('main2'))
      this.httpChart.clear()
      const option = {
        title: {
          text: 'Latency',
          subtext: 'ms',
          textStyle: {
            fontSize: 14
          }
        },
        grid: {
          left: '3%',
          right: '7%',
          bottom: '7%',
          containLabel: true
        },
        tooltip: {
          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,
          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, // 设置散点的大小
            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'
              }
            }
          }
        ]
      }
      this.httpChart.setOption(option, true)
      this.httpChart.off('brushSelected')
      // 框选选择数据
      this.httpChart.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 < tmpData.success.length; i++) {
            for (let j = 0; j < successIndexList.length; j++) {
              if (successIndexList[j] == i) {
                successList.push(tmpData.success[i])
              }
            }
          }
        }

        if (failIndexList.length > 0) {
          for (let k = 0; k < tmpData.failed.length; k++) {
            for (let l = 0; l < failIndexList.length; l++) {
              if (failIndexList[l] == k) {
                failList.push(tmpData.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
            }
          } else {
            dataRange = {
              start_time: minTime,
              end_time: maxTime,
              min_duration: minValue,
              max_duration: maxValue,
              failed: true,
              app_alias: this.app_alias
            }
          }

          const timeAndDuration = JSON.stringify(dataRange)
          const href = this.$router.resolve({
            path: '/latency/index',
            query: {
              data: timeAndDuration
            }
          })
          window.open(window.location.origin + '/' + href.href, '_blank')
          this.httpChart.dispatchAction({
            type: 'brush', // 选择action行为
            areas: []// areas表示选框的集合，此时为空即可。
          })
        }
      })

      //  this.chart.on("legendinverseselect", (params) => {
      //   })
    },
    kafkaInitChart(tmpData) {
      const _this = this
      this.kafkaChart = this.$echarts5.init(document.getElementById('main3'))
      this.kafkaChart.clear()
      const option = {
        title: {
          text: 'Latency',
          subtext: 'ms',
          textStyle: {
            fontSize: 14
          }
        },
        grid: {
          left: '3%',
          right: '7%',
          bottom: '7%',
          containLabel: true
        },
        tooltip: {
          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,
          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, // 设置散点的大小
            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'
              }
            }
          }
        ]
      }
      this.kafkaChart.setOption(option, true)
      this.kafkaChart.off('brushSelected')
      // 框选选择数据
      this.kafkaChart.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 < tmpData.success.length; i++) {
            for (let j = 0; j < successIndexList.length; j++) {
              if (successIndexList[j] == i) {
                successList.push(tmpData.success[i])
              }
            }
          }
        }

        if (failIndexList.length > 0) {
          for (let k = 0; k < tmpData.failed.length; k++) {
            for (let l = 0; l < failIndexList.length; l++) {
              if (failIndexList[l] == k) {
                failList.push(tmpData.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
            }
          } else {
            dataRange = {
              start_time: minTime,
              end_time: maxTime,
              min_duration: minValue,
              max_duration: maxValue,
              failed: true,
              app_alias: this.app_alias
            }
          }

          const timeAndDuration = JSON.stringify(dataRange)
          const href = this.$router.resolve({
            path: '/latency/index',
            query: {
              data: timeAndDuration
            }
          })
          window.open(window.location.origin + '/' + href.href, '_blank')
          this.kafkaChart.dispatchAction({
            type: 'brush', // 选择action行为
            areas: []// areas表示选框的集合，此时为空即可。
          })
        }
      })

      //  this.chart.on("legendinverseselect", (params) => {
      //   })
    }
  }
}
</script>

<style lang="scss" scoped>
.detail_box{
  background:#fff;
  margin-top: -20px;
  .titlesty{
      font-size: 14px;
      font-weight: bold;
      height: 32px;
      line-height: 32px;
      background: rgb(238, 238, 238);
      color: rgb(51, 51, 51);
      padding-left: 20px;
      margin: 20px auto;
      padding-left: 20px;
      padding-right: 15px;
      background: #eee;
      color:#333;
  }
}
</style>>

