<template>
  <!-- 点击节点后出现的 右侧抽屉 -->
  <div class="nodeDrawer">
    <el-drawer :visible.sync="isShow" direction="rtl" size="60%" append-to-body @close="drawerClose">
      <h4 slot="title" style="font-size:16px">节点相关信息</h4>
      <div class="node-details">
        <div class="node-details-content">
          <div class="node-details-flex">
            <div class="node-details-content-section node-details-warper" :style="computedStyle">
              <div style="display:flex;justify-content: space-between;">
                <div class="node-details-content-section-header">节点信息</div>
                <div>
                  <el-button size="mini" type="primary" plain @click="editNodeName()">修改节点别名</el-button>
                </div>
              </div>
              <div style="margin-top:25px">
                <div class="node-details-info-field" style="position:relative;display:flex;">
                  <div class="node-details-info-field-label w50" style="width:20%">节点名称:</div>
                  <div class="node-details-info-field-value" style="width:70%">
                    {{ detailData.name }}
                  </div>

                </div>
                <div class="node-details-info-field">
                  <div class="node-details-info-field-label w50" style="width:20%">所属服务:</div>
                  <div
                    class="node-details-info-field-value w50"
                    style="width:70%;color:#1890ff;cursor: pointer;"
                    @click="gotoPathService('/service/serviceDetail/index',detailData.service_name, detailData.service_name_cn)"
                  >
                    {{ detailData.service_name }}
                  </div>
                </div>
                <div class="node-details-info-field">
                  <div class="node-details-info-field-label w50" style="width:20%">Span名称:</div>
                  <div class="node-details-info-field-value w50" style="width:70%">{{ detailData.span_name }}
                  </div>
                </div>
                <div class="node-details-info-field">
                  <div class="node-details-info-field-label w50" style="width:20%">Span类型:</div>
                  <div class="node-details-info-field-value w50" style="width:70%">{{ detailData.span_kind }}
                  </div>
                </div>
                <div class="node-details-info-field">
                  <div class="node-details-info-field-label w50" style="width:20%">成功率:</div>
                  <div class="node-details-info-field-value w50" style="width:70%">{{ ((detailData.rate || 0
                  ) * 100).toFixed(2) + '%' }}</div>
                </div>
              </div>
            </div>

            <div v-if="detailData.span_type == &quot;http server&quot;" class="node-details-content-section node-details-warper">
              <div class="node-details-content-section-header">接口信息</div>
              <div class="node-details-info-field">
                <div class="node-details-info-field-label w50" style="width:20%">请求量:</div>
                <div class="node-details-info-field-value w50" style="width:70%">{{ nodeStats.total }}</div>
              </div>
              <div class="node-details-info-field">
                <div class="node-details-info-field-label w50" style="width:20%">错误率:</div>
                <div class="node-details-info-field-value w50" style="width:70%">{{ ((nodeStats.error_rate || 0 ) *100 ).toFixed(2) + '%' }}</div>
              </div>
              <div class="node-details-info-field">
                <div class="node-details-info-field-label w50" style="width:20%">P50:</div>
                <div class="node-details-info-field-value w50" style="width:70%">{{ (nodeStats.p50 ||
                  0).toFixed(2) + 'ms' }}</div>
              </div>
              <div class="node-details-info-field">
                <div class="node-details-info-field-label w50" style="width:20%">P90:</div>
                <div class="node-details-info-field-value w50" style="width:70%">{{ (nodeStats.p90 ||
                  0).toFixed(2) + 'ms' }}</div>
              </div>
              <div class="node-details-info-field">
                <div class="node-details-info-field-label w50" style="width:20%">P99:</div>
                <div class="node-details-info-field-value w50" style="width:70%">{{ (nodeStats.p99 ||
                  0).toFixed(2) + 'ms' }}</div>
              </div>
              <div>
                <div class="node-details-info-field">
                  <div class="node-details-info-field-label w50" style="width:20%">接口名:</div>
                  <div class="node-details-info-field-value w50" style="width:70%;">{{ nodeStats.name }}</div>
                </div>
                <div class="node-details-info-field">
                  <div class="node-details-info-field-label w50" style="width:20%">接口地址:</div>
                  <div class="node-details-info-field-value w50" style="width:70%">{{ nodeStats.value }}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="node-details-content-section">
            <div class="node-details-content-section-header">Span列表</div>
            <div>
              <el-table v-loading="nodeloading" :data="nodeSpansList" @row-click="handleSpanRowClick" @sort-change="sortChangeTable">
                <el-table-column label="链路标识" prop="trace_id" :show-overflow-tooltip="true" header-align="center" align="center" />
                <el-table-column label="方法" prop="method" :show-overflow-tooltip="true" header-align="center" align="center" />
                <el-table-column label="状态码" prop="code" :show-overflow-tooltip="true" header-align="center" align="center">
                  <template slot-scope="scope">
                    <span>
                      <el-tag
                        v-if="scope.row.code < 400"
                        class="colorwhite"
                        style="color:white"
                        type="success"
                        effect="dark"
                      >{{ scope.row.code }}</el-tag>
                      <el-tag v-else color="#F53F3F" style="color:white; border-color: rgb(245, 63, 63);" type="danger">{{ scope.row.code }}</el-tag>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="请求时长(ms)"
                  sortable="custom"
                  prop="duration"
                  :show-overflow-tooltip="true"
                  header-align="center"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.duration >= 2000" type="danger">{{ parseInt(scope.row.duration || 0)
                    }}</el-tag>
                    <el-tag v-if="scope.row.duration < 2000" type="info">{{ parseInt(scope.row.duration || 0) }}</el-tag>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-show="nodeCount > 0"
                small
                :total="nodeCount"
                :page.sync="querySpans.pageIndex"
                :limit.sync="querySpans.pageSize"
                @pagination="getNodeSpans"
              />
            </div>
          </div>

        </div>
      </div>

    </el-drawer>
    <!-- 修改节点别名 对话框 -->
    <el-dialog
      v-if="nodeOpen"
      append-to-body
      title="修改节点别名"
      :visible.sync="nodeOpen"
      width="700px"
      :center="true"
      :close-on-click-modal="false"
    >
      <el-form ref="queryName" :model="queryName" label-width="95px">
        <el-form-item label="节点别名" prop="name">
          <el-input v-model="queryName.name" placeholder="请输入节点别名" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveNodeName">确 定</el-button>
        <el-button @click="cancelNode">取 消</el-button>
      </div>
    </el-dialog>
    <LinkDetailsDrawer
      v-if="isShowLinkDrawer"
      :is-opendrawer="isShowLinkDrawer"
      :tract-i-d="tractID"
      :span-i-d="spanID"
      @handleClose="closeLinkDrawer"
    />
  </div>
