package com.jiayue.ssi.controller;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiayue.ssi.annotation.OperateLog;
import com.jiayue.ssi.annotation.PreventReplay;
import com.jiayue.ssi.backenum.AuditType;
import com.jiayue.ssi.backenum.BusinessType;
import com.jiayue.ssi.constant.CacheConstants;
import com.jiayue.ssi.constant.CustomException;
import com.jiayue.ssi.entity.SysBlacklist;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.entity.SysUserRole;
import com.jiayue.ssi.service.SysBlacklistService;
import com.jiayue.ssi.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * ip黑名单接口
 *
 * @author xsl
 * @since 2023/03/13
 */
@RestController
@RequestMapping("/ipBlacklistController")
@Slf4j
public class IpBlacklistController {
    @Autowired
    SysBlacklistService sysBlacklistService;

    /**
     * 获取ip列表分页信息
     *
     * @return 用户信息
     */
    @GetMapping(value = "/getAll")
    @PreAuthorize("@ss.hasPermi('system:ipblacklist:list')")
    @OperateLog(title = "黑名单管理", businessType = BusinessType.QUERY, auditType = AuditType.SYS,operdesc = "查询黑名单列表")
    @PreventReplay
    public ResponseVO getAll(String currentPage, String pageSize, String ip) throws CustomException {
        try {
            Integer cp;
            if (StringUtils.isNotEmpty(currentPage)) {
                if (NumberUtil.isInteger(currentPage)){
                    cp = Integer.parseInt(currentPage);
                }
                else{
                    return ResponseVO.fail("currentPage不是整数！");
                }
            }
            else{
                return ResponseVO.fail("currentPage不能是空！");
            }

            Integer ps;
            if (StringUtils.isNotEmpty(pageSize)) {
                if (NumberUtil.isInteger(pageSize)){
                    ps = Integer.parseInt(pageSize);
                }
                else{
                    return ResponseVO.fail("pageSize不是整数！");
                }
            }
            else{
                return ResponseVO.fail("pageSize不能是空！");
            }

            QueryWrapper<SysBlacklist> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(ip)) {
                if (!IPUtils.isIP(ip)) {
                    return ResponseVO.fail("查询条件ip不合法！");
                }
                wrapper.eq("ip", ip);
            }
            Page<SysBlacklist> result = sysBlacklistService.page(new Page<>(cp, ps), wrapper);
            return ResponseVO.success(result);
        } catch (Exception e) {
            throw new CustomException("获取ip列表异常", e);
        }
    }

    /**
     * 新增ip
     */
    @PostMapping(value = "/addIp")
    @OperateLog(title = "黑名单管理", businessType = BusinessType.INSERT, auditType = AuditType.SYS,operdesc = "新增黑名单")
    @PreAuthorize("@ss.hasPermi('system:ipblacklist:add')")
    @PreventReplay
    public ResponseVO addIp(@RequestBody SysBlacklist sysBlacklist) throws CustomException {
        try {
            if (!IPUtils.isIP(sysBlacklist.getIp())) {
                return ResponseVO.fail("ip不合法,不能添加！");
            }
            // ip存在的不能再次添加
            QueryWrapper<SysBlacklist> wrapper = new QueryWrapper<>();
            wrapper.eq("ip", sysBlacklist.getIp());
            SysBlacklist sysBlacklist1 = sysBlacklistService.getOne(wrapper);
            if (sysBlacklist1!=null){
                return ResponseVO.fail("ip已经存在,不能添加！");
            }

            sysBlacklist.setIp(sysBlacklist.getIp());
            sysBlacklist.setIpTime(new Date());
            sysBlacklist.setAddBy(SecurityContextUtil.getSysUser().getUsername());
            boolean bo = sysBlacklistService.save(sysBlacklist);
            if (bo) {
                CacheConstants.blacklistMap.put(sysBlacklist.getIp(),sysBlacklist);
                return ResponseVO.success("添加ip成功");
            } else {
                log.error("添加ip失败");
                return ResponseVO.fail("添加ip失败");
            }
        } catch (Exception e) {
            throw new CustomException("添加ip异常", e);
        }
    }

    /**
     * 删除用户信息
     */
    @PostMapping(value = "/delIp")
    @OperateLog(title = "黑名单管理", businessType = BusinessType.DELETE, auditType = AuditType.SYS,operdesc = "删除黑名单")
    @PreAuthorize("@ss.hasPermi('system:ipblacklist:remove')")
    @PreventReplay
    public ResponseVO delIp(String id) throws CustomException {
        try {
            if (StringUtils.isEmpty(id)) {
                return ResponseVO.fail("id不能为空!");
            }
            // id获取ip信息
            SysBlacklist sysBlacklist = sysBlacklistService.getById(id);
            if (sysBlacklist == null) {
                return ResponseVO.fail("此数据被操作过，自动刷新列表后请重试操作！");
            }

            boolean bo = sysBlacklistService.removeById(Integer.parseInt(id));
            if (bo) {
                CacheConstants.blacklistMap.remove(sysBlacklist.getIp());
                return ResponseVO.success("删除ip成功");
            } else {
                return ResponseVO.fail("删除ip失败");
            }
        } catch (Exception e) {
            throw new CustomException("删除ip异常", e);
        }
    }
}
