package com.securitycontrol.system.service;

import com.google.common.collect.Maps;
import com.securitycontrol.common.core.domain.Result;
import com.securitycontrol.common.core.utils.aes.DateTimeHelper;
import com.securitycontrol.common.core.utils.aes.ListHelper;
import com.securitycontrol.common.core.utils.aes.StringHelper;
import com.securitycontrol.common.core.utils.ip.IpUtils;
import com.securitycontrol.common.core.utils.uuid.IdUtils;
import com.securitycontrol.common.core.web.domain.AjaxResult;
import com.securitycontrol.common.security.utils.SecurityUtils;
import com.securitycontrol.entity.system.SystemGlobal;
import com.securitycontrol.system.api.domain.SysLog;
import com.securitycontrol.system.api.model.LoginUser;
import com.securitycontrol.system.mapper.ISysLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author：cwchen
 * @date：2024-02-28-14:02
 * @version：1.0
 * @description：系统日志-业务逻辑层
 */
@Service(value = "ISysLogService")
@Slf4j
public class SysLogServiceImpl implements ISysLogService {

    @Resource(name = "ISysLogMapper")
    private ISysLogMapper mapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveLogs(SysLog sysLog) {
        try {
            if(sysLog.getResult()==SystemGlobal.SUCCESS_NUM){
                sysLog.setFruit("成功");
            }else {
                sysLog.setFruit("失败");
            }
            //如果是异常日志
            if(SystemGlobal.LOG_ERR.equals(sysLog.getErrType()) &&  StringHelper.isEmpty(sysLog.getModel())) {
                SysLog  sysLog1=mapper.getModule(sysLog.getOperUri());
                if(sysLog1!=null){
                    sysLog.setModel(sysLog1.getModel());
                    sysLog.setOperateDetail(sysLog1.getOperateDetail());
                }else {
                    if(StringHelper.isEmpty(sysLog1.getModel())){
                        sysLog.setModel("未知的请求模块");
                    }
                }
            }
            mapper.saveLogs(sysLog);
        } catch (Exception e) {
            log.error("保存系统日志");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }

    @Override
    public void addLogs(SysLog sysLog, HttpServletRequest request) {
            try{
                sysLog.setFruit("失败");
                sysLog.setLogId(IdUtils.getuid());
                sysLog.setIp(IpUtils.getIpAddr(request));
                sysLog.setGrade("高");
                sysLog.setErrType("越权访问");
                sysLog.setFailureReason("页面未授权");
                sysLog.setOperType("查询");
                sysLog.setOperateDetail("查看页面");
                String module=mapper.getModuleName(sysLog);
                sysLog.setLogType(2);
                sysLog.setResult(0);
                sysLog.setOperTime(DateTimeHelper.getNowTime());
                sysLog.setModel(module);
                LoginUser user= SecurityUtils.getLoginUser();
                sysLog.setUserId(user.getUserid());
                sysLog.setOperaUserName(user.getUsername());

                String modules=mapper.getModuleIsc(sysLog);
                if(StringHelper.isNotEmpty(module)){
                    if(StringHelper.isEmpty(module)){
                        sysLog.setModel(modules);
                    }
                    mapper.saveLogs(sysLog);
                }
            }catch (Exception e){
                log.error(e.toString(),e);
            }
    }

    @Override
    public List<SysLog> getSystemLogs(SysLog dto) {
     try{
         if (StringHelper.isEmpty(dto.getOperTime())) {
              dto.setStartTime(DateTimeHelper.getNowDay());
              dto.setEndTime(DateTimeHelper.getNowDay());
         }else {
             dto.setStartTime(dto.getOperTime().split(" - ")[0].trim());
             dto.setEndTime(dto.getOperTime().split(" - ")[1].trim());
         }
         return mapper.getSystemLogs(dto);
     }catch (Exception e){
         log.error(e.toString(),e);
     }
         return new ArrayList<>();
    }

    /**
     *
     * @return
     */
    @Override
    public Result<String> getLogsSet() {
        try{
            String capacity=mapper.getLogsSet();
            if(StringHelper.isEmpty(capacity)){
                return  Result.ok("1024");
            }
            return  Result.ok(capacity);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return  Result.ok(SystemGlobal.LOG_DEFEAT+"");
    }

    /**
     * 系统日志 调试
     * @param capacity
     * @return
     */
    @Override
    public Result<String> setLogsSet(String capacity) {
        try{
            if(StringHelper.isNotEmpty(capacity)){
                if(SystemGlobal.ERR_NUM.equals(capacity.toUpperCase())){
                    return Result.fail("请输入数字");
                }
            }else{
                  return Result.fail("日志容量最低是1024Mb");
            }

            Double cap=Double.parseDouble(capacity);
            if(cap<SystemGlobal.LOG_DEFEAT){
                return Result.fail("日志容量最低是1024Mb");
            }
        }catch (Exception e){
            log.error(e.toString(),e);
            return Result.fail("请输入数字");
        }
        try{
            String city=mapper.getLogsSet();
            if(StringHelper.isEmpty(city)){
                 mapper.setLogsSet(capacity);
            }else {
                mapper.updateLogsSet(capacity);
            }
        }catch (Exception e){
            log.error(e.toString(),e);
            return Result.fail("系统异常");
        }
        return  Result.ok("设置成功","'设置成功'");
    }

    /**
     *
     * @param dto
     * @return
     */
    @Override
    public Result<Map<String, Object>> getLogStatistics(SysLog dto) {
        Map<String,Object> map= Maps.newHashMap();

         String SUCCESS="成功";
       try{
           if (StringHelper.isNotEmpty(dto.getOperTime())) {
               dto.setStartTime(dto.getOperTime().split(" - ")[0].trim());
               dto.setEndTime(dto.getOperTime().split(" - ")[1].trim());
           }else {
               dto.setStartTime(DateTimeHelper.getNowDay());
               dto.setEndTime(DateTimeHelper.getNowDay());
           }
            List<SysLog> all=mapper.getAllLogs(dto);
           if(ListHelper.isNotEmpty(all)){
               int allNum= all.stream().mapToInt(SysLog::getNum).sum();
               map.put("allNum",allNum);
               all.forEach(vo->{
                   if(SUCCESS.equals(vo.getFruit())){
                       map.put("sNum",vo.getNum());
                   }else {
                       map.put("eNum",vo.getNum());
                   }
               });
           }
           if (SystemGlobal.LOG_TYPE.equals(dto.getType())){
               List<Integer> type=new ArrayList<>();
               List<String> typeList=new ArrayList<>();
               typeList.add("系统日志");typeList.add("业务日志");typeList.add("异常日志");
               type.add(0);type.add(1);type.add(2);
               List<Integer> nums=new ArrayList<>();
               type.forEach(str->{
                   dto.setLogType(str);
                   int num=mapper.getLogStatistics(dto);
                   nums.add(num);
               });
               map.put("list",typeList);
               map.put("nums",nums);
           }else {
               List<String> typeList=new ArrayList<>();
               List<Integer> nums=new ArrayList<>();
               List<SysLog> list=mapper.getLogsList(dto);
               list.forEach(vo->{
                   typeList.add(vo.getOperType());
                   nums.add(vo.getNum());
               });
               map.put("list",typeList);
               map.put("nums",nums);
           }
           return  Result.ok(map);
           }catch (Exception e){
             log.error(e.toString(),e);
         }
        return  Result.ok(map);
    }

    /**
     * 日志容量告警
     * @return
     */
    @Override
    public Result<Map<String, Object>> logWarn() {
        Map<String, Object> map=Maps.newHashMap();
      try {
          double bfb=0.9;
            //查询当日的告警
            int num =mapper.getErrorLogs();
            if(num>0){
                map.put("logWarn","1");
                map.put("err","您有新的异常告警"+num +",请及时处理!");
            }else{
                map.put("logWarn","0");
            }
            String rl=mapper.getLogsRl();
            String city=mapper.getLogsSet();
            Double d=Double.parseDouble(rl);
            Double max=Double.parseDouble(city)*bfb;
            if(d>=max){
                map.put("warnType","1");
                map.put("warnError","日志容量告警,当日日志内存为"+d+"MB,日志内存超过总内存的90%,请及时处理!");
            }else {
                map.put("warnType","0");
            }
           return Result.ok(map);
      }catch (Exception e){
           map.put("logWarn","0");
           map.put("warnType","0");
          log.error(e.toString(),e);
      }
        return  Result.ok(map);
    }




}
