<template>
  <div>
    <el-card>
      <el-form ref="sqlMonitorFormRef" :rules="rules" :model="sqlMonitorForm" label-width="90px">
        <el-form-item label="监控名称:" style="width:400px" prop="taskName">
          <el-input v-model.trim="sqlMonitorForm.taskName" placeholder="请输入监控名称"></el-input>
        </el-form-item>
        <el-form-item label="数据源:" prop="dsId">
          <el-select v-model="sqlMonitorForm.dsId" placeholder="请选择数据源" style="width:310px" clearable>
            <el-option v-for="item in dataSourceList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="SQL脚本:" prop="sql">
          <div style="border:1.5px solid #DCDCDC;width:90%;">
            <codemirror ref="editQuerySQL" v-model.trim="sqlMonitorForm.sql" :options="cmOptions" @focus="testFoucs">
            </codemirror>
          </div>
        </el-form-item>
        <el-form-item style="margin-left:1000px">
          <el-button type="primary" size="mini" icon="el-icon-caret-right" @click="executeSqlBtn">执行</el-button>
          <el-button type="primary" size="mini" icon="el-icon-message-solid" @click="setPoliceBtn">设置报警</el-button>
        </el-form-item>
        <el-form-item style="margin-left:-80px">
          <!-- 动态绑定表格数据 -->
          <el-table id="tabId" :data="sqlList" border style="font-size:8px;"
            :header-cell-style="{background:'#eee',color:'#606266'}" v-if="isShow" ref="tabRef">
            <af-table-column v-for="(val, key) in columnArr" :label="val" :prop="val" :key="key">
            </af-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 设置报警页面 -->
    <el-dialog title="报警策略" :visible.sync="DialogVisible" width="50%">
      <el-form ref="sqlMonitorFormRef" :rules="rules" :model="sqlMonitorForm" label-width="90px">
        <el-form-item label="服务名称:" prop="serviceName">
          <el-select v-model.trim="sqlMonitorForm.serviceName" placeholder="请选择服务名称" style="width:310px" filterable
            clearable>
            <el-option v-for="item in serviceList" :key="item.name" :label="item.name" :value="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="执行策略:" prop="taskCron">
          <el-select v-model="sqlMonitorForm.taskCron" placeholder="请选择策略" style="width:310px" clearable>
            <el-option v-for="item in taskCronList" :key="item.value" :value="item.value" :label="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="钉钉地址:" style="width:800px" prop="dingUrl">
          <el-input v-model.trim="sqlMonitorForm.dingUrl" placeholder="请输入钉钉通知地址" type="textarea" :rows="3">
          </el-input>
        </el-form-item>
        <el-form-item label="消息内容:" style="width:800px" prop="dingText">
          <el-input v-model.trim="sqlMonitorForm.dingText"
            placeholder="可以使用表达式{0},{1}...表示取结果集的第一行第N列值,使用{count}表示取数据总条数" type="textarea" :rows="3">
          </el-input>
        </el-form-item>
        <el-form-item label="负责人:" style="width:300px" prop="owner">
          <el-input v-model="sqlMonitorForm.owner" placeholder="请输入负责人"></el-input>
        </el-form-item>
        <el-form-item label="是否启用:">
          <el-select v-model="sqlMonitorForm.status" placeholder="请选择是否启用" style="width:210px">
            <el-option v-for="item in enableList" :label="item.lable" :key="item.value" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="DialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="sendTest">发送测试</el-button>
        <el-button type="primary" @click="saveSqlMonitorFrom">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getSqlMonitorData,
  executeSqlMonitor,
  getMonitorStrategy,
  sendTestSqlMonitor,
  addSqlMonitor,
  editSqlMonitor,
  getDetailSqlMonitor
} from '@/api/sqlMonitor'
import { getGitProjectList } from '@/api/jira'
import { mapGetters } from 'vuex'
// 编辑器引用
import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/idea.css'
import 'codemirror/theme/panda-syntax.css'
import 'codemirror/addon/hint/show-hint.css'
require('codemirror/lib/codemirror')
require('codemirror/mode/sql/sql')
require('codemirror/addon/hint/show-hint')
require('codemirror/addon/hint/sql-hint')

