package cn.chnmuseum.party.common.log;

import cn.chnmuseum.party.auth.util.JwtTokenUtil;
import cn.chnmuseum.party.common.enums.*;
import cn.chnmuseum.party.common.util.DateUtil80;
import cn.chnmuseum.party.common.vo.AuditStatusParam;
import cn.chnmuseum.party.common.vo.GenericPageParam;
import cn.chnmuseum.party.mapper.SysLogMapper;
import cn.chnmuseum.party.model.*;
import cn.chnmuseum.party.service.TOperationLogService;
import cn.chnmuseum.party.service.impl.AuditServiceImpl;
import cn.chnmuseum.party.service.impl.CopyrightOwnerServiceImpl;
import cn.chnmuseum.party.service.impl.TUserServiceImpl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static cn.chnmuseum.party.common.enums.CopyrightOwnerTypeEnum.VIDEO_CONTENT;

@Service
@Aspect
@Transactional
public class SystemOperationLogService extends ServiceImpl<SysLogMapper, SysLog> {

    @Resource
    private SysLogMapper sysLogMapper;

    @Autowired
    private TUserServiceImpl userService;

    @Autowired
    private AuditServiceImpl auditService;

    @Autowired
    private CopyrightOwnerServiceImpl copyrightOwnerService;

    @Autowired
    private TOperationLogService operationLogService;

    public SystemOperationLogService() {
    }

    public TUser getCurAdmin(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (StringUtils.isBlank(header)) {
            throw new AuthenticationException("token失效,请重新登录");
        }
        /**
         * 决绝修改用户名会报错的问题
         */
//        String username = JwtTokenUtil.getUsername(header);
        String userId = JwtTokenUtil.getEmployeeId(header);
        return userService.selectById(userId);
    }

    /**
     * 切点
     */
    @Pointcut("@annotation(cn.chnmuseum.party.common.log.MethodLog)")
    public void methodCachePointcut() {
    }

