package org.dromara.app.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.app.domain.AppLoginUser;
import org.dromara.member.domain.AppUser;
import org.dromara.member.domain.vo.AppUserVo;
import org.dromara.app.service.AppLoginService;
import org.dromara.member.service.AppUserService;
import org.dromara.app.service.IAppAuthStrategy;
import org.dromara.app.session.AppSession;
import org.dromara.app.session.AppSessionManager;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.domain.model.PasswordLoginBody;
import org.dromara.common.core.enums.LoginType;
import org.dromara.common.core.exception.user.CaptchaException;
import org.dromara.common.core.exception.user.CaptchaExpireException;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.MessageUtils;
import org.dromara.common.core.utils.ServletUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.config.properties.CaptchaProperties;
import org.dromara.system.domain.vo.SysClientVo;
import org.dromara.web.domain.vo.LoginVo;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.Instant;
import java.util.UUID;

/**
 * App密码认证策略
 *
 * @author pengles
 */
@Slf4j
@Service("app_password" + IAppAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class AppPasswordAuthStrategy implements IAppAuthStrategy {

    private final CaptchaProperties captchaProperties;
    private final AppLoginService appLoginService;
    private final AppUserService appUserService;
    private final AppSessionManager appSessionManager;

    @Override
    public LoginVo login(String body, SysClientVo client) {
        PasswordLoginBody loginBody = JsonUtils.parseObject(body, PasswordLoginBody.class);
        ValidatorUtils.validate(loginBody);
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        String code = loginBody.getCode();
        String uuid = loginBody.getUuid();

        boolean captchaEnabled = captchaProperties.getEnable();
        // 验证码开关
//        if (captchaEnabled) {
//            validateCaptcha(username, code, uuid);
//        }

        AppUser appUser = loadUserByUsername(username);
        appLoginService.checkLogin(LoginType.PASSWORD, username, () -> !BCrypt.checkpw(password, appUser.getPassword()));

        // 创建App登录用户
        AppLoginUser loginUser = buildAppLoginUser(appUser);

        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        SaLoginParameter model = new SaLoginParameter();
        model.setDeviceType(client.getDeviceType());
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        // 生成token
        LoginHelper.login(loginUser, model);

        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(client.getClientId());

        // 注册会话
        try {
            String ua = ServletUtils.getRequest().getHeader("User-Agent");
            String deviceId = ServletUtils.getRequest().getHeader("X-Device-Id");
            String ip = LoginHelper.getLoginUser().getIpaddr();
            AppSession s = new AppSession();
            s.setSessionId(StpUtil.getTokenValue());
            s.setUserId(loginUser.getUserId());
            s.setDeviceType(client.getDeviceType());
            s.setDeviceId(deviceId != null ? deviceId : UUID.randomUUID().toString());
            s.setUserAgent(ua);
            s.setIp(ip);
            s.setLocation("");
            long now = Instant.now().toEpochMilli();
            s.setLoginAt(now);
            Long ttlSec = StpUtil.getTokenTimeout();
            s.setExpireAt(now + (ttlSec != null ? ttlSec * 1000 : 24 * 3600 * 1000));
            s.setActive(true);
            s.setToken(StpUtil.getTokenValue());
            appSessionManager.register(s, Duration.ofSeconds(ttlSec != null ? ttlSec : 86400));
        } catch (Exception ignored) {
        }
        return loginVo;
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    private void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.blankToDefault(uuid, "");
        String captcha = RedisUtils.getCacheObject(verifyKey);
        RedisUtils.deleteObject(verifyKey);
        if (captcha == null) {
            appLoginService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            appLoginService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"));
            throw new CaptchaException();
        }
    }

    /**
     * 根据用户名加载App用户
     */
    private AppUser loadUserByUsername(String username) {
        AppUserVo user = appUserService.selectUserByUserName(username);
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UserException("user.not.exists", username);
        } else if ("1".equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new UserException("user.blocked", username);
        }
        return JsonUtils.parseObject(JsonUtils.toJsonString(user), AppUser.class);
    }

    /**
     * 构建App登录用户
     */
    private AppLoginUser buildAppLoginUser(AppUser appUser) {
        AppLoginUser loginUser = new AppLoginUser();
        loginUser.setUserId(appUser.getUserId());
        loginUser.setUsername(appUser.getUserName());
        loginUser.setUserType("app");
        // 设置其他必要字段
        return loginUser;
    }

}
