<template>
  <div>
    <base-layout :showHeader="false">
      <el-row slot="form_content">
        <el-form ref="form" :model="form.queryParam" :label-position="labelPosition" label-width="110px">
          <div class="searchHeader">
            <span>查询条件</span>
            <div class="btns">
              <el-button icon="el-icon-search" @click="form.page.current = 1;searchClick()">查询</el-button>
              <el-button @click="form.page.current = 1;resetForm()">
                <icon name="reply"></icon>
                重置
              </el-button>
            </div>
          </div>
          <div class="searchBox">
            <el-row class="searchBar">
              <el-col :span="6">
                <el-form-item label="规则名称:" prop="ruleName">
                  <el-input v-model="form.queryParam.ruleName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="字段:" prop="eventFieldName">
                  <el-input v-model="form.queryParam.eventFieldName"></el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="6"> <el-form-item label="设备类型:"  prop="resultname">
                <el-input  v-model="form.queryParam.rulename1" ></el-input>
              </el-form-item></el-col> -->
            </el-row>
          </div>
        </el-form>
      </el-row>

      <div slot="table_content">
        <el-row class="tableBox">
          <div class="tableTabs">

            <el-rule-button @click="openDialog('新增')">
                <span>
                  <icon name="plus"></icon>新增</span>
            </el-rule-button>

            <el-rule-button @click="batchdel">
              <span><icon name="close"></icon>删除</span>
            </el-rule-button>

          </div>
          <el-table tooltip-effect="dark" :data="tableData" @selection-change="handleSelectionChange" stripe border>
            <el-table-column type="selection"></el-table-column>
            <el-table-column prop="ruleName" label="规则名称" :show-overflow-tooltip="true" sortable></el-table-column>
            <el-table-column prop="deviceTypeName" label="设备类型" width="150" :show-overflow-tooltip="true" sortable></el-table-column>
            <el-table-column prop="eventFieldName" label="规则字段" :show-overflow-tooltip="true" sortable></el-table-column>
            <el-table-column label="操作" fixed="right" width="140">
              <template slot-scope="scope">
                <el-context-menu :menus="menus" :scope="scope" :default="defaultV" @oper="clickRow"></el-context-menu>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination layout="total, sizes, prev, pager, next,jumper" @current-change="handleCurrentChange" :page-size="size"
                         :current-page.sync="currentPage" :total="total"></el-pagination>
        </el-row>
      </div>
    </base-layout>
    <el-dialog :visible.sync="addnewDialog" @close="clearForm">
      <div class="dialogHeader">
        <span v-text="dialogHeader"></span>
      </div>
      <el-row>
        <el-form :model="eventAdapRule" :rules="rules" label-width="110px" ref="ruleForm">
          <el-row>
            <el-col :span="12">
              <el-form-item label="规则名称：" prop="ruleName">
                <el-input v-model="eventAdapRule.ruleName" :disabled="disabled"></el-input>
              </el-form-item>
            </el-col>
            <!-- :remote-method="remoteDeviceTypeMethod" : loading="loading" remote :clearable="true"-->
            <el-col :span="12">
              <el-form-item label="设备类型：" prop="deviceTypeId">
                <el-select v-model="eventAdapRule.deviceTypeId" :filterable="true"
                           placeholder="输入名称查找"
                           style="width:100%" :disabled="disabled">
                  <el-option v-for="reliay in deviceTypeList" :label="reliay.dataName" :key="reliay.dataId" :value="reliay.dataId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="符号组合：" prop="keyword">
                <el-select :disabled="disabled" v-model="eventAdapRule.keyword">
                  <el-option v-for="reliay in deviceTypeList" :label="reliay.dataName" :key="reliay.dataId" :value="reliay.dataId"></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="规则字段" prop="eventFieldList">
                <div class="selectWarp">
                  <i v-show="!showSelectField&&(oper!='detail')" class="el-icon-close close closeAll" @click="confirmDel"></i>
                  <p v-show="showSelectField" style="color:#97A8CD">请查询后选择</p>
                  <el-tag v-for="tag in this.eventAdapRule.eventFieldList" :key="tag.fieldNote" :closable="!disabled" :type="tagType"
                          @close="tagCloseHandle(tag)" :disabled="disabled">
                    {{tag.fieldName}}
                  </el-tag>
                  <el-button @click="showComQueDialog" class="rightQueryBtn" size='small' v-show="oper!='detail'" :disabled="disabled">查询</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="正则表达式：" prop="ruleRegex">
                <el-input type="textarea" :disabled="disabled" v-model="eventAdapRule.ruleRegex"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="示例日志：" prop="demoLog">
                <el-input type="textarea" :disabled="disabled" v-model="eventAdapRule.demoLog"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <span slot="footer" class="dialog-footer">
          <el-button type="reset" icon="circle-close" @click="clearForm">关闭</el-button>
          <el-button type="primary" :disabled="disabled" icon="circle-check" @click="submit">提交</el-button>
        </span>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="comQueDialog" :modal-append-to-body="false" @close="closeComp">
      <div class="dialogHeader">
        <span>查询</span>
      </div>
      <el-row :gutter="20" style="margin:0">
        <el-col :span="10" class="formWarp" style="background-color: #fbfbfb;padding-top: 20px">
          <el-row>
            <el-form label-width="100px" :label-position="labelPosition" :model="queryCompForm.queryParam" ref="compForm">
              <el-col :span="24">
                <el-form-item label="字段名：" prop="fieldName">
                  <el-input v-model="queryCompForm.queryParam.fieldName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="字段：" prop="fieldNote">
                  <el-input v-model="queryCompForm.queryParam.fieldNote"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <hr>
              </el-col>
              <el-col :span="24" style="text-align: center;padding-bottom: 10px">
                <el-button @click="queryComp" size="small">查询</el-button>
                <el-button @click="resetComp" size="small">重置</el-button>
              </el-col>
            </el-form>
          </el-row>
        </el-col>
        <el-col :span="14" v-loading="loadingField">
          <el-table :data='tableFileData' @selection-change="handleSelectionFileChange" height="337">
            <el-table-column type="selection" width="60"></el-table-column>
            <el-table-column prop="fieldName" label="可选字段名" show-overflow-tooltip></el-table-column>
            <el-table-column prop="fieldNote" label="可选字段" show-overflow-tooltip></el-table-column>
            <el-table-column prop="fieldRegex" label="正则表达式" show-overflow-tooltip></el-table-column>
          </el-table>
          <p style="margin-top:5px">
            <span @click="more" v-show="moreBtn" v-text="tipText" style="color: #1c8de0;float: left;cursor: pointer;font-size: 12px"></span>
            <span style="float: right;">已选：{{selectData}}/{{fileTotal}}</span>
          </p>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="comQueDialog=false">关闭</el-button>
        <el-button type="primary" @click="submitField">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
    import {
        queryLogAdaptiveFieldList,
        queryLogAdaptiveRulesById,
        queryLogAdaptiveRulesList,
        addLogAdaptiveRules,
        deleteLogAdaptiveRules,
        updateLogAdaptiveRules
    } from './api/logAdaptiveRules'

    //import BaseLayout from '../../../components/layout/base'
    export default {
        data() {
            return {
                collapseVisible: false,
                addnewDialog: false,
                labelPosition: "right",
                //table数据
                tableData: [],
                dialogHeader: "新增",
                size: 10,
                total: null,
                currentPage: 1,
                disabled: false,
                form: {
                    queryParam: {
                        ruleName: null,
                        eventFieldName: null
                    },
                    page: {
                        current: "1",
                        size: "10"
                    }
                },
                //默认显示3个操作项
                defaultV: 3,
                menus: [
                    {
                        text: "查看",
                        command: "detail"
                    },
                    {
                        text: "编辑",
                        command: "modify"
                    },
                    {
                        text: "删除",
                        command: "delete"
                    }
                ],
                //删除数据
                deleteNum: {
                    "ruleId": []
                },
                oper: "",
                ruleId: null,
                comQueDialog: false,
                loadingField: false,
                loading: false,
                tagType: 'primary',
                tagClose: true,
                moreBtn: false,
                tipText: '更多',
                title: "新增",
                totalPage: '',
                tableFileData: [],
                selectData: 0,
                fileTotal: 0,
                deviceTypeList: [],

                //新增规则
                eventAdapRule: {
                    ruleId: null,
                    ruleName: null,
                    description: null,
                    ruleRegex: '',
                    deviceTypeId: null,
                    eventFieldList: [],
                    demoLog: null,
                    keyword: null
                },
                clearEventAdapRule: {
                    ruleId: null,
                    ruleName: null,
                    description: null,
                    ruleRegex: '',
                    deviceTypeId: null,
                    eventFieldList: [],
                    demoLog: null,
                    keyword: null
                },
                queryCompForm: {
                    queryParam: {
                        fieldName: null,
                        fieldNote: null
                    },
                    page: {
                        current: '1',
                        size: '10'
                    }
                },
                rules: {
                    ruleName: [
                        {required: true, message: '请输入规则名称', trigger: 'blur'},
                    ],
                    deviceTypeId: [
                        {required: true, message: '请选择设备类型', trigger: 'blur'},
                    ],
                    ruleRegex: [
                        {required: true, message: '请输入正则表达式', trigger: 'blur'},
                    ],
                    eventFieldList: [
                        {required: true, message: '请选择字段', trigger: 'blur'},
                    ]
                }
            }
        },
        methods: {
            clickRow: function (command, scope, index, rows) {
                index = scope.row.ruleId;
                console.log(index);
                if (command === 'detail') {
                    this.addnewDialog = true;
                    this.dialogHeader = "查看";
                    this.disabled = true;
                    this.SingleSearch(index);

                } else if (command === 'modify') {
                    this.addnewDialog = true;
                    this.disabled = false;
                    this.dialogHeader = "修改";
                    this.SingleSearch(index);

                } else if (command === 'delete') {
                    let list = [];
                    list.push(index);
                    this.deleteNum.ruleId = list;
                    this.confirmDelRule();
                }

            },
            //关闭弹窗
            clearForm: function () {
                this.eventAdapRule = JSON.parse(JSON.stringify(this.clearEventAdapRule));
                this.addnewDialog = false;
                this.disabled = false;
            },
            //分页
            handleCurrentChange: function (currentPage) {
                this.form.page.current = currentPage;
                this.search();
            },
            //条件查询
            search: function () {
                this.loading = true;
                queryLogAdaptiveRulesList(this.form).then((resp) => {
                    if (resp.data.returnCode == "0") {
                        this.tableData = resp.data.data.list;
                        this.size = resp.data.data.page.size;
                        this.total = resp.data.data.page.total;
                        this.currentPage = resp.data.data.page.current;
                    }
                    this.loading = false;
                }, (error) => {
                    this.loading = false;
                    this.$message.error(error.message);
                })
            },
            //查询按钮
            searchClick: function () {
                for (let i in this.selectBusinessList) {
                    this.form.queryParam.businessId.push(this.selectBusinessList[i].dataId);
                }
                for (let i in this.selectDepartList) {
                    this.form.queryParam.departId.push(this.selectDepartList[i].dataId);
                }

                this.search();
            },
            //删除资产
            tagCloseHandle: function (tag) {
                var index = this.eventAdapRule.eventFieldList.indexOf(tag);
                this.eventAdapRule.eventFieldList.splice(index, 1);
                // if(this.eventAdapRule.ruleRegex.indexOf(",")==-1){
                //   this.eventAdapRule.ruleRegex  = "";
                // }else{
                //   var arr = this.eventAdapRule.ruleRegex.split(',').splice(index-1,1);
                //   this.eventAdapRule.ruleRegex = arr.join(',');
                // }
            },
            //多选
            handleSelectionChange: function (val) {
                this.multipleSelection = val;
            },
            //重置查询条件
            resetForm() {
                this.$refs.form.resetFields();
                this.search();
            },
            //漏洞处置按钮
            openDialog(value) {
                this.addnewDialog = true;
                this.dialogHeader = value;
                if (value === '新增') {
                } else if (value === '修改') {

                }

            },
            //删除
            deletefilter: function () {
                deleteLogAdaptiveRules(this.deleteNum).then((resp) => {
                    if (resp.data.returnCode == "0") {
                        this.search();
                        this.$message.success('删除成功!');
                    }
                }, (error) => {
                    this.$message.error(error.message);
                });
            },
            //拼装批量删除数据
            batchdel: function () {
                let list = [];
                for (let temp in this.multipleSelection) {
                    list.push(this.multipleSelection[temp].ruleId);
                }
                if (list.length >= 1) {
                    this.deleteNum.ruleId = list;
                    this.confirmDelRule()
                } else {
                    this.$message.warning("请选择需删除的行");
                }
            },
            confirmDelRule() {
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.deletefilter();
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            isRepeat: function (arr) {
                var nary = arr.sort();
                if (arr.length >= 2) {
                    for (var i = 0; i < arr.length - 1; i++) {
                        if (!(nary[i] == nary[i + 1])) {
                            return true;
                        }
                    }
                    return false;
                }
                return false;
            },
            SingleSearch: function (value) {
                queryLogAdaptiveRulesById(value).then((resp) => {
                    if (resp.data.returnCode == "0") {
                        this.eventAdapRule = resp.data.data.eventAdapRule;
                        let eventfieldListTemp = resp.data.data.eventAdapRule.eventField.split(',');
                        let eventfieldNameListTemp = resp.data.data.eventAdapRule.eventFieldName.split(',');
                        let eventfieldList = [];
                        for (let option in eventfieldListTemp) {
                            eventfieldList.push({
                                fieldNote: eventfieldListTemp[option],
                                fieldName: eventfieldNameListTemp[option]
                            })
                        }
                        this.eventAdapRule.eventFieldList = eventfieldList;
                    }
                }, (error) => {
                    this.$message.error(error)
                })
            },
            //对子业务系统自动完成
            remoteDeviceTypeMethod: function (query) {
                if (query) {
                    this.loading = true;
                    setTimeout(() => {
                        this.loading = false;
                        this.deviceTypeList = this.allTypeDeviceParam.filter(item => {
                            return item.dataName
                                .indexOf(query) > -1;
                        });
                    }, 200);
                } else {
                    this.deviceTypeList = JSON.parse(JSON.stringify(this.allTypeDeviceParam));
                }
            },
            closeAll: function () {
                this.eventAdapRule.eventFieldList = [];
            },
            confirmDel() {
                this.$confirm('是否确定删除所有?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        this.closeAll()
                    })
                    .catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        })
                    })
            },
            submitField: function () {
                let eventfieldList = [].concat(this.eventAdapRule.eventFieldList);

                for (let option of this.multipleSelection) {
                    var t = 0;
                    for (let eventfield of eventfieldList) {
                        if (eventfield.fieldNote == option.fieldNote) {
                            t = 1;
                            break;
                        }
                    }
                    if (t == 0) {
                        if (this.eventAdapRule.ruleRegex != null && this.eventAdapRule.ruleRegex != "") {
                            this.eventAdapRule.ruleRegex += "," + option.fieldRegex;
                        } else {
                            this.eventAdapRule.ruleRegex = option.fieldRegex + "";
                        }
                        this.eventAdapRule.eventFieldList.push({
                            fieldNote: option.fieldNote,
                            fieldName: option.fieldName
                        })
                    }
                }

                this.comQueDialog = false
            },
            resetComp: function () {
                this.$refs['compForm'].resetFields();
                this.queryComp();

            },
            closeComp: function () {
                this.$refs['compForm'].resetFields()
                this.tableFileData = []
                this.fileTotal = 0
                this.moreBtn = false
                this.tipText = ''
            },
            //多选
            handleSelectionFileChange: function (val) {
                this.multipleSelection = val
                this.selectData = val.length
            },
            more: function () {
                this.queryCompForm.page.current++
                if (this.queryCompForm.page.current <= this.totalPage) {
                    this.loadingAsset = true
                    queryLogAdaptiveFieldList(this.queryCompForm).then(
                        resp => {
                            if (resp.data.returnCode == '0') {
                                var list = resp.data.data.list
                                this.totalPage = resp.data.data.page.pages
                                list.forEach((item, index) => {
                                    this.tableFileData.push(item)
                                    this.fileTotal = this.tableFileData.length
                                })
                            }
                            this.loadingField = false
                        },
                        error => {
                            this.loadingField = false
                            this.$message.error(error.message)
                        }
                    )
                } else {
                    this.tipText = '没有更多了'
                }
            },

            queryComp: function () {
                this.tableFileData = []
                this.loadingField = true
                this.queryCompForm.page.current = 1
                queryLogAdaptiveFieldList(this.queryCompForm).then(
                    resp => {
                        if (resp.data.returnCode == '0') {
                            this.size = resp.data.data.page.size
                            this.currentPage = resp.data.data.page.current
                            var list = resp.data.data.list
                            this.totalPage = resp.data.data.page.pages
                            if (list.length) {
                                list.forEach((item, index) => {
                                    this.tableFileData.push(item)
                                    this.fileTotal = this.tableFileData.length
                                })
                                if (this.totalPage === 1) {
                                    this.moreBtn = false
                                } else {
                                    this.tipText = '更多'
                                    this.moreBtn = true
                                }
                            } else {
                                this.moreBtn = false
                                this.tipText = ''
                            }
                        }
                        this.loadingField = false
                    },
                    error => {
                        this.loadingField = false
                        this.$message.error(error.message)
                    }
                )
            },
            showComQueDialog: function () {
                this.moreBtn = false;
                this.comQueDialog = true;
            },
            submit: function () {
                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        if (this.dialogHeader == '新增') {
                            addLogAdaptiveRules(this.eventAdapRule).then((resp) => {
                                if (resp.data.returnCode == "0") {
                                    this.$message.success("新增成功");
                                    this.clearForm();
                                    this.search();
                                }
                            }, (error) => {
                                this.$message.error(error)
                            })
                        } else if (this.dialogHeader == '修改') {
                            updateLogAdaptiveRules(this.eventAdapRule).then((resp) => {
                                if (resp.data.returnCode == "0") {
                                    this.$message.success("修改成功");
                                    this.clearForm();
                                    this.search();
                                }
                            }, (error) => {
                                this.$message.error(error)
                            })

                        }
                    } else {
                        return false;
                    }
                });

            }

        },
        computed: {
            showSelectField: function () {
                if (this.eventAdapRule.eventFieldList.length >= 1) {
                    return false
                } else {
                    return true
                }
            },
            allTypeDeviceParam: function () {
                return this.$store.getters.allTypeDeviceParam
            }
        },
        components: {
            //BaseLayout
        },
        mounted: function () {
            setTimeout(() => {
                this.searchClick();
                this.deviceTypeList = JSON.parse(JSON.stringify(this.allTypeDeviceParam));
            });
        },
    }
</script>


