<template>
  <div style="padding:16px;">
    <el-descriptions title="基本信息">
      <el-descriptions-item label="应用名称">{{ appsItem.name }}</el-descriptions-item>
      <el-descriptions-item label="应用别名">{{ appsItem.alias }}</el-descriptions-item>
      <el-descriptions-item label="负责部门/人">{{ appsItem.contractInfo }}</el-descriptions-item>
      <el-descriptions-item label="联系电话">{{ appsItem.contractPhone }}</el-descriptions-item>
      <el-descriptions-item label="系统描述">{{ appsItem.desc }}</el-descriptions-item>
    </el-descriptions>
    <!-- <el-descriptions title="阈值配置" direction="vertical" style="margin-top:15px;">
        <el-descriptions-item label="Apdex阈值" contentStyle='width:100%;'>
          <el-slider
            v-model="value"
            range
            :marks="marks">
          </el-slider>
        </el-descriptions-item>
    </el-descriptions> -->
    <div v-if="isLoading" v-loading="isLoading" class="loading-overlay" />
    <div v-else>
      <el-row :gutter="10" class="mb8" style="margin-top:16px;" type="flex" justify="space-between">
        <el-col :span="6">
          <span class="yewu_title" style="margin-right:10px">业务事件</span>
          <el-button
            type="primary"
            size="mini"
            @click="handleAddAll"
          >规则导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="rulesList">
        <el-table-column label="事件名称" header-align="center" align="center" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="事件别名" header-align="center" align="center" prop="monitorAlias" :show-overflow-tooltip="true" />
        <el-table-column label="事件类型" header-align="center" align="center" prop="kind" />
        <!-- <el-table-column label="值类型" header-align="center" align="center" prop="valueType">
          <template slot-scope="scope">
            <span>{{ scope.row.valueType=='row'?'数值型(row)':'列表型(rows)' }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="表达式" header-align="center" align="left" prop="expression" :show-overflow-tooltip="true" width="500">
          <template slot-scope="scope">
            <span style="cursor: pointer;" @click="handleOpen(scope.row)">{{ scope.row.expression }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数据范围(min)" header-align="center" align="center" prop="interval" />
        <el-table-column label="异常策略" header-align="center" align="center" prop="policy">
          <template slot-scope="scope">
            <span>
              <el-button
                v-if="scope.row.policy != ''"
                size="mini"
                type="text"
                @click="handleLook(scope.row)"
              >查看</el-button>
              <el-button
                v-else
                size="mini"
                type="text"
                @click="handleLook(scope.row)"
              >——</el-button>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" width="160" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!-- <el-switch
            :width="32"
            v-model="scope.row.verify"
            active-value="1"
            inactive-value="0"
            active-text="验证"
            @change="handleVerifyChange(scope.row)"
            style="margin-right:10px"
          /> -->
            <el-switch
              :value="scope.row.ap_power"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              style="margin-right:10px"
              @change="handlePowerChange(scope.row,$event)"
            />
            <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row,$event)"
          >修改</el-button> -->
            <el-button
              style="color:#F56C6C"
              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"
      />
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" :center="true" :close-on-click-modal="false">
      <el-checkbox-group
        v-model="checkList"
        @change="change"
      >
        <el-checkbox v-for="event in eventList" :key="event.id" :label="event">{{ event.name }}</el-checkbox>
      </el-checkbox-group>
      <pagination
        v-show="eventTotal>0"
        :total="eventTotal"
        :page.sync="queryParamsAll.pageIndex"
        :limit.sync="queryParamsAll.pageSize"
        @pagination="getAllList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 表达式 -->
    <el-dialog title="表达式详细信息" :visible.sync="openSelect" :center="true" width="700px" :close-on-click-modal="false">
      <div class="exercise">
        <codemirror
          v-model="codeSnippets"
          :options="cmOptions"
        />
      </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-dialog title="异常分析策略" :visible.sync="openLook" width="750px" :center="true" :close-on-click-modal="false">
      <el-form ref="lookForm" :model="lookForm" :rules="lookRules" label-width="120px">
        <el-form-item label="匹配值" prop="policy.point">
          <el-input v-model="lookForm.policy.point" placeholder="请输入匹配值" />
        </el-form-item>
        <el-form-item label="匹配条件" prop="policy.condition">
          <el-select v-model="lookForm.policy.condition" placeholder="请选择">
            <el-option
              v-for="dict in conditOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="值类型" prop="policy.point_type">
          <el-select v-model="lookForm.policy.point_type" placeholder="请选择">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="触发周期" prop="policy.interval">
          <el-input v-model.number="lookForm.policy.interval">
            <template slot="append">Min</template>
          </el-input>
        </el-form-item>
        <el-form-item label="周期内频率" prop="policy.tigger_hz">
          <el-input v-model.number="lookForm.policy.tigger_hz" placeholder="请输入内容">
            <template slot="append"> 次 </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormLook">确 定</el-button>
        <el-button @click="cancelLook">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listRules, getRules, updateRules } from '@/api/monitor-rules'
