<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="margin-top:10px">
        <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
          <el-row>
            <el-col :span="6">
              <!-- <el-form-item label="" prop="app_name">
                <el-select v-model="queryParams.app_id" placeholder="业务系统选择" clearable size="mini" @change='changeAppName'>
                  <el-option
                    v-for="item in listApps"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item> -->
            </el-col>
            <el-col :span="8" :offset="10">
              <el-form-item label="" prop="exception_name">
                <el-input
                  v-model="queryParams.exception_name"
                  placeholder="事件检索"
                  clearable
                  size="mini"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item class="radiobox" label="" prop="alert_status" style="margin-left:16px">
                <el-radio-group v-model="queryParams.alert_status" @input="changeStatus">
                  <el-radio size="mini" :label="4">仅告警</el-radio>
                  <el-radio size="mini" :label="0">显示全部</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item> -->
        </el-form>

        <el-table v-loading="loading" :data="eventList">
          <el-table-column label="业务系统" header-align="center" align="center" prop="app_name" :show-overflow-tooltip="true" width="140" />
          <el-table-column label="事件" header-align="center" align="left" prop="exception_name" :show-overflow-tooltip="true" />
          <el-table-column label="异常状态" header-align="center" align="center" prop="alert_status" width="200">
            <template slot-scope="scope">
              <span v-if="scope.row.alert_status === 4 || scope.row.alert_status === 8">
                <el-tag
                  type="danger"
                  disable-transitions
                  style="margin-right: 5px;"
                >已告警</el-tag>
                <el-tag
                  :type="scope.row.alert_status==4?'info': ''"
                  disable-transitions
                >{{ scope.row.alert_status==4?"通知未发送":"通知已发送" }}</el-tag>
              </span>
              <el-tag
                v-else
                type="warning"
                disable-transitions
              >{{ "触发异常" }}</el-tag>

            </template>
          </el-table-column>
          <el-table-column label="发生时间" header-align="center" align="center" prop="append_time" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.append_time) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="事件类型" header-align="center" align="center" prop="rule_info" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.rule_info.rule_kind }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="事件信息" header-align="center" align="left">
            <template slot-scope="scope">
              <span style="cursor: pointer;" @click="handleOpen(scope.row)">
                <span v-if="scope.row.row_result =='UNSET'">
                  <el-tooltip placement="bottom">
                    <div
                      slot="content"
                      style="width:400px;max-height:200px; overflow-y: scroll;"
                    >
                      {{ JSON.stringify(scope.row.rows_result) }}
                    </div>
                    <span style="display:block;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;">{{
                      JSON.stringify(scope.row.rows_result)
                    }}</span>
                  </el-tooltip>
                </span>
                <span v-else>{{ scope.row.row_result }}</span>
              </span>
            </template>
          </el-table-column> -->

          <!-- <el-table-column label="操作" header-align="center" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                v-permisaction="['admin:sysPost:edit']"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                v-permisaction="['admin:sysPost:remove']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column> -->
        </el-table>

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

        <el-dialog :title="title" :visible.sync="open" width="700px" :center="true" :close-on-click-modal="false">
          <!-- <json-viewer :value="value" copyable theme="my-awesome-json-theme"></json-viewer> -->
          <div class="exercise">
            <!-- <div id="menu" @contextmenu="showMenu(codeSnippets)"> -->
            <codemirror
              v-model="codeSnippets"
              :options="cmOptions"
            />
            <!-- <vue-context-menu :contextMenuData="contextMenuData" @goRouterFn="goRouterFn" @copyFn="copyFn"></vue-context-menu> -->
            <!-- </div> -->
          </div>
          <div slot="footer" class="dialog-footer">
            <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
            <el-button @click="cancel">关 闭</el-button>
          </div>
        </el-dialog>
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import { listEvent } from '@/api/event'
import { listApps } from '@/api/apps'
import { formatJson } from '@/utils'
import JsonViewer from 'vue-json-viewer'
import storage from '@/utils/storage'

// 编辑器代码格式
import 'codemirror/mode/properties/properties.js'
// 自动刷新(防止codemirror需要手动刷新才出数据)
// import 'codemirror/addon/display/autorefresh'
// 主题
import 'codemirror/theme/ayu-mirage.css'
import 'codemirror/theme/panda-syntax.css'
require('codemirror/mode/sql/sql')
// require("codemirror/mode/json/json");

require('codemirror/addon/hint/show-hint')
require('codemirror/addon/hint/sql-hint')

