package link.at17.mid.tushare.web.controller;

import java.time.LocalDateTime;
import java.util.Objects;

import javax.security.auth.login.LoginException;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import link.at17.mid.tushare.dto.R;
import link.at17.mid.tushare.system.util.IPTools;
import link.at17.mid.tushare.web.models.WebUser;
import link.at17.mid.tushare.web.service.AuthService;
import link.at17.mid.tushare.web.service.WebUserService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    AuthService authService;
    
    @Autowired
    WebUserService adminUserService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;
    
    @Autowired
    HttpSession session;
    
    @GetMapping({"", "/", "login"})
    private String login() {

        log.info("IP: {}", IPTools.getClientIP(request));
        
        if (authService.isLogin()) {
            return "redirect:/admin/manage";
        }
       
        return "admin/login/login.html";
    }
    

    @GetMapping("/logout")
    private String logout() {
        return "redirect:/admin";
    }
    
    @PostMapping({"", "/", "login"})
    @ResponseBody
    private R<?> login(String username, String password, String captcha) throws LoginException {
        
        if (StringUtils.isBlank(captcha)) {
            throw new LoginException("验证码不能为空");
        }
        
        Object sessionCaptcha = session.getAttribute(AuthService.CAPTCHA);
        
        if (Objects.isNull(sessionCaptcha) || !captcha.equalsIgnoreCase(sessionCaptcha.toString())) {
            throw new LoginException("验证码错误");
        }
        
        WebUser user = adminUserService.getOne(new LambdaQueryWrapper<WebUser>()
                .eq(WebUser::getUsername, username.toLowerCase())
                .eq(WebUser::getPassword, password));
        
        if (Objects.isNull(user)) {
            log.warn("{} login present with username: {} failed.", IPTools.getClientIP(request), username);
            session.removeAttribute(AuthService.CAPTCHA);
            throw new LoginException("用户名或密码错误");
        }
        else {
            session.removeAttribute(AuthService.CAPTCHA);
            user.setLastLoginTime(LocalDateTime.now()).setLastLoginIp(IPTools.getClientIP(request)).updateById();
            authService.setLogin(username, password);
            //session.setAttribute(TangdaSessionConstants.TANGDA_LOGIN_USER, user);
        }
        return R.ok("/admin/manage/");
    }

}
