<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item label="IP地址" prop="ip">
            <el-input
              maxlength="15"
              v-model="queryParams.ip"
              placeholder="请输入IP地址"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:ipblacklist:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete"
              v-hasPermi="['system:ipblacklist:remove']"
            >删除
            </el-button>
          </el-col>
        </el-row>
        <div style="padding-top: 10px">
          <vxe-table
            ref="xTable"
            align="center"
            :loading="loading"
            class="mytable-style"
            auto-resize
            border
            resizable
            export-config
            highlight-current-row
            show-overflow
            max-height="700"
            :data="userList"
            :radio-config="{trigger: 'row'}"
          >
            <vxe-column type="radio" width="60"/>
            <vxe-table-column field="ip" title="IP地址"/>
            <vxe-table-column field="ipTime" title="锁定时间"/>
            <vxe-table-column field="addBy" title="添加人"/>
          </vxe-table>
          <vxe-pager
            v-show="showTable"
            perfect
            :current-page.sync="currentPage"
            :page-size.sync="pageSize"
            :total="total"
            :page-sizes="[10,50,100]"
            :layouts="['PrevJump', 'PrevPage','JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
            @page-change="handlePageChange"
          >
          </vxe-pager>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { debounce } from 'lodash'
export default {
  name: "ipBlacklist",
  data() {
    return {
      // 遮罩层
      loading: true,
      showTable: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      currentPage: 1,
      pageSize: 10,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 默认密码
      initPassword: undefined,
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        ip: undefined
      }
    };
  },
  watch: {},
  created() {
    this.getList()
  },
  methods: {
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.getList()
    },
    /** 查询用户列表 */
    async getList(){
      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
      })

      this.loading = true;
      var searchParams = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        ip: this.queryParams.ip,
        sysTime: sysTime,
        lk: lk
      }
      await this.$axios.get('/ipBlacklistController/getAll',
        {params: searchParams}).then((res) => {
        if (res.code == 0) {
          this.userList = res.data.records
          this.total = res.data.total
          if (res.data.records == '') {
            this.showTable = false
          } else {
            this.showTable = true
          }
        } else {
          // 输出后端返回信息
          this.$message({
            type: 'error',
            message: res.data
          });
        }
        this.loading = false
      }).catch((error) => {
        this.loading = false
        this.$message.error(error)
      })
    },
    /** 搜索按钮操作 */
    handleQuery:debounce(function(){
      // 验证查询条件ip是否合理
      if (this.queryParams.ip!=undefined && this.queryParams.ip!=''){
        var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
        if (!reg.test(this.queryParams.ip)){
          this.$message({
            type: 'warning',
            message: '请输入正确ip地址!'
          });
          return
        }
      }
      this.currentPage = 1
      this.pageSize = 10
      this.getList();
    },1000),
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
    },
    /** 添加按钮操作 */
    handleAdd(){
      const ipReg = new RegExp(/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/)
      this.$prompt('请输入黑名单IP','黑名单操作',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator:(val)=>{
          if (!ipReg.test(val)){
            return false;
          }
        },
        inputErrorMessage: 'IP格式不正确',
        beforeClose(action, instance, done) {
          if (action === "confirm") {
            instance.$refs["confirm"].$el.onclick = (function (e) {
              e = e || window.event;
              if (e.detail != 0) {
                done();
              }
            })();
          } else {
            done();
          }
        }
      }).then(async({value})=>{
        this.doAdd(value)
      }).catch((e)=>{})
    },
    /** 删除按钮操作 */
    handleDelete(){
      const _selectData = this.$refs.xTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }
      this.$confirm('是否删除此IP?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDelete(_selectData)
      }).catch(() => {
      });
    },
    /**
     * 添加提交
     */
    doAdd:debounce(async function(ip){
      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
      })

      const param = {
        ip:ip,
        sysTime: sysTime,
        lk: lk
      }
      await this.$axios.post('/ipBlacklistController/addIp', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
          this.getList();
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '添加失败!'
        });
        this.loading = false
      })
    },1000),
    /**
     * 删除提交
     */
    doDelete:debounce(async function(_selectData){
      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
      })

      const param = {
        id: _selectData.id,
        sysTime: sysTime,
        lk: lk
      }
      this.$axios.post('/ipBlacklistController/delIp', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getList();
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '删除失败!'
        });
        this.loading = false
      })
    },1000)
  }
};
</script>
