<template>
  <div>
    <div class="ob-serDrawer-content">
      <div class="ob-serDrawer-left">
        <!-- 左侧table -->
        <el-table
          ref="tableRef"
          v-loading="loading"
          style="width:100%"
          highlight-current-row
          :data="serveceMapList"
          @current-change="handleCurrentChange"
          @row-click="handleRowClick"
          @sort-change="handleSortChang"
        >
          <el-table-column
            class-name="column_one"
            header-align="center"
            label="业务名"
            prop="name"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            header-align="center"
            label="请求总数"
            align="center"
            prop="total"
            :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).toFixed(2)
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            label="最大延迟(ms)"
            align="center"
            width="120"
            sortable
            prop="max"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <div :class="scope.row.max < 2000 ? 'table_bg' : 'table_bg_red'">
                {{
                  scope.row.max == undefined
                    ? 0
                    : Number(scope.row.max).toFixed(2)
                }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <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>
        <pagination
          v-show="tableCount>0"
          :total="tableCount"
          small
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList('created')"
        />
      </div>
      <div class="ob-serDrawer-right">
        <div class="ob-chart-box">
          <div class="ob-switch-box">
            <el-switch
              v-model="switchValue"
              active-color="#165DFF"
              inactive-color="#C9CDD4"
              @change="handelSwitch"
            />
          </div>
          <div v-if="switchValue">
            <div v-if="graphData && Object.keys(graphData).length > 0 ">
              <Topo v-if="graphLoading" ref="topo" :graph-data="graphData" topo-id="serviceDrawerContainer" @changeState="clickRowHandleNode" />
            </div>
          </div>
          <div v-if="!switchValue" style="position:relative;height: 100%;">
            <div v-if="isLoading" v-loading="isLoading" class="loading-overlay" />
            <div v-else>
              <NodeG6Charts v-if="sweetGraphData && Object.keys(sweetGraphData).length > 0" :chart-content-id="'serviceDrawerContainer'" :graph-data="sweetGraphData" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <LinkDetailsDrawer v-if="isShowLinkDrawer" :is-opendrawer="isShowLinkDrawer" :tract-i-d="tractID" :span-i-d="spanID" @handleClose="closeLinkDrawer" />
    <!-- 添加或修改应用配置对话框 -->
    <div v-if="open">
      <el-dialog :append-to-body="true" :title="'修改业务别名'" :visible.sync="open" width="600px" :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" 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>
    <!-- 点击节点后出现的 右侧抽屉 -->
    <NodeDetailDrawer v-if="nodeDrawerShow" :node-drawer-show="nodeDrawerShow" :detail-data="detailData" :span-id="spanId" :query-name="queryName" :span-type="spanType" @drawerClose="drawerClose" />

  </div>
</template>
<script>
import { listBiz, addUrlMapping, updateBiz, getBizDetail, listBizGraph, getSweetList } from '@/api/mapping'
import Topo from '../analysisDetail/components/Topo.vue'
import storage from '@/utils/storage'
// import LinkDetailsDrawer from './LinkDetailsDrawer.vue'
import NodeDetailDrawer from '../../service/InterfaceDetail/components/NodeDetailDrawer.vue'
import NodeG6Charts from '../../service/InterfaceDetail/components/NodeG6Charts.vue'
export default {
  components: {
    Topo,
    // LinkDetailsDrawer,
    NodeDetailDrawer,
    NodeG6Charts
  },
  props: {
    isOpendrawer: {
      type: Boolean,
      default: false
    },
    nodeServieName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      serveceMapList: [],
      // 查询参数
      queryParams: {
        app_alias: '',
        start_time: '',
        end_time: '',
        pageIndex: 1,
        pageSize: 20,
        service_name: this.nodeServieName
      },
      tableCount: 0,
      appItem: {},
      form: {
        name: ''
      },
      open: false,
      tableLoading: false,
      total: 0,
      rowData: [],
      childQueryParams: {
        start_time: 0,
        end_time: 0,
        biz_id: 0,
        pageIndex: 1,
        pageSize: 10,
        sort_type: 'desc',
        sort_field: 'max',
        min_duration: 0,
        only_exception: false
      },
      checked: false,
      onlyException: false,
      graphData: {},
      sweetGraphData: {},
      graphLoading: false,
      isShowLinkDrawer: false,
      tractID: '',
      spanID: '',
      queryStats: {},
      queryName: {
        id: 0,
        name: ''
      },
      spanType: '',
      nodeloading: false,
      nodeDrawerShow: false,
      detailData: {},
      nodeSpansList: [],
      spanId: 0,
      switchValue: false,
      sweetquanParams: {
        biz_id: 0,
        start_time: '',
        end_time: ''
      },
      isLoading: false
    }
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.queryParams.start_time = newValue.startTime
          this.queryParams.end_time = newValue.endTime
          this.queryParams.pageIndex = 1

          this.childQueryParams.start_time = newValue.startTime
          this.childQueryParams.end_time = newValue.endTime
          this.queryStats.start_time = newValue.startTime
          this.queryStats.end_time = newValue.endTime
          this.sweetquanParams.start_time = newValue.startTime
          this.sweetquanParams.end_time = newValue.endTime

          this.serveceMapList = []
          this.getList() // 左侧table数据
          this.handelgetBizDetail() // 获取右侧 table 数据
          if (this.switchValue) {
            this.getListBizGraph(this.childQueryParams.biz_id) // 获取右侧关系拓扑图数据
          } else {
            this.getSweetListFn()
          }
        }
      },
      deep: true
    },
    serveceMapList: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.serveceMapList = newVal
          this.tableflag = true
        }
      },
      deep: true
    }
  },
  created() {
    this.appItem = storage.get('appsItem')
    if (JSON.stringify(this.appItem) != '{}') {
      this.queryParams.app_alias = this.appItem.alias
      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.childQueryParams.start_time = start_time
      this.childQueryParams.end_time = end_time

      this.queryStats.start_time = start_time
      this.queryStats.end_time = end_time

      this.sweetquanParams.start_time = start_time
      this.sweetquanParams.end_time = end_time
      this.getList('created')
    }
  },
  beforeDestroy() {
    this.graphData = {}
    this.sweetGraphData = {}
  },
  methods: {
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (order === 'descending') {
        this.queryParams.sort_type = 'desc'
      } else if (order === 'ascending') {
        this.queryParams.sort_type = 'asc'
      }
      this.queryParams.sort_field = prop
      this.getList('created')
    },
    handleClose() {
      this.$emit('handleClose', false)
    },
    handleUpdate(row) {
      this.reset()
      this.form.name = row.name
      this.form.id = row.id
      this.open = true
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        url: undefined,
        type: undefined,
        module: undefined,
        summary: undefined,
        favor: undefined
      }
      this.resetForm('form')
    },
    // 左侧table 行点击-刷新右侧 graph 数据和右侧table 数据
    handleRowClick(row, column, event) {
      storage.set('detailObj', row)
      this.childQueryParams.biz_id = row.id
      this.sweetquanParams.biz_id = row.id
      const start_time = this.$store.state.time.globalTimes.startTime
      const end_time = this.$store.state.time.globalTimes.endTime
      this.childQueryParams.start_time = start_time
      this.childQueryParams.end_time = end_time
      this.childQueryParams.end_time = end_time
      this.handelgetBizDetail()
      if (this.switchValue) {
        this.getListBizGraph(row.id) // 获取右侧关系拓扑图数据
      } else {
        this.getSweetListFn()
      }
    },
    // 获取左侧table 数据
    getList(type) {
      this.loading = true
      this.serveceMapList = []
      this.queryParams.service_name = this.nodeServieName
      listBiz(this.queryParams).then(res => {
        if (res.code == 200) {
          this.serveceMapList = res.data.list || []
          this.tableCount = res.data.count || 0
          this.loading = false
          if (res.data && res.data.list && res.data.list.length > 0) {
            if (type === 'created') {
              this.childQueryParams.biz_id = res.data.list[0].id
              this.sweetquanParams.biz_id = res.data.list[0].id
              if (this.switchValue) {
                this.getListBizGraph(res.data.list[0].id) // 获取右侧关系拓扑图数据
              } else {
                this.getSweetListFn()
              }
              this.handelgetBizDetail()
              this.$refs.tableRef.setCurrentRow(res.data.list[0])
            }
          }
        }
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined || this.form.id != 0) {
            updateBiz(this.form, this.form.id).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.queryParams.pageIndex = 1
                this.serveceMapList = []
                this.tempList = []
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addUrlMapping(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('成功')
                this.open = false
                this.queryParams.pageIndex = 1
                this.serveceMapList = []
                this.tempList = []
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    sortChangeTable(val) {
      const prop = val.prop
      this.childQueryParams.sort_field = prop === 'duration' ? 'Duration' : 'Timestamp'
      // desc（倒序）和asc（正序）
      if (val.order === 'descending') {
        this.childQueryParams.sort_type = 'DESC'
      } else if (val.order === 'ascending') {
        this.childQueryParams.sort_type = 'ASC'
      }
      this.handelgetBizDetail()
    },
    // 获取右侧table
    handelgetBizDetail() {
      this.tableLoading = true
      getBizDetail(this.childQueryParams).then(res => {
        if (res.code == 200) {
          this.tableLoading = false
          this.rowData = res.data.list
          this.total = res.data.count
        }
      })
    },
    handelCheckChange() {
      this.childQueryParams.min_duration = this.checked ? 2500 : 0
      this.handelgetBizDetail()
    },
    handelChange() {
      this.childQueryParams.only_exception = this.onlyException ? 1 : 0
      this.handelgetBizDetail()
    },
    // 获取拓扑关系图
    getListBizGraph(id) {
      this.graphLoading = false
      listBizGraph({ biz_id: id }).then((res) => {
        this.graphData = {}
        if (res.code === 200) {
          const arr = res.data
          if (arr.length > 0) {
            const List = this.handelListBizData(arr)
            this.graphData = List[0]
            this.graphLoading = true
          } else {
            this.graphData = {}
          }
        }
      })
    },
    handelListBizData(data) {
      data.forEach((v, k) => {
        v.id = v.id.toString()
        v.label = v.stats.duration != undefined ? (v.stats.duration).toString() : ''
        v.currency = 'ms'
        v.rate = v.stats.success_rate
        v.status = v.stats.success_rate >= 0.6 ? 'B' : v.stats.success_rate == 0 ? 'DI' : 'R'
        v.variableValue = v.stats.success_rate
        v.variableUp = v.stats.success_rate_up
        if (v.children != undefined && v.children.length > 0) {
          v.children = this.handelListBizData(v.children)
        }
      })
      return data
    },
    clickRowHandleNode(item) {
      this.nodeDrawerShow = true
      if (item) {
        this.detailData = {}
        this.detailData = item
        this.queryStats.id = Number(item.unique_id)
        this.queryName.id = Number(item.unique_id)
        this.queryName.name = item.name
        this.spanId = Number(item.unique_id)
        this.spanType = item.span_type
      }
    },
    // 左侧 table 选中 时
    handleCurrentChange(currentRow, oldCurrentRow) {
      if (currentRow) {
        this.childQueryParams.biz_id = currentRow.id // 获取右侧table 的参数
        this.sweetquanParams.biz_id = currentRow.id
      }
    },
    handleClickRightTable(row) {
      this.isShowLinkDrawer = true
      this.tractID = row.trace_id
      this.spanID = row.span_id
    },
    closeLinkDrawer() {
      this.isShowLinkDrawer = false
    },

    drawerClose() {
      this.nodeDrawerShow = false
      this.getListBizGraph(this.childQueryParams.biz_id)
    },
    handelSwitch() {
      if (this.switchValue) {
        this.getListBizGraph(this.childQueryParams.biz_id) // 获取右侧关系拓扑图数据
      } else {
        this.getSweetListFn()
      }
    },
    async getSweetListFn() {
      this.isLoading = true
      this.sweetGraphData = {}
      const res = await getSweetList(this.sweetquanParams)
      if (res && res.code === 200) {
        this.sweetGraphData = res.data
      } else {
        this.sweetGraphData = {}
      }
      this.isLoading = false
    }
  }
}
</script>
<style lang="scss" scoped>
.ob-serDrawer-content{
  display: flex;
  width: 100%;
  .ob-serDrawer-left{
    width: 460px;
    border-radius: 12px;
    background: white;
    padding:20px;
    height: fit-content;
    margin-top: 20px;
  }
  // ::v-deep .el-table thead{
  //   background: #4E5969;
  //   font-size: 14px;
  //   color: #FFFFFF;
  // }
  .ob-serDrawer-right{
    flex:1;
    margin-left:20px;
    border-radius: 12px;
    background: white;
    padding:20px;
    height: fit-content;
    margin-top: 20px;
  }
}
::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-drawer__body{
  background: #F0F2F5;
}
::v-deep .el-table__row{
  cursor: pointer;
}
.ob-chart-box{
  width:100%;
  min-height: 400px;
  max-height: 1000px;
  #serviceDrawerContainer{
    width: 100%;
    height:100%;

  }
  .ob-switch-box{
    text-align: right;
    width: 100%;
  }
  ::v-deep.g6-legend-container{
    position: sticky !important;
  }
}
.loading-overlay  ::v-deep.el-loading-spinner{
  top:180px !important;
}

</style>
<style lang="css"> .el-tooltip__popper{ max-width:40% } </style>

