
package com.weather.modules.security.controller;

import com.weather.common.exception.ErrorCode;
import com.weather.common.exception.CommonException;
import com.weather.common.utils.IpUtils;
import com.weather.common.utils.Result;
import com.weather.common.validator.AssertUtils;
import com.weather.common.validator.ValidatorUtils;
import com.weather.modules.log.entity.SysLogLoginEntity;
import com.weather.modules.log.enums.LoginOperationEnum;
import com.weather.modules.log.enums.LoginStatusEnum;
import com.weather.modules.log.service.SysLogLoginService;
import com.weather.modules.security.dto.LoginDTO;
import com.weather.modules.security.password.PasswordUtils;
import com.weather.modules.security.service.CaptchaService;
import com.weather.modules.security.service.SysUserTokenService;
import com.weather.modules.security.user.SecurityUser;
import com.weather.modules.security.user.UserDetail;
import com.weather.modules.sys.dto.SysUserDTO;
import com.weather.modules.sys.enums.UserStatusEnum;
import com.weather.modules.sys.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

/**
 * 登录
 *
 * @author 123
 */
@RestController
@Tag(name = "登录管理")
@AllArgsConstructor
public class LoginController {
    private final SysUserService sysUserService;
    private final SysUserTokenService sysUserTokenService;
    private final CaptchaService captchaService;
    private final SysLogLoginService sysLogLoginService;

    @GetMapping("captcha")
    @Operation(summary = "验证码")
    @Parameter(in = ParameterIn.QUERY, ref = "string", name = "uuid", required = true)
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        //uuid不能为空
        AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL);

        //生成验证码
        captchaService.create(response, uuid);
    }

    @PostMapping("login")
    @Operation(summary = "登录")
    public Result login(HttpServletRequest request,
                        @RequestBody LoginDTO login) {
        // 参数校验
        ValidatorUtils.validateEntity(login);
        if (!captchaService.validate(login.getUuid(), login.getCaptcha())) {
            return new Result().error(ErrorCode.CAPTCHA_ERROR);
        }
        SysUserDTO user = sysUserService.getByUsername(login.getUsername());
        SysLogLoginEntity log = new SysLogLoginEntity();
        log.setOperation(LoginOperationEnum.LOGIN.value());
        log.setCreateDate(new Date());
        log.setIp(IpUtils.getIpAddr(request));
        log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
        // 用户真实性
        if (user != null) {
            log.setCreator(user.getId());
            log.setCreatorName(user.getUsername());
        } else {
            log.setCreatorName(login.getUsername());
        }
        LoginStatusEnum status = null;
        Integer error = 0;
        // 判断密码和账户有效性
        if (user == null ||!PasswordUtils.matches(login.getPassword(), user.getPassword())) {
            status = LoginStatusEnum.FAIL;
            error = ErrorCode.ACCOUNT_PASSWORD_ERROR;
        } else if (user.getStatus() == UserStatusEnum.DISABLE.value()) {
            status = LoginStatusEnum.LOCK;
            error = ErrorCode.ACCOUNT_DISABLE;
        }
        // 统一设置异常信息
        log.setStatus(status == null? LoginStatusEnum.SUCCESS.value(): status.value());
        sysLogLoginService.save(log);
        if (error > 0) {
            throw new CommonException(error);
        }
        return sysUserTokenService.createToken(user.getId());
    }

    @PostMapping("logout")
    @Operation(summary = "退出")
    public Result logout(HttpServletRequest request) {
        UserDetail user = SecurityUser.getUser();

        //退出
        sysUserTokenService.logout(user.getId());

        //用户信息
        SysLogLoginEntity log = new SysLogLoginEntity();
        log.setOperation(LoginOperationEnum.LOGOUT.value());
        log.setIp(IpUtils.getIpAddr(request));
        log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
        log.setIp(IpUtils.getIpAddr(request));
        log.setStatus(LoginStatusEnum.SUCCESS.value());
        log.setCreator(user.getId());
        log.setCreatorName(user.getUsername());
        log.setCreateDate(new Date());
        sysLogLoginService.save(log);

        return new Result();
    }

}