</template>
<script>
import { bizNodeSpans, bizNodeName, bizNodeStats } from '@/api/mapping'
import storage from '@/utils/storage'
import LinkDetailsDrawer from './LinkDetailsDrawer.vue'
export default {
  components: {
    LinkDetailsDrawer
  },
  props: {
    detailData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    nodeDrawerShow: {
      type: Boolean,
      default: false
    },
    spanId: {
      type: Number,
      default: 0
    },
    queryName: {
      type: Object,
      default: () => {
        return {}
      }
    },
    spanType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      nodeCount: 0,
      nodeSpansList: [],
      querySpans: {
        id: 0,
        // hash:'',//和id二选一
        start_time: '',
        end_time: '',
        pageIndex: 1,
        pageSize: 10,
        sort_field: 'Duration',
        sort_type: 'DESC'
      },
      queryStats: {
        id: this.spanId,
        start_time: 0,
        end_time: 0
      },
      nodeloading: false,
      appItem: {},
      nodeOpen: false,
      nodeStats: {},
      isShow: this.nodeDrawerShow,
      isShowLinkDrawer: false,
      tractID: '',
      spanID: ''
    }
  },
  computed: {
    computedStyle() {
      return {
        width: this.spanType == 'http server' ? '49%' : '100%'
      }
    }
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.querySpans.start_time = newValue.startTime
          this.querySpans.end_time = newValue.endTime
          this.querySpans.pageIndex = 1

          this.queryStats.start_time = newValue.startTime
          this.queryStats.end_time = newValue.endTime
        }
      },
      deep: true
    }
  },
  created() {
    this.appItem = storage.get('appsItem')
    if (JSON.stringify(this.appItem) != '{}') {
      const start_time = this.$store.state.time.globalTimes.startTime
      const end_time = this.$store.state.time.globalTimes.endTime
      this.querySpans.start_time = start_time
      this.querySpans.end_time = end_time
      this.queryStats.start_time = start_time
      this.queryStats.end_time = end_time
      this.getNodeSpans()
      if (this.spanType == 'http server') {
        this.getNodeStats()
      }
    }
  },
  methods: {
    getNodeSpans() {
      this.nodeloading = true
      this.querySpans.id = this.spanId
      bizNodeSpans(this.querySpans).then(res => {
        if (res.code === 200) {
          this.nodeloading = false
          this.nodeSpansList = res.data.list
          this.nodeCount = res.data.count
        }
      })
    },
    handleSpanRowClick(row, column, event) {
      this.isShowLinkDrawer = true
      this.spanID = row.span_id
      this.tractID = row.trace_id
    },
    closeLinkDrawer() {
      this.isShowLinkDrawer = false
    },
    drawerClose() {
      this.$emit('drawerClose', false)
    },
    editNodeName() {
      this.nodeOpen = true
    },
    cancelNode() {
      this.nodeOpen = false
    },
    // 修改节点别名
    saveNodeName() {
      bizNodeName(this.queryName).then(res => {
        if (res.code === 200) {
          this.msgSuccess(res.msg)
          this.nodeOpen = false
          this.drawerClose()
        }
      })
    },
    getNodeStats() {
      bizNodeStats(this.queryStats).then(res => {
        if (res && res.code == 200) {
          this.nodeStats = res.data || {}
        } else {
          this.nodeStats = {}
        }
      })
    },
    gotoPathService(path, service_name, service_name_cn) {
      const href = this.$router.resolve({
        path: path,
        query: {
          service_name: service_name,
          name: service_name_cn,
          isShowBackBtn: false
        }
      })
      window.open(window.location.origin + '/' + href.href, '_blank')
    },
    sortChangeTable(val) {
      // desc（倒序）和asc（正序）
      if (val.order === 'descending') {
        this.querySpans.sort_type = 'DESC'
      } else if (val.order === 'ascending') {
        this.querySpans.sort_type = 'ASC'
      }
      this.getNodeSpans()
    }
  }
}
</script>
<style lang="scss" scoped>
.node-details {
  .node-details-content {
    overflow-y: scroll;
    font-family: proxima-nova, Helvetica, Arial, sans-serif;
  }

  .node-details-content-section {
    padding: 20px;
    border-radius: 12px;
    background: white;
    height: fit-content;
    margin-bottom: 20px;
  }
  .node-details-flex{
    display:flex;
    align-items: center;
    justify-content: space-between;
    background: #F0F2F5 !important;
  }
  .node-details-warper{
    width: 49%;
    max-height:270px;
    min-height: 244px;
    box-sizing: border-box;
    overflow: overlay;
  }
  .node-details-content-section-header {
    font-size: 14px;
    color: #000;
    margin-bottom: 20px;
  }

  .node-details-info-field {
    display: flex;
    -webkit-box-align: baseline;
    box-align: baseline;
    align-items: baseline;
    margin-bottom: 8px;
  }

  .node-details-info-field-label {
    text-align: right;
    color: #000;
    padding: 0px 0.5em 0px 0px;
    white-space: nowrap;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .node-details-info-field-value {
    font-size: 14px;
    min-width: 0px;
    color: rgb(61, 61, 92);
    word-wrap: break-word;
    // overflow: hidden;
    // text-overflow: ellipsis;
    // white-space: nowrap;
  }

  .truncate {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .w50 {
    width: 50%;
  }
}
::v-deep .el-drawer__body {
  background: #F0F2F5;
}
::v-deep .el-drawer__header {
  text-align: center;
  color: white;
  font-size: 24px;
  font-weight: bold;
  height: 60px;
  background: #4E5969;
  padding: 20px;
  margin-bottom: 0;
}
::v-deep .el-table__row{
  cursor: pointer;
}
</style>
