package com.gyee.frame.aspect;


import com.gyee.frame.common.exception.TicketException;
import com.gyee.frame.model.ticket.Ibsusers;
import com.gyee.frame.model.ticket.TokenUser;
import com.gyee.frame.service.ticket.IbsusersService;
import com.gyee.frame.service.ticket.LaborService;
import com.gyee.frame.service.ticket.ShiroService;
import com.gyee.frame.util.MD5Util;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class VerificationAspect {

    @Autowired
    ShiroService shiroService;
    @Autowired
    IbsusersService ibsusersService;
    @Autowired
    LaborService laborService;


    @Pointcut("execution(* com.gyee.frame.controller.ticket.*.*(..))")
    public void pointcut(){}

    @Before("pointcut()")
    public void signVerification() {
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        String url = request.getRequestURI();
        String token = request.getHeader("token");
        if (url != null && url.contains("sys/login")) {
            TokenUser user = shiroService.findToken(token);
            /**
             * user == null 表示第一次登录
             */
            if (user == null)
                return;

            /**
             * 再次登入时验证登录信息
             */
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            Ibsusers users = ibsusersService.findUser(username);
            /**
             *  如果users == null || password不相等 表示之前的登录信息和现有的登录信息不一致
             */
            if (users == null || !users.getPassword().equals(MD5Util.encode(password))){
                throw new TicketException("请登录后使用");
            }
        } else {
            TokenUser user = shiroService.findToken(token);
            if (user == null)
                throw new TicketException("请登录后使用");

            long expireTime = user.getExpireTime();
            long nowTime = new Date().getTime();
            /**
             * 判断登录是否过期
             */
            if (nowTime - expireTime > shiroService.EXPIRE)
                throw new TicketException("请登录后使用");
        }
    }
}
