<!-- eslint-disable eqeqeq -->
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="flex:1;">
        <div class="block-container" style="margin-bottom:20px">
          <div class="row">
            <div class="col hoverCursor" @click="goPage">
              <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                <div slot="content">
                  <i class="dot" />
                  <span>{{ digitsObj.biz !=undefined? digitsObj.biz:0 }}</span>
                </div>
                <div class="border-bottom">
                  <div class="block-box px-3 py-4">
                    <div class="col-tit">业务总数</div>
                    <div class="col-con">{{ digitsObj.biz !=undefined? digitsObj.biz:0 }}</div>
                  </div>
                </div>
              </el-tooltip>
            </div>
            <div class="col hoverCursor" @click="go('/service/service/index')">
              <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                <div slot="content">
                  <i class="dot" />
                  <span>{{ digitsObj.service !=undefined? digitsObj.service:0 }}</span>
                </div>
                <div class="border-bottom">
                  <div class="block-box px-3 py-4">
                    <div class="col-tit">服务总数</div>
                    <div class="col-con">{{ digitsObj.service !=undefined? digitsObj.service: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"></i>
                  <span>12</span>
                </div>
                <div class="border-bottom">
                  <div class="block-box px-3 py-4">
                    <div class="col-tit">日志总数</div>
                    <div class="col-con">{{12}}</div>
                  </div>
                </div>
              </el-tooltip>
            </div> -->
            <!-- <div class="col">
              <el-tooltip placement="bottom" effect="dark" :visible-arrow='false'>
                <div slot="content">
                  <i class="dot"></i>
                  <span>{{digitsObj.error}}</span>
                </div>
                <div class="border-bottom">
                  <div class="block-box px-3 py-4">
                    <div class="col-tit">错误总数</div>
                    <div class="col-con">{{digitsObj.error !=undefined?digitsObj.error: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.error_rate !=undefined?Number(digitsObj.error_rate).toFixed(2):0 }}</span>
                </div>
                <div class="border-bottom">
                  <div class="block-box px-3 py-4">
                    <div class="col-tit">错误率</div>
                    <div class="col-con">{{ digitsObj.error_rate !=undefined?(digitsObj.error_rate*100).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.error_per_minute != undefined?Number(digitsObj.error_per_minute).toFixed(2):0 }}</span>
                </div>
                <div class="border-bottom">
                  <div class="block-box px-3 py-4">
                    <div class="col-tit">错误频率/min</div>
                    <div class="col-con">{{ digitsObj.error_per_minute !=undefined?(digitsObj.error_per_minute).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.trace_per_minute!=undefined?Number(digitsObj.trace_per_minute).toFixed(2):0 }}</span>
                </div>
                <div class="border-bottom">
                  <div class="block-box px-3 py-4">
                    <div class="col-tit">业务频率/min</div>
                    <div class="col-con">{{ digitsObj.trace_per_minute!=undefined?Number(digitsObj.trace_per_minute).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.database_biz_per_minute != undefined?Number(digitsObj.database_biz_per_minute).toFixed(2):0 }}</span>
                </div>
                <div class="border-bottom">
                  <div class="block-box px-3 py-4">
                    <div class="col-tit">DB查询频率/min</div>
                    <div class="col-con">{{ digitsObj.database_biz_per_minute != undefined?Number(digitsObj.database_biz_per_minute).toFixed(2):0 }}</div>
                  </div>
                </div>
              </el-tooltip>
            </div>
          </div>
        </div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="业务列表" name="second">
            <AnalysisMap v-if="activeName == &quot;second&quot; " />
          </el-tab-pane>
          <el-tab-pane label="业务质量" name="first" style="width:100%">
            <h6 class="h6">延迟分布</h6>
            <div class="echartsWrap">
              <!-- v-if="qualityObj.buckets!=undefined&&qualityObj.buckets.length>0" -->
              <div id="qualityWrap" style="width:100%;height:240px" />
            </div>
            <h6 class="h6">错误分布</h6>
            <div class="echartsWrap">
              <!-- v-if="errorObj.times!=undefined&&errorObj.times.length>0"  -->
              <div id="errorWrap" style="width:100%;height:240px" />
              <!-- <div v-else style="min-height: 240px;line-height:240px;background:#fff;color:#999;padding:10px;text-align: center;">暂无数据</div> -->
            </div>
          </el-tab-pane>

        </el-tabs>
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import resize from '../mixins/resize'
import { listUrlMappingErrors, listUrlMappingQuality, digitsBiz } from '@/api/mapping'
import storage from '@/utils/storage'
// import Biz from './components/biz'
import AnalysisMap from './components/AnalysisMap'
import moment from 'moment'

export default {
  components: {
    // Biz,
    AnalysisMap
  },
  mixins: [resize],
  data() {
    return {
      activeName: 'second',
      appItem: {},
      errorQuery: {
        app_id: 0,
        // url_type:2,   // 0未知 1对内接口 2对外接口
        // start_time:1703656033,
        // end_time:1703656333,
        time_type: 'day', // 时间单位， hour或day
        time_value: 30, // 与时间单位组合，本例为10小时
        time_base: new Date().getTime().toString()
      },
      time_base: new Date().getTime().toString(),
      timeTypeOptions: [
        {
          value: 'hour',
          label: '时'
        },
        {
          value: 'day',
          label: '天'
        }
      ],
      qualityQuery: {
        app_id: 1,
        // url_type:1,   // 0未知 1对内接口 2对外接口
        start_time: '',
        end_time: ''
      },
      errorChart: null,
      qualityChart: null,
      errorObj: {},
      qualityObj: {},
      bizList: [],
      loading: false,
      digitsQuery: {
        app_id: '',
        start_time: '',
        end_time: ''
      },
      digitsObj: {},
      timer: null,
      clickCount: 0
    }
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.qualityQuery.start_time = newValue.startTime
          this.qualityQuery.end_time = newValue.endTime

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

          this.errorQuery.start_time = newValue.startTime
          this.errorQuery.end_time = newValue.endTime
          this.getListUrlMappingErrors()
          this.getListUrlMappingQuality()
          this.getDigitsBiz()
          if (newValue.timeOut) {
            if (newValue.timeOut == 1) {
              clearInterval(this.timer)
            } else {
              clearInterval(this.timer)
              this.Refresh(newValue.timeOut)
            }
          }
        }
      },
      // immediate: true,
      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.errorQuery.app_id = this.appItem.id
      this.errorQuery.start_time = start_time
      this.errorQuery.end_time = end_time
      this.qualityQuery.app_id = this.appItem.id
      this.qualityQuery.start_time = start_time
      this.qualityQuery.end_time = end_time

      this.digitsQuery.app_id = this.appItem.id
      this.digitsQuery.start_time = start_time
      this.digitsQuery.end_time = end_time
      // this.getListBiz();
    }
  },
  mounted() {
    this.getDigitsBiz()
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    goPage() {
      this.activeName = 'second'
    },
    Refresh(timeOut) {
      this.timer = setInterval(() => {
        this.getListUrlMappingErrors()
        this.getListUrlMappingQuality()
        this.getDigitsBiz()
      }, timeOut)
    },
    handleClick(tab, event) {
      if (tab.name === 'first') {
        this.$nextTick(() => {
          this.getListUrlMappingErrors()
          this.getListUrlMappingQuality()
        })
      }
    },
    go(path) {
      this.$router.push(path)
    },
    getDigitsBiz() {
      digitsBiz(this.digitsQuery).then((res) => {
        if (res.code == 200) {
          this.digitsObj = res.data
        }
      })
    },
    changeTimeErrorQuery(val) {
      this.time_base = val
      this.getListUrlMappingErrors()
    },
    changeErrorQuery(val) {
      this.errorQuery.time_type = val
      this.getListUrlMappingErrors()
    },
    handleErrorQuery() {
      this.getListUrlMappingErrors()
    },

    getListUrlMappingErrors() {
      if (this.time_base.toString().length == 13) {
        this.errorQuery.time_base = Math.round(this.time_base / 1000)
      } else {
        this.errorQuery.time_base = this.time_base
      }
      this.errorChart = this.$echarts5.getInstanceByDom(document.getElementById('errorWrap'))
      if (this.errorChart == null) {
        this.errorChart = this.$echarts5.init(document.getElementById('errorWrap'))
      }
      this.errorChart.showLoading(
        {
          text: ''
        }
      )
      listUrlMappingErrors(this.errorQuery).then(res => {
        this.errorChart.hideLoading()
        if (res.code == 200) {
          this.errorObj = res.data
          setTimeout(() => {
            this.initErrorChart(this.errorObj)
          }, 300)
        }
      })
    },
    getListUrlMappingQuality() { // 延迟分布
      this.qualityChart = this.$echarts5.getInstanceByDom(document.getElementById('qualityWrap'))
      if (this.qualityChart == null) {
        this.qualityChart = this.$echarts5.init(document.getElementById('qualityWrap'))
      }
      this.qualityChart.showLoading(
        {
          text: ''
        }
      )
      listUrlMappingQuality(this.qualityQuery).then(res => {
        this.qualityChart.hideLoading()
        if (res.code === 200) {
          this.qualityObj = res.data
          setTimeout(() => {
            this.initQualityChart(this.qualityObj)
          }, 300)
        }
      })
    },
    initErrorChart(data) { // 错误分布
      const _this = this
      if (data.times.length > 0) {
        this.errorChart.setOption(
          {
            xAxis: {
              type: 'category',
              data: data.times
            },
            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
              }
            },
            yAxis: {
              type: 'value'
            },
            toolbox: {
              feature: {
              // dataView: { show: true, readOnly: false },
                magicType: { show: true, type: ['line', 'bar'] },
                restore: { show: true }
              // saveAsImage: { show: true }
              }
            },
            grid: {
            // top:'2%',
              left: '3%',
              right: '10%',
              bottom: '1%',
              containLabel: true
            },
            series: [
              {
                name: '错误分布',
                data: data.totals,
                type: 'bar',
                barWidth: 24
              // silent: true,
              }
            ]
          }
        )
        this.errorChart.getZr().off('click')
        this.errorChart.getZr().on('click', params => {
          const pointInPixel = [params.offsetX, params.offsetY]
          if (_this.errorChart.containPixel('grid', pointInPixel)) {
            this.clickCount++
            const data = storage.get('paramsValue')
            const timestamp = moment(data[0].name).unix()
            if (this.clickCount % 2 === 0) {
              _this.time_base = new Date().getTime().toString()
              _this.errorQuery.time_type = 'day'
              _this.errorQuery.time_value = 30
              _this.getListUrlMappingErrors()
            } else {
              _this.time_base = timestamp
              _this.errorQuery.time_type = 'hour'
              _this.errorQuery.time_value = 24
              _this.getListUrlMappingErrors()
            }
          }
        })
      } else {
        this.errorChart.setOption({
          title: {
            text: '暂无数据',
            x: 'center',
            y: 'center',
            textStyle: {
              color: '#999',
              fontSize: 14
            }
          }
        })
      }
    },
    initQualityChart(data) { // 延迟分布
      if (data.buckets.length > 0) {
        this.qualityChart.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            }
          },
          legend: {
            data: ['当前时段', '前续时段对比']
          },
          toolbox: {
            feature: {
              // dataView: { show: true, readOnly: false },
              magicType: { show: true, type: ['line', 'bar'] },
              restore: { show: true }
              // saveAsImage: { show: true }
            }
          },
          grid: {
            // top:'-1%',
            left: '3%',
            right: '10%',
            bottom: '1%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: data.buckets,
              axisPointer: {
                type: 'shadow'
              }
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: [
            {
              name: '当前时段',
              type: 'bar',
              tooltip: {
                valueFormatter: function(value) {
                  return value
                }
              },
              barWidth: 8,
              markLine: {
                label: {
                  formatter: '{b}',
                  backgroundColor: '#5A6FC0',
                  color: '#fff',
                  padding: [4, 8]
                },
                lineStyle: {
                  type: 'dashed',
                  color: '#5A6FC0',
                  width: 2
                  // dashOffset: 25
                },
                data: [
                  {
                    name: 'p50',
                    xAxis: data.buckets[data.current.quantile_indexes.p50]
                  },
                  {
                    name: 'p90',
                    xAxis: data.buckets[data.current.quantile_indexes.p90]
                  },
                  {
                    name: 'p99',
                    xAxis: data.buckets[data.current.quantile_indexes.p99]
                  }
                ]
              },
              data: data.current.counts != undefined && data.current.counts.length > 0 ? data.current.counts : []
            },
            {
              type: 'line',
              name: '前续时段对比',
              tooltip: {
                valueFormatter: function(value) {
                  return value
                }
              },
              lineStyle: {
                width: 3
              },
              markLine: {
                name: '',
                // symbol: ["none", "none"], //去掉箭头
                lineStyle: {
                  type: 'dashed',
                  color: '#9ECA7E',
                  width: 2
                },
                label: {
                  formatter: '{b}',
                  backgroundColor: '#9ECA7E',
                  color: '#fff',
                  padding: [4, 8]
                },
                data: [
                  {
                    name: 'p50',
                    xAxis: data.buckets[data.previous.quantile_indexes.p50]
                  },
                  {
                    name: 'p90',
                    xAxis: data.buckets[data.previous.quantile_indexes.p90]
                  },
                  {
                    name: 'p99',
                    xAxis: data.buckets[data.previous.quantile_indexes.p99]
                  }
                ] // 这里设置false是隐藏不了的，可以设置为-1
              },

              // data:data.previous.counts
              data: data.previous.counts != undefined && data.previous.counts.length > 0 ? data.previous.counts : []
            }
          ]
        })
      } else {
        this.qualityChart.setOption({
          title: {
            text: '暂无数据',
            x: 'center',
            y: 'center',
            textStyle: {
              color: '#999',
              fontSize: 14
            }
          }
        })
      }
    },
    handlerNumber(num) {
      // let str = num.toString();
      const str = num
      let result
      if (str.length <= 4) {
        result = num
      } else if (str.length > 4 && str.length < 7) {
        result = (num / 1000).toFixed(2) + 'K'
      } else if (str.length >= 7 && str.length < 10) {
        // result = Math.round(num/1000000) + 'M'
        result = (num / 1000000).toFixed(2) + 'M'
      } else {
        result = (num / 1000000000).toFixed(2) + 'B'
      }
      return result
    },
    handelerNumberjoin(num) {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }
  }
}
</script>

<style lang="scss" scoped>
.echartsWrap{
  width:100%;
  // height: 300px;
}
.h6{
  font-size: 16px;
  font-weight: bold;
  color: #1a2233;
}
.hoverCursor:hover{
 cursor: pointer;
}
</style>
