<template>
    <div v-resize="resize" class="classifyRules">
        <el-row type="flex" style="position: relative">
            <el-col :span="6" style="position: absolute; height: 100%">
                <div ref="leftTree" class="extra" style="padding-bottom: 48px">
                    <el-scrollbar ref="scrollbar" style="height: 100%;" wrap-style="overflow-x: hidden;">
                        <div class="box-title">事件分组</div>
                        <el-input style="padding: 20px 10px" v-model="filterText" placeholder="输入关键字过滤" clearable />
                        <el-tree ref="tree" default-expand-all :data="eventclassGroupInfoTree" accordion highlight-current :expand-on-click-node="false" @node-click="nodeClick" :filter-node-method="filterNode" class="leftTree"></el-tree>                        
                    </el-scrollbar>
                    <div class="selectClassifyBtn" :style="{width: btnWidth}">
                        <el-button type="primary" size="mini" @click="createObject">选择分类规则</el-button>
                    </div>
                </div>
            </el-col>
            <el-col :span="18" style="margin-left: 25%">
                <manager-ui
                    :show-query="false"
                    :show-pagination="true"
                    :show-download-btn="false"
                    :table-data="tableData"
                    :column-items="columnItems"
                    :pagination="page"
                    @search="search"
                    @selection-change="handleSelectionChange"
                >
                    <template #extra>
                        <el-row>
                            <el-col>
                                <div class="extra" style="padding-bottom: 10px;">
                                    <el-row type="flex" style="margin-bottom: 10px">
                                        <div class="box-title">事件分组架构配置</div>
                                    </el-row>
                                    <el-row>
                                        <el-form :model="form.eventclassGroupInfo" :rules="rules" ref="addnewForm" label-width="120px" label-position="center">
                                            <el-row>
                                                <el-col :span="12">
                                                    <el-form-item label="事件组名称：" prop="groupName">
                                                        <el-input v-model="form.eventclassGroupInfo.groupName"></el-input>
                                                    </el-form-item>
                                                </el-col>
                                                <el-col :span="12">
                                                    <el-form-item label="攻击链阶段:" prop="attackStage">
                                                        <el-select v-model="form.eventclassGroupInfo.attackStage" clearable>
                                                            <el-option
                                                                v-for="item in attackType"
                                                                :key="item.dataId"
                                                                :value="item.dataId"
                                                                :label="item.dataName"
                                                            >{{ item.dataName }}
                                                            </el-option>
                                                        </el-select>
                                                    </el-form-item>
                                                </el-col>
                                            </el-row>
                                            <el-row type="flex">
                                                <el-col :span="12">
                                                    <el-form-item label="告警类型:" prop="alertTypeList">
                                                        <el-cascader
                                                            style="width: 100%"
                                                            clearable
                                                            v-model="form.eventclassGroupInfo.alertTypeList"
                                                            :options="bigdataAlarmTypeTree"
                                                            :props="{ expandTrigger: 'hover',value:'key', label:'label',children:'children'}"
                                                        >
                                                        </el-cascader>
                                                    </el-form-item>
                                                    <el-form-item label="父节点：" v-show="!saveBtvisible">
                                                        <el-input v-model="parentGroupName" :disabled="true"></el-input>
                                                    </el-form-item>
                                                </el-col>
                                                <el-col :span="12">
                                                    <el-form-item label="描述：" prop="groupDes">
                                                        <el-input type="textarea" :autosize="{ minRows: 2 }" v-model="form.eventclassGroupInfo.groupDes"></el-input>
                                                    </el-form-item>
                                                </el-col>
                                            </el-row>
                                            <el-col :span="24" style="margin-left: 120px">
                                                <el-button type="primary" size="mini" @click="addnewClick">新增</el-button>
                                                <el-button type="danger" size="mini" @click="deleClick">删除</el-button>    
                                            </el-col>
                                            <el-col>
                                                <div style="text-align:right">
                                                    <el-button type="primary" size="mini" @click="depUpd" v-show="saveBtvisible">修改保存</el-button>
                                                    <el-button type="primary" size="mini" @click="saveClick" v-show="!saveBtvisible">新增保存</el-button>
                                                </div>
                                            </el-col>
                                        </el-form>
                                    </el-row>
                                </div>
                            </el-col>
                        </el-row>
                        <el-row>
                            <div style="background-color: #e6e9f0; height: 10px; width: 100%"></div>
                            <div class="box-title">表格</div>
                        </el-row>
                    </template>

                    <template #readOnlyTag="{scope}">
                        {{ scope.row.readOnlyTag | toCase(statics.flagList, 'value', 'label') }}
                    </template>

                    <template #ruleLevel="{scope}">
                        {{ scope.row.ruleLevel | toCase(statics.ruleLevelList, 'value', 'label') }}
                    </template>

                    <template slot="tableTools">
                        <el-button type="text" icon="el-icon-delete-solid" @click="batchdel">取消分类规则</el-button>
                    </template>
                </manager-ui>
            </el-col>
        </el-row>
    </div>
</template>
<script>

