<template>
  <div class="service-relation-content">
    <div class="service-left">
      <div v-if="isLoading" v-loading="isLoading" class="loading-overlay" />
      <div v-else style="min-height: 500px;">
        <NodeG6Charts v-if="isShowGraph" :chart-content-id="'relationContainer'" :graph-data="sweetGraphData" />
        <div class="no-data-div" v-else>暂无数据</div>
      </div>
    </div>
    <div class="service-right">
      <div class="service-right-table">
        <h3>上游调用</h3>
        <el-table
          class="my-table"
          :header-cell-style="{ background: '#fff' }"
          :data="subList"
          @row-click="onRowClick"
          @sort-change="handleSortChang"
        >
          <el-table-column label="API" prop="route" align="center" :show-overflow-tooltip="true" />
          <el-table-column label="请求总数" prop="total" align="center" :show-overflow-tooltip="true" />
          <el-table-column align="center" label="错误率" prop="error_rate" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.error_rate == 0 ? 0 :(scope.row.error_rate*100).toFixed(2)+ '%' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="中位时长(ms)" sortable prop="duration" align="center" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.duration_stats.p50 && scope.row.duration_stats.p50.length > 0? scope.row.duration_stats.p50[scope.row.duration_stats.p50.length - 1] : 0 }}</span>
            </template>
          </el-table-column>

        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          mini
          :page.sync="subListQuery.pageIndex"
          :limit.sync="subListQuery.pageSize"
          @pagination="getUrlMappingSublist(prevServiceNameArr, 'up')"
        />
      </div>

      <div class="service-right-table" style="margin-top: 40px;">
        <h3>下游调用</h3>
        <el-table
          class="my-table"
          :data="subList2"
          @row-click="onRowClick2"
          @sort-change="handleSortChang2"
        >
          <el-table-column label="API" prop="route" align="center" :show-overflow-tooltip="true" />
          <el-table-column label="请求总数" prop="total" align="center" :show-overflow-tooltip="true" />
          <el-table-column align="center" label="错误率" prop="error_rate" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.error_rate == 0 ? 0 :(scope.row.error_rate*100).toFixed(2)+ '%' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="中位时长(ms)" sortable prop="duration" align="center" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.duration_stats.p50 && scope.row.duration_stats.p50.length > 0? scope.row.duration_stats.p50[scope.row.duration_stats.p50.length - 1] : 0 }}</span>
            </template>
          </el-table-column>

        </el-table>
        <pagination
          v-show="total2>0"
          style="margin-bottom: 20px;"
          mini
          :total="total2"
          :page.sync="subListQuery2.pageIndex"
          :limit.sync="subListQuery2.pageSize"
          @pagination="getUrlMappingSublist(nextServiceNameArr, 'down')"
        />
      </div>
    </div>
  </div>
