<template>
  <div style="padding:16px;">
    <div class="TableBox">
      <el-table
        ref="tableRef"
        :key="isUpdate"
        v-loading="loading"
        :data="serveceMapList"
        @row-click="handleRowClick"
      >
        <el-table-column v-if="colData[0].istrue" align="center" header-align="center" class-name="column_one" label="业务名" prop="name" :show-overflow-tooltip="true" />
        <el-table-column v-if="colData[4].istrue" header-align="center" align="center" label="请求总数" sortable prop="request_total" :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'">
              <div class="table-num-box">
                {{ scope.row.request_total== undefined?0:Number(scope.row.request_total).toFixed(2) }}
              </div>
              <div class="table-day-rate-box">
                <i v-show="processNumber(scope.row.request_total_dod).sign" :class="processNumber(scope.row.request_total_dod).sign == 'up'? 'el-icon-up up':'el-icon-down down'" />
                <span>
                  {{ scope.row.request_total_dod==undefined?0:getErrRate(processNumber(scope.row.request_total_dod).value) }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[1].istrue" header-align="center" align="center" label="调用占比" prop="request_rate" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div class="table_bg">
              <div class="table-num-box">
                {{ getErrRate(scope.row.request_rate) }}
              </div>
              <div class="table-day-rate-box">
                <i v-show="processNumber(scope.row.request_rate_dod).sign" :class="processNumber(scope.row.request_rate_dod).sign == 'up'? 'el-icon-up up':'el-icon-down down'" />
                <span>
                  {{ scope.row.request_rate_dod==undefined?0:getErrRate(processNumber(scope.row.request_rate_dod).value) }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[2].istrue" header-align="center" align="center" label="SpanName" prop="span_name" :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" align="center" label="rpm" sortable prop="rpm" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div class="table_bg">
              {{ scope.row.rpm == undefined?0:Number(scope.row.rpm).toFixed(2) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[5].istrue" header-align="center" align="center" label="错误率" sortable prop="error_rate" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div :class="scope.row.error_rate==0?'table_bg':'table_bg_red'">
              <div class="table-num-box">
                {{ getErrRate(scope.row.error_rate) }}
              </div>
              <div class="table-day-rate-box">
                <i v-show="processNumber(scope.row.error_rate_dod).sign" :class="processNumber(scope.row.error_rate_dod).sign == 'up'? 'el-icon-up up':'el-icon-down down'" />
                <span>
                  {{ scope.row.error_rate_dod==undefined?0:getErrRate(processNumber(scope.row.error_rate_dod).value) }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="最大延迟(ms)" sortable prop="max" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div :class="scope.row.max<2000?'table_bg':'table_bg_red'">
              {{ scope.row.max==undefined?0:Number(scope.row.max).toFixed(2) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[7].istrue" header-align="center" align="center" label="平均延迟(ms)" sortable prop="duration_average" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div :class="scope.row.duration_average<2000?'table_bg':'table_bg_red'">
              <div class="table-num-box">
                {{ scope.row.duration_average==undefined?0:Number(scope.row.duration_average).toFixed(2) }}
              </div>
              <div class="table-day-rate-box">
                <i v-show="processNumber(scope.row.duration_average_dod).sign" :class="processNumber(scope.row.duration_average_dod).sign == 'up'? 'el-icon-up up':'el-icon-down down'" />
                <span>
                  {{ scope.row.duration_average_dod==undefined?0:getErrRate(processNumber(scope.row.duration_average_dod).value) }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column v-if="colData[8].istrue" header-align="center" align="center" label="中位延迟11" prop="duration_median" width="200">
          <template slot-scope="scope">
            <div :class="scope.row.duration_median<2000?'table_bg':'table_bg_red'" style="display:flex;">
              <div>
                <div class="table-num-box">
                  {{ scope.row.duration_median==undefined?0:Number(scope.row.duration_median).toFixed(2) }}
                </div>
                <div class="table-day-rate-box">
                  <i v-show="processNumber(scope.row.duration_median_dod).sign" :class="processNumber(scope.row.duration_median_dod).sign == 'up'? 'el-icon-up up':'el-icon-down down'" />
                  <span>
                    {{ scope.row.duration_median_dod==undefined?0:getErrRate(processNumber(scope.row.duration_median_dod).value) }}
                  </span>
                </div>
              </div>
              <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" />
              </span>
            </div>
          </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>
    <!-- 业务空间 -->
    <ServiceSpaceDrawer v-if="isShowServiceSpaceDrawer" :is-opendrawer="isShowServiceSpaceDrawer" :bussiness-id="currentBussinessId" :bussiness-name="currentBussinessName" @handleClose="handleClose" />
  </div>
</template>

<script>
import ServiceSpaceDrawer from './ServiceSpaceDrawer.vue'
import { addUrlMapping, getNewBusinessList, listBizStats, 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: 'KeyBusiness',
  components: {
    Topo,
    ServiceSpaceDrawer
  },
  mixins: [resize],
  data() {
    return {
      loading: false,
      // 设置选中的列的复选框
      colSelect: [
        '业务名',
        '调用占比',
        // "SpanName",
        // "rpm",
        '请求总数',
        '错误率',
        // '最大延迟(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: '中位延迟', istrue: false }
      ],
      isUpdate: false,
      isflag: false,
      tableflag: false,
      isShowServiceSpaceDrawer: false,
      topflag: 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: {
        app_alias: '', // 应用别名
        service_name: null, // 服务名称
        // duration:'',//最小延迟
        // error_rate:'',//最小错误率
        // request_total:'',//最低请求量
        // node_num:'',//最小节点数量
        // access_database: '',//是否涉及数据库
        vip: true, // 是否为重点业务
        // favor:'',//是否收藏
        page_num: 1, // 当前页码
        page_size: 10 // 每页条数
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '接口名称不能为空', trigger: 'blur' }
        ],
        url: [
          { required: true, message: 'URL组不能为空', trigger: 'blur' }
        ]
      },
      appsAction: process.env.VUE_APP_BASE_API + '/api/v1/public/uploadFile',
      appsfileList: [],
      headers: { 'Authorization': 'Bearer ' + getToken() },
      appsItem: {},
      expands: [],

      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: [],
      currentBussinessId: '', // 当前点击业务id
      currentBussinessName: '相关业务'// 当前点击业务名字
    }
  },
  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.queryParams.page_num = 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)

    this.appItem = storage.get('appsItem')
    if (JSON.stringify(this.appItem) != '{}') {
      this.appItem = storage.get('appsItem')
      this.queryParams.app_alias = this.appItem.alias
      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: {
    // 判断数字是正是负还是零并给出标识
    processNumber(num) {
      const result = {
        value: num,
        sign: ''
      }
      if (num > 0) {
        result.sign = 'up'
      } else if (num < 0) {
        result.value = Math.abs(num) // 返回绝对值
        result.sign = 'down'
      } else {
        result.sign = ''
      }
      return result
    },
    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)
    },
    handleClose() {
      this.isShowServiceSpaceDrawer = false
    },
    drawerCloseDetail() {
      this.drawerDetail = false
    },
    handleRowClick(row, column, event) {
      this.currentBussinessId = row.id
      this.currentBussinessName = row.name
      this.isShowServiceSpaceDrawer = true
    },

    getListBizGraph(id) {
      this.loading = true
      listBizGraph({ biz_id: id }).then((res) => {
        this.graphData = {}
        if (res.code == 200) {
          const arr = res.data
          console.log(10000001111, arr)
          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) {
      console.log(3000, 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.page_num++
          this.getList()
        } else {
          // this.$message("已加载完所有的数据！");
          this.loading = false
        }
      }
    },
    // 获取左侧table 数据
    getList() {
      const _this = this
      this.loading = true
      this.myChartList = []
      this.myChartboxList = []
      this.myChartBox2List = []
      getNewBusinessList(this.queryParams).then(res => {
        if (res.code == 200) {
          this.serveceMapList = res.data.list || []
          this.tableCount = res.data.total || 0
          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()
          })
        }
      })
    },
    beforeUpload(file) {
      const isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },
    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.page_num = 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
    },
    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()

      // 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(response.msg)
                this.open = false
                this.drawer = false
                this.queryParams.page_num = 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.page_num = 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.page_num = 1
        this.serveceMapList = []
        this.tempList = []
        this.msgSuccess(response.msg)
        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) {
          this.msgSuccess(res.msg)
          this.queryParams.page_num = 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(() => {
        this.$nextTick(() => {
          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)
    },
    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;
}
.table-num-box{
  height:20px;
  line-height:30px;
}
.table-day-rate-box{
  height:20px;
  line-height:20px;
  font-size:10px;
}
.up{
  color:#ea463d;
}
.down{
  color:#00b54f;
}
.el-icon-up:before{
  content:'\e6e6'
}
.el-icon-down:before{
  content:'\e6eb'
}
.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>
