package common.controller;



import com.sun.corba.se.spi.ior.ObjectKey;
import common.model.User;

import common.repository.RoleRepository;
import common.repository.RoleTypeRepository;
import common.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import security.RedisLoginStatusManager;
import security.TokenManager;
import security.annotation.CurrentAccount;

import security.interceptor.AuthorizationInterceptor;
import util.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("login")
public class LoginController {

    protected Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserRepository userRepository;
    @Autowired
    RedisLoginStatusManager redisLoginStatusManager;
    @Autowired
    TokenManager tokenManager;
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    RoleTypeRepository roleTypeRepository;


    @RequestMapping(value = "login", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel login(HttpServletResponse response, @RequestParam String email, @RequestParam String password) {
        User user = userRepository.login(email, CipherUtil.generatePassword(password));
        if(null != user){
            if(null != user.getStatus() && !user.getStatus()){
                Map<String, Object> map = new HashMap();;
                map.put("code",201);
                return ResultModel.OK(map);
            }
            //存储token
            String token = tokenManager.createToken(String.valueOf(user.getId()));
            //存储登陆密码
            redisLoginStatusManager.createLoginStatus(token, user.getPassword());

            user.setRoleName(roleRepository.getName(user.getRole()));
            if(null != user.getRoleType()){
                user.setRoleTypeName(roleTypeRepository.getName(user.getRoleType()));
            }
            Cookie cookie = new Cookie("TOKEN", token);
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie);
            Map<String, Object> map = new HashMap();
            map.put("TOKEN", token);
            map.put("user", user);
            map.put("code",200);
            return ResultModel.OK(map);
        }
        Map<String, Object> map = new HashMap();;
        map.put("code",300);
        return ResultModel.OK(map);
        }
    @RequestMapping(value = "login/check", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel loginCheck(HttpServletResponse response, @RequestParam String email) {
        User user = userRepository.login(email);
        if(null != user){
            return ResultModel.OK(true);
        }
        return ResultModel.OK(false);
    }
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel logout(HttpServletRequest request, HttpServletResponse response, @CurrentAccount User user ) {
        if (user != null) {
            String token = request.getHeader("Authorization");
            if(!ValidateUtil.isValid(token)){
                Cookie[] cookies = request.getCookies();
                if (null != cookies) {
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("TOKEN")) {
                            token = cookie.getValue();
                        }
                    }
                }
            }
            //删除session,token
            request.getSession().removeAttribute(Constant.CURRENT_ACCOUNT);
            tokenManager.delRelationshipByToken(token);
            redisLoginStatusManager.deleteLoginStatus(token);

            Cookie cookie = new Cookie("TOKEN", null);
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
        return ResultModel.OK(true);
    }

}