</template>
<script>
import NodeG6Charts from '@/views/service/InterfaceDetail/components/NodeG6Charts.vue'
import { getSweetList, urlMappingSublist } from '@/api/mapping'
import storage from '@/utils/storage'
export default {
  components: {
    NodeG6Charts
  },
  props: {
    nodeServieName: {
      type: String,
      default: ''
    },
    nodeId: {
      type: String,
      default: ''
    },
    nodeName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      sweetGraphData: null,
      sweetquanParams: {
        biz_id: 0,
        start_time: '',
        end_time: '',
        service_name: ''
      },
      subList: [],
      subList2: [],
      subListQuery: {
        start_time: 0,
        end_time: 0,
        pageIndex: 1,
        pageSize: 10,
        app_alias: '',
        service_name: '',
        sort_type: 'desc',
        sort_field: 'duration'
      },
      subListQuery2: {
        start_time: 0,
        end_time: 0,
        pageIndex: 1,
        pageSize: 10,
        app_alias: '',
        service_name: '',
        sort_type: 'desc',
        sort_field: 'duration'
      },
      total2: 0,
      total: 0,
      prevServiceNameArr: '',
      nextServiceNameArr: '',
      isLoading: false,
      isShowGraph: false
    }
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.sweetquanParams.start_time = newValue.startTime
          this.sweetquanParams.end_time = newValue.endTime
          this.subListQuery.start_time = newValue.startTime
          this.subListQuery.end_time = newValue.endTime
          this.subListQuery2.start_time = newValue.startTime
          this.subListQuery2.end_time = newValue.endTime
          this.getSweetListFn()
        }
      },
      deep: true
    }
  },
  created() {
    this.appItem = storage.get('appsItem')
    const start_time = this.$store.state.time.globalTimes.startTime
    const end_time = this.$store.state.time.globalTimes.endTime
    this.sweetquanParams.start_time = start_time
    this.sweetquanParams.end_time = end_time
    this.subListQuery.start_time = start_time
    this.subListQuery.end_time = end_time
    this.subListQuery.app_alias = this.appItem.alias
    this.subListQuery2.start_time = start_time
    this.subListQuery2.end_time = end_time
    this.subListQuery2.app_alias = this.appItem.alias
    this.getSweetListFn()
  },
  methods: {
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (order === 'descending') {
        this.subListQuery.sort_type = 'desc'
      } else if (order === 'ascending') {
        this.subListQuery.sort_type = 'asc'
      }
      this.subListQuery.sort_field = prop
      this.getUrlMappingSublist(this.prevServiceNameArr, 'up')
    },
    handleSortChang2(column, prop, order) {
      prop = column.prop
      order = column.order
      if (order === 'descending') {
        this.subListQuery2.sort_type = 'desc'
      } else if (order === 'ascending') {
        this.subListQuery2.sort_type = 'asc'
      }
      this.subListQuery2.sort_field = prop
      this.getUrlMappingSublist(this.nextServiceNameArr, 'down')
    },
    onRowClick(row) {
      const rowItem = {
        method: row.method,
        service_name: row.service_name,
        kind: row.route,
        name: row.name,
        route: row.route
      }
      storage.set('row', rowItem)
      const href = this.$router.resolve({
        path: '/service/InterfaceDetail/index',
        query: {
          kind: row.route,
          method: row.method,
          name: row.name,
          service_name: row.service_name,
          route: row.route
        }
      })
      window.open(window.location.origin + '/' + href.href, '_blank')
    },
    onRowClick2(row) {
      const rowItem = {
        method: row.method,
        service_name: row.service_name,
        kind: row.route,
        name: row.name,
        route: row.route
      }
      storage.set('row', rowItem)
      const href = this.$router.resolve({
        path: '/service/InterfaceDetail/index',
        query: {
          kind: row.route,
          method: row.method,
          name: row.name,
          service_name: row.service_name,
          route: row.route
        }
      })
      window.open(window.location.origin + '/' + href.href, '_blank')
    },
    async getSweetListFn() {
      this.sweetGraphData = {}
      this.sweetquanParams.service_name = this.nodeServieName
      const queryString = window.location.href
      const urlParams = new URLSearchParams(queryString)
      this.sweetquanParams.biz_id = urlParams.get('rowId')
      this.isLoading = true
      const res = await getSweetList(this.sweetquanParams)
      if (res && res.code === 200) {
        this.sweetGraphData = res.data || {}
        const { combos = [], edges = [], nodes = [] } = res.data || {}
        this.isShowGraph = Object.keys(this.sweetGraphData).length > 0 && (combos.length > 0 || edges.length > 0 || nodes.length > 0)
        const allEdges = res.data.edges || []
        this.nextServiceNameArr = ''
        this.prevServiceNameArr = ''
        allEdges.forEach(item => {
          if (item.source === this.nodeId) { // 下游
            if (item.target.indexOf('svc') !== -1) {
              if (this.nextServiceNameArr == '') {
                this.nextServiceNameArr = item.target.split('-')[1]
              } else {
                this.nextServiceNameArr = this.nextServiceNameArr + ',' + item.target.split('-')[1]
              }
            }
          }
        })
        this.prevServiceNameArr = this.nodeServieName // 上游：任何时候都要调用

        this.getUrlMappingSublist(this.prevServiceNameArr, 'up')
        if (nodes.length > 1 && this.nextServiceNameArr !== '') { // 下游：仅存在下游的时候才调用
          this.getUrlMappingSublist(this.nextServiceNameArr, 'down')
        }
      } else {
        this.sweetGraphData = {}
      }
      this.isLoading = false
    },
    getUrlMappingSublist(serviceNameArr, type) { // 获取table数据
      // this.loading = true
      let obj = {}
      if (type === 'up') {
        this.subListQuery.service_name = serviceNameArr
        obj = this.subListQuery
      } else if (type === 'down') {
        this.subListQuery2.service_name = serviceNameArr
        obj = this.subListQuery2
      }
      urlMappingSublist(obj).then(res => {
        if (res && res.code === 200) {
          if (type == 'up') {
            this.subList = res.data.list
            this.total = res.data.count
          } else if (type == 'down') {
            this.subList2 = res.data.list
            this.total2 = res.data.count
          }
        } else {
          this.subList = []
          this.subList2 = []
        }
        // this.loading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.service-relation-content{
  display: flex;
  width: 100%;
}
.service-left{
  width: 40%;
  position:relative;
  height: 100%;
  background: white;
  border-radius: 12px;
  margin-right: 20px;
  margin-top: 20px;
}
::v-deep .el-table__row{
  cursor: pointer;
}
.service-right{
  width: 58%;
  margin-top: 20px;
}
.service-right-table{
  width: 100%;
  background: white;
  border-radius: 12px;
  padding: 20px;
  min-height: 500px;
}
::v-deep .el-pagination__jump{
  display: none !important;
}
.no-data-div{
  min-height: 498px;
  height:498px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #606266;
  font-size: 14px;
}
</style>
