<template>
  <div style="padding:16px;">
    <el-row :gutter="10" class="mb8">
      <el-col :span="10">
        <el-form ref="queryForm" style="margin-top: -4px;" :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-item label="" prop="service_name">
            <!-- <el-input
                  v-model="queryParams.service_name"
                  placeholder="请输入服务名称"
                  clearable
                  size="mini"
                  @keyup.enter.native="handleQuery"
                /> -->
            <el-select
              v-model="queryParams.service_name"
              placeholder="请选择服务"
              clearable
              filterable
              value-key="id"
              size="mini"
              @change="handChange"
            >
              <el-option
                v-for="item in serviceList"
                :key="item.id"
                :label="item.name"
                :value="item.service_name"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <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-col :span="2">
        <el-upload
          ref="upload"
          class="comp-start-upload"
          drag
          action="#"
          :auto-upload="false"
          :multiple="false"
          :show-file-list="false"
          accept=".xls, .xlsx"
          :on-change="handelUpload"
        >
          <el-button size="mini" icon="el-icon-upload2" type="primary">上传Excel</el-button>
        </el-upload>
      </el-col>
    </el-row>

    <div class="TableBox">
      <el-table
        v-loading="loading"
        :data="serveceMapList"
        @row-click="handleRowClick"
      >
        <el-table-column v-if="colData[0].istrue" class-name="column_one" header-align="left" label="接口组名" prop="name" align="left" :show-overflow-tooltip="true" />
        <el-table-column v-if="colData[1].istrue" header-align="left" label="所属服务" prop="service_name_cn" align="left" :show-overflow-tooltip="true" />
        <el-table-column v-if="colData[2].istrue" header-align="center" label="请求方法" prop="method" align="center">
          <template slot-scope="scope">
            <el-tag type="info">{{ scope.row.method }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[3].istrue" header-align="left" label="URL前缀" prop="url" align="left" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.url }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[4].istrue" header-align="center" label="rpm" sortable prop="rpm" align="right" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div class="table_bg">
              <!-- <el-tag>{{ scope.row.rpm == undefined?0:Number(scope.row.rpm).toFixed(2)}}</el-tag> -->
              {{ 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" label="请求总数" sortable prop="total" align="right" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div :class="scope.row.total!=0&&scope.row.total!= undefined?'table_bg':'table_bg_yellow'">
              <!-- <el-tag>{{ scope.row.total== undefined?0:Number(scope.row.total).toFixed(2)}}</el-tag> -->
              {{ scope.row.total== undefined?0:Number(scope.row.total).toFixed(2) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[6].istrue" header-align="center" label="errRate" 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[7].istrue" header-align="center" label="最大延迟(ms)" sortable prop="max" align="right" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div :class="scope.row.max<2000?'table_bg':'table_bg_red'">
              <!-- <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> -->
              {{ scope.row.max==undefined?0:Number(scope.row.max).toFixed(2) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[8].istrue" header-align="center" label="avg(ms)" sortable prop="avg" align="right" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div :class="scope.row.avg<2000?'table_bg':'table_bg_red'">
              <!-- <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> -->
              {{ scope.row.avg==undefined?0:Number(scope.row.avg).toFixed(2) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[9].istrue" header-align="center" label="中位延迟" prop="p50" align="center" width="200">
          <template slot-scope="scope">
            <span v-if="scope.row.duration_stats!=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.duration_stats.p50!= undefined&&scope.row.duration_stats.p50.length>0?timeConversion(scope.row.duration_stats.p50[scope.row.duration_stats.p50.length-1]):'' }}
                <div slot="reference" class="name-wrapper">
                  <div class="P_box">{{ scope.row.duration_stats.p50!= undefined&&scope.row.duration_stats.p50.length>0?timeConversion(scope.row.duration_stats.p50[scope.row.duration_stats.p50.length-1]):'' }}</div>
                </div>
              </el-popover>
            </span>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[10].istrue" header-align="center" label="90分位延迟" prop="p90" align="center" width="200">
          <template slot-scope="scope">
            <span v-if="scope.row.duration_stats!=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.duration_stats.p90!= undefined&&scope.row.duration_stats.p90.length>0?timeConversion(scope.row.duration_stats.p90[scope.row.duration_stats.p90.length-1]):'' }}
                <div slot="reference" class="name-wrapper">
                  <div class="P_box">{{ scope.row.duration_stats.p90!= undefined&&scope.row.duration_stats.p90.length>0?timeConversion(scope.row.duration_stats.p90[scope.row.duration_stats.p90.length-1]):'' }}</div>
                </div>
              </el-popover>
            </span>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[11].istrue" header-align="center" label="99分位延迟" prop="p99" align="center" width="200">
          <template slot-scope="scope">
            <span v-if="scope.row.duration_stats!=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.duration_stats.p99!= undefined&&scope.row.duration_stats.p99.length>0?timeConversion(scope.row.duration_stats.p99[scope.row.duration_stats.p99.length-1]):'' }}
                <div slot="reference" class="name-wrapper">
                  <div class="P_box">{{ scope.row.duration_stats.p99!= undefined&&scope.row.duration_stats.p99.length>0?timeConversion(scope.row.duration_stats.p99[scope.row.duration_stats.p99.length-1]):'' }}</div>
                </div>
              </el-popover>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="160"
          class-name="small-padding fixed-width"
          prop="favor"
        >
          <template slot-scope="scope">
            <el-button
              v-permisaction="['disposition:index:edit']"
              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)"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination
      v-show="tableCount>0"
      :total="tableCount"
      :page.sync="queryParams.pageIndex"
      :limit.sync="queryParams.pageSize"
      @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-item v-if="isEdit == true" 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>
              <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="55%"
      @close="drawerClose"
    >
      <div style="margin-bottom:16px">

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

        <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" />{{ scope.row.status_code }}</span>
                <span v-else><i class="red_small" />{{ scope.row.status_code }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column header-align="center" label="Duration(ms)" prop="duration" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.duration>=2000" type="danger">{{ scope.row.duration }}</el-tag>
              <el-tag v-if="scope.row.duration<2000" type="info">{{ scope.row.duration }}</el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column header-align="center" label="max(ms)" sortable="custom" prop="duration_stats" align="center" width="100">
                <template slot-scope="scope">
                  <span>{{ Number(scope.row.max).toFixed(2)}}</span>
                </template>
              </el-table-column>
              <el-table-column header-align="center" label="avg(ms)" sortable="custom" prop="duration_stats" align="center" width="100">
                <template slot-scope="scope">
                  <span>{{ Number(scope.row.avg).toFixed(2)}}</span>
                </template>
              </el-table-column> -->
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="childQueryParams.pageIndex"
          :limit.sync="childQueryParams.pageSize"
          @pagination="handelgetUrlMappingRange"
        />
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listUrlMapping, addUrlMapping, getUrlMapping, updateUrlMapping, delUrlMapping, favor, getUrlMappingRange, uploadExcel } from '@/api/mapping'
import { listService } from '@/api/service'
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 BigNumber from 'bignumber.js'
export default {
  name: 'ServiceMap',
  mixins: [resize],
  // directives: {
  //   'el-table-infinite-scroll': elTableInfiniteScroll
  // },
  data() {
    return {
      // 设置选中的列的复选框
      colSelect: [
        '接口名',
        '所属服务',
        '请求方法',
        'URL前缀',
        // "rpm",
        '请求总数',
        // "errRate",
        '最大延迟(ms)',
        // "延迟比例",
        '中位延迟',
        '90分位延迟',
        '99分位延迟'

      ],
      colData: [
        { title: '接口名', istrue: false },
        { title: '所属服务', istrue: false },
        { title: '请求方法', istrue: false },
        { title: 'URL前缀', istrue: false },
        { title: 'rpm', istrue: false },
        { title: '请求总数', istrue: false },
        { title: 'errRate', istrue: false },
        { title: '最大延迟(ms)', istrue: false },
        { title: 'avg(ms)', istrue: false },
        // { title: "延迟比例", istrue: false },
        { title: '中位延迟', istrue: false },
        { title: '90分位延迟', istrue: false },
        { title: '99分位延迟', istrue: false }
      ],
      serviceList: [],
      serviceParams: {
        app_alias: '',
        start_time: '',
        end_time: '',
        pageIndex: 1,
        pageSize: 200
      },
      drawer: false,
      detailData: {},
      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),
        start_time: 0,
        end_time: 0,
        app_id: undefined,
        favor: '',
        url: '',
        pageIndex: 1,
        pageSize: 10,
        service_name: ''
        // level:1,//新增加的字段
      },
      // 表单参数
      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,
        id: 0,
        app_id: 0,
        kind: '',
        only_error: 0,
        pageIndex: 1,
        pageSize: 10
      },
      rowData: [],
      serviceMapTimer: null,
      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.childQueryParams.start_time = newValue.startTime
          this.childQueryParams.end_time = newValue.endTime
          this.queryParams.pageIndex = 1
          this.serviceParams.start_time = newValue.startTime
          this.serviceParams.end_time = newValue.endTime
          this.serviceParams.pageIndex = 1
          this.serveceMapList = []
          this.getList()
          this.getServiceList()
          if (newValue.timeOut) {
            if (newValue.timeOut == 1) {
              clearInterval(this.serviceMapTimer)
            } else {
              clearInterval(this.serviceMapTimer)
              this.Refresh(newValue.timeOut)
            }
          }
        }
      },
      // immediate: true,
      deep: true
    }
  },
  created() {
    // this.queryParams.start_time = this.$store.getters.globalTimes.startTime;
    // this.queryParams.end_time = this.$store.getters.globalTimes.endTime
    // this.childQueryParams.start_time = this.$store.getters.globalTimes.startTime;
    // this.childQueryParams.end_time = this.$store.getters.globalTimes.endTime
    const windowHeight = document.documentElement.clientHeight || document.body.clientHeight
    // 动态计算表格的高度，200为屏幕内除了表格以外其他元素的高度，依实际情况而定
    this.tableHeight = windowHeight - 200 + 'px'
    this.appsItem = storage.get('appsItem')
    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.serviceParams.start_time = start_time
    this.serviceParams.end_time = end_time
    if (JSON.stringify(this.appsItem) != '{}') {
      this.queryParams.app_id = this.appsItem.id
      this.childQueryParams.app_id = this.appsItem.id
      this.serviceParams.app_alias = this.appsItem.alias
      // this.getList()
    }
    if (this.$route.query.service_name != undefined && this.$route.query.url != undefined) {
      this.queryParams.url = this.$route.query.url
      this.queryParams.service_name = this.$route.query.service_name
    }

    this.getList()
    this.getServiceList()
    this.columnChange()
  },
  mounted() {
  },
  beforeDestroy() {
    clearInterval(this.serviceMapTimer)
    this.disposeEcharts(this.myChartList)
    this.disposeEcharts(this.myChartboxList)
    this.disposeEcharts(this.myChartBox2List)
  },
  methods: {
    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)
      }
      //  0.00000000000000000003---->3e-20
      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)}%`
      }
    },
    handChange(val) {
      this.queryParams.service_name = val
      this.handleQuery()
    },
    // 使用该业务的服务list
    getServiceList() {
      listService(this.serviceParams).then(res => {
        if (res.code == 200) {
          this.serviceList = res.data.list
        } else {
          this.serviceList = []
        }
      })
    },
    // 控制列的显示和隐藏
    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()
        this.getServiceList()
      }, timeOut)
    },
    goto(row) {
      const datetime = Date.parse(row.datetime) / 1000
      const 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
    },
    toogleExpand(row, column, event) {
      this.drawer = true
      this.childQueryParams.id = row.id
      this.handelgetUrlMappingRange()
    },
    handleRowClick(row, column, event) {
      storage.set('row', row)
      this.$router.push({
        path: '/service/InterfaceSublist/index',
        query: {
          id: row.id,
          name: row.name
        }
      })
    },
    handelgetUrlMappingRange() {
      this.tableLoading = true
      getUrlMappingRange(this.childQueryParams).then(res => {
        if (res.code == 200) {
          this.tableLoading = false
          this.rowData = res.data.list
          this.total = res.data.count
        }
      })
    },
    // 根据行的id判断
    getRowKeys(row) {
      return row.id
    },
    clickRowHandle(row, column, event) {
    //  alert('a')
    },
    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
      this.myChartList = []
      this.myChartboxList = []
      this.myChartBox2List = []
      listUrlMapping(this.queryParams).then(res => {
        if (res.code == 200) {
          this.loading = false
          this.serveceMapList = res.data.list
          this.tableCount = res.data.count
        }
      })
    },
    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.pageIndex = 1
      this.serveceMapList = []
      const newValue = this.queryParams.service_name // 设置要传递的数据
      this.$emit('updateData', newValue)
      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 = '修改URL前缀'
          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) {
            updateUrlMapping(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.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.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 delUrlMapping(id)
      }).then((response) => {
        this.queryParams.pageIndex = 1
        this.serveceMapList = []
        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'
      }

      favor({ favor: row.favor }, row.id).then(res => {
        if (res.code = 200) {
          this.msgSuccess(res.msg)
          this.queryParams.pageIndex = 1
          this.serveceMapList = []
          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
        })
      })
    },
    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(() => {
        let myChart = this.$echarts5.getInstanceByDom(document.getElementById(chartId))
        if (myChart == null) {
          myChart = this.$echarts5.init(document.getElementById(chartId), 'macarons')
        }
        myChart.setOption(option)
        myChart.resize()
      })
    },
    drawEchartsp5(row, index) {
      const that = this
      if (row.duration_stats != undefined) {
        const option = {
          tooltip: {
            trigger: 'axis',
            // confine: false,
            appendToBody: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: row.duration_stats.time,
            show: false
          },
          grid: {
            top: '15%',
            bottom: '10%',
            left: '1%',
            right: '1%'
          },
          yAxis: {
            type: 'value',
            show: false
          },
          series: [
            {
              name: 'P50',
              data: row.duration_stats.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' })
          that.myChartList.push(myChart)
          myChart.setOption(option)

          myChart.group = `index${row.id}`
          this.$echarts5.connect(`index${row.id}`)
        }, 1000)
      }
    },
    drawEchartsp90(row, index) {
      const that = this
      if (row.duration_stats != undefined) {
        const option = {
          tooltip: {
            trigger: 'axis',
            // confine: false,
            appendToBody: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: row.duration_stats.time,
            show: false
          },
          grid: {
            top: '15%',
            bottom: '10%',
            left: '1%',
            right: '1%'
          },
          yAxis: {
            type: 'value',
            show: false
          },
          series: [
            {
              name: 'P90',
              data: row.duration_stats.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')
          }
          that.myChartboxList.push(myChartbox)
          myChartbox.dispatchAction({ type: 'hideTip' })
          myChartbox.setOption(option)
          myChartbox.resize()
          // myChartbox.group = 'group1'
          // this.$echarts5.connect('group1')

          myChartbox.group = `index${row.id}`
          this.$echarts5.connect(`index${row.id}`)
        }, 1000)
      }
    },
    drawEchartsp99(row, index) {
      const that = this
      if (row.duration_stats != undefined) {
        const option = {
          tooltip: {
            trigger: 'axis',
            // confine: false,
            appendToBody: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: row.duration_stats.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.duration_stats.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')
          }

          that.myChartBox2List.push(myChartBox2)
          myChartBox2.dispatchAction({ type: 'hideTip' })
          myChartBox2.setOption(option)
          myChartBox2.resize()
          // myChartBox2.group = 'group1'
          // this.$echarts5.connect('group1')
          myChartBox2.group = `index${row.id}`
          this.$echarts5.connect(`index${row.id}`)
        }, 1000)
      }
    },
    drawEchartsScale(row) {
      const _this = this
      const 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)
          //   return params
          // },
          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
          }
        },
        grid: {
          left: '4%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: row.duration_stats.time
          // show:true
        },
        yAxis: {
          type: 'value',
          scale: true,
          gridIndex: 0,
          axisLabel: {
            formatter: '{value}'
          },
          axisLine: {
            show: true
          },
          axisTick: {
            show: true
          },
          splitLine: {
            show: true
          }
        },
        series: [
          {
            name: 'P.50',
            type: 'line',
            stack: 'Total',
            symbol: 'none',
            // symbol: 'emptyCircle',//拐点
            data: row.duration_stats.p50
          },
          {
            name: 'P.95',
            type: 'line',
            stack: 'Total',
            symbol: 'none', // 拐点
            // symbol: 'emptyCircle',//拐点
            data: row.duration_stats.p90
          },
          {
            name: 'P.99',
            type: 'line',
            stack: 'Total',
            symbol: 'none', // 拐点
            // symbol: 'emptyCircle',//拐点
            data: row.duration_stats.p99
          }
        ]
      }
      // 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
        //  // 获取数据，进行操作
        // }
        const data = storage.get('paramsValue')
        const timestamp = moment(data[0].name).unix()

        _this.childQueryParams.start_time = timestamp
        _this.childQueryParams.end_time = timestamp
        _this.handelgetUrlMappingRange()
      })
    },
    disposeEcharts(echartsList) {
      if (echartsList.length > 0) {
        for (let i = 0; i < echartsList.length; i++) {
          if (echartsList[i]) {
            window.removeEventListener('resize', echartsList[i].resize)// 销毁图表监听事件

            echartsList[i].dispose()
          }
        }
      }
      this.myChartList = []
      this.myChartboxList = []
      this.myChartBox2List = []
    },
    async handelUpload(file, fileList) {
      const isLt5M = file.size / 1024 / 1024 < 5
      if (isLt5M) {
        const param = new FormData()
        param.append('file', file.raw)
        param.append('app_alias', this.appsItem.alias)
        const res = await uploadExcel(param)
        if (res.code == 200) {
          this.$message.success('上传成功!')
        }
        await this.getList()
      } else {
        this.$message.error('上传文件不能超过5M!')
        return false
      }
    }
  }
}
</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;
  }
.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: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;
}
.comp-start-upload ::v-deep .el-upload-dragger{
  width: auto;
  height: auto;
  border:none;
  border-radius: 0;
  margin-left:10px;
}
</style>
