<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="flex:1;">
        <div class="back-header-warpper">
          <span v-if="isShowBackBtn" class="back-header-left" @click="back">
            <i class="el-icon-back" />
            <span class="back-font">返回</span>
          </span>
          <span style="font-size:18px;">{{ cnName }}【 {{ spansQuery.service_name }} 】</span>
        </div>
        <div v-if="activeName==&quot;first&quot;" class="block-container" style="margin-bottom:20px">
          <div class="row">
            <div class="col">
              <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                <div slot="content">
                  <i class="dot" />
                  <span>{{ digitsObj.total }}</span>
                </div>
                <div class="border-bottom">
                  <div class="block-box px-3 py-4">
                    <div class="col-tit">请求总数</div>
                    <div class="col-con">{{ digitsObj.total !=undefined?digitsObj.total:0 }}</div>
                  </div>
                </div>
              </el-tooltip>
            </div>
            <div class="col">
              <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                <div slot="content">
                  <i class="dot" />
                  <span>{{ getErrRate(digitsObj.error_rate) }}</span>
                </div>
                <div class="border-bottom">
                  <div class="block-box px-3 py-4">
                    <div class="col-tit">错误率</div>
                    <div class="col-con">{{ getErrRate(digitsObj.error_rate) || 0 }}</div>
                  </div>
                </div>
              </el-tooltip>
            </div>
            <div class="col">
              <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                <div slot="content">
                  <i class="dot" />
                  <span>{{ digitsObj.avg !=undefined?(digitsObj.avg).toFixed(2):0 }}</span>
                </div>
                <div class="border-bottom">
                  <div class="block-box px-3 py-4">
                    <div class="col-tit">平均延迟(ms)</div>
                    <div class="col-con">{{ digitsObj.avg !=undefined?(digitsObj.avg).toFixed(2):0 }}</div>
                  </div>
                </div>
              </el-tooltip>
            </div>
            <div class="col">
              <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                <div slot="content">
                  <i class="dot" />
                  <span>{{ digitsObj.p50!=undefined?digitsObj.p50.toFixed(2):0 }}</span>
                </div>
                <div class="border-bottom">
                  <div class="block-box px-3 py-4">
                    <div class="col-tit">中位延迟(ms)</div>
                    <div class="col-con">{{ digitsObj.p50!=undefined?(digitsObj.p50.toFixed(2)):0 }}</div>
                  </div>
                </div>
              </el-tooltip>
            </div>
            <!-- <div class="col">
              <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                <div slot="content">
                  <i class="dot" />
                  <span>{{ digitsObj.DB }}</span>
                </div>
                <div class="border-bottom">
                  <div class="block-box px-3 py-4">
                    <div class="col-tit">DATABASE/min</div>
                    <div class="col-con">{{ digitsObj.DB !=undefined?digitsObj.DB :0 }}</div>
                  </div>
                </div>
              </el-tooltip>
            </div> -->
          </div>
        </div>
        <div v-if="activeName==&quot;second&quot;" class="scaleMain-warrper">
          <div v-if="chartLoading3" v-loading="chartLoading3" />
          <div v-else>
            <div v-if="isShowChart3" id="scaleMain" class="scaleMain-box" />
            <div v-else class="no-data-des">暂无数据</div>
          </div>
        </div>
        <div class="link-box">
          <router-link class="to-inline-block" :to="{path:'/service/InterfaceSublist/index'}">
            <el-button type="primary" size="mini">接口解析</el-button>
          </router-link>
          <router-link class="to-inline-block" :to="{path:'/service/process/index'}">
            <el-button type="primary" size="mini">进程解析</el-button>
          </router-link>
        </div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="对比分析" name="first">
            <el-form ref="timeQuery" :model="timeQuery" :inline="true" label-width="100px" style="text-align: right;">
              <el-form-item label="时间跨度" prop="hour_num">
                <el-select v-model="timeQuery.hour_num" placeholder="时间选择" clearable size="small" @keyup.enter.native="handletimeQuery" @change="changetimeQuery">
                  <el-option
                    v-for="time in timeOptions"
                    :key="time.value"
                    :label="time.label"
                    :value="time.value"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <div>
              <h6 class="h6">活跃度</h6>
              <div class="echartsWrap">
                <div>
                  <div id="serviceActive" ref="Echarts" style="width:100vw;height:220px" />
                  <!-- <div v-else class="no-data-des">暂无数据</div> -->
                </div>
              </div>

              <h6 class="h6">错误率分布</h6>
              <div class="echartsWrap">
                <div >
                  <div id="errorRate" style="width:100vw;height:220px" />
                </div>
              </div>

            </div>
          </el-tab-pane>
          <el-tab-pane label="Span列表" name="second">
            <div style="display:flex">
              <el-form ref="spansQuery" :model="spansQuery" :inline="true" label-width="100px">
                <el-form-item label="自定义属性" prop="span_attribute_key">
                  <el-input
                    v-model="spansQuery.span_attribute_key"
                    placeholder="请输入自定义属性"
                    clearable
                    size="small"
                    @keyup.enter.native="handleSpansQuery"
                  />
                </el-form-item>
                <el-form-item label="自定义属性值" prop="span_attribute_value">
                  <el-input
                    v-model="spansQuery.span_attribute_value"
                    placeholder="请输入自定义属性值"
                    clearable
                    size="small"
                    @keyup.enter.native="handleSpansQuery"
                  />
                </el-form-item>
                <el-form-item label="Span类型" prop="span_kind">
                  <el-select v-model="spansQuery.span_kind" placeholder="Span类型" clearable size="small" @keyup.enter.native="handleSpansQuery" @change="changeSpansQuery">
                    <el-option
                      v-for="kind in spanOptions"
                      :key="kind.value"
                      :label="kind.label"
                      :value="kind.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="延迟大于" prop="min_duration">
                  <el-input
                    v-model="spansQuery.min_duration"
                    placeholder=""
                    clearable
                    size="small"
                    type="number"
                    class="Dur_input"
                    @keyup.enter.native="handleSpansQuery"
                  >
                    <template slot="append">ms</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="调用方法" prop="request_method">
                  <el-input
                    v-model="spansQuery.request_method"
                    placeholder="请输入调用方法"
                    clearable
                    size="small"
                    @keyup.enter.native="handleSpansQuery"
                  />
                </el-form-item>
                <!-- <el-form-item label="最大延迟" prop="max_duration">
                  <el-input
                    v-model="spansQuery.max_duration"
                    placeholder="请输入最大延迟"
                    clearable
                    size="small"
                    type="number"
                    @keyup.enter.native="handleSpansQuery"
                  />
                </el-form-item> -->
                <el-form-item label="" prop="only_exception">
                  <el-checkbox v-model="spansQuery.only_exception" :true-label="1" :false-label="0" @keyup.enter.native="handleSpansQuery" @change="changeErrorSpans">仅异常</el-checkbox>
                </el-form-item>
                <el-form-item label="" prop="only_database">
                  <!-- <el-checkbox v-model="spansQuery.only_database"></el-checkbox> -->
                  <el-checkbox v-model="spansQuery.only_database" :true-label="1" :false-label="0" @keyup.enter.native="handleSpansQuery" @change="changeSQLSpans">仅SQL</el-checkbox>
                </el-form-item>
              </el-form>
              <div style="display:inline-block;vertical-align: middle;">
                <el-dropdown
                  style="margin-left: 10px"
                  size="mini"
                  trigger="click"
                  placement="bottom"
                >
                  <el-button type="primary" size="mini">
                    <!-- 下拉菜单 -->
                    <i class="el-icon-s-grid" />
                    <!-- 配置项 -->
                    <i class="el-icon-arrow-down" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-checkbox-group
                      v-model="colSelect"
                      style="text-align: left"
                      @change="columnChange"
                    >
                      <el-dropdown-item
                        v-for="(item, index) in colData"
                        :key="index"
                      ><el-checkbox :label="item.title">{{
                        item.title
                      }}</el-checkbox></el-dropdown-item>
                    </el-checkbox-group>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
            <div style="padding-bottom:16px;">
              <el-table
                v-loading="loading"
                :data="spansList"
                @sort-change="sortChangeTable"
              >
                <el-table-column v-if="isShow('TraceId')" label="TraceId" header-align="center" align="center" prop="trace_id" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    <span @click="goto(scope.row)">{{ scope.row.trace_id }}</span>
                  </template>
                </el-table-column>
                <el-table-column v-if="isShow('服务名')" label="服务名" header-align="center" align="center" prop="service_name" :show-overflow-tooltip="true" />
                <el-table-column v-if="isShow('日期')" label="日期" header-align="center" align="center" sortable="custom" prop="datetime" :show-overflow-tooltip="true" />
                <el-table-column v-if="isShow('方法')" label="方法" header-align="center" align="center" prop="method" :show-overflow-tooltip="true" />
                <el-table-column v-if="isShow('Code')" label="Code" header-align="center" align="center" prop="code" :show-overflow-tooltip="true" />
                <el-table-column v-if="isShow('持续时间(ms)')" header-align="center" align="center" label="持续时间(ms)" prop="duration" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.duration>=2000" type="danger">{{ scope.row.duration }}</el-tag>
                    <el-tag v-if="scope.row.duration<2000" type="info">{{ scope.row.duration }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="isShow('SpanId')"
                  label="SpanId"
                  prop="span_id"
                  header-align="center"
                  align="center"
                  :show-overflow-tooltip="true"
                />
              </el-table>

              <pagination
                v-show="total>0"
                :total="total"
                :page.sync="spansQuery.pageIndex"
                :limit.sync="spansQuery.pageSize"
                @pagination="getServiceSpans"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </template>
  </BasicLayout>
</template>
<script>
import { digitsService, serviceSpans, serviceCompare, serviceErrors, listServiceStats, listService } from '@/api/service'
import storage from '@/utils/storage'
import moment from 'moment'
import BigNumber from 'bignumber.js'
export default {
  data() {
    return {
      timeQuery: {
        app_alias: '',
        service_name: '',
        hour_num: 1
      },
      timeOptions: [
        {
          value: 1,
          label: '1 小时'
        },
        {
          value: 3,
          label: '3 小时'
        },
        {
          value: 6,
          label: '6 小时'
        },
        {
          value: 12,
          label: '12 小时'
        },
        {
          value: 24,
          label: '24 小时'
        }
      ],
      spanOptions: [
        {
          value: 'SPAN_KIND_CLIENT',
          label: 'SPAN_KIND_CLIENT'
        },
        {
          value: 'SPAN_KIND_SERVER',
          label: 'SPAN_KIND_SERVER'
        },
        {
          value: 'SPAN_KIND_INTERNAL',
          label: 'SPAN_KIND_INTERNAL'
        },
        {
          value: 'SPAN_KIND_CONSUMER',
          label: 'SPAN_KIND_CONSUMER'
        },
        {
          value: 'SPAN_KIND_PRODUCER',
          label: 'SPAN_KIND_PRODUCER'
        }
      ],
      // 设置选中的列的复选框
      colSelect: [
        'TraceId',
        '服务名',
        '日期',
        '方法',
        'Code',
        '持续时间(ms)'
      ],
      colData: [
        { title: 'TraceId', istrue: false },
        { title: '服务名', istrue: false },
        { title: '日期', istrue: false },
        { title: '方法', istrue: false },
        { title: 'Code', istrue: false },
        { title: '持续时间(ms)', istrue: false },
        { title: 'SpanId', istrue: false }
      ],
      loading: false,
      total: 0,
      activeName: 'first',
      digitsObj: {},
      digitsQuery: {
        app_alias: '',
        service_name: ''
      },
      timer: null,
      spansQuery: {
        app_alias: '',
        request_method: '',
        service_name: '', // 支持多个，多个并列
        only_exception: 0, // 仅显示异常trace相关
        only_database: 0, // 仅显示数据库相关
        // 支持分页，参数与之前一致
        // 支持时间筛选，参数与之前一致
        trace_id: '', // trace id, 字符串
        span_kind: '', // 固定5个值,建议下拉列表,分别为SPAN_KIND_CLIENT SPAN_KIND_SERVER SPAN_KIND_INTERNAL SPAN_KIND_CONSUMER SPAN_KIND_PRODUCER
        span_attribute_key: '', // 字符串
        span_attribute_value: '', // 字符串
        min_duration: 0, // 最小耗时
        max_duration: 0, // 最大耗时
        start_time: 0,
        end_time: 0,
        pageIndex: 1,
        pageSize: 10,
        sort_field: 'Timestamp',
        sort_type: 'DESC'
      },
      spansList: [],
      ServiceCompareObj: {
        current: [],
        forward: [],
        time: []
      },
      errorRateObj: {
        current: [],
        forward: [],
        time: []
      },
      compareChart: null,
      errorChart: null,
      cnName: '',
      statsQuery: {
        id: 0,
        start_time: '',
        end_time: '',
        service_name: '',
        app_alias: ''
      },
      statsObj: {
        quantiles: {
          p50: [],
          p90: [],
          p99: [],
          time: []
        }
      },
      chartLoading3: false,
      isShowChart3: false,
      isShowBackBtn: true,
      // 查询参数
      queryParams: {
        app_alias: '',
        start_time: '',
        end_time: '',
        pageIndex: 1,
        pageSize: 1,
        service_name: '',
        sort_type: 'desc',
        sort_field: 'total'// total, error_num, max, avg, p50, p90, p99
      }
    }
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.digitsQuery.start_time = newValue.startTime
          this.digitsQuery.end_time = newValue.endTime
          this.statsQuery.start_time = newValue.startTime
          this.statsQuery.end_time = newValue.endTime

          this.spansQuery.start_time = newValue.startTime
          this.spansQuery.end_time = newValue.endTime

          this.queryParams.start_time = newValue.startTime
          this.queryParams.end_time = newValue.endTime

          this.getBasicInfo()// 获取上面基础信息
          this.getlistServiceStats()// 获取延迟比例charts 数据
          this.getServiceSpans()// 获取span列表的table 数据
          this.getServiceCompare()// 获取活跃度echarts数据
          this.getErrorRateCompare()// 获取错误率分布 Echarts数据
          this.isShowChart3 = (((this.statsObj || {}).quantiles || {}).time || []).length > 0
          if (this.activeName === 'second' && this.isShowChart3) {
            setTimeout(() => {
              this.drawEchartsScale(this.statsObj)
            }, 300)
          }
          if (newValue.timeOut) {
            if (newValue.timeOut == 1) {
              clearInterval(this.timer)
            } else {
              clearInterval(this.timer)
              this.Refresh(newValue.timeOut)
            }
          }
        }
      },
      // immediate: true,
      deep: true
    }
    // '$store.state.alias.currentAlias': { // 当前应用切换
    //   handler(newValue, oldValue) {
    //     this.appItem = storage.get('appsItem')
    //     this.currentAlias = newValue
    //     this.statsQuery.app_alias = newValue
    //     this.spansQuery.app_alias = newValue
    //     this.timeQuery.app_alias = newValue
    //     this.digitsQuery.app_alias = newValue
    //     this.getBasicInfo()// 获取上面基础信息
    //     this.getlistServiceStats()// 获取延迟比例charts 数据
    //     this.getServiceSpans()// 获取span列表的table 数据
    //     this.getServiceCompare()// 获取活跃度echarts数据
    //     this.getErrorRateCompare()// 获取错误率分布 Echarts数据
    //   },
    //   deep: true
    // }
  },
  created() {
    // 说明
    // appItem中的id和app_id是一样的
    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.statsQuery.app_alias = this.appItem.alias
      this.digitsQuery.app_alias = this.appItem.alias
      this.queryParams.app_alias = this.appItem.alias
      this.digitsQuery.app_id = this.appItem.id
      this.digitsQuery.start_time = start_time
      this.digitsQuery.end_time = end_time
      this.spansQuery.app_alias = this.appItem.alias
      this.spansQuery.start_time = start_time
      this.spansQuery.end_time = end_time
      this.timeQuery.app_alias = this.appItem.alias
      this.statsQuery.start_time = start_time
      this.statsQuery.end_time = end_time
      this.queryParams.start_time = start_time
      this.queryParams.end_time = end_time
    }

    // 从业务解析中节点中的所属服务跳转过来的和业务解析列表中每列跳转过来的，服务名
    if (this.$route.query.service_name != undefined) {
      this.statsQuery.service_name = this.$route.query.service_name
      this.digitsQuery.service_name = this.$route.query.service_name
      this.spansQuery.service_name = this.$route.query.service_name
      this.timeQuery.service_name = this.$route.query.service_name
      this.queryParams.service_name = this.$route.query.service_name
      this.statsQuery.id = this.$route.query.id

      this.getBasicInfo()// 获取上面基础信息
      this.getServiceSpans()// 获取span列表的table 数据
      this.getServiceCompare()// 获取活跃度echarts数据
      this.getErrorRateCompare()// 获取错误率分布 Echarts数据
      this.getlistServiceStats()// 获取延迟比例charts 数据
    }

    if (this.$route.query.name != undefined) {
      this.cnName = this.$route.query.name
    }

    const strr = window.location.href
    const param = this.parseQueryString(strr)
    if (param.app_alias != undefined && param.service_name != undefined) {
      this.digitsQuery.app_alias = param.app_alias
      this.spansQuery.app_alias = param.app_alias
      this.timeQuery.app_alias = param.app_alias
      this.digitsQuery.service_name = param.service_name
      this.spansQuery.service_name = param.service_name
      this.timeQuery.service_name = param.service_name
      this.getBasicInfo()// 获取上面基础信息
      this.getServiceSpans()// 获取span列表的table 数据
      this.getServiceCompare()// 获取活跃度echarts数据
      this.getErrorRateCompare()// 获取错误率分布 Echarts数据
    }

    this.columnChange()
  },
  mounted() {
    this.getBtnShow()
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    getBasicInfo() { // 获取上面基础信息
      listService(this.queryParams).then(res => {
        if (res.code == 200) {
          this.digitsObj = res.data?.list[0] || {}
        } else {
          this.digitsObj = {}
        }
      })
    },
    getErrRate(error_rate) {
      if (error_rate !== undefined || error_rate !== null) {
        const strErrorRate = numToString(error_rate) // 0.17857142857142858
        let length = 0
        if (strErrorRate !== '0') {
          const arr = strErrorRate && strErrorRate.split('.')
          if (arr && arr.length > 1) {
            length = arr[1].length
          }
        }
        if (error_rate == 0) {
          return error_rate
        } else if (error_rate == 1) {
          return error_rate * 100 + '%'
        } else if (length <= 2) {
          return error_rate * 100 + '%'
        } else {
          return convertToPercentage(error_rate)
        }
      }
      function numToString(num) {
        if (num) {
          let str = num.toString()
          if (str.includes('e')) {
            const parts = str.split('e')
            const base = parts[0]
            const exp = parseInt(parts[1])
            const decimalPlaces = base.split('.')[1]?.length || 0
            const zerosNeeded = Math.abs(exp) - decimalPlaces
            if (exp < 0) {
              str = '0.' + '0'.repeat(zerosNeeded) + base.replace('.', '')
            } else {
              str = base + '0'.repeat(zerosNeeded)
            }
          }
          return str
        }
      }
      function convertToPercentage(value) {
        const bnValue = new BigNumber(value)
        const percentage = bnValue.multipliedBy(100)// 乘法运算
        let roundedPercentage = percentage.decimalPlaces(2, BigNumber.ROUND_FLOOR)// decimalPlaces保留小数位

        // 如果四舍五入后的值小于原始值，手动增加 0.01
        if (roundedPercentage.isLessThan(percentage)) { // 判断是否小于
          roundedPercentage = roundedPercentage.plus(0.01)
        }
        return `${roundedPercentage.toFixed(2)}%`
      }
    },
    getBtnShow() {
      this.$nextTick(() => {
        if (this.$route.query.isShowBackBtn !== undefined) {
          if (this.$route.query.isShowBackBtn == 'false') {
            this.isShowBackBtn = false
          }
        }
        return this.isShowBackBtn
      })
    },
    Refresh(timeOut) {
      this.timer = setInterval(() => {
        this.getBasicInfo()// 获取上面基础信息
        this.getlistServiceStats()// 获取延迟比例charts 数据
        this.getServiceSpans()// 获取span列表的table 数据
        this.getServiceCompare()// 获取活跃度echarts数据
        this.getErrorRateCompare()// 获取错误率分布 Echarts数据
      }, timeOut)
    },
    // 获取延迟比例charts 数据
    getlistServiceStats() {
      this.chartLoading3 = true
      this.statsObj = {}
      listServiceStats(this.statsQuery).then(response => {
        this.chartLoading3 = false
        if (response && response.code == 200) {
          this.statsObj = response.data
        } else {
          this.statsObj = {}
        }
      })
    },
    drawEchartsScale(row) {
      const _this = this
      const myChartScale = this.$echarts5.init(document.getElementById('scaleMain'))
      // 绘制趋势echarts
      const option = {
        tooltip: {
          trigger: 'axis',
          // confine: false,
          // appendToBody: true,
          show: true,
          formatter: function(params) {
            storage.set('paramsValue', params)
            const axisValueLabel = params[0].axisValueLabel
            let str0 = ''
            params.forEach((item, idx) => {
              // str1+=`${}`
              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
          }
        },
        title: {
          text: '延迟比例',
          // subtext: 'ms',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
            color: '#1a2233'
          }
          // triggerEvent: true,
        },
        grid: {
          // top:'5%',
          left: '3%',
          right: '6%',
          bottom: '1%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: row.quantiles.time,
          axisLabel: {
            textStyle: {
              fontSize: 12,
              textAlign: 'center'
            },
            formatter: function(params) {
              // let newParams = moment(params).format('YYYY-MM-DD HH:mm:ss');
              // let newArr = newParams.split(' ')
              // let time = newArr[0] + "\n" + newArr[1]
              // return time;

              let newParams = ''
              const dateStr = params.substring(0, 10)
              // dateStr = dateStr.replace(/\-/g, function(match) {
              //   return match.replace(/\-/g, '.');
              // });
              const timeStr = params.substring(11, 19)
              newParams = dateStr + '\n' + timeStr
              return newParams
            }
          }
        },
        yAxis: {
          type: 'value',
          scale: true,
          gridIndex: 0,
          axisLabel: {
            formatter: '{value}'
          },
          axisLine: {
            show: true
          },
          axisTick: {
            show: true
          },
          splitLine: {
            show: true
          }
        },
        series: [
          {
            name: 'P.50',
            type: 'line',
            stack: 'Total',
            smooth: true,
            symbol: 'none',
            // symbol: 'emptyCircle',//拐点
            data: row.quantiles.p50
          },
          {
            name: 'P.95',
            type: 'line',
            smooth: true,
            stack: 'Total',
            symbol: 'none', // 拐点
            // symbol: 'emptyCircle',//拐点
            data: row.quantiles.p90
          },
          {
            name: 'P.99',
            type: 'line',
            smooth: true,
            stack: 'Total',
            symbol: 'none', // 拐点
            // symbol: 'emptyCircle',//拐点
            data: row.quantiles.p99
          }
        ]
      }
      myChartScale.setOption(option)
      myChartScale.getZr().off('click')
      myChartScale.getZr().on('click', params => {
        const data = storage.get('paramsValue')
        const timestamp = moment(data[0].name).unix()
        _this.spansQuery.start_time = timestamp
        _this.spansQuery.end_time = timestamp
        _this.getServiceSpans()// 获取span列表的table 数据
      })
    },
    parseQueryString(url) {
      var json = {}
      var arr = url.substr(url.indexOf('?') + 1).split('&')
      arr.forEach(item => {
        var tmp = item.split('=')
        json[tmp[0]] = decodeURIComponent(tmp[1])
      })
      return json
    },
    handletimeQuery() {
      this.getServiceCompare()// 获取活跃度echarts数据
      this.getErrorRateCompare()// 获取错误率分布 Echarts数据
    },
    changetimeQuery(val) {
      this.timeQuery.hour_num = val
      this.getServiceCompare()// 获取活跃度echarts数据
      this.getErrorRateCompare()// 获取错误率分布 Echarts数据
    },
    handleSpansQuery() {
      this.getServiceSpans()// 获取span列表的table 数据
    },
    changeErrorSpans(val) {
      this.spansQuery.only_exception = val
      this.getServiceSpans()// 获取span列表的table 数据
    },
    changeSQLSpans(val) {
      this.spansQuery.only_database = val
      this.getServiceSpans()// 获取span列表的table 数据
    },
    changeSpansQuery(val) {
      this.spansQuery.span_kind = val
      this.getServiceSpans()// 获取span列表的table 数据
    },
    // 控制列的显示和隐藏
    columnChange(val) {
      this.colData.filter((i) => {
        if (this.colSelect.indexOf(i.title) !== -1) {
          i.istrue = true
        } else {
          i.istrue = false
        }
      })
    },
    handleClick(tab, event) {
      if (tab.name === 'second') {
        this.isShowChart3 = (((this.statsObj || {}).quantiles || {}).time || []).length > 0
        if (this.isShowChart3) {
          this.$nextTick(() => {
            this.drawEchartsScale(this.statsObj)
          })
        }
      }
    },

    // getDigitsService() {// 原来老的获取上面基础信息
    //   digitsService(this.digitsQuery).then((res) => {
    //     if (res && res.code == 200) {
    //       this.digitsObj = res.data || {}
    //     } else {
    //       this.digitsObj = {}
    //     }
    //   })
    // },
    getServiceSpans() { // 获取span列表的table 数据
      serviceSpans(this.spansQuery).then((res) => {
        if (res && res.code == 200) {
          this.spansList = res.data.list || []
          this.total = Number(res.data.count)
        } else {
          this.spansList = []
          this.total = 0
        }
      })
    },
    getServiceCompare() { // 获取活跃度echarts数据
      this.ServiceCompareObj = {}
      this.$nextTick(() => {
        this.compareChart = this.$echarts5.getInstanceByDom(this.$refs.Echarts)
        if (this.compareChart == null) {
          this.compareChart = this.$echarts5.init(this.$refs.Echarts)
        }
        this.compareChart.showLoading({
          text: ''
        })
        serviceCompare(this.timeQuery).then(res => {
          this.compareChart.hideLoading()
          if (res && res.code == 200) {
            this.ServiceCompareObj = res.data
            this.$nextTick(() => {
              this.initServiceCompareChart(this.ServiceCompareObj)
            })
          } else {
            this.ServiceCompareObj = {}
          }
        })
      })
    },
    initServiceCompareChart(data) {
      if ((data.time || []).length > 0) {
        this.compareChart.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            }
          },
          legend: {
            data: ['当前时段', '前续时段']
            // selected: {
            //       '当前时段': true,
            //       '前续时段对比': false
            //   }
          },
          // toolbox: {
          //   show:true,
          //   feature: {
          //     // dataView: { show: true, readOnly: false },
          //     magicType: { show: true, type: ['line', 'bar'] },
          //     restore: { show: true },
          //     // saveAsImage: { show: true }
          //   }
          // },
          grid: {
            // top:'5%',
            left: '3%',
            right: '16%',
            bottom: '1%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              // type:'time',
              data: data.time
              // axisPointer: {
              //   type: 'shadow'
              // },
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: [
            {
              name: '当前时段',
              type: 'bar',
              tooltip: {
                valueFormatter: function(value) {
                  return value
                }
              },
              barWidth: 8,
              data: data.current != undefined ? data.current : []
            },
            {
              type: 'line',
              name: '前续时段',
              smooth: true,
              tooltip: {
                valueFormatter: function(value) {
                  return value
                }
              },
              lineStyle: {
                width: 3
              },
              data: data.forward != undefined ? data.forward : []
            }
          ]
        })

        this.compareChart.group = 'group1'
        this.$echarts5.connect('group1')
      } else {
        this.compareChart.setOption({
          title: {
            text: '暂无数据',
            x: 'center',
            y: 'center',
            textStyle: {
              color: '#999',
              fontSize: 14
            }
          }
        })
      }
    },
    getErrorRateCompare() { // 获取错误率分布 Echarts数据
      this.errorRateObj = {}
      this.$nextTick(() => {
        this.errorChart = this.$echarts5.getInstanceByDom(document.getElementById('errorRate'))
        if (this.errorChart == null) {
          this.errorChart = this.$echarts5.init(document.getElementById('errorRate'))
        }
        this.errorChart.showLoading({
          text: ''
        })
        serviceErrors(this.timeQuery).then(res => {
          this.errorChart.hideLoading()
          if (res.code == 200) {
            this.errorRateObj = res.data
            this.isShowChart2 = (((res.data || {}).time) || []).length > 0
            this.initErrorRateCompareChart(this.errorRateObj)
          } else {
            this.errorRateObj = {}
          }
        })
      })
    },
    initErrorRateCompareChart(data) {
      if ((data.time || []).length > 0) {
        this.errorChart.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            }
          },
          legend: {
            data: ['当前时段', '前续时段']
            // selected: {
            //       '当前时段': true,
            //       '前续时段对比': false
            //   }
          },
          // toolbox: {
          //   show:true,
          //   feature: {
          //     // dataView: { show: true, readOnly: false },
          //     magicType: { show: true, type: ['line', 'bar'] },
          //     restore: { show: true },
          //     // saveAsImage: { show: true }
          //   }
          // },
          grid: {
            // top:'5%',
            left: '3%',
            right: '16%',
            bottom: '1%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: data.time
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: [
            {
              name: '当前时段',
              type: 'bar',
              tooltip: {
                valueFormatter: function(value) {
                  return value
                }
              },
              barWidth: 8,
              data: data.current != undefined ? data.current : []
            },
            {
              type: 'line',
              name: '前续时段',
              tooltip: {
                valueFormatter: function(value) {
                  return value
                }
              },
              lineStyle: {
                width: 3
              },
              data: data.forward != undefined ? data.forward : []
            }
          ]
        })

        this.errorChart.group = 'group1'
        this.$echarts5.connect('group1')
      } else {
        this.errorChart.setOption({
          title: {
            text: '暂无数据',
            x: 'center',
            y: 'center',
            textStyle: {
              color: '#999',
              fontSize: 14
            }
          }
        })
      }
    },
    back() {
      this.$router.go(-1)
      // this.$router.push({
      //   path: '/service/service/index'
      // })
    },
    goto(row) {
      const datetime = Date.parse(row.datetime) / 1000
      const href = this.$router.resolve({
        path: '/latency/index',
        query: {
          id: row.trace_id,
          span_id: row.span_id,
          datetime: datetime
        }
      })
      window.open(window.location.origin + '/' + href.href, '_blank')
    },
    isShow(label) {
      return this.colData.filter(i => i.title === label)[0].istrue
    },
    sortChangeTable(val) {
      // desc（倒序）和asc（正序）
      if (val.order === 'descending') {
        this.spansQuery.sort_type = 'DESC'
      } else if (val.order === 'ascending') {
        this.spansQuery.sort_type = 'ASC'
      }
      this.getServiceSpans()// 获取span列表的table 数据
    }

  }

}
</script>
<style lang="scss" scoped>
.echartsWrap{
  width:100%;
  height: 240px;
}
.h6{
  font-size: 16px;
  font-weight: bold;
  color: #1a2233;
}
.Dur_input ::v-deep .el-input__inner{
  width:100px;
}
.noData{
    width: 100%;
    height: 200px;
    background: #fff;
}
.no-data-des{
  text-align: center;
  font-size: 14px;
  height: 288px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
}
.noData_title{
    margin-bottom: 0px;
    padding: 2px 5px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    font-size: 14px;
    font-weight: 500;
    line-height: 1.57143;
    font-family: Inter, Helvetica, Arial, sans-serif;
}
.link-box{
  display:none;
  text-align: right;
  // position:relative;
  // top:26px;
  .to-inline-block{
    display: inline-block;
    + .to-inline-block{
      margin-left:10px;
    }
    button{
      font-size:14px;
    }
  }
}
.scaleMain-warrper{
  width:100%;
  height:240px;
  margin-bottom:36px;
  margin-top:16px
}

.scaleMain-box{
  width:100%;
  height:240px;
}
.back-font{
  font-size: 14px;
  font-weight: bold;
}
.back-header-left .el-icon-back{
  font-size: 18px;
  margin-right: 6px;
  align-self: center;
}
.back-header-left{
  display: flex;
  align-items: center;
  margin-right: 40px;
  border-right: 1px solid #dcdfe6;
  padding-right: 20px;
  cursor: pointer;
  display: inline-block;
}
.back-header-warpper{
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
::v-deep .el-table tr{
  cursor: pointer;
}
</style>
