<template>
    <div style="padding:16px;">
        <!-- <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px" @submit.native.prevent>
          <el-form-item label="" prop="url">
              <el-input
                v-model="queryParams.url"
                placeholder="请输入url"
                clearable
                size="mini"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
        </el-form> -->

        <!-- <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
        </el-row> -->

        <div>
          <!-- <el-table
            v-loading="loading"
            :key="isUpdate"
            :data="serveceMapList"
            :default-sort = "{prop: 'total', order: 'descending'}"
            @row-click="handleRowClick"
          > -->
          <el-table
            v-loading="loading"
            :key="isUpdate"
            :data="serveceMapList"
            @row-click="handleRowClick"
          >
            <el-table-column header-align="left" label="服务名" prop="name" align="left" :show-overflow-tooltip="true"/>
            <el-table-column header-align="left" label="起始服务" prop="service_name" align="left" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{scope.row.service_name}}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column header-align="left" label="SpanName" prop="span_name" align="left" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{scope.row.span_name}}</span>
              </template>
            </el-table-column> -->
            <el-table-column header-align="center" label="rpm" sortable prop="rpm" align="center" :show-overflow-tooltip="true">
              <template slot-scope="scope">

                <el-tag>{{ scope.row.rpm == undefined?0:Number(scope.row.rpm).toFixed(2)}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column header-align="center" label="请求总数" sortable prop="total" align="center">
              <template slot-scope="scope">
                <!-- <span>{{ Number(scope.row.rpm).toFixed(2)}}</span> -->
                <el-tag>{{ scope.row.total== undefined?0: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">
              <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="最大延迟(ms)" sortable prop="max" align="center" width="100">
              <template slot-scope="scope">
                <!-- <span>{{ Number(scope.row.max).toFixed(2)}}</span> -->
                <el-tag v-if="scope.row.max>=2000" type="danger">{{ Number(scope.row.max).toFixed(2) }}</el-tag>
                <el-tag v-if="scope.row.max<2000">{{ Number(scope.row.max).toFixed(2) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column header-align="center" label="avg(ms)" sortable prop="avg" align="center" width="100">
              <template slot-scope="scope">
                <!-- <span>{{ Number(scope.row.avg).toFixed(2)}}</span> -->
                <el-tag v-if="scope.row.avg>=2000" type="danger">{{ Number(scope.row.avg).toFixed(2) }}</el-tag>
                <el-tag v-if="scope.row.avg<2000">{{ Number(scope.row.avg).toFixed(2) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column header-align="center" label="延迟比例" prop="duration_stats" align="center">
                <template slot-scope="scope">
                  {{ drawEchartsp5(scope.row, scope.$index, 'five') }}
                  <div :id="`tiger-five-trend-index` + scope.$index" class="tiger-trend-charts"></div>
                </template>
            </el-table-column>
            <!-- <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
              sortable prop="favor"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click.native.stop="handleUpdate(scope.row)"
                >标注</el-button>
                <el-button
                  v-if="scope.row.favor == 0"
                  size="mini"
                  type="text"
                  icon="el-icon-star-off"
                  @click.native.stop="handleFavor(scope.row)"
                ></el-button>
                <el-button
                  v-if="scope.row.favor == 1"
                  size="mini"
                  type="text"
                  icon="el-icon-star-on"
                  @click.native.stop="handleFavor(scope.row)"
                ></el-button>
                <el-button
                  style='color:#F56C6C'
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click.native.stop="handleDelete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column> -->
          </el-table>
        </div>
        <div class="more" v-if="serveceMapList.length<tableCount" @click="loadMore">加载更多</div>
        <div class="more nomore" v-if="loading==false&&serveceMapList.length>=tableCount">已加载完所有的数据！</div>
        <!-- <pagination
          v-show="total>0"
          :total="total"
          :page.sync="childQueryParams.pageIndex"
          :limit.sync="childQueryParams.pageSize"
          @pagination="handelgetBizDetail"
        /> -->

        <!-- 添加或修改应用配置对话框 -->
        <el-dialog v-if="open" :title="title" :visible.sync="open" width="700px" :center='true' :close-on-click-modal="false">
          <el-form ref="form" :model="form" :rules="rules" label-width="95px">
            <el-form-item label="业务定义" prop="name">
              <el-input v-model="form.name" placeholder="请输入业务定义" />
            </el-form-item>
            <el-form-item label="URL组" prop="url">
              <span slot="label">
                URL组
                <el-tooltip>
                  <div slot="content">
                    <div>URL匹配示例：</div>
                    <div style="display:flex;justify-content:space-between;font-size:12px;">
                      <div>1、/aaa/bbb 完全匹配</div>
                    </div>
                    <div>
                      <div>2、/aaa/{regexp}, 如/aaa/.*  正则匹配</div>
                    </div>
                    <!-- <div>
                      <div>3、/aaa/{:words} 匹配任意字母</div>
                    </div> -->
                  </div>
                  <i class="el-icon-question" />
                </el-tooltip>
              </span>
               <el-input v-model="form.url" placeholder="请输入URL组"/>
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio label="1">对外</el-radio>
                <el-radio label="2">对内</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="所属模块" prop="module">
              <el-input v-model="form.module" placeholder="所属模块" />
            </el-form-item>
            <el-form-item label="业务概述" prop="summary">
              <el-input v-model="form.summary" type="textarea" placeholder="请输入业务概述" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
         <!-- <div class="back" @click="toggle()">
            <i class="iconfont icon-qiehuan1"></i>
          </div> -->
        <el-drawer
            :visible.sync="drawer"
            direction="rtl"
            size="calc( 100vw - 210px)"
            @close="drawerClose"
          >
          <div style="margin-bottom:16px;margin-top:-32px;">
            <div class="flexWrap">
              <div class="flex-left">
                <!-- <Topo /> -->
                <Topo v-if='drawer' :graphData='graphData' topoId='container' v-on:changeState="clickRowHandleNode" ref='topo'/>
              </div>
              <div class="flex-right">
                  <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="handelgetBizDetail"
                  />
              </div>
            </div>


          </div>
        </el-drawer>

        <el-drawer
            :visible.sync="drawerDetail"
            direction="rtl"
            size="55%"
            @close="drawerCloseDetail"
            v-if='JSON.stringify(detailData) != "{}"'
          >
            <el-collapse v-model="activeNames">
              <el-collapse-item title="属性" name="one">
                <ul class='ul_box' v-if='detailData.span_attributes !=null'>
                  <li v-for='(value,key) in detailData.span_attributes' :key='key'>
                    <div class="ul_label">{{key}}</div>
                    <div class="ul_value" style='color:#008080;white-space: pre-wrap;'>"{{value}}"</div>
                  </li>
                </ul>
              </el-collapse-item>
              <el-collapse-item title="资源" name="tow">
                <ul class='ul_box' v-if='detailData.resource_attributes !=null'>
                  <li v-for='(value,key) in detailData.resource_attributes' :key='key'>
                    <div class="ul_label">{{key}}</div>
                    <div class="ul_value" style='color:#008080;white-space: pre-wrap;'>"{{value}}"</div>
                  </li>
                </ul>
              </el-collapse-item>
              <el-collapse-item v-if='detailData.events_timestamp.length>0 && detailData.events_timestamp!=null' :title="'事件'+'('+ detailData.events_timestamp.length +')'" name="three">
                <div class='events_box'>
                  <el-collapse :value="activeIn">
                    <el-collapse-item v-for='(item,index) in detailData.events_timestamp' :key='index' :title="item" :name="index">
                      <ul class='ul_box'>
                        <li>
                          <div class="ul_label">message</div>
                          <div class="ul_value" style='color:#008080;white-space: pre-wrap;'>"{{detailData.events_name[index]}}"</div>
                        </li>
                        <li v-for='(value,key) in detailData.events_attributes[index]' :key='key'>
                          <div class="ul_label">{{key}}</div>
                          <div class="ul_value" style='color:#008080;white-space: pre-wrap;'>"{{value}}"</div>
                        </li>
                      </ul>
                    </el-collapse-item>
                  </el-collapse>
                </div>
              </el-collapse-item>
            </el-collapse>
        </el-drawer>
    </div>
</template>

<script>
import { listUrlMapping, addUrlMapping, getUrlMapping, updateUrlMapping, delUrlMapping, favor,getUrlMappingRange,getBizDetail,listBizGraph,listBizGraphStats,updateBiz,delBiz,favorBiz } from '@/api/mapping'
import { formatJson } from '@/utils'
import storage from '@/utils/storage'
// import bus from '@/utils/bus'
import {listService,listServiceStats} from "@/api/service"

import { getToken } from '@/utils/auth'
// import echarts from 'echarts'
import resize from './mixins/resize'
import moment from 'moment'
// import elTableInfiniteScroll from 'el-table-infinite-scroll';
// import Topo from './TopoNew1'
export default {
  name: 'ServiceMap',
  mixins: [resize],
  // directives: {
  //   'el-table-infinite-scroll': elTableInfiniteScroll
  // },
  data() {
    return {
      isUpdate:false,
      isflag:false,
      tableflag:false,
      drawer:false,
      detailData:{},
      drawerDetail:false,
      tableLoading:false,
      // 表格高度
      tableHeight:"",
      // 数据总数
      tableCount:0,
      serveceMapList:[],
      //应用数据列表
      appData:[],
      // 遮罩层
      loading: false,
      // 选中数组
      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),
        app_id:'',
        start_time:'',
        end_time:'',
        pageIndex:1,
        pageSize:50,
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '接口名称不能为空', trigger: 'blur' }
        ],
        url: [
          { required: true, message: 'URL组不能为空', trigger: 'blur' }
        ]
      },
      headers: { 'Authorization': 'Bearer ' + getToken() },
      appsItem:{},
      expands:[],
      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,
        biz_id:1,
        pageIndex: 1,
        pageSize: 10,
      },
      rowData:[],
      serviceMapTimer:null,
      BizStatsQuery:{
        id:0,
        start_time:'',
        end_time:'',
      },
      tempList:[],
      graphData:{},
      graphStatsQuery:{
        biz_node_id:0,// 仅支持传递单个节点，多个节点需要并发请求分别调用
        end_time:1702972800,
        start_time:1702969200,
      },
      graphObj:[],
      myChartList:[],
      myChartboxList:[],
      myChartBox2List:[]
    }
  },
  watch: {
     '$store.state.time.globalTimes': {
        handler(newValue, oldValue) {
            if(newValue){
              this.queryParams.start_time = newValue.startTime;
              this.queryParams.end_time = newValue.endTime
              this.BizStatsQuery.start_time= newValue.startTime;
              this.BizStatsQuery.end_time= newValue.endTime;
              this.graphStatsQuery.start_time= newValue.startTime;
              this.graphStatsQuery.end_time= newValue.endTime;
              this.childQueryParams.start_time = newValue.startTime;
              this.childQueryParams.end_time = newValue.endTime
              this.queryParams.pageIndex = 1
              this.serveceMapList=[];
              this.getList();
              if(newValue.timeOut){
                if(newValue.timeOut == 1){
                  clearInterval(this.serviceMapTimer);
                }else{
                  clearInterval(this.serviceMapTimer);
                  this.Refresh(newValue.timeOut);
                }
              }
            }
        },
        // immediate: true,
        deep: true
    },
    serveceMapList:{
      handler(newVal,oldVal){
        if(newVal){
          this.serveceMapList = newVal;
          this.tableflag = true;
        }
      },
      // immediate: true,
      deep:true
    }
  },
  created(){
    this.$store.commit('time/setTimeFlag',false)
    const start_time = this.$store.state.time.globalTimes.startTime
    const end_time = this.$store.state.time.globalTimes.endTime
    this.appItem=storage.get('appsItem');
    if(JSON.stringify(this.appItem) !="{}"){
      this.queryParams.app_id = this.appItem.id;
      this.queryParams.start_time = start_time;
      this.queryParams.end_time = end_time;
      this.BizStatsQuery.start_time= start_time;
      this.BizStatsQuery.end_time= end_time;
      this.childQueryParams.start_time = start_time;
      this.childQueryParams.end_time = end_time;
      this.getList()
      this.$forceUpdate();
    }
    // this.columnChange();
  },
  mounted(){
    this.$forceUpdate();
  },
  methods: {
    // clickFull() {
    //     this.Visible=true;
    //     this.$refs['topo'].initGraph();
    // },
    Refresh(timeOut){
      this.serviceMapTimer = setInterval(()=>{
        this.getList();
      },timeOut)
    },
    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;
    },
    drawerCloseDetail(){
      this.drawerDetail = false;
    },
    toogleExpand(row, column, event){
      this.drawer=true;
      this.childQueryParams.id = row.id;
      this.handelgetBizDetail();
    },
    handleRowClick(row, column, event){
      this.childQueryParams.biz_id = row.id;
      this.handelgetBizDetail();
      this.getListBizGraph(row.id)



      setTimeout(()=>{
        // this.childQueryParams.biz_id = row.id;
        // this.handelgetBizDetail();
        // this.getListBizGraph(row.id)
        this.drawer=true;
        this.$nextTick(() =>{
          this.drawEchartsScale(row);
        })
      },300)
    },
    handelgetBizDetail(){
      this.tableLoading = true
      getBizDetail(this.childQueryParams).then(res => {
          if(res.code == 200){
            this.tableLoading = false;
            this.rowData= res.data.list;
            this.total = res.data.count;
          }
      })
    },
    getListBizGraph(id){
      listBizGraph({biz_id:id}).then((res)=>{
        if(res.code == 200){
          let arr = res.data
          if(arr.length>0){
            let List = this.handelListBizData(arr)
            this.graphData =List[0];
          }
        }
      })
    },
    handelListBizData(data){
      data.forEach((v,k)=>{
        v.collapsed = false;
        v.id = String(v.id);
        v.name = v.name;
        v.label = v.stats.duration!=undefined?v.stats.duration.toFixed(2):0;
        v.currency = 'ms';
        v.rate = v.stats.success_rate;
        v.status = 'B'
        v.variableValue = v.stats.success_rate;
        if (v.children != undefined && v.children.length > 0) {
          v.children = this.handelListBizData(v.children)
        }
      })
      return data;
    },
    handleData(data) {
      data.forEach((v, k) => {
      // let string = key === '' ? k + 1 : key + '.' + (k + 1)

      // v.span_name += '---' + string
      // v.id = v.span_name;

      v.id = v.biz_id;

      v.collapsed = false;
      v.name = v.name;
      // v.label = (v.duration).toFixed(2);
      v.label = v.service_name;
      v.currency='ms';
      v.rate = v.duration_persent;
      v.status = (v.status_code == 'STATUS_CODE_ERROR'||v.events_timestamp.length>0||v.http_code>399)?'R':(v.duration>500)?'Y':'G';
      v.variableValue = v.duration_persent;
      // v.status_code = 'UNSET'

      if (v.children != undefined && v.children.length > 0) {
          v.children = this.handleData(v.children)
        }
      })
      return data
    },
    // 根据行的id判断
    getRowKeys(row) {
      return row.id;
    },
    clickRowHandle(row, column, event) {
    //  alert('a')
    },
    clickRowHandleNode(item){
      this.detailData = item;
      this.drawerDetail=true;
    },
    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()
    },
    toggle(){
      this.$router.push({
        path:'dashboard'
      })
    },
     // 加载更多
    loadMore() {
        if (!this.loading) {
            this.loading = true;
            if (this.serveceMapList.length < this.tableCount) {
                this.queryParams.pageIndex++;
                this.getList();
            } else {
                // this.$message("已加载完所有的数据！");
                this.loading = false;
            }
        }
    },
    getList() {
      this.loading = true
      const _this = this;
      this.myChartList=[];
      this.myChartboxList=[];
      this.myChartBox2List=[];
      listService(this.queryParams).then(res => {
          if(res.code == 200){
            _this.serveceMapList= _this.serveceMapList.concat(res.data.list);
            this.tableCount = res.data.count;
            this.queryParams.pageIndex = res.data.pageIndex;
            this.loading = false;

            // this.tempList = this.tempList.concat(res.data.list);
            if(_this.serveceMapList.length>0){
              for(let i=0;i<_this.serveceMapList.length;i++){
                this.BizStatsQuery.id = _this.serveceMapList[i].id
                listServiceStats(this.BizStatsQuery).then(resq=>{
                  if(resq.data.id != undefined){
                    if(_this.serveceMapList[i].id == resq.data.id){
                      _this.serveceMapList[i] = Object.assign({},_this.serveceMapList[i], resq.data);
                      _this.isUpdate = !_this.isUpdate;
                    }
                  }
                })
              }
            }
            this.$nextTick(()=>{
              this.$forceUpdate();
            })
          }
      })
    },
    uploadSuccess(response, file, fileList) {
      this.form.imgUrl = process.env.VUE_APP_BASE_API + response.data.full_path
    },
    // 取消按钮
    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')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.serveceMapList=[];
      this.tempList=[];
      this.getList()
      // this.getList()
      // if(this.queryParams.url != ''){
      //   this.serveceMapList=this.serveceMapList.map((item)=>{
      //     if (item.url.includes(this.queryParams.url)){
      //       return item;
      //     }
      //   })
      // }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // this.getMenuTreeselect(0)
      this.open = true
      this.title = '新增URL组'
      this.isEdit = false
    },
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      if(row.id != 0){
         getUrlMapping(id).then(response => {
          this.form = response.data
          this.form.id = row.id
          this.title = '修改业务名'
          this.isEdit = true
          this.open = true
        })
      }else{
        this.form = row
        // this.form.id = undefined
        this.isEdit = true
        this.open = true
      }

    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined || this.form.id !=0) {
            updateBiz(this.form, this.form.id).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.queryParams.pageIndex =1;
                this.serveceMapList=[];
                this.tempList=[];
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addUrlMapping(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.queryParams.pageIndex =1;
                this.serveceMapList=[];
                this.tempList=[];
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // const id = (row.id && [row.id]) || this.ids
      const id = row.id
      this.$confirm('是否确认删除接口映射编号为"' + id + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delBiz(id)
      }).then((response) => {
        this.queryParams.pageIndex =1;
        this.serveceMapList=[];
        this.tempList=[];
        this.msgSuccess(response.msg);
        this.getList()
      }).catch(function() {})
    },
    handleFavor(row){
        if(row.favor == 1){
          row.favor = '0';
        }else if(row.favor==0){
          row.favor = '1';
        }

      favorBiz({favor:row.favor},row.id).then(res=>{
          if(res.code = 200){
            this.msgSuccess(res.msg);
            this.queryParams.pageIndex =1;
            this.serveceMapList=[];
             this.tempList=[];
            this.getList()
          }
      })


      // if(row.id != 0){
      //   favor({favor:row.favor},row.id).then(res=>{
      //     if(res.code = 200){
      //       this.msgSuccess(res.msg);
      //       this.queryParams.pageIndex =1;
      //       this.serveceMapList=[];
      //       this.getList()
      //     }
      //   })
      // }else{
      //   this.form = row.favor;
      //   this.submitForm();
      // }

    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出所有角色数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['角色编号', '角色名称', '权限字符', '显示顺序', '状态', '创建时间']
          const filterVal = ['roleId', 'roleName', 'roleKey', 'roleSort', 'status', 'createdAt']
          const list = this.roleList
          const data = formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '角色管理',
            autoWidth: true, // Optional
            bookType: 'xlsx' // Optional
          })
          this.downloadLoading = false
        })
      })
    },
    drawEchartsp5(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: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          data: row.quantiles.time,
          show:false
        },
        yAxis: {
          type: 'value',
          show:false
        },
        series: [
          {
            name: 'P.50',
            type: 'line',
            stack: 'Total',
            symbol: 'none',
            // // data: [120, 132, 101, 134, 90, 230, 210]
            // data: Number(row.duration_stats.p50).toFixed(2)
            data:row.quantiles.p50
          },
          {
            name: 'P.95',
            type: 'line',
            stack: 'Total',
            symbol: 'none',
            // data: [320, 332, 301, 334, 390, 330, 320]
            // data: Number(row.duration_stats.p90).toFixed(2)
            data:row.quantiles.p90
          },
          {
            name: 'P.99',
            type: 'line',
            stack: 'Total',
            symbol: 'none',
            // data: [820, 932, 901, 934, 1290, 1330, 1320]
            // data: Number(row.duration_stats.p99).toFixed(2)
            data:row.quantiles.p99
          }
        ]
      };
      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();
      });
    },
    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)
          //   return params
          // },
           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: {
          top:'2%',
          left: '3%',
          right: '4%',
          bottom: '1%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: row.quantiles.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.quantiles.p50
          },
          {
            name: 'P.95',
            type: 'line',
            stack: 'Total',
            symbol: 'none',//拐点
            // symbol: 'emptyCircle',//拐点
            data:row.quantiles.p90
          },
          {
            name: 'P.99',
            type: 'line',
            stack: 'Total',
            symbol: 'none',//拐点
            // symbol: 'emptyCircle',//拐点
            data:row.quantiles.p99
          }
        ]
      };
      // this.$nextTick(() => {
      //   let myChartScale = this.$echarts5.init(document.getElementById('scale'));
        myChartScale.setOption(option);
      //   myChartScale.resize();
      // });
      // myChartScale.on('click',params=>{
      // })

      myChartScale.getZr().on('click', params => {
        //  myChartScale.on('click', params => {
        //    const {target} = params;
        //     if (target && target.z === 3) {
        //   const parent = params.target.parent.parent;
        //   let seriesIndex = parent.__ecComponentInfo ? parent.__ecComponentInfo.index : parent.parent.__ecComponentInfo.index
        //  // 获取数据，进行操作
        // }
        let data = storage.get('paramsValue')
        let timestamp = moment(data[0].name).unix();

        _this.childQueryParams.start_time = timestamp
        _this.childQueryParams.end_time =timestamp
        _this.handelgetBizDetail();
      })
    },
    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();
      });
    },
    disposeEcharts(echartsList){
      if(echartsList.length>0){
        for(let i=0;i<echartsList.length;i++){
          echartsList[i].dispose();
        }
      }
    },
  },
   beforeDestroy() {
    clearInterval(this.serviceMapTimer);
    this.disposeEcharts(this.myChartList);
    this.disposeEcharts(this.myChartboxList);
    this.disposeEcharts(this.myChartBox2List);
  },
}
</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;
  }
  .more{
    margin:16px 0;
    text-align: center;
    font-size: 16px;
    color:#1890ff;
    cursor: pointer;
  }
  .nomore{
    color:#999;
  }
  .green_small{
    display: inline-block;
    width:8px;
    height: 8px;
    border-radius: 50%;
    background:#67C23A;
    margin-right:8px;
  }
  .red_small{
    width:8px;
    height: 8px;
    display: inline-block;
    border-radius: 50%;
    background:#F56C6C;
    margin-right:8px;
  }
  .flexWrap{
    display:flex;
    justify-content: space-between;
  }
  .flex-left{
    width:60%;
  }
  .flex-right{
    width:39.99
  }
</style>
