<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="flex:1;">
        <div style="margin-bottom:16px;">
          <!-- <el-row type="flex" justify="space-between" :gutter="24">
            <el-col :span="6" :lg="6" :md="8" :sm="4">
              <div class="left-box" style="display:flex">
                <div class="form-box">
                  <el-form ref="spansQuery" :inline="true" :model="spansQuery"  label-width="100px">
                    <el-form-item label="自定义属性" prop="span_attribute_key">
                      <el-input
                        v-model="spansQuery.span_attribute_key"
                        placeholder="请输入自定义属性"
                        clearable
                        size="small"
                        @keyup.enter.native="handleSpansQuery"
                      />
                    </el-form-item>
                    <el-form-item label="自定义属性值" prop="span_attribute_value">
                      <el-input
                        v-model="spansQuery.span_attribute_value"
                        placeholder="请输入自定义属性值"
                        clearable
                        size="small"
                        @keyup.enter.native="handleSpansQuery"
                      />
                    </el-form-item>
                    <el-form-item label="Span类型" prop="span_kind">
                      <el-select v-model="spansQuery.span_kind" placeholder="Span类型" clearable size="small" @keyup.enter.native="handleSpansQuery" @change='changeSpansQuery'>
                        <el-option
                          v-for="kind in spanOptions"
                          :key="kind.value"
                          :label="kind.label"
                          :value="kind.value"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="延迟大于" prop="min_duration">
                      <el-input
                        v-model="spansQuery.min_duration"
                        placeholder=""
                        clearable
                        size="small"
                        type="number"
                        @keyup.enter.native="handleSpansQuery"
                        class="Dur_input"
                      >
                      <template slot="append">ms</template>
                      </el-input>
                    </el-form-item>
                    <el-form-item label="调用方法" prop="method">
                      <el-input
                        v-model="spansQuery.method"
                        placeholder="请输入调用方法"
                        clearable
                        size="small"
                        @keyup.enter.native="handleSpansQuery"
                      >
                      </el-input>
                    </el-form-item>
                    <el-form-item label="" prop="only_exception">
                      <el-checkbox :true-label='1' :false-label='0' v-model="spansQuery.only_exception" @keyup.enter.native="handleSpansQuery" @change='changeErrorSpans'>仅异常</el-checkbox>
                    </el-form-item>
                    <el-form-item label="" prop="only_database">
                      <el-checkbox v-model="spansQuery.only_database" :true-label='1' :false-label='0' @keyup.enter.native="handleSpansQuery" @change='changeSQLSpans'>仅SQL</el-checkbox>
                    </el-form-item>
                  </el-form>
                </div>
                <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"></i>
                    </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>
            </el-col>
            <el-col :span="18" :lg="18" :md="16" :sm="20">
              <div class="right-box">
                <el-table
                  v-loading="loading"
                  :data="spansList"
                >
                  <el-table-column type="selection" width="45" align="center" />
                  <el-table-column label="TraceId" prop="trace_id" :show-overflow-tooltip="true" v-if="colData[0].istrue">
                    <template slot-scope="scope">
                      <span @click="goto(scope.row)">{{scope.row.trace_id}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="ServiceName" prop="service_name" :show-overflow-tooltip="true" v-if="colData[1].istrue"/>
                  <el-table-column label="DateTime" prop="datetime" :show-overflow-tooltip="true" v-if="colData[2].istrue"/>
                  <el-table-column label="Method" prop="method" :show-overflow-tooltip="true" v-if="colData[3].istrue"/>
                  <el-table-column label="Code" prop="code" :show-overflow-tooltip="true" v-if="colData[4].istrue"/>
                  <el-table-column label="Duration(ms)" prop='duration' :show-overflow-tooltip="true" v-if="colData[5].istrue">
                      <template slot-scope="scope">
                          <el-tag v-if="scope.row.duration>=2000" type="danger">{{ scope.row.duration }}</el-tag>
                          <el-tag v-if="scope.row.duration<2000" type="info">{{ scope.row.duration }}</el-tag>
                      </template>
                  </el-table-column>
                  <el-table-column
                    label="SpanId"
                    prop="span_id"
                    :show-overflow-tooltip="true" 
                    v-if="colData[6].istrue"
                  >
                  </el-table-column>
                </el-table>

                <pagination
                  v-show="total>0"
                  :total="total"
                  :page.sync="spansQuery.pageIndex"
                  :limit.sync="spansQuery.pageSize"
                  @pagination="getServiceSpans"
                />
              </div>
            </el-col>
          </el-row> -->
          <div class="left-box" style="display:flex">
            <div class="form-box">
              <el-form ref="spansQuery" :inline="true" :model="spansQuery"  label-width="100px">
                <el-form-item label="自定义属性" prop="span_attribute_key">
                  <el-input
                    v-model="spansQuery.span_attribute_key"
                    placeholder="请输入自定义属性"
                    clearable
                    size="small"
                    @keyup.enter.native="handleSpansQuery"
                  />
                </el-form-item>
                <el-form-item label="自定义属性值" prop="span_attribute_value">
                  <el-input
                    v-model="spansQuery.span_attribute_value"
                    placeholder="请输入自定义属性值"
                    clearable
                    size="small"
                    @keyup.enter.native="handleSpansQuery"
                  />
                </el-form-item>
                <el-form-item label="Span类型" prop="span_kind">
                  <el-select v-model="spansQuery.span_kind" placeholder="Span类型" clearable size="small" @keyup.enter.native="handleSpansQuery" @change='changeSpansQuery'>
                    <el-option
                      v-for="kind in spanOptions"
                      :key="kind.value"
                      :label="kind.label"
                      :value="kind.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="延迟大于" prop="min_duration">
                  <el-input
                    v-model="spansQuery.min_duration"
                    placeholder=""
                    clearable
                    size="small"
                    type="number"
                    @keyup.enter.native="handleSpansQuery"
                    class="Dur_input"
                  >
                  <template slot="append">ms</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="调用方法" prop="method">
                  <el-input
                    v-model="spansQuery.method"
                    placeholder="请输入调用方法"
                    clearable
                    size="small"
                    @keyup.enter.native="handleSpansQuery"
                  >
                  </el-input>
                </el-form-item>
                <!-- <el-form-item label="最大延迟" prop="max_duration">
                  <el-input
                    v-model="spansQuery.max_duration"
                    placeholder="请输入最大延迟"
                    clearable
                    size="small"
                    type="number"
                    @keyup.enter.native="handleSpansQuery"
                  />
                </el-form-item> -->
                <el-form-item label="" prop="only_exception">
                  <el-checkbox :true-label='1' :false-label='0' v-model="spansQuery.only_exception" @keyup.enter.native="handleSpansQuery" @change='changeErrorSpans'>仅异常</el-checkbox>
                </el-form-item>
                <el-form-item label="" prop="only_database">
                  <!-- <el-checkbox v-model="spansQuery.only_database"></el-checkbox> -->
                  <el-checkbox v-model="spansQuery.only_database" :true-label='1' :false-label='0' @keyup.enter.native="handleSpansQuery" @change='changeSQLSpans'>仅SQL</el-checkbox>
                </el-form-item>
              </el-form>
            </div>
            <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"></i>
                </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 class="right-box">
            <el-table
              v-loading="loading"
              :data="spansList"
            >
              <!-- <el-table-column type="selection" width="45" align="center" /> -->
              <el-table-column label="TraceId" prop="trace_id" :show-overflow-tooltip="true" v-if="colData[0].istrue">
                <template slot-scope="scope">
                  <span @click="goto(scope.row)">{{scope.row.trace_id}}</span>
                </template>
              </el-table-column>
              <el-table-column label="ServiceName" prop="service_name" :show-overflow-tooltip="true" v-if="colData[1].istrue"/>
              <el-table-column label="DateTime" prop="datetime" :show-overflow-tooltip="true" v-if="colData[2].istrue"/>
              <el-table-column label="Method" prop="method" :show-overflow-tooltip="true" v-if="colData[3].istrue"/>
              <el-table-column label="Code" prop="code" :show-overflow-tooltip="true" v-if="colData[4].istrue"/>
              <el-table-column label="Duration(ms)" prop='duration' :show-overflow-tooltip="true" v-if="colData[5].istrue">
                  <template slot-scope="scope">
                      <el-tag v-if="scope.row.duration>=2000" type="danger">{{ scope.row.duration }}</el-tag>
                      <el-tag v-if="scope.row.duration<2000" type="info">{{ scope.row.duration }}</el-tag>
                  </template>
              </el-table-column>
              <el-table-column
                label="SpanId"
                prop="span_id"
                :show-overflow-tooltip="true" 
                v-if="colData[6].istrue"
              >
              </el-table-column>
            </el-table>

            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="spansQuery.pageIndex"
              :limit.sync="spansQuery.pageSize"
              @pagination="getServiceSpans"
            />
          </div>
        </div>
      </el-card>
    </template>
  </BasicLayout>
</template>
<script>
import {serviceSpans} from "@/api/service"
import storage from '@/utils/storage'
export default {
  data(){
    return {
      timeQuery:{
        app_alias:'',
        service_name:'',
        hour_num:1, 
      },
      timeOptions:[
        {
          value: 1,
          label: '1 小时'
        },
        {
          value: 3,
          label: '3 小时'
        },
        {
          value: 6,
          label: '6 小时'
        },
        {
          value: 12,
          label: '12 小时'
        },
        {
          value: 24,
          label: '24 小时'
        },
      ],
      spanOptions:[
        {
          value: 'SPAN_KIND_CLIENT',
          label: 'SPAN_KIND_CLIENT'
        },
        {
          value: 'SPAN_KIND_SERVER',
          label: 'SPAN_KIND_SERVER'
        },
        {
          value: 'SPAN_KIND_INTERNAL',
          label: 'SPAN_KIND_INTERNAL'
        },
        {
          value: 'SPAN_KIND_CONSUMER',
          label: 'SPAN_KIND_CONSUMER'
        },
        {
          value: 'SPAN_KIND_PRODUCER',
          label: 'SPAN_KIND_PRODUCER'
        },
      ],
      // 设置选中的列的复选框
      colSelect: [
        "TraceId",
        "ServiceName",
        "DateTime",
        "Method",
        "Code",
        "Duration(ms)",
      ],
      colData: [
        { title: "TraceId", istrue: false },
        { title: "ServiceName", istrue: false },
        { title: "DateTime", istrue: false },
        { title: "Method", istrue: false },
        { title: "Code", istrue: false },
        { title: "Duration(ms)", istrue: false },
        { title: "SpanId", istrue: false },
      ],
      loading:false,
      total:0,
      timer:null,
      spansList:[],
      name:'',
      statsQuery:{
        id:0,
        start_time:'',
        end_time:'',
      },
      statsObj:{},
      spansQuery:{
        app_alias:'',
        // method:'',
        request_method:'',
        service_name:'', // 支持多个，多个并列
        only_exception:0 ,   // 仅显示异常trace相关
        only_database:0,    // 仅显示数据库相关
          // 支持分页，参数与之前一致
          // 支持时间筛选，参数与之前一致
        trace_id: '',// trace id, 字符串
        span_kind: '',// 固定5个值,建议下拉列表,分别为SPAN_KIND_CLIENT SPAN_KIND_SERVER SPAN_KIND_INTERNAL SPAN_KIND_CONSUMER SPAN_KIND_PRODUCER
        span_attribute_key: '',// 字符串
        span_attribute_value:'', // 字符串
        min_duration:0,  // 最小耗时
        max_duration:0, // 最大耗时
        start_time:0,
        end_time:0,
        pageIndex:1,
        pageSize:10
      },
    }
  },
  watch: {
     '$store.state.time.globalTimes': {
        handler(newValue, oldValue) {
            if(newValue){
              this.spansQuery.start_time=newValue.startTime;
              this.spansQuery.end_time=newValue.endTime;
              this.getServiceSpans();
            
              if(newValue.timeOut){
                if(newValue.timeOut == 1){
                  clearInterval(this.timer);
                }else{
                  clearInterval(this.timer);
                  this.Refresh(newValue.timeOut);
                }
              }
            }
        },
        // immediate: true,
        deep: true
    },
  },
  created(){
     // 说明
    // appItem中的id和app_id是一样的
    this.appItem=storage.get('appsItem');
    const start_time = this.$store.state.time.globalTimes.startTime
    const end_time = this.$store.state.time.globalTimes.endTime
    if(JSON.stringify(this.appItem) !="{}"){
      this.spansQuery.app_alias=this.appItem.alias;
      this.spansQuery.start_time= start_time;
      this.spansQuery.end_time= end_time;
      this.getServiceSpans();
    }

    this.columnChange();
  },
  mounted(){
     this.$nextTick(()=>{

     })
  },
  methods:{
    Refresh(timeOut){
      this.timer = setInterval(()=>{

      },timeOut)
    },
    getlistServiceStats(){
        listServiceStats(this.statsQuery).then(response=>{
          if(response.code == 200){
            this.statsObj = response.data;
          }
        })
    },

    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;
    },
    handletimeQuery(){
      this.getServiceCompare();
      this.getErrorRateCompare()
    },
    changetimeQuery(val){
      this.timeQuery.hour_num = val;
      this.getServiceCompare();
      this.getErrorRateCompare()
    },
    handleSpansQuery(){
      this.getServiceSpans();
    },
    changeErrorSpans(val){
      this.spansQuery.only_exception=val;
      this.getServiceSpans();
    },
    changeSQLSpans(val){
      this.spansQuery.only_database=val;
      this.getServiceSpans();
    },
    changeSpansQuery(val){
      this.spansQuery.span_kind = val;
      this.getServiceSpans();
    },
    //控制列的显示和隐藏
    columnChange(val) {
      this.colData.filter((i) => {
        if (this.colSelect.indexOf(i.title) !== -1) {
          i.istrue = true;
        } else {
          i.istrue = false;
        }
      });
    },
    getServiceSpans(){
      serviceSpans(this.spansQuery).then((res)=>{
        if(res.code == 200){
          this.spansList= res.data.list
          this.total = res.data.count
        }
      })
    },
    back(){
      this.$router.push({
        path:'/service/service/index'
      })
    },
    goto(row){
      let datetime = Date.parse(row.datetime)/1000;
      let href = this.$router.resolve({
        path:'/latency/index',
        query:{
          id:row.trace_id,
          span_id:row.span_id,
          datetime:datetime
        }
      })
      window.open(window.location.origin+"/"+href.href,"_blank")
    },
    
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },

}
</script>
<style lang="scss" scoped>
.h6{
  font-size: 14px;
}
.Dur_input ::v-deep .el-input__inner{
  width:100px;
}
.noData{
    width: 100%;
    height: 200px;
    background: #fff;
}
.noData_title{
    margin-bottom: 0px;
    padding: 2px 5px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    font-size: 14px;
    font-weight: 500;
    line-height: 1.57143;
    font-family: Inter, Helvetica, Arial, sans-serif;
}
.trace-box{
  display: flex;

}
  .left-box{
    // border-radius: 8px;
    // margin-bottom: 16px;
    // border: thin solid rgba(0,0,0,.12);
    // background-color: #fff;
    // color: rgba(0,0,0,.87);
    // font-family: Roboto,sans-serif;
    // line-height: 1.5;
    // .form-box{
    //   display: block;
    //   padding: 8px 0;
    //   position: static;
    //   transition: box-shadow .28s cubic-bezier(.4,0,.2,1);
    // }
  }
  .right-box{

  }
</style>