<template>
      <div id="service">
        <el-table
          v-loading="loading"
          :data="serveceMapListFavor"
          @row-click="handleRowClick"
        >
          <el-table-column header-align="left" label="接口名" prop="name" align="left" :show-overflow-tooltip="true"/>
          <el-table-column header-align="center" label="rpm" prop="rpm" sortable align="center" :show-overflow-tooltip="true" width='80'>
            <template slot-scope="scope">
                <el-tag>{{ Number(scope.row.rpm).toFixed(2)}}</el-tag>
              </template>
          </el-table-column>
          <el-table-column header-align="center" label="count" prop="total" sortable align="center" width="100">
             <template slot-scope="scope">
                <el-tag>{{ Number(scope.row.total).toFixed(2)}}</el-tag>
              </template>
          </el-table-column>
          <el-table-column header-align="center" label="errRate" sortable prop="error_rate" align="center" width="100">
            <template slot-scope="scope">
                 <el-tag v-if="scope.row.error_rate==0">{{  scope.row.error_rate }}</el-tag>
                    <el-tag v-else type="danger">{{  Number(scope.row.error_rate).toFixed(2)}}</el-tag>
              </template>
          </el-table-column>

          <el-table-column header-align="center" label="延迟比例" prop="duration_stats" align="center">
              <template slot-scope="scope">
                {{ drawEchartsp(scope.row, scope.$index, 'service') }}
                <div :id="`tiger-service-trend-index` + scope.$index" class="tiger-trend-charts"></div>
              </template>
          </el-table-column>
        </el-table>

         <el-drawer
            :visible.sync="drawer"
            direction="rtl"
            size="55%"
            @close="drawerClose"
          >
          <div style="margin-bottom:16px">

            <div id="scaleMain" style="width:100%;min-width:500px;height:180px;margin-bottom:24px"></div>

            <el-table
              v-loading="tableLoading"
              :data="rowData"
            >
              <el-table-column header-align="center" label="TraceID" prop="trace_id" align="center" width="240">
              <template slot-scope="scope">
                <span @click="goto(scope.row)">{{scope.row.trace_id}}</span>
              </template>
              </el-table-column>
              <el-table-column header-align="center" label="ServiceName" prop="service_name" align="center" :show-overflow-tooltip="true" />
              <!-- <el-table-column header-align="center" label="SpanName" prop="span_name" align="center" :show-overflow-tooltip="true" />
              <el-table-column header-align="center" label="SpanKind" prop="span_kind" align="center" width="100"/> -->
              <el-table-column header-align="center" label="Target" prop="target" align="center" :show-overflow-tooltip="true" />
              <el-table-column header-align="center" label="Method" prop="method" align="center">
                <template slot-scope="scope">
                    <el-tag type="info">{{ scope.row.method }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column header-align="center" label="StatusCode" prop="status_code" align="center">
              <template slot-scope="scope">
                <span>
                  <span v-if="scope.row.status_code<400"><i class="green_small"></i>{{scope.row.status_code}}</span>
                  <span v-else><i class="red_small"></i>{{scope.row.status_code}}</span>
                </span>
              </template>
              </el-table-column>
              <el-table-column header-align="center" label="Duration(ms)" prop="duration" align="center">
                <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 header-align="center" label="max(ms)" sortable="custom" prop="duration_stats" align="center" width="100">
                <template slot-scope="scope">
                  <span>{{ Number(scope.row.max).toFixed(2)}}</span>
                </template>
              </el-table-column>
              <el-table-column header-align="center" label="avg(ms)" sortable="custom" prop="duration_stats" align="center" width="100">
                <template slot-scope="scope">
                  <span>{{ Number(scope.row.avg).toFixed(2)}}</span>
                </template>
              </el-table-column> -->
            </el-table>
            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="childQueryParams.pageIndex"
              :limit.sync="childQueryParams.pageSize"
              @pagination="handelgetUrlMappingRange"
            />
          </div>
        </el-drawer>
    </div>
</template>

<script>
import { getUrlMappingRange,favorList } from '@/api/mapping'
import storage from '@/utils/storage'

import moment from 'moment'
import { getToken } from '@/utils/auth'
// import echarts from 'echarts'
import resize from './mixins/resize'
export default {
  name: 'Service',
  mixins: [resize],
  components: {

  },
  props: {
    height:{
      type:Number
    }
  },
  data() {
    return {
      drawer:false,
      tableLoading:false,
      serveceMapListFavor:[],
      //应用数据列表
      appData:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      menuIdsChecked: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      isEdit: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        // start_time:Math.round((new Date().getTime())/1000 - (5*60)),
        // end_time:Math.round(new Date().getTime()/1000),
        start_time:0,
        end_time:0,
        app_id:undefined,
        // favor:1,

        // pageIndex: 0,
        // pageSize: 200
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '接口名称不能为空', trigger: 'blur' }
        ],
        url: [
          { required: true, message: 'URL组不能为空', trigger: 'blur' }
        ]
      },
      appsfileList: [],
      headers: { 'Authorization': 'Bearer ' + getToken() },
      appsItem:{},
      serviceTimer:null,
      childQueryParams:{
        // start_time:Math.round((new Date().getTime())/1000 - (5*60)),
        // end_time:Math.round(new Date().getTime()/1000),
        start_time:0,
        end_time:0,
        id:0,
        app_id:0,
        kind:'',
        only_error:0,
        pageIndex: 1,
        pageSize: 10,
      },
      rowData:[],
      serviceMapTimer:null
    }
  },
   watch: {
     '$store.state.time.globalTimes': {
        handler(newValue, oldValue) {
            if(newValue){
              this.queryParams.start_time = newValue.startTime;
              this.queryParams.end_time = newValue.endTime;
              this.getList();
              if(newValue.timeOut){
                if(newValue.timeOut == 1){
                  clearInterval(this.serviceTimer);
                }else{
                   clearInterval(this.serviceTimer);
                  this.Refresh(newValue.timeOut);
                }
              }
            }
        },
        // immediate: true,
        deep: true
    },
  },
  created() {
    // this.queryParams.start_time = this.$store.getters.globalTimes.startTime;
    // this.queryParams.end_time = this.$store.getters.globalTimes.endTime
    this.appsItem=storage.get('appsItem');
     if(this.appsItem.id!=''||this.appsItem.id!=undefined){
      this.queryParams.app_id=this.appsItem.id;
      this.childQueryParams.app_id = this.appsItem.id;
      this.getList()
    }
  },
  beforeDestroy() {
    clearInterval(this.serviceTimer);
  },
  mounted(){
    // this.getList()
  },
  methods: {
    handelgetUrlMappingRange(){
      this.tableLoading = true
      getUrlMappingRange(this.childQueryParams).then(res => {
          if(res.code == 200){
            this.tableLoading = false;
            this.rowData= res.data.list;
            this.total = res.data.count;
          }
      })
    },
    goto(row){
      let datetime = Date.parse(row.datetime)/1000;
      let 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")
    },
    drawerClose(){
      this.drawer = false;
    },
    handleRowClick(row, column, event){
      this.drawer=true;
      this.$nextTick(() =>{
        this.drawEchartsScale(row);
       })
      setTimeout(()=>{

        this.childQueryParams.id = row.id;
        this.childQueryParams.kind = row.kind;
        this.handelgetUrlMappingRange();
      },0)
    },
     drawEchartsScale(row) {
      let _this = this;
      let myChartScale = this.$echarts5.init(document.getElementById('scaleMain'));
      //绘制趋势echarts
      let option = {
        tooltip: {
          trigger: 'axis',
          confine: false,
          appendToBody: true,
          show: true,
           formatter: function (params) {
            storage.set('paramsValue',params)
            let 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
          }
        },
        grid: {
          left: '4%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: row.duration_stats.time,
          // show:true
        },
        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',
            symbol: 'none',
            // symbol: 'emptyCircle',//拐点
            data:row.duration_stats.p50
          },
          {
            name: 'P.95',
            type: 'line',
            stack: 'Total',
            symbol: 'none',//拐点
            // symbol: 'emptyCircle',//拐点
            data:row.duration_stats.p90
          },
          {
            name: 'P.99',
            type: 'line',
            stack: 'Total',
            symbol: 'none',//拐点
            // symbol: 'emptyCircle',//拐点
            data:row.duration_stats.p99
          }
        ]
      };
      myChartScale.setOption(option);
      myChartScale.getZr().on('click', params => {
        let data = storage.get('paramsValue')
        let timestamp = moment(data[0].name).unix();

        _this.childQueryParams.start_time = timestamp
        _this.childQueryParams.end_time =timestamp
        _this.handelgetUrlMappingRange();
      })
    },
    Refresh(timeOut){
      this.serviceTimer = setInterval(()=>{
        this.getList();
      },timeOut)
    },
    handleSortChang(column, prop, order) {

      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    getList() {
      this.loading = true
      favorList(this.queryParams).then(res => {
          if(res.code == 200){
            this.loading = false;
            this.serveceMapListFavor= res.data;
          }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        url: undefined,
        type: undefined,
        module:undefined,
        summary:undefined,
        favor:undefined
      }
      this.resetForm('form')
    },
    drawEchartsp(row, index) {
      let option = {
        tooltip: {
          trigger: 'axis',
          confine: false,
          appendToBody: true
        },
        grid: {
          top:10,
          left: 0,
          right: '4%',
          bottom: "-2%",
          containLabel: false
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: row.duration_stats.time,
          show:false
        },
        yAxis: {
          type: 'value',
          show:false
        },
        series: [
          {
            name: 'P.50',
            type: 'line',
            stack: 'Total',
            symbol: 'none',
            // data: Number(row.duration_stats.p50).toFixed(2)
            data:row.duration_stats.p50
          },
          {
            name: 'P.95',
            type: 'line',
            stack: 'Total',
            symbol: 'none',
            // data: Number(row.duration_stats.p95).toFixed(2)
            data:row.duration_stats.p90
          },
          {
            name: 'P.99',
            type: 'line',
            stack: 'Total',
            symbol: 'none',
            // data: Number(row.duration_stats.p99).toFixed(2)
            data:row.duration_stats.p99
          }
        ]
      };
      let chartId = 'tiger-' + arguments[2] + '-trend-index' + arguments[1];
      // this.$nextTick(() => {
      //   let myChart = this.$echarts5.init(document.getElementById(chartId), 'macarons');
      //   myChart.setOption(option,true);
      //   myChart.resize();
      // });
      let _this = this;
      setTimeout(function () {
          let myChart = _this.$echarts5.init(document.getElementById(chartId), 'macarons1');
          myChart.setOption(option,true);
          myChart.resize();
      }, 500)
    },
    drawEchartsp9() {
      //绘制趋势echarts
      let option = {
          xAxis: {
            type: 'category',
            boundaryGap: false,
            show:false,
            // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          },
          yAxis: {
            type: 'value',
            show:false,
          },
          series: [
            {
              data: arguments[0].duration_stats.p90,
              //  data:[820, 932, 901, 934, 1290, 1330, 1320],
              type: 'line',
               areaStyle: {
                color:'#F9E7E6'
              },
              lineStyle:{
                color:'#E26F6D'
              },
              symbol: 'none',
            }
          ]
      };
      let chartId = 'tiger-' + arguments[2] + '-trend-index' + arguments[1];
      this.$nextTick(() => {
        let myChart = this.$echarts5.init(document.getElementById(chartId), 'macarons');
        myChart.setOption(option);
        myChart.resize();
      });
    },
    drawEchartsp99() {
      //绘制趋势echarts
      let option = {
          xAxis: {
            type: 'category',
            boundaryGap: false,
            show:false,
            // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          },
          yAxis: {
            type: 'value',
            show:false,
          },
          series: [
            {
              data: arguments[0].duration_stats.p99,
              // data:[156, 932, 876, 234, 424, 189, 1320],
              type: 'line',
              smooth: true,
               areaStyle: {
                color:'#EAF5F8'
              },
              lineStyle:{
                color:'#7EBBD6'
              },
              symbol: 'none',
            }
          ]
      };
      let chartId = 'tiger-' + arguments[2] + '-trend-index' + arguments[1];
      this.$nextTick(() => {
        let myChart = this.$echarts5.init(document.getElementById(chartId), 'macarons');
        myChart.setOption(option);
        myChart.resize();
      });
    },
  }
}
</script>
<style lang="scss" scoped>
@font-face {
  font-family: 'iconfont';  /* Project id 4241886 */
  src: url('https://at.alicdn.com/t/c/font_4241886_44emlzl9ad4.woff2?t=1694073615647') format('woff2'),
       url('https://at.alicdn.com/t/c/font_4241886_44emlzl9ad4.woff?t=1694073615647') format('woff'),
       url('https://at.alicdn.com/t/c/font_4241886_44emlzl9ad4.ttf?t=1694073615647') format('truetype');
}
.iconfont {
  font-family: "iconfont" !important;
  font-size: 20px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-jiantou_zuoyouqiehuan:before {
  content: "\eb0d";
}

.icon-qiehuan:before {
  content: "\e606";
}

.icon-qiehuan1:before {
  content: "\e789";
}
::v-deep .el-card__body{
  position: relative !important;
}
.back{
  position: absolute;
  top:10px;
  right:10px;
  width:20px;
  height:20px;
}
.tiger-trend-charts {
   height: 40px;
   width:100px;
   min-width: 80px;
   max-width: 100px;
  }
  ::v-deep .el-icon-star-on{
    font-size: 16px;
  }
#service{
    width: 100%;
      height:288px;
    box-sizing: border-box;
}
</style>
