<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="margin-top:10px">
        <el-row :gutter="10" class="mb8">
          <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="kind" width="100" />
          <el-table-column label="值类型" header-align="center" align="center" prop="valueType" width="100">
             <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">
            <template slot-scope="scope">
              <span @click="handleOpen(scope.row)" style="cursor: pointer;">{{scope.row.expression}}</span>
            </template>
          </el-table-column>
          <el-table-column label="数据范围(min)" header-align="center" align="center" prop="interval" width='120'/>
          <el-table-column label="异常策略" header-align="center" align="center" prop="policy" width="100">
            <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="280" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-switch
                :value="scope.row.verify"
                :active-value="1"
                :inactive-value="0"
                active-text="验证"
                @change="handleVerifyChange(scope.row,$event)"
                style="margin-right:10px"
              />
              <el-switch
                :value="scope.row.power"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                @change="handlePowerChange(scope.row,$event)"
                style="margin-right:10px"
              />
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</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"
        />

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" :center='true' :close-on-click-modal="false">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="事件名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入事件名称" />
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="事件类型" prop="kind">
                  <el-select v-model="form.kind" placeholder="请选择">
                      <el-option
                        v-for="dict in eventOptions"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="事件组" prop="group">
                  <el-input v-model="form.group" />
                </el-form-item>
               </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="数据源" prop="dataSource">
                  <el-select v-model="form.dataSource" placeholder="请选择">
                      <el-option
                        v-for="dict in sourceOptions"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="源表名" prop="table">
                  <el-input v-model="form.table" placeholder="请输入事件名称" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                 <el-form-item label="分析类型" prop="valueType">
                    <el-select v-model="form.valueType" placeholder="请选择">
                        <el-option
                          v-for="dict in analystOptions"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                    </el-select>
                  </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="数据范围" prop="interval">
                  <el-input v-model.number="form.interval">
                    <template slot="append"> Min </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="规则别名" prop="monitorAlias">
              <el-input v-model="form.monitorAlias">
                <template slot="prepend">{{form.group}}::</template>
                <template slot="append"> :{{form.interval}}m </template>
              </el-input>
            </el-form-item>
            <el-form-item label="表达式" prop="expression" style="margin-bottom:0">
              <el-input v-model="form.expression" type="textarea" placeholder="请输入内容" :autosize="{ minRows: 10, maxRows: 20}">
              </el-input>
              <!-- <div style="color:#999">{{str}}</div> -->
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer" style="padding-top:0">
            <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>


      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import { listRules, getRules, addRules, updateRules,delRules} from '@/api/monitor-rules'
import { listPolicy, getPolicy, addPolicy, updatePolicy,delPolicy } from '@/api/alert-policy'
import { formatJson } from '@/utils'


// 编辑器代码格式
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 {
  name: 'policy',
  data() {
    return {
      //查看
      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:999999
      },
      // 表单参数
      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: 999999,
        ruleId: undefined,
        monitorAlias: "",
        policy: {
          condition:"",
          point:undefined,
          point_type:"",
          tigger_hz:0,
          interval:0,
        },
        power: 0,
        policyId : 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"
        },
      ],
      str:'AND Timestamp >= now() - INTERVAL ? MINUTE AND AppAlias =  ?'
    }
  },
  created() {
    this.$store.commit('time/setTimeFlag',true)
    this.getList()
  },
  methods: {
    //启用
    handlePowerChange(row,val){
      row.createdAt=0
      row.updatedAt=0
      row.power = val

      updateRules(row, row.id).then(response => {
        if (response.code === 200) {
          this.msgSuccess(response.msg)
          this.getList()
        } else {
          this.msgError(response.msg)
        }
      })
    },
    //验证
    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;
      // this.codeSnippets=JSON.stringify(row.expression, null, 2)
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      listRules(this.queryParams).then(response => {
        this.rulesList = response.data.list
        this.total = response.data.count
        this.loading = false
      })
    },
    // 取消按钮
    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: 999999,
        ruleId: undefined,
        monitorAlias: "",
        policy: {
          condition:"",
          point:'',
          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
        let monitorAlias = response.data.monitorAlias.substr(response.data.monitorAlias.indexOf("::")+2, response.data.monitorAlias.length);
        let alias = monitorAlias.substr(0,monitorAlias.indexOf(":"));
        this.form.monitorAlias = alias;
        if(response.data.expression.indexOf(this.str) != -1){
          let expression=response.data.expression.substr(0,response.data.expression.indexOf(this.str));
          this.form.expression = expression;
        }
        this.open = true
        this.title = '修改事件'
      })
    },
    handleLook(row){
      if(row.policy_id != 0){
        // 注意这个位置，判断是否存在policy需要使用policy_id,因为可能绑定过，
        // 但是没有输入policy，在业务内比较常见，此处在页面操作一般不会出现这个问题，做一个容错处理。
        this.lookFlag=true;
        this.lookForm.appId=999999;
        this.lookForm.ruleId = row.id;
        this.lookForm.power =0;
        this.lookForm.policyId = row.policy_id;
        this.lookForm.monitorAlias= row.monitorAlias;
        if (row.policy != '') {
          this.lookForm.policy= JSON.parse(row.policy);
        }
      }else{
        //不存在policy_id，新增policy
        this.lookFlag=false;
        this.lookForm.ruleId = row.id;
        this.lookForm.monitorAlias= row.monitorAlias;
      }

      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 {

            // this.lookForm.policy = JSON.stringify(this.lookForm.policy)
            addPolicy(this.lookForm).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.openLook = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.monitorAlias= this.form.group+'::'+this.form.monitorAlias+':'+this.form.interval+'m'
          // this.form.expression= this.form.expression+' AND Timestamp >= now() - INTERVAL ? MINUTE AND AppAlias = ?'
          this.form.createdAt=0
          this.form.updatedAt=0
          if (this.form.id !== undefined) {
            updateRules(this.form, this.form.id).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addRules(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // const postIds = row.postId || this.ids
      const Ids = [row.id]
      this.$confirm('是否确认删除事件编号为"' + Ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delRules({ '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>
.CodeMirror{
  font-family: monospace;
  height: 100vh;
  color: black;
  direction: ltr;
}
::v-deep .el-dialog__footer{
  padding-top:0;
}
::v-deep .el-tooltip__popper{ max-width:50% }
::v-deep .el-switch__label {
  font-size: 12px!important;
}

::v-deep .el-switch__label--right {
    margin-left: 2px;
}
::v-deep .el-button--mini{
  font-size: 14px;
  font-weight: bold;
}
</style>
<style>
.el-tooltip__popper{ max-width:50% }
</style>
