<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="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">
            <codemirror ref="editQuerySQL" v-model="sqlMonitorForm.sql" :options="cmOptions"></codemirror>
          </div>
        </el-form-item>
        <el-form-item style="margin-left:1000px">
          <el-button type="primary" icon="el-icon-caret-right" @click="executeSqlBtn">执行</el-button>
          <el-button type="primary" icon="el-icon-message-solid" @click="setPoliceBtn">设置报警</el-button>
        </el-form-item>
        <el-form-item style="margin-left:-80px">
          <!-- 动态绑定表格数据 -->
          <el-table :data="sqlList" border style="font-size:8px;"
            :header-cell-style="{background:'#eee',color:'#606266'}" v-if="isShow">
            <af-table-column v-for="(val, key) in columnArr" :label="val" :prop="val" :key="key" class="table-dynamic">
            </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="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="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="sqlMonitorForm.dingText" placeholder="可以使用表达式{0},{1}...表示取结果集的第N列值,使用{count}表示取数据总条数"
            type="textarea" :rows="3">
          </el-input>
        </el-form-item>
        <el-form-item label="是否启用:">
          <el-select v-model="sqlMonitorForm.status" placeholder="请选择是否启用" style="width:310px">
            <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
} 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: 4,
        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: this.getUserName
      },
      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'
          }
        ]
      },
      tableWidth: ''
    }
  },
  watch: {
    tableWidth: 'getTableWidth'
  },
  // 接收列表页面传递的参数
  activated() {
    var data = this.$route.query.data
    // console.log('rrr', data)
    if (data === 'add') {
      this.sqlMonitorForm = {}
      this.sqlMonitorForm.status = 1
    } else {
      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
    }
  },
  created() {
    this.getSqlMonitorDataSource()
  },
  mounted() {
    var editor = this.$refs.editQuerySQL.codemirror
    editor.on('cursorActivity', function () {
      editor.showHint()
    })
  },
  methods: {
    getTableWidth() {
      for (let i = 0; i < document.getElementsByClassName('table-dynamic').length; i++) {
        var item = document.getElementsByClassName('table-dynamic')[i]
        console.log(item)
      }
    },
    // 获取数据源列表
    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() {
      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
        console.log('ww', this.taskCronList)
      })
    },
    // 获取服务列表
    getServiceList() {
      getGitProjectList().then((resp) => {
        this.serviceList = resp.data.data
      })
    },
    // 保存按钮
    saveSqlMonitorFrom() {
      this.sqlMonitorForm.owner = this.getUserName
      this.sqlMonitorForm.taskClass = 'SqlMonitorHandler'
      // 编辑接口
      if (this.sqlMonitorForm.id) {
        editSqlMonitor(this.sqlMonitorForm).then((resp) => {
          if (resp.data.businessCode === '0000') {
            this.$message.success('编辑成功！')
            this.$router.push({
              path: `/monitor/sqlMonitorList`,
              query: { data: 'refresh' }
            })
          } else {
            return this.$message.error(resp.data.msg)
          }
        })
      } else {
        // 添加接口
        addSqlMonitor(this.sqlMonitorForm).then((resp) => {
          if (resp.data.businessCode === '0000') {
            this.$message.success('添加成功！')
            this.$router.push({
              path: `/monitor/sqlMonitorList`,
              query: { data: 'refresh' }
            })
          } else {
            return this.$message.error(resp.data.msg)
          }
        })
      }
      // 添加接口
    }
  }
}
</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>
