<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="flex:1;">
        <!-- <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
        </el-row> -->
        <div>
          <h6 class="h6" style="margin-top: 0;">服务性能</h6>
          <div style="min-height: 288px;">
            <div>
              <div id="serviceBox" class="serviceBox" />
            </div>
          </div>
        </div>
        <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 class="TableBox">
          <el-table
            :key="isUpdate"
            v-loading="loading"
            :data="serveceMapList"
            @row-click="handleRowClick"
            @cell-click="handleCellClick"
            @sort-change="sortChangeTable"
          >
            <el-table-column v-if="colData[0].istrue" class-name="column_one" header-align="center" label="服务别名" prop="name" align="center" :show-overflow-tooltip="true" />
            <el-table-column v-if="colData[1].istrue" header-align="center" label="服务名" prop="service_name" align="center" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ scope.row.service_name }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="colData[2].istrue" header-align="center" label="kind" prop="kind" align="center" :show-overflow-tooltip="true" />
            <el-table-column v-if="colData[3].istrue" header-align="center" label="rpm" 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[4].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'">
                  {{ scope.row.total== undefined?0:Number(scope.row.total) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="colData[5].istrue" header-align="center" label="错误率" 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'">
                  <!-- {{ scope.row.error_rate==0?scope.row.error_rate:Number(scope.row.error_rate).toFixed(2) }} -->
                  {{ getErrRate(scope.row.error_rate) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="colData[6].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&&scope.row.max!=undefined?'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?Number(scope.row.max).toFixed(2):0.00 }}
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="colData[7].istrue" header-align="center" label="平均延迟(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?Number(scope.row.avg).toFixed(2):0.00 }}
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column v-if="colData[8].istrue" header-align="center" label="中位延迟" prop="p50" align="center">
              <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" >
              <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" >
              <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"
              prop="action"
              width="150"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click.native.stop="handleUpdate(scope.row)"
                >标注</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- <div class="more" v-if="serveceMapList.length<tableCount" @click="loadMore">加载更多</div>
        <div class="more nomore" v-if="loading==false&&serveceMapList.length>=tableCount">已加载完所有的数据！</div> -->
        <pagination
          v-show="tableCount>0"
          :total="tableCount"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改应用配置对话框  :rules="rules"-->
        <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" label-width="95px">
            <el-form-item label="中文别名" prop="name">
              <el-input v-model="form.name" size="small" placeholder="请输入帐户服务" />
            </el-form-item>
            <el-form-item label="语言类型" prop="kind">
              <el-input v-model="form.kind" size="small" placeholder="请输入语言类型" />
            </el-form-item>
            <!-- <el-form-item label="URL组" prop="url">
              <span slot="label">
                URL组
                <el-tooltip>
                  <div slot="content">
                    <div>URL匹配示例：</div>
                    <div style="display:flex;justify-content:space-between;font-size:12px;">
                      <div>1、/aaa/bbb 完全匹配</div>
                    </div>
                    <div>
                      <div>2、/aaa/{regexp}, 如/aaa/.*  正则匹配</div>
                    </div>
                  </div>
                  <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-select v-model="form.type" placeholder="服务类型" clearable size="small">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </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-card>
    </template>
  </BasicLayout>
</template>
<script>
// import ServiceMap from './components/ServiceMap.vue'
import { listService, listServiceStats, digitsService, updateService, addService, serviceAppsScore, serviceBar } from '@/api/service'
import storage from '@/utils/storage'
import resize from './mixins/resize'
import BigNumber from 'bignumber.js'
export default {
  components: {
    // ServiceMap
  },
  mixins: [resize],
  data() {
    return {
      // flag:false,
      // 设置选中的列的复选框
      colSelect: [
        '服务别名',
        '错误率',
        // "kind",
        // "rpm",
        '请求总数',
        '最大延迟(ms)'
        // '中位延迟',
        // '90分位延迟',
        // '99分位延迟'
      ],
      colData: [
        { title: '服务别名', istrue: false },
        { title: '服务名', istrue: false },
        { title: 'kind', 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 }
      ],
      appItem: {},
      form: {
        name: '', // 文本框展示，标题：“中文别名”
        kind: '', // 文本框展示，标题：“语言类型”
        type: 1
      },
      typeOptions: [
        {
          value: 1,
          label: '对内服务'
        },
        {
          value: 2,
          label: '对外服务'
        },
        {
          value: 3,
          label: '内外结合'
        }
      ],
      title: '',
      open: false,
      digitsObj: {},
      digitsQuery: {
        app_alias: '',
        service_name: ''
      },
      timer: null,
      loading: false,
      serveceMapList: [],
      tableCount: 0,
      // 查询参数
      queryParams: {
        app_alias: '',
        start_time: '',
        end_time: '',
        pageIndex: 1,
        pageSize: 10,
        sort_type: 'desc',
        sort_field: 'total'// total, error_num, max, avg, p50, p90, p99
      },
      statsQuery: {
        id: 0,
        start_time: '',
        end_time: ''
      },
      isUpdate: false,
      serviceBarQuery: {
        start_time: '',
        end_time: '',
        app_alias: ''
      },
      serviceBarObj: {},
      myChart: null,
      myChartbox: null,
      myChartBox2: null,
      rowFive: {},
      rowNine: {},
      rowHundred: {},
      myChartList: [],
      myChartboxList: [],
      myChartBox2List: [],
      compareChart: null
    }
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.queryParams.start_time = newValue.startTime
          this.queryParams.end_time = newValue.endTime
          this.statsQuery.start_time = newValue.startTime
          this.statsQuery.end_time = newValue.endTime
          this.getList()
          this.digitsQuery.start_time = newValue.startTime
          this.digitsQuery.end_time = newValue.endTime
          this.getDigitsService()
          this.serviceBarQuery.start_time = newValue.startTime
          this.serviceBarQuery.end_time = newValue.endTime
          this.getServiceBar()
          if (newValue.timeOut) {
            if (newValue.timeOut == 1) {
              clearInterval(this.timer)
            } else {
              clearInterval(this.timer)
              this.Refresh(newValue.timeOut)
            }
          }
        }
      },
      // immediate: true,
      deep: true
    },
    serveceMapList: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.serveceMapList = newVal
          // setTimeout(()=>{
          //   this.flag=true;
          // },500)
        }
      },
      // immediate: true,
      deep: true
    }
  },
  mounted() {
    this.getList()
    // this.$nextTick(() => {
    //   this.initServiceChart(this.serviceBarObj)
    // })
    // this.$forceUpdate();
  },
  created() {
    this.appItem = storage.get('appsItem')
    const start_time = this.$store.state.time.globalTimes.startTime
    const end_time = this.$store.state.time.globalTimes.endTime

    if (JSON.stringify(this.appItem) != '{}') {
      this.queryParams.app_alias = this.appItem.alias
      this.queryParams.start_time = start_time
      this.queryParams.end_time = end_time
      this.statsQuery.start_time = start_time
      this.statsQuery.end_time = end_time
      this.digitsQuery.app_alias = this.appItem.alias
      this.digitsQuery.app_id = this.appItem.id
      this.digitsQuery.start_time = start_time
      this.digitsQuery.end_time = end_time
      this.serviceBarQuery.app_alias = this.appItem.alias
      this.serviceBarQuery.start_time = start_time
      this.serviceBarQuery.end_time = end_time
      this.getServiceBar()
      // this.getList()

      this.$forceUpdate()
    }
    if (this.$route.query.id != undefined) {
      this.digitsQuery.service_name = this.$route.query.service_name
      this.getDigitsService()
    }
    this.columnChange()
  },
  beforeDestroy() {
    this.serveceMapList = []
    clearInterval(this.timer)
    this.disposeEcharts(this.myChartList)
    this.disposeEcharts(this.myChartboxList)
    this.disposeEcharts(this.myChartBox2List)
  },
  methods: {
    getErrRate(error_rate) {
      if (error_rate !== undefined || error_rate !== null) {
        const strErrorRate = numToString(error_rate) // 0.17857142857142858
        let length = 0
        if (strErrorRate !== '0') {
          const arr = strErrorRate && strErrorRate.split('.')
          if (arr && arr.length > 1) {
            length = arr[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) {
        if (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)}%`
      }
    },
    getDigitsService() {
      digitsService(this.digitsQuery).then((res) => {
        if (res.code == 200) {
          this.digitsObj = res.data
        }
      })
    },
    // 控制列的显示和隐藏
    columnChange(val) {
      this.colData.filter((i) => {
        if (this.colSelect.indexOf(i.title) !== -1) {
          i.istrue = true
        } else {
          i.istrue = false
        }
      })
    },
    Refresh(timeOut) {
      this.timer = setInterval(() => {
        this.getList()
        this.getServiceBar()
        this.getDigitsService()
      }, timeOut)
    },
    handleRowClick(row, column, event) {
      this.serveceMapList = []
      this.$router.push({
        path: '/service/serviceDetail/index',
        query: {
          id: row.id,
          name: row.name,
          service_name: row.service_name
        }
      })
    },
    handleCellClick(row, column, cell, event) {
    },
    // 加载更多
    loadMore() {
      if (!this.loading) {
        this.loading = true
        if (this.serveceMapList.length < this.tableCount) {
          this.queryParams.pageIndex++
          this.getList()
        } else {
          // this.$message("已加载完所有的数据！");
          this.loading = false
        }
      }
    },
    sortChangeTable(val) {
      const prop = val.prop
      this.queryParams.sort_field = prop
      // desc（倒序）和asc（正序）
      if (val.order === 'descending') {
        this.queryParams.sort_type = 'desc'
      } else if (val.order === 'ascending') {
        this.queryParams.sort_type = 'asc'
      }
      this.getList()
    },
    getList() {
      this.loading = true
      const _this = this
      _this.serveceMapList = []
      this.myChartList = []
      this.myChartboxList = []
      this.myChartBox2List = []
      listService(this.queryParams).then(res => {
        if (res.code == 200) {
          _this.serveceMapList = res.data.list
          this.tableCount = res.data.count
          this.loading = false
          // if (_this.serveceMapList.length > 0) {
          //   for (let i = 0; i < _this.serveceMapList.length; i++) {
          //     this.statsQuery.id = _this.serveceMapList[i].id
          //     listServiceStats(this.statsQuery).then(response => { // 请求总数和最大延迟这两个字段 取这个接口返回的
          //       if (response.code == 200) {
          //         if (response.data.id != undefined) {
          //           if (_this.serveceMapList[i].id == response.data.id) {
          //             _this.serveceMapList[i] = Object.assign({}, _this.serveceMapList[i], response.data)
          //             _this.isUpdate = !_this.isUpdate
          //           }
          //         }
          //       }
          //     })
          //   }
          // }

          this.$nextTick(() => {
            this.$forceUpdate()
          })
        }
      })
    },
    drawEchartsp5(row, index) {
      const that = this
      let obj = {}
      obj = row
      // if(obj.quantiles != undefined){
      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 = that.$echarts5.getInstanceByDom(document.getElementById(chartId))
        // 如果不存在，就进行初始化
        if (myChart == null) {
          myChart = that.$echarts5.init(document.getElementById(chartId), 'macarons')
        }
        myChart.dispatchAction({ type: 'hideTip' })
        this.myChartList.push(myChart)
        if (myChart != null && !myChart.disposed) {
          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(obj.quantiles != undefined){
      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 = that.$echarts5.getInstanceByDom(document.getElementById(chartId))
        if (myChartbox == null) {
          myChartbox = that.$echarts5.init(document.getElementById(chartId), 'ninebox')
        }
        this.myChartboxList.push(myChartbox)
        myChartbox.dispatchAction({ type: 'hideTip' })
        if (myChartbox != null && !myChartbox.disposed) {
          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){
      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
        },
        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 = that.$echarts5.getInstanceByDom(document.getElementById(chartId))
        if (myChartBox2 == null) {
          myChartBox2 = that.$echarts5.init(document.getElementById(chartId), 'hundredbox')
        }
        this.myChartBox2List.push(myChartBox2)
        myChartBox2.dispatchAction({ type: 'hideTip' })
        if (myChartBox2 != null && !myChartBox2.disposed) {
          option && myChartBox2.setOption(option, true)
        }
        // myChartBox2.group = `index${row.id}`
        // this.$echarts5.connect(`index${row.id}`)
      }, 1000)
      // }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // this.getMenuTreeselect(0)
      this.open = true
      this.title = '新增服务信息'
      this.isEdit = false
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        kind: undefined,
        type: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      if (row.id != 0) {
        //  getUrlMapping(id).then(response => {
        // this.form = response.data
        this.form = row
        this.form.id = row.id
        this.title = '更新服务信息'
        this.isEdit = true
        this.open = true
        // })
      } else {
        this.form = row
        // this.form.id = undefined
        this.isEdit = true
        this.open = true
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined || this.form.id != 0) {
            updateService(this.form, this.form.id).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.queryParams.pageIndex = 1
                this.serveceMapList = []
                this.tempList = []
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addService(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.queryParams.pageIndex = 1
                this.serveceMapList = []
                this.tempList = []
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    getServiceBar() {
      this.serviceBarObj = {}
      this.$nextTick(() => {
        this.compareChart = this.$echarts5.getInstanceByDom(document.getElementById('serviceBox'))
        if (this.compareChart == null) {
          this.compareChart = this.$echarts5.init(document.getElementById('serviceBox'))
        }
        this.compareChart.showLoading({
          text: ''
        })
        serviceBar(this.serviceBarQuery, this.serviceBarQuery.app_alias).then(res => {
          this.compareChart.hideLoading()
          if (res && res.code == 200) {
            this.serviceBarObj = res.data
            if (res.data) {
              this.initServiceChart(this.serviceBarObj)
            }
          } else {
            this.serviceBarObj = {}
          }
        })
      })
    },
    initServiceChart(data) {
      if (Object.keys(data).length > 0) {
        const option = {
          color: ['#91CC75', '#EE6666', '#5470C6'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            },
            formatter: function(params) {
              // params 是一个数组，数组中包含每个系列的数据信息
              let res = ''
              params.forEach(function(item) {
                // 对 item.data 进行两位小数的格式化
                res += item.seriesName + ': ' + (item.seriesName === '性能' ? item.value.toFixed(2) : item.value) + '<br/>'
              })
              return res
            }
          },
          grid: {
            right: '15%',
            bottom: '25%'
          },
          // toolbox: {
          //   feature: {
          //     // dataView: { show: true, readOnly: false },
          //     magicType: { show: true, type: ['line', 'bar'] },
          //     restore: { show: true },
          //     // saveAsImage: { show: true }
          //   }
          // },
          legend: {
            data: ['性能', '错误率', '活跃度']
          },
          xAxis: [
            {
              type: 'category',
              axisTick: {
                alignWithLabel: true
              },
              axisLabel: {
                show: true,
                rotate: 20 // 设置x轴标签旋转角度
              },
              // axisLabel:{
              //   show:false
              // },
              // prettier-ignore
              // data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
              data: data.serivce_data
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '性能',
              position: 'left',
              alignTicks: true,
              axisLine: {
                show: true,
                lineStyle: {
                  // color: colors[2]
                }
              },
              axisLabel: {
                formatter: '{value}'
              }
            },
            {
              type: 'value',
              name: '错误率',
              position: 'right',
              alignTicks: true,
              axisLine: {
                show: true,
                lineStyle: {
                  // color: '#EE6666'
                }
              },
              axisLabel: {
                formatter: '{value} %'
              }
            },
            {
              type: 'value',
              name: '活跃度',
              position: 'right',
              offset: 80,
              alignTicks: true,
              axisLine: {
                show: true,
                lineStyle: {
                  // color: '#EE6666'
                }
              },
              axisLabel: {
                formatter: '{value}'
              }
            }
          ],
          series: [
            {
              name: '性能',
              type: 'bar',
              data: data.apdex_data
            },
            {
              name: '错误率',
              type: 'line',
              yAxisIndex: 1,
              data: data.faild_data,
              smooth: true
            },
            {
              name: '活跃度',
              type: 'line',
              yAxisIndex: 2,
              smooth: true,
              data: data.liveness_data
            }
          ]
        }
        this.compareChart.setOption(option)
        window.addEventListener('resize', () => {
          this.compareChart.resize()
        })
        const that = this
        that.compareChart.off('click')
        that.compareChart.on('click', function(params) {
          var dataIndex = params.dataIndex
          var seriesIndex = params.seriesIndex
          var service_name = data.serivce_data[dataIndex]
          // 目前后端没有返回中文名
          that.$router.push({
            path: '/service/serviceDetail/index',
            query: {
              service_name: service_name
            }
          })
        })
        that.compareChart.on('restore', function(params) {
          that.compareChart.setOption(option)
        })
      } else {
        this.compareChart.setOption({
          title: {
            text: '暂无数据',
            x: 'center',
            y: 'center',
            textStyle: {
              color: '#999',
              fontSize: 14
            }
          }
        })
      }
    },
    disposeEcharts(echartsList) {
      if (echartsList.length > 0) {
        for (let i = 0; i < echartsList.length; i++) {
          window.removeEventListener('resize', echartsList[i].resize)// 销毁图表监听事件
          if (!echartsList[i]._disposed) {
            echartsList[i].dispose()
          }
        }
      }
      window.removeEventListener('resize', this.compareChart.resize)// 销毁图表监听事件
      this.compareChart.dispose()

      this.myChartList = []
      this.myChartboxList = []
      this.myChartBox2List = []
    }
  }
}
</script>
<style scoped lang='scss'>
.more{
  margin:16px 0;
  text-align: center;
  font-size: 16px;
  color:#1890ff;
  cursor: pointer;
}
.nomore{
  color:#999;
}
.tiger-trend-charts {
   height: 40px;
  //  width:100px;
   min-width: 80px;
   max-width: 140px;
  }
.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{
  height: calc(100% - 300px);
}
.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;
}
::v-deep.el-card__body{
  padding: 20px;
}
.no-data-des{
  text-align: center;
  font-size: 14px;
  height: 288px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
}
</style>
<style>
.el-tooltip__popper{ max-width:50% }
.el-tooltip__popper {
      display: -webkit-box;
      overflow: hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 15;
      -webkit-box-orient: vertical;
}
.workorder-remark {
    background-color: #000;
    color: #ffffff;
    border-color: #000;
    max-width: 50%;
    font-size: 12px;
     /* 想要显示全部，下面就不用写了 */
    /* padding-bottom: 4px !important;
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 15;
    -webkit-box-orient: vertical; */
}
.h6{
  font-size: 16px;
  font-weight: bold;
  color: #1a2233;
}
.serviceBox{
   width: 100%;
    height:288px;
    box-sizing: border-box;
}
/* .P_box{
  width:52px;
  min-width: 52px;
  text-align: right;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space:nowrap;
  padding-right: 10px;
  box-sizing: border-box;
} */

.TableBox ::v-deep .el-table__cell.column_one .cell{
  padding-left:10px !important;
  padding-right:10px !important;
}
</style>