export default {
  name: 'Evnet',
  components: {
    JsonViewer
  },
  data() {
    return {
      codeSnippets: '',
      cmOptions: {
        autorefresh: true,
        tabSize: 4,
        mode: 'application/json',
        theme: 'panda-syntax',
        line: true,
        viewportMargin: Infinity, // 处理高度自适应时搭配使用
        highlightDifferences: true,
        autofocus: false,
        indentUnit: 4, // 智能缩进单位为4个空格长度
        smartIndent: true,
        readOnly: true, // 只读
        showCursorWhenSelecting: true,
        firstLineNumber: 1,

        flattenSpans: false, // 默认情况下，CodeMirror会将使用相同class的两个span合并成一个。通过设置此项为false禁用此功能
        matchBrackets: true, // 匹配符号
        lineWiseCopyCut: true, // 如果在复制或剪切时没有选择文本，那么就会自动操作光标所在的整行
        lineNumbers: true, // 显示行号
        autoCloseBrackets: true, // 自动输入括弧
        foldGutter: true, // 允许在行号位置折叠
        styleActiveLine: true // 激活当前行样式
      },
      value: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      eventList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        // start_time:Math.round((new Date().getTime())/1000 - (5*60)),
        // end_time:Math.round(new Date().getTime()/1000),
        start_time: 0,
        end_time: 0,
        app_id: '',
        alert_status: 0,
        app_name: '',
        exception_name: ''
      },
      listApps: [],
      form: {},
      menu: false,
      contextMenuData: {
        menuName: 'demo',
        // 菜单显示的位置
        axis: {
          x: null,
          y: null
        },
        // 菜单选项
        menulists: [
          {
            fnHandler: 'goRouterFn', // 事件
            btnName: '链路跳转'
          },
          {
            fnHandler: 'copyFn',
            btnName: '复制'
          }
        ]

      },
      appItem: {}
    }
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.queryParams.start_time = newValue.startTime
          this.queryParams.end_time = newValue.endTime
          this.getList()
        }
      },
      // immediate: true,
      deep: true
    }
  },
  created() {
    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.appItem = storage.get('appsItem')
    if (JSON.stringify(this.appItem) != '{}') {
      this.queryParams.app_id = this.appItem.id
      this.getListApps()
      this.getList()
    }
  },
  methods: {
    showMenu(event, item) {
      event.preventDefault()
      var x = event.clientX
      var y = event.clientY
      // 获取当前位置
      this.contextMenuData.axis = { x, y }
    },
    goRouterFn() {
    },
    copyFn() {
    },
    changeStatus(val) {
      this.queryParams.alert_status = val
      this.getList()
    },
    changeAppName(val) {
      this.queryParams.app_id = val
      this.getList()
    },
    /** 查询事件列表 */
    getList() {
      this.loading = true
      listEvent(this.queryParams).then(response => {
        if (response && response.code == 200) {
          this.eventList = response.data.list || []
          this.total = response.data.count
        } else {
          this.eventList = []
          this.total = 0
        }
        this.loading = false
      })
    },
    /** 获取所有应用列表 */
    getListApps() {
      listApps({ pageIndex: 0, pageSize: 200 }).then(res => {
        this.listApps = res.data.list
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 事件信息 */
    handleOpen(row) {
      // this.reset()
      this.open = true
      this.title = '事件信息'
      if (row.row_result == 'UNSET') {
        this.value = JSON.stringify(row.rows_result)
        this.codeSnippets = JSON.stringify(row.rows_result, null, 2)
        //  this.codeSnippets=row.rows_result
      } else {
        this.value = row.row_result
        this.codeSnippets = row.row_result
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.CodeMirror{
  font-family: monospace;
  height: 100vh;
  color: black;
  direction: ltr;
}
::v-deep .el-tooltip__popper{ max-width:50% }
.radiobox ::v-deep .el-radio__label {
  padding-left:2px;
}
.radiobox ::v-deep .el-radio{
  margin-right: 16px;
}
::v-deep .jv-item .jv-string{
 line-height: 2!important;
}
</style>
<style>
.el-tooltip__popper{ max-width:50% }
.el-tooltip__popper {
      display: -webkit-box;
      overflow: hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 15;
      -webkit-box-orient: vertical;
}
.workorder-remark {
    background-color: #000;
    color: #ffffff;
    border-color: #000;
    max-width: 50%;
    font-size: 12px;
     /* 想要显示全部，下面就不用写了 */
    padding-bottom: 4px !important;
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 15;
    -webkit-box-orient: vertical;
}

</style>

