<template>
  <div class="alarmRules">
    <bread-crumb :bread-crumb-list="breadCrumbList"></bread-crumb>
    <div class="tableCon" ref="tableDataRef">
      <div class="tableTop" ref="tableTopRef">
        <el-button type="info" size="small" @click="addRules">添加规则</el-button>
        <el-button type="danger" size="small" @click="deletePart">批量删除规则</el-button>
      </div>
      <!-- 表格 -->  
      <table-form 
        v-loading.body="isLoadingTableData" 
        :selectionIsChear="isChecked"
        :colData="colData" 
        :data="tableData"    
        :row-key="rowKey" 
        :max-height="height" 
        :submiting="submiting" 
        :isShowOper="isShowOper" 
        border 
        :stripe="true"
        :sortable="sortable" 
        @selection-change="handleSelectChange"     
        @clear-selection="handleClearSelection"
        :row-class-name="tableRowClassName">
        <el-table-column 
          v-if="reserveSelection" 
          :reserve-selection="reserveSelection" 
          type="selection" 
          width="35">
        </el-table-column>
        <el-table-column 
          v-for="item in colData"       
          :key="item.prop" 
          :prop="item.prop" 
          :label="item.label" 
          :width="item.width" 
          :align="item.align"
          :sortable="item.sortable || sortable">    
          <template slot-scope="scope">
            <div v-if="item.prop === 'rulestatus'">          
              <el-button style="display:inline-block;margin-left:4px;"
                size="mini"            
                plain                 
                @click="handleStart($event, scope.row)">
                {{ scope.row.rulestatus === '01' ? '禁用': '启用' }}
              </el-button>
            </div>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <!-- :disabled="scope.row.rulestatus !== '01'"  当要求在禁用时不能修改可以加这条语句    -->
        <el-table-column slot="fixedColumn" label="操作" fixed="right" width="330" align="center" >
           <template slot-scope="scope">             
           <el-button style="display:inline-block;margin-left:4px;"
              size="mini"
              plain
              @click="handleDetail($event, scope.row)">
              查看
            </el-button>          
            <el-button style="display:inline-block;margin-left:4px;"
              size="mini"
              plain               
              @click="handleEdit($event, scope.row)">
              修改
            </el-button>          
            <el-button style="display:inline-block;margin-left:4px;"
              size="mini"            
              plain
              @click="handleHistory($event, scope.row)">
              报警历史
            </el-button>        
            <el-popover style="display:inline-block;margin-left:2px;"
                ref="popover"
                trigger="click"
                placement="top"
                width="160"
                v-model="scope.row.visible">
                <p style="font-size:14px;padding: 6px 0;">确定删除吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" @click="scope.row.visible = false">取消</el-button>
                  <el-button type="primary" size="mini" :loading="submiting" @click="handleDelete(scope.row, scope.$index)">确定</el-button>
                </div>         
                <div slot="reference">
                  <el-button
                    size="mini"
                    type="danger"
                    plain                 
                    @click.stop.prevent="scope.row.visible = true">
                    删除
                  </el-button>
                </div>
              </el-popover>
            </template>
        </el-table-column>
      </table-form>   
      <!-- 分页 -->
      <el-row type="flex" justify="end" class="tableBottom">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange" 
          :current-page="currentPage" 
          :page-sizes="pageSizes" 
          :page-size="pageSize" 
          layout="total, sizes, prev, pager, next, jumper" 
          :total="total">
        </el-pagination>
      </el-row>
      </div> 
      <!--  创建规则 -->
      <add-rules-dialog
        v-if="addRulesOnoff" 
        :dialog-form-visible="addRulesOnoff"
        :rule-title="title"
        :row-edit-onoff="rowOnoff"
        :is-click-on-modal="isClickOnModal"
        :rule-form-data="ruleData"
        :is-read="isRead"
        :is-readonly="isReadonly"
        @dialog-sure="sureRegister"
        @dialog-cancel="closeHanlder">
      </add-rules-dialog>      
      <!-- 删除规则 -->
      <el-dialog title="信息" 
        :visible.sync="deleteRuleDialog" 
        top="10%" 
        width="400px">
        <span>是否删除所选中的规则</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteRuleDialog = false">取 消</el-button>
          <el-button type="primary" @click="sureRuleDelete">确 定</el-button>
        </span>
      </el-dialog>
 </div>
  
