package com.jiayue.ssi.controller;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.CustomException;
import com.jiayue.ssi.entity.SysPolicy;
import com.jiayue.ssi.service.SysPolicyService;
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.HashMap;
import java.util.Map;

/**
 * 策略配置接口
 *
 * @author xsl
 * @since 2023/03/13
 */
@RestController
@RequestMapping("/sysPolicyController")
@Slf4j
public class SysPolicyController {
    @Autowired
    SysPolicyService sysPolicyService;

    /**
     * 获取策略配置
     *
     * @return 用户信息
     */
    @GetMapping(value = "/getAll")
    @PreAuthorize("@ss.hasPermi('system:policy:getAll')")
    @PreventReplay
    public ResponseVO getAll() throws CustomException {
        try {
            SysPolicy sysPolicy = sysPolicyService.getOne(new QueryWrapper<>());
            return ResponseVO.success(sysPolicy);
        } catch (Exception e) {
            throw new CustomException("获取策略配置信息异常", e);
        }
    }

    /**
     * 保存策略配置
     */
    @PostMapping
    @OperateLog(title = "策略配置", businessType = BusinessType.UPDATE, auditType = AuditType.SYS)
    @PreAuthorize("@ss.hasPermi('system:policy:update')")
    @PreventReplay
    public ResponseVO update(@RequestBody SysPolicy sysPolicy) throws CustomException {
        try {
            if (sysPolicy.getLoginFails() == null) {
                return ResponseVO.fail("登录失败次数限制不能为空!");
            } else if (!String.valueOf(sysPolicy.getLoginFails()).matches("^([1-9]|10)$")) {
                return ResponseVO.fail("登录失败次数限制请输入1-10整数");
            }

            if (sysPolicy.getLoginLock() == null) {
                return ResponseVO.fail("登录失败锁定时长不能为空!");
            } else if (!String.valueOf(sysPolicy.getLoginLock()).matches("^(?:[2-9]\\d|100)$")) {
                return ResponseVO.fail("登录失败锁定时长请输入20-100整数");
            }

            if (sysPolicy.getInactiveLogout() == null) {
                return ResponseVO.fail("非活动状态登出系统不能为空!");
            } else if (!String.valueOf(sysPolicy.getInactiveLogout()).matches("^(?:[2-9]\\d|100)$")) {
                return ResponseVO.fail("非活动状态登出系统请输入20-100整数");
            }

            if (sysPolicy.getMemoryWarn() == null) {
                return ResponseVO.fail("内存低于阈值告警不能为空!");
            } else if (!String.valueOf(sysPolicy.getMemoryWarn()).matches("^(?:[2-8]\\d|90)$")) {
                return ResponseVO.fail("内存低于阈值告警请输入20-90整数");
            }

            if (sysPolicy.getLogSpaceWarn() == null) {
                return ResponseVO.fail("日志存储低于阈值告警不能为空!");
            } else if (!String.valueOf(sysPolicy.getMemoryWarn()).matches("^(?:[2-8]\\d|90)$")) {
                return ResponseVO.fail("日志存储低于阈值告警请输入20-90整数");
            }

            if (sysPolicy.getAuditLog() == null) {
                return ResponseVO.fail("审计日志保留月数不能为空!");
            } else if (!String.valueOf(sysPolicy.getAuditLog()).matches("^([3-9]|(1[0-2]))$")) {
                return ResponseVO.fail("审计日志保留月数请输入3-12整数");
            }

            if (sysPolicy.getScanAccount() == null) {
                return ResponseVO.fail("扫描未使用的账号不能为空！");
            } else if (!String.valueOf(sysPolicy.getScanAccount()).matches("^([0-9]|(1[0-2]))$")) {
                return ResponseVO.fail("扫描未使用的账号请输入0-12整数");
            }

            if (StringUtils.isEmpty(sysPolicy.getExcNoticeWayA())) {
                return ResponseVO.fail("A级别异常通知方式不能为空！");
            } else if (!NumberUtil.isInteger(sysPolicy.getExcNoticeWayA())) {
                return ResponseVO.fail("A级别异常通知方式不是整型！");
            }
            if (StringUtils.isEmpty(sysPolicy.getExcNoticeWayB())) {
                return ResponseVO.fail("B级别异常通知方式不能为空！");
            } else if (!NumberUtil.isInteger(sysPolicy.getExcNoticeWayB())) {
                return ResponseVO.fail("B级别异常通知方式不是整型！");
            }
            if (StringUtils.isEmpty(sysPolicy.getExcLevelLogin())) {
                return ResponseVO.fail("连续登录失败异常级别不能为空！");
            } else if (!NumberUtil.isInteger(sysPolicy.getExcLevelLogin())) {
                return ResponseVO.fail("连续登录失败异常级别不是整型！");
            }
            if (StringUtils.isEmpty(sysPolicy.getExcLevelSameUser())) {
                return ResponseVO.fail("同一用户多点登录异常级别不能为空！");
            } else if (!NumberUtil.isInteger(sysPolicy.getExcLevelSameUser())) {
                return ResponseVO.fail("同一用户多点登录异常级别不是整型！");
            }
            boolean bo = sysPolicyService.saveOrUpdate(sysPolicy);
            if (bo) {
                return ResponseVO.success("策略配置保存成功");
            } else {
                log.error("添加用户信息失败");
                return ResponseVO.fail("策略配置保存失败");
            }
        } catch (Exception e) {
            throw new CustomException("策略配置保存异常", e);
        }
    }

    /**
     * 获取授权码
     */
    @GetMapping(value = "/getLicenseKey")
    public ResponseVO getLicenseKey() throws CustomException {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("sysTime", System.currentTimeMillis()+"");
            // 生成随机授权码
            String lk = IdUtils.fastSimpleUUID();
            map.put("lk", lk);
            // 服务端保留授权码1分钟
            LocalCache.set(lk, lk, 60000);
            return ResponseVO.success(map);
        } catch (Exception e) {
            throw new CustomException("获取授权码异常", e);
        }
    }
}
