package me.qwq.doghouse.controller.admin;

import java.util.Objects;

import javax.security.auth.login.LoginException;
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 jodd.util.Base64;
import me.qwq.doghouse.controller.common.BaseController;
import me.qwq.doghouse.entity.User;
import me.qwq.doghouse.pojo.dto.R;
import me.qwq.doghouse.service.UserService;
import me.qwq.doghouse.util.CookieUtils;
import me.qwq.doghouse.util.Cryptos;
import me.qwq.doghouse.util.SessionUtils;

@Controller
@RequestMapping("/admin/v2")
public class LoginController extends BaseController {

    @Autowired
    private UserService adminUserService;
    
    
    @GetMapping("/login")
    public String loginPage() {
        
        if (isLogin()) {
            return "redirect:/admin/v2/index";
        }
        
        return "admin/login";
    }
    
    @PostMapping("/login")
    @ResponseBody
    public R<?> login(String username, String password, String captcha, String redirect) throws LoginException {
        if (StringUtils.isBlank(captcha)) {
            throw new LoginException("验证码不能为空");
        }
        Object sessionCaptcha = session.getAttribute(SessionUtils.CAPTCHA);
        if (Objects.isNull(sessionCaptcha) ||
            !captcha.equalsIgnoreCase(sessionCaptcha.toString())) {
            throw new LoginException("验证码错误");
        }
        if (StringUtils.isBlank(username) || !passwordIsNotEmpty(password)) {
            throw new LoginException("用户名和密码不能为空");
        }
        User adminUser = adminUserService.getOne(
                new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
                .eq(User::getPassword, password));
        if (adminUser != null) {
            SessionUtils.setUser(session, adminUser);
            CookieUtils.setUserToCookie(response, adminUser);
            
            String to = "/admin/v2";
            if (StringUtils.isNotEmpty(redirect)) {
                to = Base64.decodeToString(redirect);
            }
            session.removeAttribute(SessionUtils.CAPTCHA);
            return R.ok(to);
        } else {
            // 清除 session 中验证码，避免单次输入验证码后的碰撞
            // 直到下一次请求 kaptcha 接口再重新设置
            session.removeAttribute(SessionUtils.CAPTCHA);
            throw new LoginException("用户名和/或密码错误");
        }
    }
    
    @GetMapping("/logout")
    public String logout() {
        session.removeAttribute(SessionUtils.LOGIN_USER);
        return "redirect:/admin/v2/login";
    }

    
    static final String EMPTY_PASSWORD = Cryptos.sha3("", 224);
    
    static boolean passwordIsNotEmpty(String password) {
        return StringUtils.isNotEmpty(password) &&
                !password.equalsIgnoreCase(EMPTY_PASSWORD);
    }
}
