<template>
  <div style="padding:16px;">
    <el-row :gutter="10" class="mb8">
      <el-col :span="2">
        <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>
      </el-col>
    </el-row>

    <div v-if="serveceMapList.length>0" class="TableBox">
      <el-table
        :key="isUpdate"
        v-loading="loading"
        :data="serveceMapList"
        @row-click="handleRowClick"
      >
        <el-table-column v-if="colData[0].istrue" class-name="column_one" header-align="center" label="业务名称" prop="name" align="center" :show-overflow-tooltip="true" width="450" />
        <el-table-column v-if="colData[1].istrue" header-align="center" label="起始服务" prop="service_name_cn" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.service_name_cn }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[2].istrue" header-align="center" label="SpanName" prop="span_name" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.span_name }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[3].istrue" header-align="center" label="rpm" sortable prop="rpm" align="right" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div class="table_bg">
              {{ getRPCMetadata(scope.row) }}
              <!-- {{ scope.row.rpm == undefined?0:Number(scope.row.rpm).toFixed(2) }} -->
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[4].istrue" header-align="center" label="请求总数" sortable prop="request_total" align="right" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div :class="scope.row.request_total!=0&&scope.row.request_total!= undefined?'table_bg':'table_bg_yellow'">
              {{ scope.row.request_total== undefined?0:scope.row.request_total }}
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[5].istrue" header-align="center" label="错误率" sortable prop="error_rate" align="right" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div :class="scope.row.error_rate==0?'table_bg':'table_bg_red'">
              {{ getErrRate(scope.row.error_rate) }}
              <!-- {{ scope.row.error_rate==0?scope.row.error_rate:Number(scope.row.error_rate).toFixed(2) }} -->
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[6].istrue" header-align="center" label="最大延迟(ms)" sortable prop="duration_max" align="right" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div :class="scope.row.max<2000?'table_bg':'table_bg_red'">
              {{ scope.row.duration_max==undefined?0:Number(scope.row.duration_max).toFixed(2) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[7].istrue" header-align="center" label="平均延迟(ms)" sortable prop="duration_average" align="right" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div :class="scope.row.duration_average<2000?'table_bg':'table_bg_red'">
              {{ scope.row.duration_average==undefined?0:Number(scope.row.duration_average).toFixed(2) }}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="colData[8].istrue" header-align="center" label="中位延迟" prop="p50" align="center" width="200">
          <template slot-scope="scope">
            <span v-if="scope.row.quantiles!=undefined" style="display:flex;">
              {{ drawEchartsp5(scope.row, scope.$index, 'five') }}
              <div :id="`tiger-five-trend-index` + scope.$index" style="flex:1;padding-left:10px" class="tiger-trend-charts" />
              <el-popover trigger="hover" placement="top">
                {{ scope.row.quantiles.p50!= undefined&&scope.row.quantiles.p50.length>0?timeConversion(scope.row.quantiles.p50[scope.row.quantiles.p50.length-1]):'' }}
                <div slot="reference" class="name-wrapper">
                  <div class="P_box">{{ scope.row.quantiles.p50!= undefined&&scope.row.quantiles.p50.length>0?timeConversion(scope.row.quantiles.p50[scope.row.quantiles.p50.length-1]):'' }}</div>
                </div>
              </el-popover>
            </span>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[9].istrue" header-align="center" label="90分位延迟" prop="p90" align="center" width="200">
          <template slot-scope="scope">
            <span v-if="scope.row.quantiles!=undefined" style="display:flex;">
              {{ drawEchartsp90(scope.row, scope.$index, 'nine') }}
              <div :id="`tiger-nine-trend-index` + scope.$index" style="flex:1;padding-left:10px" class="tiger-trend-charts" />
              <el-popover trigger="hover" placement="top">
                {{ scope.row.quantiles.p90!= undefined&&scope.row.quantiles.p90.length>0?timeConversion(scope.row.quantiles.p90[scope.row.quantiles.p90.length-1]):'' }}
                <div slot="reference" class="name-wrapper">
                  <div class="P_box">{{ scope.row.quantiles.p90!= undefined&&scope.row.quantiles.p90.length>0?timeConversion(scope.row.quantiles.p90[scope.row.quantiles.p90.length-1]):'' }}</div>
                </div>
              </el-popover>
            </span>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[10].istrue" header-align="center" label="99分位延迟" prop="p99" align="center" width="200">
          <template slot-scope="scope">
            <span v-if="scope.row.quantiles!=undefined" style="display:flex;">
              {{ drawEchartsp99(scope.row, scope.$index, 'hundred') }}
              <div :id="`tiger-hundred-trend-index` + scope.$index" style="flex:1;padding-left:10px" class="tiger-trend-charts" />
              <el-popover trigger="hover" placement="top">
                {{ scope.row.quantiles.p99!= undefined&&scope.row.quantiles.p90.length>0?timeConversion(scope.row.quantiles.p99[scope.row.quantiles.p99.length-1]):'' }}
                <div slot="reference" class="name-wrapper">
                  <div class="P_box">{{ scope.row.quantiles.p99!= undefined&&scope.row.quantiles.p99.length>0?timeConversion(scope.row.quantiles.p99[scope.row.quantiles.p99.length-1]):'' }}</div>
                </div>
              </el-popover>
            </span>
          </template>
        </el-table-column> -->
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="160"
          sortable
        >
          <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
              v-if="scope.row.favor == 1"
              size="mini"
              type="text"
              icon="el-icon-star-on"
              @click.native.stop="handleFavor(scope.row)"
            />
            <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>
    <pagination
      v-show="tableCount>0"
      :total="tableCount"
      :page.sync="queryParams.page_num"
      :limit.sync="queryParams.page_size"
      @pagination="getList"
    />

    <!-- 添加或修改应用配置对话框 -->
    <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>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer
      :visible.sync="drawer"
      direction="rtl"
      size="calc( 100vw - 210px)"
      @close="drawerClose"
    >
      <div slot="title">
        <span style="font-size:16px;font-weight:500;margin-right:24px" @click="handleUpdate">{{ detailTitle }}</span>
        <el-button
          size="small"
          type="primary"
          @click.native.stop="handleUpdateName()"
        >修改别名</el-button>
      </div>
      <div style="margin-bottom:16px;">
        <div class="flexWrap">
          <div class="flex-left">
            <div v-loading="loading">
              <Topo v-if="topflag" ref="topo" :graph-data="graphData" topo-id="container" />
            </div>
          </div>
          <div class="flex-right">
            <div id="scaleMain" style="width:100%;height:240px;margin-bottom:36px;margin-top:16px" />
            <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="SpanName" prop="span_name" align="center" :show-overflow-tooltip="true" />

              <el-table-column header-align="center" label="日期" prop="datetime" align="center" :show-overflow-tooltip="true" />

              <el-table-column header-align="center" label="请求时长(ms)" prop="duration" width="140" 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>
            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="childQueryParams.pageIndex"
              :limit.sync="childQueryParams.pageSize"
              @pagination="handelgetBizDetail"
            />
          </div>
        </div>

      </div>
    </el-drawer>

    <el-drawer
      v-if="JSON.stringify(detailData) != &quot;{}&quot;"
      :visible.sync="drawerDetail"
      direction="rtl"
      size="55%"
      @close="drawerCloseDetail"
    >
      <el-collapse v-model="activeNames">
        <el-collapse-item title="属性" name="one">
          <ul v-if="detailData.span_attributes !=null" class="ul_box">
            <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 v-if="detailData.resource_attributes !=null" class="ul_box">
            <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 { addUrlMapping, getNewBusinessList, getBizDetail, listBizGraph, updateBiz, delBiz, favorBiz } from '@/api/mapping'
import { formatJson } from '@/utils'
import storage from '@/utils/storage'
// import bus from '@/utils/bus'

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 './Topo'
import BigNumber from 'bignumber.js'
export default {
  name: 'ServiceMap',
  components: {
    Topo
  },
  mixins: [resize],
  data() {
    return {
      loading: false,
      // 设置选中的列的复选框
      colSelect: [
        '业务名称',
        '起始服务',
        '请求总数',
        '错误率',
        '最大延迟(ms)'
        // '中位延迟',
        // '90分位延迟',
        // '99分位延迟'
      ],
      colData: [
        { title: '业务名称', istrue: false },
        { title: '起始服务', istrue: false },
        { title: 'SpanName', istrue: false },
        { title: 'rpm', istrue: false },
        { title: '请求总数', istrue: false },
        { title: '错误率', istrue: false },
        { title: '最大延迟(ms)', istrue: false },
        { title: '平均延迟(ms)', istrue: false }
        // { title: '中位延迟', istrue: false },
        // { title: '90分位延迟', istrue: false },
        // { title: '99分位延迟', istrue: false }
      ],
      isUpdate: false,
      isflag: false,
      tableflag: false,
      drawer: false,
      topflag: false,
      detailData: {},
      drawerDetail: false,
      tableLoading: false,
      // 表格高度
      tableHeight: '',
      // 数据总数
      tableCount: 0,
      serveceMapList: [],
      // 应用数据列表
      appData: [],
      // 遮罩层
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      menuIdsChecked: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      isEdit: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        app_alias: '', // 应用别名
        service_name: '', // 服务名称
        duration: '', // 最小延迟
        error_rate: '', // 最小错误率
        request_total: '', // 最低请求量
        node_num: '', // 最小节点数量
        access_database: '', // 是否涉及数据库
        favor: '', // 是否收藏
        sort_field: 'request_total', // 支持 request_total(请求总数，调用占比)、error_rate(错误率)、duration_median(中位延迟)
        sort_type: 'desc',
        page_num: 1, // 当前页码
        page_size: 10// 每页条数
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '接口名称不能为空', trigger: 'blur' }
        ],
        url: [
          { required: true, message: 'URL组不能为空', trigger: 'blur' }
        ]
      },
      appsfileList: [],
      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: {
        biz_id: 0,
        start_time: '',
        end_time: ''
      },
      tempList: [],
      graphData: {},
      graphStatsQuery: {
        biz_node_id: 0, // 仅支持传递单个节点，多个节点需要并发请求分别调用
        end_time: 1702972800,
        start_time: 1702969200
      },
      graphObj: [],
      detailTitle: '',
      detailObj: {},
      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
    },
    '$store.state.alias.currentAlias': { // 当前应用切换
      handler(newValue, oldValue) {
        this.appItem = storage.get('appsItem')
        this.queryParams.app_alias = newValue
        this.getList()
      },
      deep: true
    }
  },
  created() {
    this.$store.commit('time/setTimeFlag', false)

    this.appItem = storage.get('appsItem')
    if (JSON.stringify(this.appItem) != '{}') {
      this.queryParams.app_alias = this.appItem.alias
      const start_time = this.$store.state.time.globalTimes.startTime
      const end_time = this.$store.state.time.globalTimes.endTime
      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()
  },
  beforeDestroy() {
    clearInterval(this.serviceMapTimer)
    this.disposeEcharts(this.myChartList)
    this.disposeEcharts(this.myChartboxList)
    this.disposeEcharts(this.myChartBox2List)
  },
  methods: {
    getRPCMetadata(row) {
      const { request_total = 0 } = row
      // 获取当前时间
      const now = moment()
      // 获取当天凌晨的时间
      const midnight = moment().startOf('day')
      // 计算时间差（以毫秒为单位）
      const diffInMilliseconds = now.diff(midnight)
      // 将毫秒转换为分钟
      const minutesFromMidnight = diffInMilliseconds / (1000 * 60)
      return (parseFloat(Number(request_total) / minutesFromMidnight) || 0).toFixed(2)
    },
    getErrRate(error_rate) {
      const strErrorRate = numToString(error_rate)
      let length = 0
      if (strErrorRate !== '0') {
        const arr = strErrorRate.split('.')
        if (arr.length > 1) {
          length = strErrorRate.split('.')[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) {
        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)}%`
      }
    },
    handleUpdateName() {
      this.open = true
      this.form = this.detailObj
    },
    // 控制列的显示和隐藏
    columnChange(val) {
      this.colData.filter((i) => {
        if (this.colSelect.indexOf(i.title) !== -1) {
          i.istrue = true
        } else {
          i.istrue = false
        }
      })
    },
    Refresh(timeOut) {
      this.serviceMapTimer = setInterval(() => {
        this.getList()
      }, timeOut)
    },
    goto(row) {
      const href = this.$router.resolve({
        path: '/latency/index',
        query: {
          id: row.trace_id,
          span_id: row.span_id
        }
      })
      window.open(window.location.origin + '/' + href.href, '_blank')
    },
    drawerClose() {
      this.drawer = false
      this.topflag = false
      // this.graphData = {}
    },
    drawerCloseDetail() {
      this.drawerDetail = false
    },
    toogleExpand(row, column, event) {
      // this.drawer=true;
      this.childQueryParams.id = row.id
      this.handelgetBizDetail()
    },
    handleRowClick(row, column, event) {
      storage.set('detailObj', row)
      // this.$router.push({
      //   path: '/business-analysis/analysisDetail/index',
      //   query: {
      //     id: row.id,
      //     name: row.name
      //   }
      // })
      const href = this.$router.resolve({
        path: '/business-analysis/business-topics/index',
        query: {
          rowHash: row.hash,
          rowId: row.id,
          service_name: row.service_name,
          name: row.name,
          subconditionValue: this.appItem.alias
        }
      })
      window.open(window.location.origin + '/' + href.href, '_blank')
    },
    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) {
      this.loading = true
      listBizGraph({ biz_id: id }).then((res) => {
        this.graphData = {}
        if (res.code == 200) {
          const arr = res.data
          if (arr.length > 0) {
            const List = this.handelListBizData(arr)
            this.graphData = List[0]
            this.loading = false
          } else {
            this.graphData = {}
          }
        }
      })
    },
    handelListBizData(data) {
      data.forEach((v, k) => {
        // v.collapsed = false;
        v.id = v.id.toString()
        v.name = v.name
        v.label = v.stats.duration != undefined ? (v.stats.duration).toString() : ''
        v.currency = 'ms'
        v.rate = v.stats.success_rate
        v.status = v.stats.success_rate >= 0.6 ? 'B' : v.stats.success_rate == 0 ? 'DI' : 'R'
        v.variableValue = v.stats.success_rate
        v.variableUp = v.stats.success_rate_up
        if (v.children != undefined && v.children.length > 0) {
          v.children = this.handelListBizData(v.children)
        }
      })
      return data
    },
    handleData(data) {
      data.forEach((v, k) => {
        v.id = v.biz_id

        v.collapsed = false
        v.name = v.name
        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
    },
    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() { // 解析列表的table 数据
      this.loading = true
      // const _this = this
      this.myChartList = []
      this.myChartboxList = []
      this.myChartBox2List = []
      getNewBusinessList(this.queryParams).then(res => {
        if (res.code == 200) {
          this.serveceMapList = res.data.list
          this.tableCount = Number(res.data.total)
          this.loading = false
          // if (_this.serveceMapList.length > 0) {
          //   for (let i = 0; i < _this.serveceMapList.length; i++) {
          //     this.BizStatsQuery.biz_id = _this.serveceMapList[i].id
          //     listBizStats(this.BizStatsQuery).then(response => {
          //       if (response.code == 200) {
          //         if (response.data.biz_id != undefined) {
          //           if (_this.serveceMapList[i].id == response.data.biz_id) {
          //             _this.serveceMapList[i] = Object.assign({}, _this.serveceMapList[i], response.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()
    },
    /** 重置按钮操作 */
    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
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()

      // this.form = row;
      this.form.name = row.name
      this.form.id = row.id
      this.title = '修改业务别名'
      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('修改成功')
                this.open = false
                this.drawer = 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('成功')
                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('删除成功')
        this.getList()
      }).catch(function() {})
    },
    handleFavor(row) {
      let favor = ''
      if (row.favor == 1) {
        favor = '0'
      } else if (row.favor == 0) {
        favor = '1'
      }

      favorBiz({ favor: favor }, row.id).then(res => {
        if (res.code === 200) {
          if (favor == '1') {
            this.msgSuccess('已收藏')
          } else {
            this.msgSuccess('已取消收藏')
          }
          this.queryParams.pageIndex = 1
          this.serveceMapList = []
          this.tempList = []
          this.getList()
        }
      })
    },
    /** 导出按钮操作 */
    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
        })
      })
    },
    drawEcharts(row, index) {
      const 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.duration_stats.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.duration_stats.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.duration_stats.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.duration_stats.p99
          }
        ]
      }
      const chartId = 'tiger-' + arguments[2] + '-trend-index' + arguments[1]
      this.$nextTick(() => {
        const myChart = this.$echarts5.init(document.getElementById(chartId), 'macarons')
        myChart.setOption(option)
        myChart.resize()
      })
    },
    drawEchartsp5(row, index) {
      const that = this
      let obj = {}
      obj = row
      // if(row.quantiles != undefined&&row.quantiles.time !=null){
      const option = {
        tooltip: {
          trigger: 'axis',
          confine: false,
          appendToBody: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: obj.quantiles.time,
          show: false
        },
        grid: {
          top: '15%',
          bottom: '10%',
          left: '1%',
          right: '1%'
        },
        yAxis: {
          type: 'value',
          show: false
        },
        series: [
          {
            name: 'P50',
            data: obj.quantiles.p50,
            type: 'line',
            showSymbol: false,
            lineStyle: {
              width: 1
            },
            areaStyle: {
              z: 3,
              coordinateSystem: 'cartesian2d',
              legendHoverLink: true,
              clip: true,
              color: 'rgba(0, 0, 180, 0.2)'
            },
            tooltip: {
              valueFormatter: function(value) {
                return value + ' ms'
              }
            }
          }
        ]
      }

      setTimeout(() => {
        const chartId = 'tiger-' + arguments[2] + '-trend-index' + arguments[1]
        let myChart = this.$echarts5.getInstanceByDom(document.getElementById(chartId))
        if (myChart == null) {
          myChart = that.$echarts5.init(document.getElementById(chartId), 'macarons')
        }
        myChart.dispatchAction({ type: 'hideTip' })
        this.myChartList.push(myChart)
        option && myChart.setOption(option, true)
        // myChart.group = `index${row.id}`
        // this.$echarts5.connect(`index${row.id}`)
      }, 1000)

      // }
    },
    drawEchartsp90(row, index) {
      const that = this
      let obj = {}
      obj = row
      // if(row.quantiles != undefined&&row.quantiles.time !=null){
      const option = {
        tooltip: {
          trigger: 'axis',
          confine: false,
          appendToBody: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: obj.quantiles.time,
          show: false
        },
        grid: {
          top: '15%',
          bottom: '10%',
          left: '1%',
          right: '1%'
        },
        yAxis: {
          type: 'value',
          show: false
        },
        series: [
          {
            name: 'P90',
            data: obj.quantiles.p90,
            type: 'line',
            showSymbol: false,
            lineStyle: {
              width: 1
            },
            areaStyle: {
              z: 3,
              coordinateSystem: 'cartesian2d',
              legendHoverLink: true,
              clip: true,
              color: 'rgba(0, 0, 180, 0.3)'
            },
            tooltip: {
              valueFormatter: function(value) {
                return value + ' ms'
              }
            }
          }
        ]
      }

      setTimeout(() => {
        const chartId = 'tiger-' + arguments[2] + '-trend-index' + arguments[1]
        let myChartbox = this.$echarts5.getInstanceByDom(document.getElementById(chartId))
        if (myChartbox == null) {
          myChartbox = that.$echarts5.init(document.getElementById(chartId), 'ninebox')
        }
        this.myChartboxList.push(myChartbox)
        myChartbox.dispatchAction({ type: 'hideTip' })
        option && myChartbox.setOption(option, true)
        // myChartbox.group = `index${row.id}`
        // this.$echarts5.connect(`index${row.id}`)
      }, 1000)
      // }
    },
    drawEchartsp99(row, index) {
      const that = this
      // if(row.quantiles != undefined&&row.quantiles.time !=null){
      const option = {
        tooltip: {
          trigger: 'axis',
          confine: false,
          appendToBody: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: row.quantiles.time,
          show: false
        },
        grid: {
          top: '15%',
          bottom: '10%',
          left: '1%',
          right: '1%'
        },
        yAxis: {
          type: 'value',
          show: false
        },
        animation: true,
        animationDuration: 1000,
        series: [
          {
            name: 'P99',
            data: row.quantiles.p99,
            type: 'line',
            showSymbol: false,
            lineStyle: {
              width: 1
            },
            areaStyle: {
              z: 3,
              coordinateSystem: 'cartesian2d',
              legendHoverLink: true,
              clip: true,
              color: 'rgba(0, 0, 180, 0.3)'
            },
            tooltip: {
              valueFormatter: function(value) {
                return value + ' ms'
              }
            }
          }
        ]
      }

      setTimeout(() => {
        const chartId = 'tiger-' + arguments[2] + '-trend-index' + arguments[1]
        let myChartBox2 = this.$echarts5.getInstanceByDom(document.getElementById(chartId))
        if (myChartBox2 == null) {
          myChartBox2 = that.$echarts5.init(document.getElementById(chartId), 'hundredbox')
        }
        this.myChartBox2List.push(myChartBox2)
        myChartBox2.dispatchAction({ type: 'hideTip' })
        option && myChartBox2.setOption(option, true)
        // myChartBox2.group = `index${row.id}`
        // this.$echarts5.connect(`index${row.id}`)
      }, 1000)
      // }
    },
    drawEchartsScale(row) {
      const _this = this
      let myChartScale = this.$echarts5.getInstanceByDom(document.getElementById(chartId))
      if (myChartScale == null) {
        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: 14
          }
          // 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 = ''
              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',
            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
          }
        ]
      }
      myChartScale.setOption(option)

      myChartScale.getZr().on('click', params => {
        const data = storage.get('paramsValue')
        const timestamp = moment(data[0].name).unix()

        _this.childQueryParams.start_time = timestamp
        _this.childQueryParams.end_time = timestamp
        _this.handelgetBizDetail()
      })
    },
    disposeEcharts(echartsList) {
      if (echartsList.length > 0) {
        for (let i = 0; i < echartsList.length; i++) {
          echartsList[i].dispose()
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.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: 140px;
  }
  ::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:calc (100% - 720px);
    width:100%;
  }
  .flex-right{
    width:100%;
    // width:39.99%;
    // width: 720px;
  }
.noData{
    width: 100%;
    height: calc(100vh - 120px);
    background: #fff;
}
.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;
}
::v-deep .el-drawer__title{
  margin-top:50px;
}
.table_bg{
  background: #e8f4ff;
  color:#1890ff;
  padding:0 4px;
}
.table_bg_red{
  background-color: #fef0f0;
  color: #f56c6c;
  padding:0 8px;
}
.table_bg_yellow{
    background-color: #fdf6ec;
    color: #e6a23c;
    padding:0 4px;
}
.TableBox ::v-deep .el-table .cell{
  line-height: 40px !important;
  padding-left: 1px;
  padding-right: 1px;
  cursor: pointer;
}
.TableBox ::v-deep .el-table--medium .el-table__cell {
    padding: 2px 0!important;
}
// .P_box{
//   width:58px;
//   min-width: 58px;
//   text-align: right;
//   overflow: hidden;
//   text-overflow: ellipsis;
//   white-space:nowrap;
//   padding-right: 10px;
//   box-sizing: border-box;
// }
.P_box{
  // width:68px;
  min-width: 68px;
  max-width: 100px;
  // text-align: right;
  text-align:left;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space:nowrap;
  padding-right: 10px;
  box-sizing: border-box;
   margin-left: 10px;
}
.TableBox ::v-deep .el-table__cell.column_one .cell{
  padding-left:10px !important;
  padding-right:10px !important;
}
</style>