export default {
  components: { codemirror },
  name: 'codeMirror',
  computed: {
    ...mapGetters({
      // 获取用户名称(可当作全局变量使用)
      getUserName: 'user/chineseName'
    }),
    // 设置编辑器
    codemirror() {
      return this.$refs.editQuerySQL.codemirror
    }
  },
  data() {
    return {
      cmOptions: {
        tabSize: 6,
        lineNumbers: true,
        line: true,
        indentWithTabs: true,
        smartIndent: true,
        autofocus: false,
        mode: 'text/x-mysql',
        theme: 'idea',
        hintOptions: {
          completeSingle: false
        }
      },
      isShow: false,
      sqlMonitorForm: {
        id: '',
        taskName: '',
        taskCron: '',
        sql: '',
        dsId: '',
        dingUrl: '',
        dingText: '',
        status: 1,
        serviceName: '',
        owner: ''
      },
      dataSourceList: [],
      sqlList: [],
      DialogVisible: false,
      columnArr: [],
      taskCronList: [],
      serviceList: [],
      enableList: [
        {
          lable: '启用',
          value: 1
        },
        {
          lable: '禁用',
          value: 0
        }
      ],
      rules: {
        taskName: [
          {
            required: true,
            message: '监控名称不能为空！',
            trigger: 'blur'
          }
        ],
        dsId: [
          {
            required: true,
            message: '数据源不能为空！',
            trigger: 'blur'
          }
        ],
        sql: [
          {
            required: true,
            message: 'sql脚本不能为空！',
            trigger: 'blur'
          }
        ],
        serviceName: [
          {
            required: true,
            message: '服务名称不能为空！',
            trigger: 'blur'
          }
        ],
        taskCron: [
          {
            required: true,
            message: '执行策略不能为空！',
            trigger: 'blur'
          }
        ],
        dingUrl: [
          {
            required: true,
            message: '钉钉地址不能为空！',
            trigger: 'blur'
          }
        ],
        dingText: [
          {
            required: true,
            message: '消息内容不能为空！',
            trigger: 'blur'
          }
        ],
        owner: [
          {
            required: true,
            message: '负责人不能为空！',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  // 接收列表页面传递的参数，赋值到编辑页面中
  activated() {
    this.DialogVisible = false
    var id = this.$route.query.id
    getDetailSqlMonitor({ id: id }).then((resp) => {
      if (resp.data.businessCode === '0000') {
        var data = resp.data.data
        this.isShow = false
        this.sqlMonitorForm.id = data.id
        this.sqlMonitorForm.dingText = data.dingText
        this.sqlMonitorForm.dingUrl = data.dingUrl
        this.sqlMonitorForm.dsId = data.dsId
        this.sqlMonitorForm.serviceName = data.serviceName
        this.sqlMonitorForm.sql = data.sql
        this.sqlMonitorForm.status = data.status
        this.sqlMonitorForm.taskCron = data.taskCron
        this.sqlMonitorForm.taskName = data.taskName
        this.sqlMonitorForm.owner = data.owner
      }
    })
  },
  created() {
    this.getSqlMonitorDataSource()
    this.$bus.$on('data', (row) => {
      if (row !== null) {
        if (row === 'add') {
          // console.log('rrr')
          // 整体页面刷新
          // location.reload()
          this.isShow = false
          this.sqlMonitorForm = {}
          // this.sqlMonitorForm.owner = ''
          // this.sqlMonitorForm.status = 1
          this.sqlMonitorForm.sql = ''
        }
      }
    })
  },
  methods: {
    testFoucs() {
      var editor = this.$refs.editQuerySQL.codemirror
      editor.on('inputRead', function () {
        editor.showHint()
      })
    },
    // 获取数据源列表
    getSqlMonitorDataSource() {
      getSqlMonitorData().then((resp) => {
        this.dataSourceList = resp.data.data
      })
    },
    // 执行sqla按钮
    executeSqlBtn() {
      var formData = new FormData()
      formData.set('dsId', this.sqlMonitorForm.dsId)
      formData.set('sql', this.sqlMonitorForm.sql)
      if (this.sqlMonitorForm.dsId === undefined) {
        return this.$message.error('请选择数据源！')
      }
      executeSqlMonitor(formData).then((resp) => {
        if (resp.data.businessCode === '0000') {
          var data = resp.data.data
          // 给表格绑定数据源
          this.sqlList = data
          if (data !== null) {
            if (data.length) {
              this.isShow = true
              // 获取表格第一行数据
              const row = data[0]
              const columnArr = []
              // 循环获取第一行的表头数据
              for (let i in row) {
                columnArr.push(i)
              }
              this.columnArr = columnArr
            } else {
              return this.$message.error('没有查询到任何数据！')
            }
          } else {
            return this.$message.error('没有查询到任何数据！')
          }
        } else {
          return this.$message.error(resp.data.msg)
        }
      })
    },
    // 点击设置报警按钮
    setPoliceBtn() {
      this.DialogVisible = true
      this.getMonitorStrategy()
      this.getServiceList()
    },
    // 发送测试按钮
    sendTest() {
      this.sqlMonitorForm.dingUrl.replace('\\n', '')
      sendTestSqlMonitor(this.sqlMonitorForm).then((resp) => {
        if (resp.data.businessCode === '0000') {
          return this.$message.success(resp.data.msg)
        } else {
          return this.$message.error(resp.data.msg)
        }
      })
    },
    // 获取执行策略列表
    getMonitorStrategy() {
      getMonitorStrategy().then((resp) => {
        this.taskCronList = resp.data.data
      })
    },
    // 获取服务列表
    getServiceList() {
      getGitProjectList().then((resp) => {
        this.serviceList = resp.data.data
      })
    },
    // 保存按钮
    saveSqlMonitorFrom() {
      this.sqlMonitorForm.taskClass = 'SqlMonitorHandler'
      // 将换行符转化为空
      this.sqlMonitorForm.dingUrl.replace('\\n', '')
      this.$refs.sqlMonitorFormRef.validate((valid) => {
        if (!valid) {
          return false
        } else {
          // 编辑接口
          if (this.sqlMonitorForm.id) {
            editSqlMonitor(this.sqlMonitorForm).then((resp) => {
              if (resp.data.businessCode === '0000') {
                this.$message.success('编辑成功！')
                this.DialogVisible = false
                this.$router.push({
                  path: `/monitor/sqlMonitorList`
                })
                this.sendResh()
              } else {
                return this.$message.error(resp.data.msg)
              }
            })
          } else {
            // 添加接口
            addSqlMonitor(this.sqlMonitorForm).then((resp) => {
              if (resp.data.businessCode === '0000') {
                this.$message.success('添加成功！')
                this.DialogVisible = false
                this.$router.push({
                  path: `/monitor/sqlMonitorList`
                })
                this.sendResh()
              } else {
                return this.$message.error(resp.data.msg)
              }
            })
          }
        }
      })
    },
    // 刷新列表
    sendResh() {
      // bus使用
      this.$nextTick(function () {
        // DOM 现在更新了
        this.$bus.$emit('refresh')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.codesql {
  font-size: 11pt;
  font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono,
    DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
}
</style>