import { addPolicy, updatePolicy, delPolicy, importPolicy } from '@/api/alert-policy'
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/addon/hint/show-hint')
require('codemirror/addon/hint/sql-hint')

export default {
  data() {
    return {
      isLoading: false,
      // 新增弹窗里面的列表
      eventList: [],
      eventTotal: [],
      // 选中的，只能选一个
      checkList: [],
      queryParamsAll: {
        pageIndex: 1,
        pageSize: 10,
        appId: 999999
      },
      value: [30, 60],
      marks: {
        0: '0',
        8: '8',
        37: '37',
        50: {
          style: {
            color: '#1989FA'
          },
          label: this.$createElement('strong', '50%')
        }
      },
      // 查看
      openLook: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      rulesList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      openSelect: false,
      titleSelect: '',
      value: '',
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        appId: 0,
        start_time: 0,
        end_time: 0
      },
      // 表单参数
      form: {
        id: undefined,
        kind: '',
        group: '',
        name: '',
        monitorAlias: '',
        dataSource: '',
        table: '',
        valueType: '',
        expression: '',
        interval: 0,
        verify: 0,
        power: 0
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '事件名称不能为空', trigger: 'blur' }
        ],
        kind: [
          { required: true, message: '事件类型不能为空', trigger: 'change' }
        ],
        group: [
          { required: true, message: '事件组不能为空', trigger: 'blur' },
          { pattern: /^[A-z]*$/, message: '填写英文', trigger: ['blur'] }
        ],
        dataSource: [
          { required: true, message: '事件名称不能为空', trigger: 'blur' }
        ],
        valueType: [
          { required: true, message: '事件类型不能为空', trigger: 'change' }
        ],
        table: [
          { pattern: /^[A-z]*$/, message: '填写英文', trigger: ['blur'] }
        ],
        interval: [
          { required: true, message: '事件名称不能为空', trigger: 'blur' },
          { type: 'number', message: '填写数值', trigger: 'blur' }
        ],
        monitorAlias: [
          { required: true, message: '事件类型不能为空', trigger: 'change' }
        ],
        expression: [
          { required: true, message: '事件类型不能为空', trigger: 'change' }
        ]
      },
      codeSnippets: '',
      cmOptions: {
        autorefresh: true,
        tabSize: 4,
        mode: 'text/x-sql',
        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 // 激活当前行样式
      },
      lookForm: {
        appId: 0,
        ruleId: undefined,
        monitorAlias: '',
        policy: {
          condition: '',
          point: undefined,
          point_type: '',
          tigger_hz: 0,
          interval: 0
        },
        policyId: 0,
        power: 0
      },
      lookRules: {
        'policy.point': [
          { required: true, message: '匹配值不能为空', trigger: 'blur' }
        ],
        'policy.condition': [
          { required: true, message: '匹配条件不能为空', trigger: 'blur' }
        ],
        'policy.point_type': [
          { required: true, message: '值类型不能为空', trigger: 'blur' }
        ],
        'policy.tigger_hz': [
          { required: true, message: '周期内频次不能为空', trigger: 'blur' },
          { type: 'number', message: '必须为数值', trigger: 'blur' }
        ],
        'policy.interval': [
          { required: true, message: '触发周期不能为空', trigger: 'blur' },
          { type: 'number', message: '必须为数值', trigger: 'blur' }
        ]
      },
      lookFlag: false,
      // 条件下拉框
      conditOptions: [
        {
          label: '>',
          value: '>'
        },
        {
          label: '<',
          value: '<'
        },
        {
          label: '=',
          value: '='
        },
        {
          label: '!=',
          value: '!='
        },
        {
          label: '>=',
          value: '>='
        },
        {
          label: '<=',
          value: '<='
        }
      ],
      // 值类型下拉框
      typeOptions: [
        {
          label: 'int',
          value: 'int'
        },
        {
          label: 'float',
          value: 'float'
        },
        {
          label: 'string',
          value: 'string'
        }
      ],
      // 事件类型下拉框
      eventOptions: [
        {
          label: 'trace',
          value: 'trace'
        }
      ],
      // source数据源下拉框
      sourceOptions: [
        {
          label: 'clickhouse',
          value: 'clickhouse'
        }
      ],
      // Analysis分析类型下拉框
      analystOptions: [
        {
          label: '数值型(row)',
          value: 'row'
        },
        {
          label: '列表型(rows)',
          value: 'rows'
        }
      ],
      appsItem: {},
      appId: 0
    }
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.queryParams.start_time = newValue.startTime
          this.queryParams.end_time = newValue.endTime
          this.getList()
        }
      },
      deep: true
    }
  },
  created() {
    this.appsItem = storage.get('appsItem')
    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
    if (JSON.stringify(this.appsItem) != '{}') {
      this.queryParams.appId = Number(this.appsItem.id)
      this.lookForm.appId = Number(this.appsItem.id)
      this.appId = Number(this.appsItem.id)
      this.getList()
    }
    this.getAllList()
  },
  methods: {
    handleAddAll() {
      this.isLoading = true
      importPolicy({ appId: this.appId }).then((res) => {
        if (res.code == 200) {
          this.msgSuccess(res.msg)
          this.isLoading = false
          this.getList()
          //  location.reload()
        }
      })
    },
    // 启用
    handlePowerChange(row, val) {
      this.lookForm.ruleId = row.id
      this.lookForm.power = val
      this.lookForm.policyId = row.policy_id
      this.lookForm.monitorAlias = row.monitorAlias
      if (row.policy != '') {
        this.lookForm.policy = JSON.stringify(JSON.parse(row.policy))
      } else {
        this.lookForm.policy = ''
      }
      if (this.lookForm.policy === '' && val === 1) {
        this.msgError('请先添加检测策略再启用')
      } else {
        updatePolicy(this.lookForm, row.policy_id).then(response => {
          if (response.code === 200) {
            this.msgSuccess(response.msg)
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
      }

      // const text = row.power === 1 ? '启用' : '停用'
      // this.$confirm('确认要"' + text + '""' + row.name + '"吗?', '警告', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(function() {
      //   return updatePolicy(row,row.id)
      // }).then(() => {
      //   this.msgSuccess(text + '成功')
      // }).catch(function() {
      //   row.power = row.power === 1 ? 0 : 1
      // })
    },
    // 验证
    handleVerifyChange(row, val) {
      row.verify = val
      row.createdAt = 0
      row.updatedAt = 0
      updateRules(row, row.id).then(response => {
        if (response.code === 200) {
          this.msgSuccess(response.msg)
          this.getList()
        } else {
          this.msgError(response.msg)
        }
      })
    },
    handleOpen(row) {
      this.reset()
      this.openSelect = true
      this.titleSelect = '表达式'
      this.codeSnippets = row.expression
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      listRules(this.queryParams).then(response => {
        this.rulesList = response.data.list || []
        this.total = response.data.count || 0
        this.loading = false
      })
    },
    getAllList() {
      this.loading = true
      listRules(this.queryParamsAll).then(response => {
        this.eventList = response.data.list
        this.eventTotal = response.data.count
        this.loading = false
      })
    },
    // 岗位状态字典翻译
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.openSelect = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        kind: '',
        group: '',
        name: '',
        monitorAlias: '',
        dataSource: '',
        table: '',
        valueType: '',
        expression: '',
        interval: 0,
        verify: 0,
        power: 0
      }
      this.resetForm('form')
    },
    resetLook() {
      this.lookForm = {
        appId: this.appsItem.id,
        ruleId: undefined,
        monitorAlias: '',
        policy: {
          condition: '',
          point: undefined,
          point_type: '',
          tigger_hz: 0,
          interval: 0
        },
        power: 0
      }
      this.resetForm('lookForm')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增事件'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      getRules(row.id).then(response => {
        this.form = response.data
        // this.form.status = String(this.form.status)
        this.open = true
        this.title = '修改事件'
      })
    },
    handleLook(row) {
      if (row.policy_id != 0) {
        this.lookFlag = true
        this.lookForm.ruleId = row.id
        this.lookForm.policyId = row.policy_id
        this.lookForm.power = 0
        this.lookForm.monitorAlias = row.monitorAlias
        if (row.policy != '') {
          this.lookForm.policy = JSON.parse(row.policy)
        }
      } else {
        this.lookFlag = false
        this.lookForm.ruleId = row.id
      }

      this.openLook = true
    },
    // 取消按钮
    cancelLook() {
      this.openLook = false
      this.resetLook()
    },
    /** 提交按钮 */
    submitFormLook: function() {
      this.$refs['lookForm'].validate(valid => {
        if (valid) {
          if (this.lookForm.policy.point_type != 'string') {
            this.lookForm.policy.point = Number(this.lookForm.policy.point)
          }
          this.lookForm.policy = JSON.stringify(this.lookForm.policy)
          // this.lookForm.power = String(this.lookForm.power)
          if (this.lookFlag == true) {
            updatePolicy(this.lookForm, this.lookForm.policyId).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.openLook = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addPolicy(this.lookForm).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.openLook = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    change(val) {
      if (this.checkList.length > 1) {
        this.checkList.splice(0, 1)
      }
      this.lookForm.ruleId = this.checkList[0].id
      this.lookForm.monitorAlias = this.checkList[0].monitorAlias
      this.lookForm.policy = this.checkList[0].policy
    },
    /** 提交按钮 */
    submitForm: function() {
      // this.lookForm.ruleId = ''
      // this.lookForm.monitorAlias = ''
      // this.lookForm.policy = ''
      // this.checkList.forEach(item => {
      //   this.lookForm.ruleId = this.lookForm.ruleId === '' ? item.id : this.lookForm.ruleId + ',' + item.id
      //   this.lookForm.monitorAlias = this.lookForm.monitorAlias === '' ? item.monitorAlias : this.lookForm.monitorAlias + ',' + item.monitorAlias
      //   this.lookForm.policy = this.lookForm.policy === '' ? item.policy : this.lookForm.policy + ',' + item.policy
      // })
      addPolicy(this.lookForm).then(response => {
        if (response.code === 200) {
          this.msgSuccess(response.msg)
          this.open = false
          this.getList()
        } else {
          this.msgError(response.msg)
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = [row.policy_id]
      this.$confirm('是否确认删除事件编号为"' + Ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delPolicy({ 'ids': Ids })
      }).then((response) => {
        if (response.code === 200) {
          this.msgSuccess(response.msg)
          this.open = false
          this.getList()
        } else {
          this.msgError(response.msg)
        }
      }).catch(function() {})
    }
  }
}
</script>

<style lang="scss" scoped>
.flex{
  display: flex;
  justify-content: space-between;
  padding:8px 12px;
  box-sizing: border-box;
  border-bottom: 1px solid #f1f1f1;
}
::v-deep .el-descriptions__header{
  margin-bottom: 0;
}
::v-deep .el-descriptions__title{
    margin-top: 0px;
    margin-bottom: 16px;
    font-size: 16px;
    line-height: 1.5;
    color:#1d2129;
    font-weight: 500;
    word-break: break-all;
}
::v-deep .el-descriptions__body{
  padding:24px;
  background: rgb(247,248,250);
}
::v-deep .el-descriptions-item__label,::v-deep .el-descriptions-item__cell{
    padding: 0 10px 12px 0;
    box-sizing: border-box;
    font-size: 14px;
    line-height: 1.5715;
    color: #86909c;
    font-weight: 500;
    white-space: nowrap;
}
::v-deep .el-descriptions-item__content{
    padding: 0 4px 12px 0;
    box-sizing: border-box;
    font-size: 14px;
    line-height: 1.5715;
    font-weight: 400;
    color:#1d2129;
}

.CodeMirror{
  font-family: monospace;
  height: 100vh;
  color: black;
  direction: ltr;
}
::v-deep .el-tooltip__popper{ max-width:50% }
::v-deep .el-switch__label {
  font-size: 12px!important;
  font-weight: normal!important;
  height: 16px;
  line-height: 16px;
}

::v-deep .el-switch__label--right {
    margin-left: 2px;
}
::v-deep .el-button--mini{
  font-size: 14px;
  font-weight: bold;
}

::v-deep .el-checkbox {
    width: 45%;
    margin-bottom: 16px;
}
.yewu_title{
    margin-top: 0px;
    margin-bottom: 16px;
    font-size: 16px;
    line-height: 1.5;
    color: #1d2129;
    font-weight: 500;
    word-break: break-all;
    // margin-left:5px;
}
</style>
<style>
.el-tooltip__popper{ max-width:50% }
</style>