    /**
     * 切面
     *
     * @param point
     * @return
     */
    @Before("methodCachePointcut()")
    public Object doBefore(JoinPoint point) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        MethodLog methodLog = getAnnotationLog(point);
        String ip = getIp(request);
        TUser user;
        try {
            user = getCurAdmin(request);
        } catch (Exception e) {
            HashMap<Object, Object> resultMap = new HashMap<>();
            resultMap.put("resultCode", "500");
            resultMap.put("message", e.getMessage());
            return resultMap;
        }
        String packages = point.getThis().getClass().getName();
        if (packages.contains("$$EnhancerByCGLIB$$")) { // 如果是CGLIB动态生成的类
            try {
                packages = packages.substring(0, packages.indexOf("$$"));
            } catch (Exception ex) {
                return getFailResult();
            }
        }
        Object[] method_param = point.getArgs(); //获取方法参数;
        if (OperModule.STBOPERATION.getMsg().equals(methodLog.operModule().getMsg())) {
            Object obj = method_param[0];
            String status;
            if (obj instanceof TBoxOperation) {
                TBoxOperation t = (TBoxOperation) obj;
                status = t.getStatus() + "";
            } else {
                status = (String) obj;
            }
            TOperationLog operationLog = new TOperationLog();
            operationLog.setCreateTime(LocalDateTime.now());
            operationLog.setUserId(user.getId());
            if (user.getAreaName() != null) {
                operationLog.setArea(user.getAreaName());
            }
            if (OperType.ACTIVATION.getMsg().equals(methodLog.operType().getMsg()) && "3".equals(status)) {
                operationLog.setOperationType(OperType.FAULT.getMsg());
            } else {
                operationLog.setOperationType(OperType.ACTIVATION.getMsg());
            }
            operationLogService.save(operationLog);
            return method_param;
        }
        SysLog sysLog = new SysLog();
        // todo null
        if (user.getRoleList().contains("1")) {
            sysLog.setType(1);
        } else {
            sysLog.setType(2);
        }
        sysLog.setOperator(user.getUserName());
        sysLog.setOperationIp(ip);
//        sysLog.setOperationContent(methodName);
        sysLog.setOperationTime(DateUtil80.getDateTimeOfTimestamp(System.currentTimeMillis()));
        // 处理设置注解上的参数
        getControllerMethodDescription(user, methodLog, sysLog, method_param);
        sysLogMapper.insert(sysLog);
        return method_param;
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param sysLog 日志
     * @param
     */
    public void getControllerMethodDescription(TUser user, MethodLog methodLog, SysLog sysLog, Object[] method_param) {
        // 设置action动作
        sysLog.setOperationType(methodLog.operType().getMsg());
        sysLog.setOperationContent(methodLog.operType().getMsg());
        sysLog.setOperationObject(methodLog.operModule().getMsg());
        //判断是哪个页面调的用户接口,返回不同日志操作对象
        if (methodLog.operModule().getCode().equals(OperModule.USER.getCode())) {
            TUser u;
            String type;
            if (methodLog.operType().getCode().equals(OperType.ADD.getCode()) || methodLog.operType().getCode().equals(OperType.UPDATE.getCode())) {
                u = (TUser) method_param[0];
                type = u.getType();
            } else if (methodLog.operType().getCode().equals(OperType.CHANGE_PASSWORD.getCode())) {
                u = user;
                type = u.getType();
            } else if (methodLog.operType().getCode().equals(OperType.SELECT.getCode())) {
                type = (String) method_param[0];
            } else {
                String s = (String) method_param[0];
                u = userService.getById(s);
                type = u.getType();
            }
            switch (type) {
                case "1":
                    // 设置标题
                    sysLog.setOperationObject(OperModule.USER.getMsg());
                    break;
                case "2":
                    sysLog.setOperationObject(OperModule.UNITADMIN.getMsg());
                    break;
                case "3":
                    sysLog.setOperationObject(OperModule.STBBASE.getMsg());
                    break;
                case "4":
                    sysLog.setOperationObject(OperModule.STBACCOUNT.getMsg());
                    break;
                case "5":
                    sysLog.setOperationObject(OperModule.STATISTICALUSER.getMsg());
                    break;
            }
        }
        //判断是哪个页面调的审核接口,返回不同日志操作对象
        else if (methodLog.operModule().getCode().equals(OperModule.CHECKVIDEO.getCode())) {
            String type = null;
            String status;
            if (methodLog.operType().getCode().equals(OperType.AUDIT.getCode())) {
                AuditStatusParam auditStatusParam = (AuditStatusParam) method_param[0];
                Audit byId = auditService.getById(auditStatusParam.getId());
                if (byId != null) {
                    type = byId.getType();
                    status = auditStatusParam.getStatus();
                    if (AuditStatusEnum.REFUSED.name().equals(status)) {
                        sysLog.setOperationContent(AuditStatusEnum.REFUSED.getMsg());
                    } else {
                        sysLog.setOperationContent(AuditStatusEnum.APPROVED_FINAL.getMsg());
                    }
                } else {
                    sysLog.setOperationContent(AuditStatusEnum.APPROVED_FINAL.getMsg());
                }
            } else if (methodLog.operType().getCode().equals(OperType.DETAILS.getCode())) {
                type = (String) method_param[1];
            } else if (methodLog.operType().getCode().equals(OperType.SELECT.getCode())) {
                type = (String) method_param[2];
            }
            if (AuditTypeEnum.EXHIBITION_BOARD.name().equals(type)) {
                sysLog.setOperationObject(OperModule.CHECKDISPLAY.getMsg());
            } else if (AuditTypeEnum.LEARNING_CONTENT.name().equals(type)) {
                sysLog.setOperationObject(OperModule.CHECKLEARN.getMsg());
            } else if (AuditTypeEnum.VIDEO_CONTENT.name().equals(type)) {
                sysLog.setOperationObject(OperModule.CHECKVIDEO.getMsg());
            }
        } else if (methodLog.operModule().getCode().equals(OperModule.STBOPERATION.getCode()) && methodLog.operType().getCode().equals(OperType.ACTIVATION.getCode())) {
            TBoxOperation o = (TBoxOperation) method_param[0];
            if (o.getStatus() == 2) {
                sysLog.setOperationType(OperType.ACTIVATION.getMsg());
            } else {
                sysLog.setOperationType(OperType.FAULT.getMsg());
            }
        } else if (methodLog.operModule().getCode().equals(OperModule.LEARNCONTENT.getCode()) && methodLog.operType().getCode().equals(OperType.ENABLE.getCode())) {
            Boolean o = (Boolean) method_param[1];
            if (o) {
                sysLog.setOperationType(OperType.ENABLE.getMsg());
            } else {
                sysLog.setOperationType(OperType.DISABLE.getMsg());
            }
        } else if (methodLog.operModule().getCode().equals(OperModule.DISPLAYCONTENT.getCode()) && methodLog.operType().getCode().equals(OperType.UPDATE.getCode())) {
            sysLog.setOperationType(OperType.UPDATE.getMsg());
        } else if (methodLog.operModule().getCode().equals(OperModule.VIDEOCOPYRIGHT.getCode())) {
            GenericPageParam g = (GenericPageParam) method_param[0];
            if (VIDEO_CONTENT.name().equals(g.getOwnerType())) {
                sysLog.setOperationObject(OperModule.VIDEOCOPYRIGHT.getMsg());
            } else {
                sysLog.setOperationObject(OperModule.DISPLAYCOPYRIGHT.getMsg());
            }
        } else if (methodLog.operModule().getCode().equals(OperModule.DISPLAYCOPYRIGHT.getCode())) {
            CopyrightOwner c;
            String type = null;
            if (methodLog.operType().getCode().equals(OperType.ADD.getCode()) || methodLog.operType().getCode().equals(OperType.UPDATE.getCode())) {
                c = (CopyrightOwner) method_param[0];
                type = c.getOwnerType();
            } else if (methodLog.operType().getCode().equals(OperType.DETAILS.getCode()) || methodLog.operType().getCode().equals(OperType.DELETE.getCode())) {
                String id = (String) method_param[0];
                CopyrightOwner byId = copyrightOwnerService.getById(id);
                type = byId.getOwnerType();
            } else if (methodLog.operType().getCode().equals(OperType.SELECT.getCode())) {
                CopyrightOwnerTypeEnum s = (CopyrightOwnerTypeEnum) method_param[0];
                type = s.name();
            }
            switch (Objects.requireNonNull(type)) {
                case "EXHIBITION_BOARD":
                    // 设置标题
                    sysLog.setOperationObject(OperModule.DISPLAYCOPYRIGHT.getMsg());
                    break;
                case "VIDEO_CONTENT":
                    sysLog.setOperationObject(OperModule.VIDEOCOPYRIGHT.getMsg());
                    break;
            }
        }
    }

    /**
     * 是否存在注解,如果存在就获取
     */
    private MethodLog getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(MethodLog.class);
        }
        return null;
    }

    protected Map<String, Object> getFailResult() {
        Map<String, Object> map = new HashMap<>();
        map.put(RESULT_INFO_ENUM.RESULT_CODE.getKey(), RESPONSE_CODE_ENUM.SERVER_ERROR.getResultCode());
        map.put(RESULT_INFO_ENUM.RESULT_MSG.getKey(), RESPONSE_CODE_ENUM.SERVER_ERROR.getMessage());
        return map;
    }

    /**
     * 方法异常时调用
     *
     * @param
     */
    @AfterThrowing("methodCachePointcut()")
    public void afterThrowing(JoinPoint point) {

    }

    /**
     * 获取请求ip
     *
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
//        String ip = request.getHeader("x-forwarded-for");
        String ip = ip = request.getRemoteAddr();
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

            if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ip = inet.getHostAddress();
            }
        }
        return ip;
    }
}