<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="margin-top:10px;overflow: auto;">
        <el-form ref="queryTrace" :model="queryTrace" :inline="true" label-width="68px" @submit.native.prevent>
          <el-form-item label="traceID" prop="trace_id">
            <el-input
              v-model="queryTrace.trace_id"
              style="width:260px"
              placeholder="TraceID"
              clearable
              size="mini"
              @input="$forceUpdate()"
              @paste.native.capture.prevent="handlePaste"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="应用别名" prop="app_alias">
            <el-input
              v-model="queryTrace.app_alias"
              style="width:220px"
              placeholder="请输入应用别名"
              clearable
              size="mini"
              @input="$forceUpdate()"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="服务名称" prop="service_name">
            <el-input
              v-model="queryTrace.service_name"
              style="width:220px"
              placeholder="请输入服务名称"
              clearable
              size="mini"
              @input="$forceUpdate()"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item prop="failed">
            <el-checkbox v-model="queryTrace.failed">仅请求异常</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="mini"
              @click="handleClickSearchList"
            >搜索</el-button>
          </el-form-item>
        </el-form>
        <el-table
          ref="table"
          v-loading="loading"
          :data="selectList"
          border
          highlight-current-row
          @row-click="handleRowClick"
        >
          <el-table-column
            type="index"
            width="50"
            label="#"
          />
          <el-table-column label="TraceID" prop="trace_id" header-align="center" align="center" />
          <el-table-column label="开始时间" prop="timestamp" header-align="center" align="center" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span style="display: inline-block;text-align: center;width: 100%;">{{ parseTime(scope.row.timestamp) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="持续时间(ms)" header-align="center" prop="duration" align="center">
            <template slot-scope="scope">
              <span style="display: inline-block;text-align: center;width: 100%;">{{ scope.row.duration&&scope.row.duration.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="涉及的服务数量" header-align="center" prop="service_num" align="center" />
          <el-table-column label="包含的span数量" header-align="center" prop="span_num" align="center" />
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryTrace.pageIndex"
          :limit.sync="queryTrace.pageSize"
          @pagination="getTraceList"
        />

        <div style="margin-top:32px;">
          <div class="css-container" style="margin-bottom:24px;">
            <div class="css-header">
              <div class="css-title">Trace</div>
            </div>
            <div v-if="tableDetail !=null" class="css-content">
              <div class="css-page-header">
                <div class="css-name">
                  <div class="css-name-title">
                    <span class="trace-name">
                      <span class="css-text">{{ tableDetail.service_name }}:</span>
                      <span class="css-text">{{ tableDetail.span_name }}</span>
                    </span>
                    <small class="css-small">{{ tableDetail.duration }}ms</small>
                  </div>
                  <div class="css-action">
                    <span style="font-weight:bold">TraceID: </span> <span v-cloak>{{ tractID }}</span>
                  </div>
                </div>
                <div class="css-time-box">
                  <span class="css-time-wrap">
                    <span v-if="tableDetail.timestamp !='0001-01-01T00:00:00Z'" class="css-time-value">{{ parseTime(tableDetail.timestamp) }}
                    </span>
                  </span>
                  <span class="css-type">
                    <el-tag v-if="tableDetail.http_method !=undefined&& tableDetail.http_method !=&quot;&quot;" size="mini" style="margin-right:8px">{{ tableDetail.http_method != undefined?tableDetail.http_method:tableDetail.http.request.method }}</el-tag>
                    <el-tag v-if="tableDetail.http_code !=undefined && tableDetail.http_code>=200" size="mini" :type="tableDetail.http_code>300?'danger':'success'" style="margin-right:8px">{{ tableDetail.http_code!=undefined?tableDetail.http_code:tableDetail.http.response.status_code }}</el-tag>
                    <span class="css-api">{{ tableDetail.span_attributes!=undefined?tableDetail.span_attributes['http.url']:tableDetail.http_url }}</span>
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div class="TreeBox" style="margin-bottom:24px;">
            <div>
              <el-button-group>
                <el-button size="mini" type="primary" @click="toggleTab(1)">东西链路</el-button>
                <el-button size="mini" type="primary" @click="toggleTab(2)">链路列表</el-button>
                <el-button size="mini" type="primary" @click="toggleTab(3)">南北链路</el-button>
                <el-button size="mini" type="primary" @click="toggleTab(4)">火焰分析</el-button>
              </el-button-group>
              <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>
            </div>
            <div style="font-size:14px;font-weight:bold;">
              <svg-icon :icon-class="isFull?'exit-fullscreen':'fullscreen'" @click.native.prevent="clickFull" />
            </div>
          </div>

          <div v-if="flag==true" style="position:relative;">
            <div v-if="num == 1" class="tree_box">
              <Topo v-if="graphflag" ref="topo" :graph-data="graphData" topo-id="container" @changeState="clickRowHandleNode" />
            </div>
            <div v-if="num ==2">
              <el-table
                ref="scrollTable"
                v-loading="treeLoading"
                :data="tableData"
                :row-key="getRowKeys"
                :indent="4"
                style="width: 100%;margin-bottom: 20px;"
                border
                default-expand-all
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                :row-class-name="status_change"
                :row-style="rowClassRender"
                :cell-class-name="tableCellClassName"
                @row-click="clickRowHandle"
                tooltip-effect="dark my-tooltip"
              >
                <el-table-column
                  v-if="colData[0].istrue"
                  prop="service_name"
                  label="服务名(span名称)"
                  header-align="center"
                  align="center"
                  width="250"
                  :show-overflow-tooltip="true"
                >
                  <template slot-scope="scope">
                    <span style="display: flex; align-items: center;">
                      <!-- <i v-if="scope.row.spanSelect == true" class="spanselect" /> -->
                      <i v-if="scope.row.spanSelect == true" class="el-icon-caret-right" />
                      {{ scope.row.service_name }}<span>({{ scope.row.span_name }})</span>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="colData[1].istrue"
                  prop="timestamp"
                  label="开始时间"
                  header-align="center"
                  align="center"
                  width="250"
                  :show-overflow-tooltip="true"
                >
                  <template slot-scope="scope">
                    <span style="display: inline-block;text-align: center;width: 100%;">{{ parseTime(scope.row.timestamp) }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="colData[2].istrue"
                  prop="duration"
                  label="延迟(ms)"
                  header-align="center"
                  align="center"
                />
                <el-table-column
                  v-if="colData[3].istrue"
                  prop="duration_persent"
                  label="延迟占比(%)"
                  width="250"
                  header-align="center"
                  align="center"
                >
                  <template slot-scope="scope">
                    <div>
                      <el-progress :percentage="scope.row.duration_persent * 100" color="#4343c8" :show-text="false" define-back-color="#E3E7ED" />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="colData[4].istrue"
                  prop="span_kind"
                  label="SpanKind"
                  header-align="center"
                  align="center"
                />
                <el-table-column
                  v-if="colData[5].istrue"
                  prop="service_name"
                  label="服务名"
                  header-align="center"
                  align="center"
                />
                <el-table-column
                  v-if="colData[6].istrue"
                  prop="events_attributes"
                  label="EventsAttributes"
                  header-align="center"
                  align="center"
                  width="120"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  v-if="colData[7].istrue"
                  prop="events_name"
                  label="EventsName"
                  header-align="center"
                  align="center"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  v-if="colData[8].istrue"
                  prop="events_timestamp"
                  label="EventsTimestamp"
                  header-align="center"
                  align="center"
                  width="120"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  v-if="colData[9].istrue"
                  prop="http_url"
                  label="HttpUrl"
                  header-align="center"
                  align="center"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  v-if="colData[10].istrue"
                  prop="http_method"
                  label="HttpMethod"
                  header-align="center"
                  align="center"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  v-if="colData[11].istrue"
                  prop="container_id"
                  label="ContainerId"
                  header-align="center"
                  align="center"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  v-if="colData[12].istrue"
                  prop="http_code"
                  label="httpCode"
                  header-align="center"
                  align="center"
                />
                <el-table-column
                  v-if="colData[13].istrue"
                  prop="db_connection_string"
                  label="DbConnectionString"
                  header-align="center"
                  align="center"
                  :show-overflow-tooltip="true"
                >
                  <template slot-scope="scope">
                    <span>{{ scope.row.db_connection_string }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="colData[14].istrue"
                  prop="rpc_method"
                  label="RpcMethod"
                  header-align="center"
                  align="center"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  v-if="colData[15].istrue"
                  prop="resource_attributes"
                  label="ResourceAttributes"
                  header-align="center"
                  align="center"
                  :show-overflow-tooltip="true"
                  width="400"
                >
                  <template slot-scope="scope">
                    <span style="display: inline-block;text-align: center;width:100%;">{{ JSON.stringify(scope.row.resource_attributes) }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="colData[16].istrue"
                  prop="span_attributes"
                  label="SpanAttributes333"
                  :tooltip-options="{ maxWidth: '700px' }"
                  header-align="center"
                  align="center"
                  width="400"
                  :show-overflow-tooltip="true"
                >
                  <template slot-scope="scope">
                    <span >{{ JSON.stringify(scope.row.span_attributes) }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="colData[17].istrue"
                  prop="max_depth"
                  label="MaxDepth"
                  header-align="center"
                  align="center"
                />
                <el-table-column
                  v-if="colData[18].istrue"
                  prop="db_statement"
                  label="DbStatement"
                  header-align="center"
                  align="center"
                  :show-overflow-tooltip="true"
                >
                  <template slot-scope="scope">
                    <div v-if="scope.row.db_statement !=&quot;UNSET&quot;" style="width:100%;color:#fff;background-color:rgba(153,102,51,0.5);padding:0 10px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;text-align:center;">{{ scope.row.db_statement }}</div>
                    <div v-else style="display: inline-block;text-align: center;width:100%">{{ scope.row.db_statement }}</div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-if="num ==3" style="position:relative;">
              <iframe
                id="myIframe"
                src="gi-topo-analyst2.html"
                style="width:100%;height:calc(100vh - 60px);min-height:800px;margin-top: -10px;"
                scrolling="auto"
                frameBorder="no"
                border="0"
                marginWidth="0"
                marginHeight="0"
              />
            </div>
            <div v-if="num ==4" style="position:relative;">
              <FlameGraph :tract-i-d="tractID" />
            </div>
          </div>
        </div>
        <el-dialog
          :visible.sync="Visible"
          :fullscreen="true"
          center
          :show-close="false"
          :close-on-press-escape="true"
          :append-to-body="true"
          @before-close="beforecloseFullGraph"
          @close="closeFullGraph"
        >
          <div v-if="graphBigFlag" style="margin-top:-40px">
            <div class="css-container" style="margin-bottom:24px;">
              <div class="css-header">
                <div class="css-title">Trace</div>
              </div>
              <div v-if="tableDetail !=null" class="css-content">
                <div class="css-page-header">
                  <div class="css-name">
                    <div class="css-name-title">
                      <span class="trace-name">
                        <span class="css-text">{{ tableDetail.service_name }}:</span>
                        <span class="css-text">{{ tableDetail.span_name }}</span>
                      </span>
                      <small class="css-small">{{ tableDetail.duration }}ms</small>
                    </div>
                    <div class="css-action">
                      <span style="font-weight:bold">TraceID: </span>  <span v-cloak>{{ tractID }}</span>
                    </div>
                  </div>
                  <div class="css-time-box">
                    <span class="css-time-wrap">
                      <span v-if="tableDetail.timestamp !='0001-01-01T00:00:00Z'" class="css-time-value">{{ parseTime(tableDetail.timestamp) }}</span>
                    </span>
                    <span class="css-type">
                      <el-tag v-if="tableDetail.http_method !=undefined&& tableDetail.http_method !=&quot;&quot;" size="mini" style="margin-right:8px">{{ tableDetail.http_method }}</el-tag>
                      <el-tag v-if="tableDetail.http_code !=undefined && tableDetail.http_code>=200" size="mini" :type="tableDetail.http_code>300?'danger':'success'" style="margin-right:8px">{{ tableDetail.http_code }}</el-tag>
                      <span class="css-api">{{ tableDetail.span_attributes!=undefined?tableDetail.span_attributes['http.url']:tableDetail.http_url }}</span>
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div class="TreeBox" style="margin-bottom:24px;">
              <div>
                <el-button-group>
                  <el-button size="mini" type="primary" @click="toggleTab(1)">东西链路</el-button>
                  <el-button size="mini" type="primary" @click="toggleTab(2)">链路列表</el-button>
                  <el-button size="mini" type="primary" @click="toggleTab(3)">南北链路</el-button>
                </el-button-group>
                <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>
              </div>
              <div style="font-size:14px;font-weight:bold;" />
            </div>

            <div v-if="flag==true" style="position:relative;">
              <div v-if="num == 1" class="tree_box">
                <Topo v-if="graphBigFlag" :graph-data="graphData" topo-id="container1" @changeState="clickRowHandleNode" />
              </div>
              <div v-if="num ==2">
                <el-table
                  ref="scrollTable"
                  v-loading="treeLoading"
                  :data="tableData"
                  :row-key="getRowKeys"
                  :indent="4"
                  style="width: 100%;margin-bottom: 20px;"
                  border
                  default-expand-all
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  :row-class-name="status_change"
                  :row-style="rowClassRender"
                  :cell-class-name="tableCellClassName"
                  @row-click="clickRowHandle"
                >
                  <el-table-column
                    v-if="colData[0].istrue"
                    prop="service_name"
                    label="服务名(span名称)"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  >
                    <template slot-scope="scope">
                      <span style="display: flex; align-items: center;">
                        <!-- <i v-if="scope.row.spanSelect == true" class="spanselect" /> -->
                        <i v-if="scope.row.spanSelect == true" class="el-icon-caret-right" />
                        {{ scope.row.service_name }}<span>({{ scope.row.span_name }})</span>
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="colData[1].istrue"
                    prop="timestamp"
                    label="开始时间"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  >
                    <template slot-scope="scope">
                      <span>{{ parseTime(scope.row.timestamp) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="colData[2].istrue"
                    prop="duration"
                    label="延迟(ms)"
                    header-align="center"
                    align="center"
                    width="120"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    v-if="colData[3].istrue"
                    prop="duration_persent"
                    label="延迟占比(%)"
                    header-align="center"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <div>
                        <el-progress :percentage="scope.row.duration_persent * 100" color="#4343c8" :show-text="false" define-back-color="#E3E7ED" />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="colData[4].istrue"
                    prop="span_kind"
                    label="SpanKind"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    v-if="colData[5].istrue"
                    prop="service_name"
                    label="服务名"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    v-if="colData[6].istrue"
                    prop="events_attributes"
                    label="EventsAttributes"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                    width="120"
                  />
                  <el-table-column
                    v-if="colData[7].istrue"
                    prop="events_name"
                    label="EventsName"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    v-if="colData[8].istrue"
                    prop="events_timestamp"
                    label="EventsTimestamp"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                    width="120"
                  />
                  <el-table-column
                    v-if="colData[9].istrue"
                    prop="http_url"
                    label="HttpUrl"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    v-if="colData[10].istrue"
                    prop="http_method"
                    label="HttpMethod"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    v-if="colData[11].istrue"
                    prop="container_id"
                    label="ContainerId"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    v-if="colData[12].istrue"
                    prop="http_code"
                    label="httpCode"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    v-if="colData[13].istrue"
                    prop="db_connection_string"
                    label="DbConnectionString"
                    :show-overflow-tooltip="true"
                    header-align="center"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <span>{{ scope.row.db_connection_string }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="colData[14].istrue"
                    prop="rpc_method"
                    label="RpcMethod"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    v-if="colData[15].istrue"
                    prop="resource_attributes"
                    label="ResourceAttributes"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  >
                    <template slot-scope="scope">
                      <span>{{ JSON.stringify(scope.row.resource_attributes) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="colData[16].istrue"
                    prop="span_attributes"
                    label="SpanAttributes"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  >
                    <template slot-scope="scope">
                      <span>{{ JSON.stringify(scope.row.span_attributes) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="colData[17].istrue"
                    prop="max_depth"
                    label="MaxDepth"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    v-if="colData[18].istrue"
                    prop="db_statement"
                    label="DbStatement"
                    header-align="center"
                    align="center"
                    :show-overflow-tooltip="true"
                  >
                    <template slot-scope="scope">
                      <div v-if="scope.row.db_statement !=&quot;UNSET&quot;" style="width:100%;color:#fff;background-color:rgba(153,102,51,0.5);padding:0 10px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">{{ scope.row.db_statement }}</div>
                      <div v-else>{{ scope.row.db_statement }}</div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div v-if="num ==3" style="position:relative;">
                <iframe
                  id="myIframe"
                  src="gi-topo-analyst2.html"
                  style="width:100%;height:calc(100vh - 60px);min-height:800px;margin-top: -10px;"
                  scrolling="auto"
                  frameBorder="no"
                  border="0"
                  marginWidth="0"
                  marginHeight="0"
                />
              </div>
            </div>
          </div>
        </el-dialog>

        <el-drawer
          v-if="JSON.stringify(detailData) != &quot;{}&quot;"
          :visible.sync="drawer"
          direction="rtl"
          size="55%"
          @close="drawerClose"
        >
          <div v-if="getShow().totalShow">
            <el-collapse v-model="activeNames">
              <el-collapse-item title="属性" name="one">
                <ul v-if="getShow().showAttr" class="ul_box">
                  <li v-for="(value,key) in detailData.span_attributes" :key="key">
                    <div class="ul_label">{{ key }}</div>
                    <div class="ul_value" style="color:#008080;white-space: pre-wrap;">"{{ value }}"</div>
                  </li>
                </ul>
                <el-collapse-item v-if="getShow().showHiddenAttr" name="1">
                  <template #title>
                    <span class="custom-title">查看全部</span>
                  </template>
                  <ul class="ul_box">
                    <li v-for="(value,key) in detailData.HiddenSpanAttributes" :key="key">
                      <div class="ul_label">{{ key }}</div>
                      <div class="ul_value" style="color:#008080;white-space: pre-wrap;">"{{ value }}"</div>
                    </li>
                  </ul>
                </el-collapse-item>
              </el-collapse-item>
              <el-collapse-item title="资源" name="tow">
                <ul v-if="getShow().showResource" class="ul_box">
                  <li v-for="(value,key) in detailData.resource_attributes" :key="key">
                    <div class="ul_label">{{ key }}</div>
                    <div class="ul_value" style="color:#008080;white-space: pre-wrap;">"{{ value }}"</div>
                  </li>
                </ul>
                <el-collapse-item v-if="getShow().showHiddenResource" name="2">
                  <template #title>
                    <span class="custom-title">查看全部</span>
                  </template>
                  <ul class="ul_box">
                    <li v-for="(value,key) in detailData.HiddenResourceAttributes" :key="key">
                      <div class="ul_label">{{ key }}</div>
                      <div class="ul_value" style="color:#008080;white-space: pre-wrap;">"{{ value }}"</div>
                    </li>
                  </ul>
                </el-collapse-item>
              </el-collapse-item>
              <el-collapse-item v-if="getShow().showEvents" :title="'事件'+'('+ detailData.events_timestamp.length +')'" name="three">
                <!-- <el-collapse-item title="Events" name="three"> -->
                <div class="events_box">
                  <el-collapse :value="activeIn">
                    <el-collapse-item v-for="(item,index) in detailData.events_timestamp" :key="index" :title="getTime(item)" :name="index">
                      <ul class="ul_box">
                        <li>
                          <div class="ul_label">message</div>
                          <div class="ul_value" style="color:#008080;white-space: pre-wrap;">"{{ detailData.events_name[index] }}"</div>
                        </li>
                        <li v-for="(value,key) in detailData.events_attributes[index]" :key="key">
                          <div class="ul_label">{{ key }}</div>
                          <div class="ul_value" style="color:#008080;white-space: pre-wrap;">"{{ value }}"</div>
                        </li>
                      </ul>
                    </el-collapse-item>
                  </el-collapse>
                </div>
              </el-collapse-item>
              <el-collapse-item title="异常" v-if="getShow().showException">
                <ul class="ul_box">
                  <li>信息</li>
                  <li v-for="(value,key) in detailData['exceptions.message']" :key="key">
                    <div class="ul_value" style="color:#008080;white-space: pre-wrap;">"{{ value }}"</div>
                  </li>
                </ul>
                <ul class="ul_box">
                  <li>堆栈</li>
                  <li v-for="(value,key) in detailData['exceptions.stacktrace']" :key="key">
                    <div class="ul_value" style="color:#008080;white-space: pre-wrap;">"{{ value }}"</div>
                  </li>
                </ul>
                <ul class="ul_box">
                  <li>标题</li>
                  <li v-for="(value,key) in detailData['exceptions.type']" :key="key">
                    <div class="ul_value" style="color:#008080;white-space: pre-wrap;">"{{ value }}"</div>
                  </li>
                </ul>
              </el-collapse-item>
            </el-collapse>
          </div>
          <div v-else>
            <el-collapse v-model="activeNames">
              <el-collapse-item title="详细信息" name="one">
                <div style="padding:10px;text-align:center">
                  <img style="width:24px;height:24px;" :src="detailData.span_category =='apm'?apm:apis">
                </div>
                <ul class="ul_box">
                  <li>
                    <div class="ul_label">SpanID：</div>
                    <div class="ul_value">"{{ detailData.span_id }}"</div>
                  </li>
                  <li>
                    <div class="ul_label">SpanName：</div>
                    <div class="ul_value">"{{ detailData.span_name }}"</div>
                  </li>
                  <!-- <li>
                    <div class="ul_label">采集器：</div>
                    <div class="ul_value">"{{detailData.span_category =='apm'?this.apm:this.apis}}"</div>
                  </li> -->
                  <li>
                    <div class="ul_label">SpanCategory：</div>
                    <div class="ul_value">"{{ detailData.span_category }}"</div>
                  </li>
                  <li>
                    <div class="ul_label">Duration：</div>
                    <div class="ul_value">"{{ detailData.duration }}"</div>
                  </li>
                  <li>
                    <div class="ul_label">FlatDuration：</div>
                    <div class="ul_value">"{{ detailData.flat_duration }}"</div>
                  </li>
                  <li v-for="(value,key) in detailData.detail" :key="key">
                    <div class="ul_label">{{ key }}</div>
                    <div class="ul_value">"{{ value }}"</div>
                  </li>
                </ul>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-drawer>
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import { mapGetters } from 'vuex'
import { traceList, traceDetail, traceGraph } from '@/api/trace'
import Topo from './components/TopoTree'
import storage from '@/utils/storage'
import FlameGraph from './components/FlameGraph.vue'
import moment from 'moment'
export default {
  components: {
    Topo,
    FlameGraph
  },
  data() {
    return {
      networkOpen: false,
      networkData: {},
      netWorkflag: false,
      graphflag: false,
      graphBigFlag: false,
      apis: require('../../assets/apis.jpg'),
      apm: require('../../assets/apm.jpg'),
      left: '84px',
      Visible: false,
      isFull: false,
      drawer: false,
      // activeIn:['1'],
      detailData: {},
      expands: [],
      activeNames: ['one', 'tow', 'three'],
      loading: false,
      topoUrl: 'http://observe-front.cestong.com.cn/ui/index.html',
      flag: false,
      graphData: {},
      graphDataNew: {},
      // 设置选中的列的复选框
      colSelect: [
        '服务名(span名称)',
        '开始时间',
        '延迟(ms)',
        '延迟占比(%)',
        '服务名',
        'DbStatement'
      ],
      colData: [
        { title: '服务名(span名称)', istrue: false },
        { title: '开始时间', istrue: false },
        { title: '延迟(ms)', istrue: false },
        { title: '延迟占比(%)', istrue: false },
        // { title: "StatusCode", istrue: false },
        { title: 'SpanKind', istrue: false },
        { title: '服务名', istrue: false },
        { title: 'EventsAttributes', istrue: false },
        { title: 'EventsName', istrue: false },
        { title: 'EventsTimestamp', istrue: false },
        { title: 'HttpUrl', istrue: false },
        { title: 'HttpMethod', istrue: false },
        { title: 'ContainerId', istrue: false },
        { title: 'httpCode', istrue: false },
        { title: 'DbConnectionString', istrue: false },
        { title: 'RpcMethod', istrue: false },
        { title: 'ResourceAttributes', istrue: false },
        { title: 'SpanAttributes', istrue: false },
        { title: 'MaxDepth', istrue: false },
        // { title: "dbConnectionString", istrue: false },
        { title: 'DbStatement', istrue: false }
      ],
      num: 0,
      tableData: [],
      tableDetail: null,
      selectList: [],
      treeList: [],
      // 总条数
      total: 0,
      appsItem: {},
      queryTrace: {
        start_time: 0,
        end_time: 0,
        min_duration: 0, // 单位 ms
        max_duration: 0,
        pageIndex: 1,
        pageSize: 10,
        trace_id: '',
        app_alias: '',
        failed: false
      },
      // 查询参数
      queryParams: {
        trace_id: '',
        pageIndex: 1,
        pageSize: 10
      },
      tractID: '',
      spanID: '',
      treeLoading: false,
      appItem: {},
      uniqueKeys: [],

    }
  },
  computed: {
    ...mapGetters([
      'sidebarRouters',
      'sidebar'
    ]),
    isCollapse() {
      return !this.sidebar.opened
    },
    activeIn() {
      if (this.detailData?.events_timestamp.length > 0 && this.detailData?.events_timestamp != null) {
        return this.detailData.events_timestamp.map((item, i) => {
          return i
        })
      }
    }
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.queryTrace.start_time = newValue.startTime
          this.queryTrace.end_time = newValue.endTime
          this.getTraceList()
        }
      },
      // immediate: true,
      deep: true
    },
    'isCollapse': {
      handler(newValue, oldValue) {
        if (newValue == true) {
          this.left = '84px'
        } else {
          this.left = '240px'
        }
      }
    }
  },
  created() {
    this.$store.commit('time/setTimeFlag', false)
    // if (this.$route.query.id != undefined) {
    //   this.queryTrace.trace_id = this.$route.query.id
    //   this.tractID = this.$route.query.id
    //   this.getTraceList()
    // }

    // if (this.$route.query.span_id != undefined) {
    //   this.spanID = this.$route.query.span_id
    // }
    // if (this.$route.query.datetime != undefined) {
    //   this.queryTrace.start_time = this.$route.query.datetime
    //   this.queryTrace.end_time = this.$route.query.datetime
    //   this.queryTrace.trace_id = this.$route.query.traceId

    //   this.getTraceList()
    // }

    const strr = window.location.href
    this.appsItem = storage.get('appsItem')
    const param = this.parseQueryString(strr)
    if (param.datetime != undefined || param.datetime != null || param.datetime != 'NaN') {
      this.queryTrace.start_time = param.datetime
      this.queryTrace.end_time = param.datetime
    }
    if (param.traceId != undefined || param.id != undefined) {
      this.queryTrace.trace_id = param.traceId || param.id // 此处兼容traceId传递不统一的问题
      this.queryTrace.app_alias = param.app_alias || storage.get('appsItem').alias // 此处兼容应用名字未传递的情景
      this.tractID = param.traceId || param.id
      if (!param.datetime || param.datetime == 'NaN') {
        this.queryTrace.start_time = this.$store.state.time.globalTimes.startTime
        this.queryTrace.end_time = this.$store.state.time.globalTimes.endTime
      }
      this.getTraceList()
    }
    if (param.span_id != undefined) {
      this.spanID = param.span_id
    }
    if (param.min_duration != undefined && param.max_duration != undefined) {
      this.queryTrace.start_time = param.start_time
      this.queryTrace.end_time = param.end_time
      this.queryTrace.min_duration = param.min_duration
      this.queryTrace.max_duration = param.max_duration
      this.queryTrace.app_alias = param.app_alias || storage.get('appsItem').alias // 此处兼容应用名字未传递的情景
      if (param.failed != undefined) {
        this.queryTrace.failed = JSON.parse(param.failed)
      }
      this.queryTrace.pageIndex = 1
      this.queryTrace.pageSize = 10
      this.queryTrace.trace_id = ''
      this.getTraceList()
    }

    this.columnChange()
  },
  mounted() {
    if (this.isCollapse == true) {
      this.left = '84px'
    } else {
      this.left = '240px'
    }
  },
  methods: {
    getShow() {
      const flag1 = (this.detailData.span_attributes !== null && this.detailData.span_attributes !== undefined) && Object.keys(this.detailData.span_attributes).length > 0
      const flag2 = (this.detailData.resource_attributes !== null && this.detailData.resource_attributes !== undefined) && Object.keys(this.detailData.resource_attributes).length > 0
      const flag3 = (this.detailData.events_timestamp !== null && this.detailData.events_timestamp !== undefined) && this.detailData.events_timestamp.length > 0
      const flag4 = (this.detailData.HiddenSpanAttributes !== null && this.detailData.HiddenSpanAttributes !== undefined) && Object.keys(this.detailData.HiddenSpanAttributes).length > 0
      const flag5 = (this.detailData.HiddenResourceAttributes !== null && this.detailData.HiddenResourceAttributes !== undefined) && Object.keys(this.detailData.HiddenResourceAttributes).length > 0
      const flag6 = (this.detailData['exceptions.message'] !== null && this.detailData['exceptions.message'] !== undefined) && (this.detailData['exceptions.message']).length > 0
      const flag7 = (this.detailData['exceptions.stacktrace'] !== null && this.detailData['exceptions.stacktrace'] !== undefined) && (this.detailData['exceptions.stacktrace']).length > 0
      const flag8 = (this.detailData['exceptions.type'] !== null && this.detailData['exceptions.type'] !== undefined) && (this.detailData['exceptions.type']).length > 0
      const excFlag = flag6 || flag7 || flag8
      const obj = {
        totalShow: flag1 || flag2 || flag3 || flag4 || flag5 || excFlag,
        showAttr: flag1,
        showResource: flag2,
        showEvents: flag3,
        showHiddenAttr: flag4,
        showHiddenResource: flag5,
        showException: excFlag
      }
      return obj
    },
    getTime(item) {
      return item && moment(item).format('YYYY-MM-DD HH:mm:ss')
    },
    clickFull() {
      this.Visible = true
      this.graphBigFlag = true
    },
    beforecloseFullGraph() {
      // this.graphDataNew = {};
      this.Visible = false
      this.graphBigFlag = false
    },
    closeFullGraph() {
      this.Visible = false
      this.graphBigFlag = false
      // done();
    },
    closeNetwork() {
      this.networkOpen = false
      this.netWorkflag = false
      // done();
    },
    beforecloseNetwork() {
      this.networkOpen = false
      this.netWorkflag = false
    },
    handlePaste(e) {
      var clip = e.clipboardData.getData('Text')
      this.queryTrace.trace_id = clip
      this.$forceUpdate()
    },
    change(e) {
      this.$forceUpdate()
    },
    parseQueryString(url) {
      var json = {}
      var arr = url.substr(url.indexOf('?') + 1).split('&')
      arr.forEach(item => {
        var tmp = item.split('=')
        json[tmp[0]] = tmp[1]
      })
      return json
    },
    drawerClose() {
      this.drawer = false
    },
    // 根据行的id判断
    getRowKeys(row, index) {
      return row.span_id
    },
    clickRowHandleNode(item) {
      this.detailData = item
      this.drawer = true
    },
    clickRowHandleEge(item) {
      this.networkOpen = true
      this.networkData = item
      this.netWorkflag = true
    },
    clickRowHandle(row, column, event) {
      this.detailData = row
      this.drawer = true
    },
    rowClassRender({ row }) {
    },
    status_change(row) {
      if (row.row.events_timestamp != null) {
        if (row.row.status_code == 'STATUS_CODE_ERROR') {
          return 'table-error-row'
        } else {
          return ''
        }
      } else {
        return ''
      }
    },
    // 用来修改单元格css
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryTrace.trace_id = this.queryTrace.trace_id.trim()
      this.queryTrace.app_alias = this.queryTrace.app_alias.trim()
      this.queryTrace.pageIndex = 1
      // this.queryParams.pageIndex = 1
      // this.getSingleTrace()
      this.getTraceList()
    },
    // 控制列的显示和隐藏
    columnChange(val) {
      this.colData.filter((i) => {
        if (this.colSelect.indexOf(i.title) !== -1) {
          i.istrue = true
        } else {
          i.istrue = false
        }
      })
    },
    // 获取trace table 数据
    getTraceList() {
      this.loading = true
      traceList(this.queryTrace).then(res => {
        this.loading = false
        this.graphData = {}
        this.graphflag = false
        if (res.code == 200) {
          this.selectList = res.data.list || []
          this.total = res.data.count || 0
          if (this.selectList && this.selectList.length === 1) {
            const row = this.selectList[0]
            setTimeout(() => {
              this.flag = true
              this.tractID = row.trace_id
              this.$refs.table.setCurrentRow(row)
              this.getTraceDetail(row.trace_id, row.timestamp)
            }, 0)
          }
        } else {
          this.selectList = []
          this.total = 0
        }
      })
    },
    getTraceDetail(trace_id, time) {
      this.treeLoading = true
      const timeObj = {
        start_time: Math.floor(Date.parse(time) / 1000),
        end_time: Math.floor(Date.parse(time) / 1000)
      }
      this.graphflag = false
      traceDetail(trace_id, timeObj).then(res => {
        if (res.code == 200) {
          this.num = 1

          if (JSON.stringify(res.data) != '{}') {
            this.graphflag = true
            this.graphData = {}
            this.tableDetail = res.data

            const arr = [res.data]
            this.tableData = this.handlerTreeTableList(arr, this.spanID)
            if (arr.length > 0) {
              const List = this.handleData(arr)
              this.graphData = List[0]
            }
          } else {
            this.msgInfo('暂无数据')
          }
        } else {
          this.$message.error(res.msg)
        }
        this.treeLoading = false
      })
    },
    handlerTreeTableList(arr, targetId) {
      let obj = {}
      const list = []
      for (let i = 0; i < arr.length; i++) {
        const node = arr[i]
        if (node.span_id == targetId) {
          obj = node
          obj.spanSelect = true
          //  this.tableScrollTorow(this.$refs.scrollTable,i)
        } else {
          obj = node
          obj.spanSelect = false
        }

        if (node.children != undefined && node.children.length > 0) {
          obj.children = this.handlerTreeTableList(node.children, targetId)
        }
        list.push(obj)
      }
      return list
    },
    tableScrollTorow(tableElement, rowIndex) {
      const tableRows = tableElement.querySelectorAll('.el-table__body tbody .el-table__row')
      let scrollTop = 0
      for (let i = 0; i < tableRows.length; i++) {
        if (i == rowIndex) {
          break
        }
        scrollTop += tableRows[i].offsetHeight
      }
      tableElement.scrollTop = scrollTop
    },
    handleData(data) {
      if (data.length > 0) {
        data.forEach((v, k) => {
          v.id = v.span_id + k + Math.random()
          v.collapsed = false
          v.name = v.span_name
          v.label = v.duration.toFixed(2)
          v.currency = 'ms'
          v.rate = v.duration_persent
          v.status = (v.status_code == 'STATUS_CODE_ERROR' || v?.events_timestamp?.length > 0 || v?.http_code > 399) ? 'R' : (v.duration > 500) ? 'Y' : 'G'
          v.variableValue = v.duration_persent

          if (v.children != undefined && v.children.length > 0) {
            v.children = this.handleData(v.children)
          }
        })
      }
      return data
    },
    getTraceGraph(trace_id) {
      traceGraph(trace_id).then(res => {
        if (res.code == 200) {
          res.data.nodes = res.data.nodes.map((item) => ({
            label: item.title,
            id: item.id,
            title: item.title,
            subtitle: item.subtitle,
            mainstat: item.mainstat,
            secondarystat: item.secondarystat,
            arc_green: item.arc_green, // 结点圆圈颜色，1代表纯绿色，与red和为1
            arc_red: item.arc_red, // 计算方式为当spankind为client时， current/total的值
            icon: item.icon
          }))
        }
      })
    },
    handleRowClick(row, column, event) {
      setTimeout(() => {
        this.flag = true
        this.tractID = row.trace_id
        this.$refs.table.toggleRowSelection(row)
        this.getTraceDetail(row.trace_id, row.timestamp)
      }, 0)
    },
    toggleTab(val) {
      this.num = val
    },
    handleClickSearchList() {
      // 如果不存在该dom需要做判断兼容
      if (this.$refs.topo) {
        this.$refs.topo.clearGraph()
      }
      if (this.queryTrace.app_alias === '') {
        this.queryTrace.app_alias = storage.get('appsItem').alias
      }
      this.getTraceList()
    }
  }
}
</script>

<style lang='scss' scoped>
.TreeBox{
  display: flex;
  justify-content: space-between;
}

 [v-cloak]{
    display: none!important;
  }
::v-deep .el-tooltip__popper{ max-width: 700px !important }

::v-deep .el-table__row.table-error-row td{
  background-color: #fef0f0 !important;
}
::v-deep td.table-border{
  border-top:2px solid #67C23A;
  border-bottom:2px solid #67C23A;
}

::v-deep .collapse-title {
  flex: 1 0 90% !important;
  order: 1 !important;
}
::v-deep .el-collapse-item__header {
    flex: 1 0 auto !important;
    order: -1 !important;
    padding-left:8px!important;
    height: 30px;
    line-height: 30px;
  }
::v-deep .el-collapse-item__header:hover{
    background: rgb(232, 232, 232);
}
::v-deep .el-drawer__header{
  margin-bottom: 0!important;
  font-weight: 500;
}
ul {
    display: block;
    list-style-type: disc;
    margin-block-start: 0;
    margin-block-end: 0;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    padding-inline-start: 0;
}
.ul_box{
      border: 1px solid rgba(36, 41, 46, 0.12);
      box-sizing: border-box;
      padding:4px;
      margin:8px;
      border-radius: 3px;
}
.custom-title{
  text-align: right;
  display: inline-block;
  width: 100%;
  color: #999;
}
.ul_box li{
  display: flex;
  min-height: 30px;
  line-height: 30px;
  box-sizing: border-box;
  // padding:0 4px;
}
.ul_box li .ul_label{
    color: rgb(136, 136, 136);
    // white-space: pre;
    width: 180px;
    min-width: 180px;
    display: flex;
    flex-direction: column;
    // align-items: flex-end;
    // justify-content: flex-end;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.ul_box li .ul_value{
  // white-space: nowrap;
  // word-break: keep-all;
  // overflow: hidden;
  // text-overflow: ellipsis;
  font-family: monospace;
  display: flex;
  flex-direction: column;
  // align-items: flex-end;
  justify-content: flex-end;
}
.ul_box li:nth-child(even) {
  background: rgb(245, 245, 245);
}
.events_box{
  padding:8px;
  border: 1px solid rgba(36, 41, 46, 0.12);
  border-radius: 3px;
}
.events_box ::v-deep .el-collapse-item__header {
    background-color: rgb(244, 245, 245)
        // background: rgb(228, 228, 228);
}
.css-container{
  background-color: rgb(255, 255, 255);
    border: 1px solid rgba(36, 41, 46, 0.12);
    position: relative;
    border-radius: 2px;
    height: 100%;
    display: flex;
    flex-direction: column;
}
.css-header{
    display: flex;
    -webkit-box-align: center;
    align-items: center;
    height: 32px;
    cursor: auto;
    .css-title{
      margin-bottom: 0px;
      padding: 0px 8px;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
      font-size: 14px;
      font-weight: 550;
      line-height: 1.57143;
      letter-spacing: 0.2px;
      font-family: Inter, Helvetica, Arial, sans-serif;
    }
}
.css-content{
    padding: 0px;
    box-flex:1;
    -webkit-box-flex: 1;
    flex-grow: 1;
    contain: none;
}
.css-page-header{
  background-color: rgb(255, 255, 255);
  padding: 0.5em 0px 0px;
  position: sticky;
  top: 0px;
  z-index: 5;
}
.css-name{
    align-items: flex-start;
    display: flex;
    padding: 0px 8px;
    .css-name-title{
          color: inherit;
          flex: 1 1 0%;
          font-size: 1.7em;
          line-height: 1em;
          margin: 0px 0px 0.45em;
          font-weight: 400;
          letter-spacing: -0.00893em;
          font-family: Inter, Helvetica, Arial, sans-serif;
          .trace-name{
            font-size: 18px;
          }
          .css-text{
            display: inline-block;
            white-space: pre;
          }
      }
}
.css-small{
  color: rgb(170, 170, 170);
  margin: 0px 12px;
  font-size: 12px;
  font-weight: 400;
}
.css-action{
    font-size: 14px;
    font-weight: 500;
    font-family: Inter, Helvetica, Arial, sans-serif;
}
.css-time-box{
    flex: 1 1 0%;
    line-height: 1.5;
    margin: -8px 8px 12px;
}
.css-time-wrap{
  vertical-align: middle;
}
.css-time-vlaue-detail{
      color: rgb(170, 170, 170);
}
.css-type {
    margin: 0px 12px;
    // vertical-align: text-top;
}
.css-api{
  margin: -2.5px 2.4px;
  height: 15px;
  overflow: hidden;
  word-break: break-all;
  line-height: 20px;
}
.full{
  width:32px;
  height:32px;
  position: absolute;
  top:-35px;
  right:0px;
  display: block;
  i{
    font-size: 16px;
    color:#999;
  }
}

.cell-start {
  border-top: 1px solid #ebeff0;
  border-bottom: 1px solid #ebeff0 !important;
  border-left: 1px solid #ebeff0;
}
.cell-end {
  border-top: 1px solid #ebeff0;
  border-bottom: 1px solid #ebeff0 !important;
  border-right: 1px solid #ebeff0;
}
.cell-middle {
  border-top: 1px solid #ebeff0;
  border-bottom: 1px solid #ebeff0 !important;
}

.el-table__body {
  border-spacing: 0px 6px !important;
}
.spanselect{
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: red;
}
.legend{
  position: fixed;
  left:240px;
  bottom:30px;
  // z-index: 1001;
  transition: all .3s;
}
.listwrap{
  color:#666;
  span{
    display: inline-block;
    padding:4px;
  }
  .value{
    width:80px;
    box-sizing: border-box;
    padding-right: 10px;
  }
}
::v-deep .el-icon-caret-right:before{
  color:#165DFF;
  font-size: 14px;
}
::v-deep .el-table .cell.el-tooltip{
  display: flex;
  align-items: center;
  width: 100% !important;
}
::v-deep .el-table tr{
  cursor: pointer;
}
</style>
<style >
[v-cloak]{
  display:none!important;
}
.my-tooltip{
  max-width: 700px;
}

</style>
