package xyz.wbsite.action.ajax.system;

import org.springframework.beans.factory.annotation.Value;
import xyz.wbsite.frame.auth.LocalData;
import xyz.wbsite.frame.auth.Token;
import xyz.wbsite.frame.base.ErrorType;
import xyz.wbsite.frame.utils.CookieUtil;
import xyz.wbsite.frame.utils.IDgenerator;
import xyz.wbsite.frame.utils.MD5Util;
import xyz.wbsite.frame.utils.ValidationUtil;
import xyz.wbsite.module.system.req.UserLoginRequest;
import xyz.wbsite.module.system.req.UserLogoutRequest;
import xyz.wbsite.module.system.rsp.UserLoginResponse;
import xyz.wbsite.module.system.rsp.UserLogoutResponse;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Date;

public class UserAjax {

    @Value("${web.url.auth.admin}")
    private String admin;
    @Value("${web.url.auth.pwd}")
    private String pwd;

    public UserLoginResponse login(UserLoginRequest request, Token token, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        UserLoginResponse response = new UserLoginResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        if (request.getUsername().equals(admin)) {//超级管理员登录
            String generatePwd = MD5Util.generatePwd(request.getPassword());
            if (!generatePwd.equals(pwd)) {
                response.addError(ErrorType.BUSINESS_ERROR, "用户名或密码错误!");
            } else {
                Date current = new Date();
                Calendar instance = Calendar.getInstance();
                instance.setTime(current);
                instance.add(Calendar.HOUR_OF_DAY, 1);//默认一个小时内有效

                Token sysToken = LocalData.getSysToken();
                sysToken.setToken(IDgenerator.nextUUID());

                Cookie cookie = CookieUtil.newCookie("token", sysToken.getToken());
                httpServletResponse.addCookie(cookie);
                response.setToken(sysToken.getToken());
            }
        }
        return response;
    }

    public UserLogoutResponse logout(UserLogoutRequest request, Token token) {
        UserLogoutResponse response = new UserLogoutResponse();
        CookieUtil.clearCookie("token");
        return response;
    }
}