</template>
<script>
import BreadCrumb from '@/components/BreadCrumb.vue'
import TableForm from '@/components/Table.vue'
import AddRulesDialog from './otherComponent/AddRulesDialog.vue'

import Api from '@/api/index.js'

export default {
  name: 'AlarmRules',
  components: {
    BreadCrumb,
    TableForm,
    AddRulesDialog
  },
  data () {
    return {
      text: true,
      hostid: '',
      dialogLoading: false,
      breadCrumbList: [], // 面包屑
      /* -- 表格数据 -- */
      isQuery: false,
      colData: [], // 表格信息
      tableData: [],
      rowKey: 'ruleid',
      userguid: '',
      submiting: false,
      sortable: true,
      isShowOper: false,
      isChecked: false,
      selectionData: [], // 已勾选数据列表
      /* --- 分页 -- */
      reserveSelection: true,
      currentPage: 1,
      pageSize: 15,
      pageSizes: [15, 30, 50, 100],
      total: null,
      height: '330',
      isLoadingTableData: false,
      deleteRuleDialog: false,
      checkAll: true,
      ruleid: '',
      ruleids: '',
      index: null, // 当前行
      addRulesOnoff: false,
      isButtonOnOff: false,
      isClickOnModal: false,
      rowOnoff: false,
      ruleData: {},
      rulestatus: '01',
      getHostid: ''
    }
  },
  computed: {
    setKeyAlarmRuleId() {
      return this.$store.state.setKeyAlarmRuleId
    },
    gisopUserInfo() {      
      return this.$store.state.gisopUserInfo
    }
  },
  created() {
    this.hostid = this.$route.params.hostid
    this.getselectRuleByPageList(this.currentPage, this.pageSize, this.hostid)
  },
  destroyed () {
    window.removeEventListener('resize', this.handleFn)
  },
  mounted() {
    this.breadCrumbList = [
      { title: '服务器监控' },
      { title: '报警规则' }
    ]
    this.colData = [
      { prop: 'rulename', label: '规则名称', width: '160', sortable: true, align: 'center' },
      { prop: 'rulestatusStr', label: '状态', width: '140', sortable: true, align: 'center' },
      { prop: 'hostname', label: '主机名称', width: '160', sortable: true, align: 'center' },
      { prop: 'ruleDescribe', label: '报警规则', width: '500', sortable: true, align: 'center' },
      { prop: 'notifyobject', label: '通知对象', width: '160', sortable: false, align: 'center' },
      { prop: 'rulestatus', label: '是否启用', sortable: true, align: 'center' }
      ]
    this.loginduserguid = this.gisopUserInfo.userguid
    if (this.loginduserguid === undefined) {
      return false
    } else {
      this.loginduserguid = this.loginduserguid.trim()
    }
          // 钩子
    this.$nextTick(() => {
      this.handleFn()
    })
    window.addEventListener('resize', this.handleFn)
  },
  watch: {
    gisopUserInfo (val) {
      if (val.userguid === undefined) {
        return false
      } else {
        this.loginduserguid = val.userguid.trim()
      }
    }
  },
  methods: {
      tableRowClassName (row, index) {
        if (index === this.index) {
          return 'info-row'
      }
      return ''
    },
      // resize的函数
      handleFn () {
        this.height = this.$refs.tableDataRef.clientHeight - this.$refs.tableTopRef.clientHeight - 52   
      },
      // 清空选中
      handleClearSelection() {
        this.isChecked = false
        this.selectionData = []
      },
        // 当选项发生
      handleSelectChange (selection) {
        if (selection.length !== 0) {
          this.isChecked = true
          this.selectionData = selection
        } else {
          this.isChecked = false
          this.selectionData = []
        }
      },
      // 添加报警规则
      addRules() {
        this.title = '创建报警规则'
        this.addRulesOnoff = true   
        this.isClickOnModal = false
        this.rowEditOnoff = false
        this.rowOnoff = false
        this.isRead = false
        this.isReadonly = false
      }, 
        // 查看
      handleDetail(e, rowData) { 
        this.title = '查看报警规则'
        this.addRulesOnoff = true  
        this.isReadonly = true
        this.isClickOnModal = true
        this.rowEditOnoff = true
        this.rowOnoff = true
        this.ruleData = rowData
        this.isRead = true
      },
      // 修改
      handleEdit (e, rowData) {
        this.title = '修改报警规则'
        this.addRulesOnoff = true  
        this.isReadonly = false
        this.isClickOnModal = false
        this.rowEditOnoff = true
        this.rowOnoff = true
        this.ruleData = rowData
        this.isRead = false
      },
       // 单个删除规则
      handleDelete (scope) {
        this.deleteRules(scope.id)
      },
      // 单条规则删除接口
      deleteRules(ruleid) {
        this.ruleid = ruleid
          Api.deleteRule(this.ruleid)
          .then(data => {
            if (data.status === 0) {            
              this.$message({
                type: 'success',
                message: '删除规则成功'
              })
              this.getselectRuleByPageList(this.currentPage, this.pageSize, this.hostid)  // 查询规则列表
            } else {
              this.$message({
                type: 'warning',
                message: '删除规则失败'
              })
            }
          })
          .catch(res => {
            this.$message({
              type: 'error',
              message: '请求数据失败'
            })
          })
      },
      // 批量删除接口
      deleteRuleBatch(ruleids) {
        this.ruleids = ruleids
          Api.deleteRuleBatch(this.ruleids)
          .then(data => {
            if (data.status === 0) {
              this.$message({
                type: 'success',
                message: '删除规则成功'
              }) 
              this.getselectRuleByPageList(this.currentPage, this.pageSize, this.hostid)  // 查询规则列表
            } else {
              this.$message({
                type: 'warning',
                message: '删除规则失败'
              })
            }
          })
          .catch(res => {
            this.$message({
              type: 'error',
              message: '请求数据失败'
            })
          })
      },
       // 批量删除规则
      deletePart () {
        if (this.selectionData.length !== 0) {          
          this.deleteRuleDialog = true
        } else {
          this.$message({
            type: 'warning',
            message: '请选择需要删除的规则'
          })
        }
      },
      // 确定批量删除
      sureRuleDelete () {
        this.deleteRuleDialog = false

        var deleteArr = []
        this.selectionData.forEach(item => {
          deleteArr.push(item.id)
        })
        this.ruleids = deleteArr.join(';')
        this.deleteRuleBatch(this.ruleids)
      },
      // 报警历史
      handleHistory(e, rowData) {
        this.ruleid = rowData.id
        this.$router.push({
          name: 'AlarmHistory',
          params: {       
            ruleid: this.ruleid
          }
        })      
      },
      // 启用 + 禁用规则
      handleStart(e, rowData) {
        this.ruleData = rowData
        var formData = new FormData()
        formData.append('id', this.ruleData.id)
        formData.append('hostid', this.ruleData.hostid)    
           
        if (this.ruleData.rulestatus === '02') {        // 启用 
          this.ruleData.rulestatus = '01'   
          formData.append('rulestatus', this.ruleData.rulestatus) 
          Api.updateRule(formData)     // 调用修改接口    
          .then(data => {
            this.dialogLoading = false
            if (data.status === 0) {    
              this.ruleData.rulestatusStr = '已启用'          
              this.$message({
                type: 'success',
                message: '启用规则成功'
              })
            } else {
              this.$message({
                type: 'warning',
                message: '启用规则失败'
              })
            }
          })
          .catch(res => {
            this.$message({
              type: 'error',
              message: '请求数据失败'
            })
          })             
          } else if (this.ruleData.rulestatus === '01') {          
              this.ruleData.rulestatus = '02'
              formData.append('rulestatus', this.ruleData.rulestatus) 
              Api.updateRule(formData)     // 调用修改接口    
              .then(data => {
                this.dialogLoading = false
                if (data.status === 0) {       
                  this.ruleData.rulestatusStr = '已禁用'          
                  this.$message({
                    type: 'success',
                    message: '禁用规则成功'
                  })
                } else {
                  this.$message({
                    type: 'warning',
                    message: '禁用规则失败'
                  })
                }
              })
              .catch(res => {
                this.$message({
                  type: 'error',
                  message: '请求数据失败'
                })
              })    
          }
      },  
      // 确定添加规则或修改规则
      sureRegister (datas) {
      this.dialogLoading = true
      var formData = new FormData()
      formData.append('hostname', datas[0].hostname)
      formData.append('hostid', datas[0].hostid)
      formData.append('rulename', datas[0].rulename)
      formData.append('alarmitem', datas[0].alarmitem)
      formData.append('monitortime', datas[0].monitortime)
      formData.append('monitortype', datas[0].monitortype)
      formData.append('comparetype', datas[0].comparetype)
      formData.append('comparenum', datas[0].comparenum)
      formData.append('silenttime', datas[0].silenttime)
      formData.append('maxalarmtimes', datas[0].maxalarmtimes)
      formData.append('validtimefrom', datas[0].validtimefrom)
      formData.append('validtimeto', datas[0].validtimeto)
      formData.append('notifyobject', datas[0].notifyobject)
      formData.append('email', datas[0].email)
      formData.append('notifytype', datas[0].notifytype)
      formData.append('emailtheme', datas[0].emailtheme)
      formData.append('emailbody', datas[0].emailbody)
      formData.append('rulestatus', datas[0].rulestatus)    
      if (datas[1]) { // 修改规则           
        formData.append('id', datas[0].ruleid)
        Api.updateRule(formData)       
          .then(data => {
            this.dialogLoading = false
            if (data.status === 0) {
              this.addRulesOnoff = false
              this.getselectRuleByPageList(this.currentPage, this.pageSize, this.hostid)  // 查询规则列表
              this.$message({
                type: 'success',
                message: '修改规则成功'
              })
            } else {
              this.$message({
                type: 'warning',
                message: '修改规则失败,请检查数据是否有误'
              })
            }
          })
          .catch(res => {
            this.$message({
              type: 'error',
              message: '请求数据失败'
            })
          })
      } else { // 添加规则     
        Api.getAlarmRulesSubmit(formData)
          .then(data => {
            this.dialogLoading = false
            if (data.status === 0) {
              this.addRulesOnoff = false
              this.getselectRuleByPageList(this.currentPage, this.pageSize, this.hostid) // 查询规则列表
              this.$message({
                type: 'success',
                message: '添加规则成功'
              })              
            } else {        
              this.$message({
                type: 'warning',
                message: '添加规则失败,请检查数据是否有误'
              })
            }
          })
          .catch(res => {
            this.$message({
              type: 'error',
              message: '请求数据失败'
            })
          })
      }
    },
     // 取消创建规则
    closeHanlder() {
      this.addRulesOnoff = false
    },
    getselectRuleByPageList (currentPage, pageSize, hostid) {     
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.hostid = hostid
        Api.getselectRuleByPage(this.currentPage, this.pageSize, this.hostid)
        .then(data => {
        this.isLoadingTableData = false
        let datas = data.data
        if (data.status === 0) {
          if (datas.total > 0) {
           this.tableData = datas.data  
           this.total = datas.total      
          } else {           
            this.$message({
              type: 'warning',
              message: '获取数据为空！'
            })
          }
        } else {
          this.$message({
            type: 'error',
            message: '获取数据失败！'
          })
        }
      })    
    },
    // 分页操作
    handleSizeChange(val) {
      this.pageSize = val
      if (this.tableData !== null) {
        this.getselectRuleByPageList(this.currentPage, this.pageSize, this.hostid) 
      }
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      if (this.tableData !== null) {
        this.getselectRuleByPageList(this.currentPage, this.pageSize, this.hostid) 
      }
    }
   // 查询
  /*   searchHandler () {
      this.getPartList()
    }  */
    }
}

</script>
<style lang="scss">
.alarmRules {
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .tableCon {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
    .tableTop {
      padding: 20px 10px;
      background: #fbfbfb;

    }
    .tableBottom {
      padding-top: 10px;
      height: 51px;
    }
}
</style>