import { getEventGroup } from '../logAuditManage/api/log-retrival-manage'
import { 
    getEventclassRuleInfoByGroupId, 
    delEventclassGroupInfo,
    addEventclassGroupInfo,
    updEventclassGroupInfo,
    cancelEventclassGroupInfo,
    getAttackTypeEvent
} from './api/eventStrategy'
import _ from '@ability/utils/params.js'

export default {
  directives: {
    resize: {
        bind(el, binding) {
            let width = '', height = '';
            function isReize() {
                const style = document.defaultView.getComputedStyle(el);
                if (width !== style.width || height !== style.height) {
                    binding.value();
                }
                width = style.width;
                height = style.height;
            }
            el.__vueSetInterval__ = setInterval(isReize, 300);
        },
        unbind(el) {
            clearInterval(el.__vueSetInterval__);
        }
    }
  },
  computed: {
    bigdataAlarmTypeTree() {
        return this.$store.state.alarm.newAlarmTypeTree
    },
  },
  watch: {
    filterText(val) {
        this.$refs.tree.filter(val)
    }
  },
  data() {
    let validatorName = (rule, value, callback) => {
        console.log('value', value)
        if (!value) {
            callback()
        }
    }
    return {
        btnWidth: '',
        attackType: [],
        tableData: [],
        multipleSelection: [],
        statics: {
            ruleLevelList: [
                {
                    value: '1',
                    label: '轻微'
                }, 
                {
                    value: '2',
                    label: '低级'
                }, 
                {
                    value: '3',
                    label: '中级'
                }, 
                {
                    value: '4',
                    label: '高级'
                }, 
                {
                    value: '5',
                    label: '严重'
                }
            ],
            flagList: [
                {
                    value: '1',
                    label: '是'
                },
                {
                    value: '0',
                    label: '否'
                }
            ]
        },
        columnItems: [
            {
                _key: 'selection',
                type: 'selection',
                width: '50'
            },
            {
                _key: 'ruleName',
                prop: 'ruleName',
                label: '规则名称'
            },
            {
                _key: 'ruleLevel',
                prop: 'ruleLevel',
                label: '分类等级',
                render: true
            },
            {
                _key: 'cveName',
                prop: 'cveName',
                label: 'CVE编号'
            },
            {
                _key: 'readOnlyTag',
                prop: 'readOnlyTag',
                label: '是否只读',
                render: true
            }
        ],
        queryParams: {
            eventclassRuleInfoQuery: {
                groupId: null
            },
            page: {
                current: 1,
                size: 10
            }
        },
        page: {
            current: 1,
            size: 10,
            total: 0
        },
        parentGroupName: null,
        detailvisible: false,
        saveBtvisible: true,
        deleteNum: {
            groupId: []
        },
        deleteNums: {
            groupId: null,
            ruleId: []
        },
        formClear: {
            eventclassGroupInfo: {
                groupName: "",
                parentId: "",
                leafTag: "0",
                positionNum: "0",
                groupDes: "",
                readOnlyTag: "0",
                validTag: "1",
                alertTypeList: []
            }
        },
        form: {
            eventclassGroupInfo: {
                groupId: null,
                groupName: "",
                parentId: "",
                leafTag: "0",
                positionNum: "0",
                groupDes: "",
                readOnlyTag: "0",
                validTag: "1",
                alertTypeList: [],
                attackStage: ''
            }
        },
        rules: {
            groupName: [
                { required: true, message: '请输入名称', trigger: 'blur' }
            ]
        },
        eventclassGroupInfoTree: [],
        filterText: ''
    }
  },
  mounted() {
    this.getEventGroup()
    this.getAttackTypeEvent()
  },
  methods: {
    resize() {
        this.$nextTick(() => {
            this.getLeftWidth()
            this.$refs.scrollbar && this.$refs.scrollbar.update()
        }, 100)
    },
    getLeftWidth() {
        this.btnWidth = this.$refs.leftTree && (this.$refs.leftTree.offsetWidth + 'px')
    },
    filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
    },
    deleClick() {
        if (!this.deleteNum.groupId.length) {
            this.$message.warning("未选中事件或者选中事件下有子事件");
        } else {
            this.$confirm('确认删除该事件吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.depDel()
                this.detailvisible = false
            }).catch(() => {})
        }
    },
    depDel() {
        delEventclassGroupInfo(this.deleteNum).then(
            (resp) => {
                if (resp.data.returnCode == "0") {
                    this.$message.success("删除成功")
                    this.deleteNum.groupId = []
                    this.tableData = []
                    this.getEventGroup()
                    this.choose = false
                }
            }, (error) => {
                this.$message.error(error.message)
            }
        )
    },
    addnewClick() {
        if (this.choose) {
            let currentNode = this.$refs.tree.getCurrentNode()
            this.deleteNum.groupId = []
            this.form = JSON.parse(JSON.stringify(this.formClear))
            this.form.eventclassGroupInfo.alertTypeList = currentNode.alertTypeList
            this.form.eventclassGroupInfo.attackStage = currentNode.attackStage
            this.saveBtvisible = false
            this.detailvisible = true
        } else {
            this.$message.warning("请先在左侧列表选中父节点")
        }
    },
    // 获取攻击链
    getAttackTypeEvent() {
        getAttackTypeEvent().then(resp => {
            if (resp.data.returnCode == '0') {
                this.attackType = resp.data.data.list
            }
        }, error => {
            this.$message.error(error.message)
        })
    },
    // 获取事件分组
    getEventGroup() {
      return new Promise((resole, reject) => {
        this.eventclassGroupInfoTree = []
        getEventGroup().then(resp => {
          if (resp.data.returnCode == '0') {
            this.eventclassGroupInfoTree.push(resp.data.data.list)
          }
          resole()
        }, error => {
          this.$message.error('事件分组获取失败')
          reject()
        })
      })
    },
    handleSelectionChange(val) {
        this.multipleSelection = val
    },
    // 查询
    search() {
        let { current, size } = this.page
        this.queryParams.page = { current, size }
        getEventclassRuleInfoByGroupId(this.queryParams).then((resp) => {
            if (resp.data.returnCode == '0') {
                this.tableData = resp.data.data.list
                const { current, size, total } = resp.data.data.page
                this.page.current = current
                this.page.size = size
                this.page.total = total
            }
        }, error => {
            this.$message.error(error.message)
        })
    },
    //拼装批量取消规则数据
    batchdel() {
        let list = []
        for (let temp in this.multipleSelection) {
            list.push(this.multipleSelection[temp].ruleId);
        }
        this.deleteNums.ruleId = list
        this.confirmDel()
    },
    //取消前确认
    confirmDel() {
        this.$confirm('此操作将取消该规则, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            this.deleteRule()
        }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消'
            })
        })
    },
    //取消规则
    deleteRule: function () {
        cancelEventclassGroupInfo(this.deleteNums).then((resp) => {
            if (resp.data.returnCode == "0") {
                this.search()
                this.$message.success('取消成功!')
            }
        }, (error) => {
            this.$message.error(error.message)
        })
    },
    // 创建对象 选择分类规则
    createObject() {
        let groupid = this.form.eventclassGroupInfo.groupId
        if(groupid == '' || groupid == null) {
            this.$message.warning("请选择事件组")
            return
        }
        // this.$router.push({name:"editclassifyRules", params:{groupid:groupid}})
        this.$router.push({ name: 'classifyRulesList', params: { id: groupid } })
    },
    // 修改保存
    depUpd() {
        if (!this.choose) {
            this.$message.warning("请先在左侧列表选中父节点")
            return
        }
        this.$refs['addnewForm'].validate((valid) => {
            if (valid) {
                updEventclassGroupInfo(this.form).then(
                    (resp) => {
                        if (resp.data.returnCode == "0") {
                            this.$message.success("修改成功");
                            this.getEventGroup()
                        }
                    }, (error) => {
                        this.$message.error(error.message);
                    }
                )
            }
        })
        
    },
    // 新增保存
    saveClick() {
        this.$refs['addnewForm'].validate((valid) => {
            if (valid) {
                addEventclassGroupInfo(this.form).then(
                    (resp) => {
                        if (resp.data.returnCode == "0") {
                            this.$message.success("新增成功");
                            this.saveBtvisible = true;
                            this.getEventGroup()
                        }
                    }, (error) => {
                        this.$message.error(error.message);
                    }
                )
            }
        });
    },
    // 节点单击
    nodeClick(node) {
        this.$refs['addnewForm'].resetFields();
        this.detailvisible = true;
        this.choose = true;
        this.form.eventclassGroupInfo.parentId = node.parentId;
        this.form.eventclassGroupInfo.groupId = node.dataId;
        this.form.eventclassGroupInfo.groupName = node.label;
        this.form.eventclassGroupInfo.groupDes = node.desction;
        this.form.eventclassGroupInfo.alertTypeList = node.alertTypeList
        this.form.eventclassGroupInfo.attackStage = node.attackStage
        this.formClear.eventclassGroupInfo.parentId = node.dataId;
        this.saveBtvisible = true
        this.parentGroupName = node.label;
        this.deleteNum.groupId = [node.dataId]
        this.deleteNums.groupId = node.dataId;
        this.queryParams.eventclassRuleInfoQuery.groupId = node.dataId;
        this.search();
    },
  }
}
</script>
<style lang="scss" scoped>
.classifyRules {
    background-color: #e6e9f0;
    .selectClassifyBtn {
        width: 100%;
        height: 48px;
        line-height: 48px;
        text-align: right;
        position: fixed;
        bottom: 0;
        padding-right: 10px;
        background: rgba(255, 255, 255, 0.86);
        box-shadow: 0px 8px 21px 0px rgba(10, 13, 14, 0.14);
    }
    .extra {
        height: 100%;
        background-color: #fff;
        margin-right: 10px;
        overflow: hidden;
    }
    .box-title {
        color: #666666;
        font-size: 14px;
        padding: 12px 0 0 24px;
        position: relative;
        &::before {
            content: '';
            display: block;
            width: 3px;
            height: 13px;
            background: #4C8AE8;
            position: absolute;
            left: 12px;
        }
    }
}
</style>
