<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="type" title="限制类型" :formatter="typeFormat"/>
            <vxe-table-column field="limitStartTime" title="限制开始时间"/>
            <vxe-table-column field="limitEndTime" title="限制结束时间"/>
            <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>

    <!-- 添加对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" width="630px" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="IP地址" prop="ip">
              <el-input id="ip" ref="ip" style="width: 220px" v-model="form.ip" placeholder="请输入IP"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="限制类型">
              <el-select style="width: 220px" v-model="form.type" placeholder="请选择类型" @change="changeType">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="isShow">
          <el-col :span="12">
            <el-form-item label="限制时间">
              <el-date-picker
                value-format="yyyy-MM-dd HH:mm:ss"
                v-model="form.limitTime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {debounce} from 'lodash'

export default {
  name: "ipBlacklist",
  data() {
    return {
      isShow:false,
      // 遮罩层
      loading: true,
      showTable: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      currentPage: 1,
      pageSize: 10,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "IP黑名单",
      // 是否显示弹出层
      open: false,
      // 默认密码
      initPassword: undefined,
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {
        type: "0",
      },
      // 查询参数
      queryParams: {
        ip: undefined
      },
      typeOptions: [
        {value: '0', label: '永久'},
        {value: '1', label: '时间范围'}
      ],
      // 表单校验
      rules: {
        ip: [
          {required: true, message: "ip不能为空", trigger: "blur"},
          {pattern: /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/, message: "请输入正确的IP", trigger: "blur"}
        ]
      }
    };
  },
  watch: {},
  created() {
    this.getList()
  },
  methods: {
    changeType(val){
      if (val=="0"){
        this.isShow = false;
      }
      else{
        this.isShow = true;
      }
    },
    /** 提交按钮 */
    submitForm: debounce(function () {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          if (this.form.type=="1"){
            if (this.form.limitTime==undefined){
              this.$message({
                type: 'warning',
                message: '请录入限制时间!'
              });
              return
            }
            else{
              this.form.limitStartTime = this.form.limitTime[0]
              this.form.limitEndTime = this.form.limitTime[1]
            }
          }

          await this.$axios.post('/ipBlacklistController/addIp', this.form).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: 'success',
                message: '添加成功!'
              });
              this.open = false;
              this.getList();
              this.reset();
            } else {
              this.$message({
                type: 'error',
                message: res.data
              });
            }
          }).catch((error) => {
            this.$message({
              type: 'error',
              message: '添加失败!'
            });
            this.loading = false
          })
        }
      });
    }, 1000),
    // 表单重置
    reset() {
      this.form = {
        ip: undefined,
        type: "0",
        limitTime: undefined,
        limitStartTime: undefined,
        limitEndTime: undefined,
        sysTime: undefined,
        lk: undefined
      };
      this.isShow = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 列表状态格式化
    typeFormat({cellValue}) {
      let belongTo = '未知的类型'
      for (let i = 0; i < this.typeOptions.length; i++) {
        if (cellValue == "0") {
          belongTo = "永久"
        } else if (cellValue == "1") {
          belongTo = "时间范围"
        }
      }
      return belongTo
    },
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.getList()
    },
    /** 查询用户列表 */
    async getList() {
      this.loading = true;
      var searchParams = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        ip: this.queryParams.ip,
      }
      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() {
      this.open = true;
    },
    /** 删除按钮操作 */
    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(() => {
      });
    },
    /**
     * 删除提交
     */
    doDelete: debounce(async function (_selectData) {
      const param = {
        id: _selectData.id,
      }
      this.$axios.post('/ipBlacklistController/delIp', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
        this.getList();
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '删除失败!'
        });
        this.loading = false
      })
    }, 1000)
  }
};
</script>
