package com.cf.imes.module.system.service.auth;

import cn.hutool.core.util.BooleanUtil;
import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.cf.imes.framework.common.enums.CommonStatusEnum;
import com.cf.imes.framework.common.enums.UserTypeEnum;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.cf.imes.framework.common.util.monitor.TracerUtils;
import com.cf.imes.framework.common.util.servlet.ServletUtils;
import com.cf.imes.framework.common.util.validation.ValidationUtils;
import com.cf.imes.framework.ip.core.service.IPQueryService;
import com.cf.imes.framework.ip.core.service.dto.IPQueryDataRespDTO;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import com.cf.imes.framework.organ.core.service.OrganFrameworkService;
import com.cf.imes.framework.security.core.LoginUser;
import com.cf.imes.framework.security.core.service.SecurityFrameworkService;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.module.system.api.logger.dto.LoginLogCreateReqDTO;
import com.cf.imes.module.system.api.sms.SmsCodeApi;
import com.cf.imes.module.system.controller.admin.auth.vo.AuthLoginReqVO;
import com.cf.imes.module.system.controller.admin.auth.vo.AuthLoginRespVO;
import com.cf.imes.module.system.controller.admin.auth.vo.AuthLoginSmsCheckReqVO;
import com.cf.imes.module.system.controller.admin.auth.vo.AuthSmsSendReqVO;
import com.cf.imes.module.system.convert.auth.AuthConvert;
import com.cf.imes.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import com.cf.imes.module.system.dal.dataobject.organ.OrganizationDO;
import com.cf.imes.module.system.dal.dataobject.user.AdminUserDO;
import com.cf.imes.module.system.enums.logger.LoginLogTypeEnum;
import com.cf.imes.module.system.enums.logger.LoginResultEnum;
import com.cf.imes.module.system.enums.oauth2.OAuth2ClientConstants;
import com.cf.imes.module.system.framework.chenfeng.config.ChenfengProperties;
import com.cf.imes.module.system.framework.jwt.config.JwtProperties;
import com.cf.imes.module.system.framework.product.ProductProperties;
import com.cf.imes.module.system.service.dept.DeptService;
import com.cf.imes.module.system.service.logger.LoginLogService;
import com.cf.imes.module.system.service.oauth2.OAuth2TokenService;
import com.cf.imes.module.system.service.sms.SmsCodeService;
import com.cf.imes.module.system.service.organ.OrganService;
import com.cf.imes.module.system.service.user.AdminUserService;
import com.cf.imes.module.system.enums.ErrorCodeConstants;
import com.google.common.annotations.VisibleForTesting;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import jakarta.validation.Validator;
import org.springframework.transaction.support.TransactionTemplate;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Objects;

import static com.cf.imes.framework.common.util.servlet.ServletUtils.getClientIP;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.ORGAN_DATA_CODE_NOT_EXISTS;

/**
 * Auth Service 实现类
 *
 * @author 晨丰科技
 */
@Service
@Slf4j
public class AdminAuthServiceImpl implements AdminAuthService {

    @Resource
    private AdminUserService userService;
    @Resource
    private LoginLogService loginLogService;
    @Resource
    private OAuth2TokenService oauth2TokenService;
    @Resource
    private Validator validator;
    @Resource
    private CaptchaService captchaService;
    @Resource
    private SmsCodeApi smsCodeApi;
    @Resource
    private OrganService organService;
    @Resource
    private OrganFrameworkService organFrameworkService;

    @Resource
    private SmsCodeService smsCodeService;

    @Resource
    private IPQueryService ipQueryService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private SecurityFrameworkService securityFrameworkService;

    @Resource
    private DeptService deptService;

    @Resource
    private ProductProperties productProperties;

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private ChenfengProperties chenfengProperties;

    @Override
    public AdminUserDO authenticate(AuthLoginReqVO reqVO) {
        String username = reqVO.getUsername();
        String password = reqVO.getPassword();
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME;
        // 查询账号
        AdminUserDO user = userService.getUserUniqueByUserName(username);
        // 校验用户是否存在
        if (user == null) {
            createLoginLog(null, username, null, null, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw new ServiceException(ErrorCodeConstants.AUTH_LOGIN_USER_NOT_EXISTS);
        }
        Long organId = user.getOrganId();
        // 校验机构有效性
        organFrameworkService.validOrgan(organId);
        // 校验部门有效性
        OrganContextHolder.setOrganId(organId);
        deptService.validUserLoginDept(user.getDeptId());
        // 校验密码
        if (!userService.isPasswordMatch(password, user.getPassword())) {
            createLoginLog(user.getId(), username, null, organId, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw new ServiceException(ErrorCodeConstants.AUTH_LOGIN_BAD_CREDENTIALS);
        }
        // 校验是否禁用
        if (CommonStatusEnum.isDisable(user.getStatus())) {
            createLoginLog(user.getId(), username, null, organId, logTypeEnum, LoginResultEnum.USER_DISABLED);
            throw new ServiceException(ErrorCodeConstants.AUTH_LOGIN_USER_DISABLED);
        }
        return user;
    }


    @Override
    public AuthLoginRespVO login(AuthLoginReqVO reqVO, boolean isManageEndPoint) {
        // 校验验证码
        validateCaptcha(reqVO);

        // 使用账号密码，进行登录
        AdminUserDO user = authenticate(reqVO);

        // 非管理端设置产品id到token
        user.setProductId(!isManageEndPoint ? productProperties.getImesProduct() : null);

        // 管理端只允许超管登录
        Long userId = user.getId();
        boolean isSuperAdmin = securityFrameworkService.hasAnyRoles(userId, "super_admin");
        user.setSuperAdmin(isSuperAdmin);
        if (isSuperAdmin || SecurityFrameworkUtils.isCfOrg(user.getOrganId())) {
            user.setUserType(isManageEndPoint ? UserTypeEnum.ADMIN : UserTypeEnum.MEMBER);
        } else {
            user.setUserType(UserTypeEnum.MEMBER);
            if (isManageEndPoint) {
                throw new ServiceException(ErrorCodeConstants.AUTH_MANAGEENDPOINT_LOGIN_PERMISSION_ERROR);
            }
        }

        Long organId = user.getOrganId();
        OrganizationDO organ = organService.getOrgan(organId);
        String dataSourceCode = organ.getDataSourceCode();
        // 校验机构数据源
        if (StringUtils.isBlank(dataSourceCode)) {
            throw new ServiceException(ORGAN_DATA_CODE_NOT_EXISTS);
        }
        if (CommonStatusEnum.ENABLE.getStatus().equals(organ.getGrayStatus())) {
            // 机构启用灰度、版本赋值到user
            user.setGrayVersion(chenfengProperties.getGray().getVersion());
        } else {
            // 未启用灰度的机构需要默认版本号来做网关实例选择
            user.setGrayDefaultVersion(chenfengProperties.getGray().getDefaultVersion());
        }
        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME, dataSourceCode);
    }

    @Override
    public boolean loginCheck(String mobile) {
        // 查询账号
        AdminUserDO user = userService.getUserUniqueByUserName(mobile);
        // 校验用户是否存在
        if (user == null) {
            createLoginLog(null, mobile, null, null, LoginLogTypeEnum.LOGIN_USERNAME, LoginResultEnum.BAD_CREDENTIALS);
            return false;
        }
        if (StringUtils.isEmpty(user.getPassword())) {
            return true;
        }
        return false;
    }

    @Override
    public boolean loginSmsCheck(AuthLoginSmsCheckReqVO reqVO) {
        String mobile = reqVO.getMobile();
        // 查询账号
        AdminUserDO user = userService.getUserUniqueByUserName(mobile);
        // 校验用户是否存在
        if (user == null) {
            createLoginLog(null, mobile, null, null, LoginLogTypeEnum.LOGIN_USERNAME, LoginResultEnum.BAD_CREDENTIALS);
            return false;
        }
        // 校验验证码正确性
        smsCodeService.validateSmsCode(reqVO);
        return true;
    }

    @Override
    public void sendSmsCode(AuthSmsSendReqVO reqVO) {
        // 登录场景，验证是否存在
        if (userService.getUserByMobile(reqVO.getMobile()) == null) {
            throw new ServiceException(ErrorCodeConstants.AUTH_MOBILE_NOT_EXISTS);
        }
        // 发送验证码
        smsCodeApi.sendSmsCode(AuthConvert.INSTANCE.convert(reqVO).setCreateIp(getClientIP()));
    }

    protected void createLoginLog(Long userId, String username, UserTypeEnum userTypeEnum, Long organId,
                                LoginLogTypeEnum logTypeEnum, LoginResultEnum loginResult) {
        // 手动控制事务
        transactionTemplate.executeWithoutResult(status -> {
            try {
                String clientIP = getClientIP();
                // 插入登录日志
                LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
                reqDTO.setLogType(logTypeEnum.getType());
                reqDTO.setTraceId(TracerUtils.getTraceId());
                reqDTO.setUserId(userId);
                reqDTO.setUserType(getUserType().getValue());
                reqDTO.setUsername(username);
                reqDTO.setUserAgent(ServletUtils.getUserAgent());
                reqDTO.setUserIp(clientIP);
                reqDTO.setResult(loginResult.getResult());
                reqDTO.setOrganId(organId);
                // 设置登录时通过ip云服务查询到的地域信息
                if (ipQueryService.serviceEnable()) {
                    IPQueryDataRespDTO ipQueryDataRespDTO = ipQueryService.querySource(clientIP);
                    reqDTO.setRegion(StringUtils.join(ipQueryDataRespDTO.getProv(), ipQueryDataRespDTO.getCity(), ipQueryDataRespDTO.getArea()));
                }
                loginLogService.createLoginLog(reqDTO);
                // 更新最后登录时间
                if (BooleanUtil.and(userId != null, Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult()))) {
                    userService.updateUserLogin(userId, clientIP);
                }
            } catch (Exception e) {
                status.setRollbackOnly(); // 显式标记事务回滚
                log.error("login log record error", e);
            }
        });
    }

    @VisibleForTesting
    void validateCaptcha(AuthLoginReqVO reqVO) {
        // 如果验证码关闭，则不进行校验
        if (!chenfengProperties.getCaptcha().getEnable()) {
            return;
        }
        // 校验验证码
        ValidationUtils.validate(validator, reqVO, AuthLoginReqVO.CodeEnableGroup.class);
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaVerification(reqVO.getCaptchaVerification());
        ResponseModel response = captchaService.verification(captchaVO);
        // 验证不通过
        if (!response.isSuccess()) {
            // 创建登录失败日志（验证码不正确)
            createLoginLog(null, reqVO.getUsername(), null, null, LoginLogTypeEnum.LOGIN_USERNAME, LoginResultEnum.CAPTCHA_CODE_ERROR);
            throw new ServiceException(ErrorCodeConstants.AUTH_LOGIN_CAPTCHA_CODE_ERROR, response.getRepMsg());
        }
    }

    /**
     * 登陆成功后创建token
     *
     * @param user
     * @param username
     * @param logType
     * @param dataCode
     * @return
     */
    private AuthLoginRespVO createTokenAfterLoginSuccess(AdminUserDO user, String username, LoginLogTypeEnum logType, String dataCode) {
        // 插入登陆日志
        createLoginLog(user.getId(), username, user.getUserType(), user.getOrganId(), logType, LoginResultEnum.SUCCESS);
        // 创建访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.createAccessToken(user, getUserType().getValue(), OAuth2ClientConstants.CLIENT_ID_DEFAULT, dataCode);
        // 构建返回结果
        return AuthConvert.INSTANCE.convert(accessTokenDO);
    }

    @Override
    public void logout(String token, Integer logType) {
        // 删除访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.removeAccessToken(token);
        if (accessTokenDO == null) {
            return;
        }
        // 删除成功，则记录登出日志
        createLogoutLog(accessTokenDO.getUserId(), accessTokenDO.getNickname(), accessTokenDO.getUserType(), logType);
    }

    protected void createLogoutLog(Long userId, String userName, Integer userType, Integer logType) {
        String clientIP = getClientIP();
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logType);
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(userType);
        reqDTO.setUsername(userName);
        // 设置登出时通过ip云服务查询到的地域信息
        if (ipQueryService.serviceEnable()) {
            IPQueryDataRespDTO ipQueryDataRespDTO = ipQueryService.querySource(clientIP);
            reqDTO.setRegion(StringUtils.join(ipQueryDataRespDTO.getProv(), ipQueryDataRespDTO.getCity(), ipQueryDataRespDTO.getArea()));
        }
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(clientIP);
        reqDTO.setResult(LoginResultEnum.SUCCESS.getResult());
        loginLogService.createLoginLog(reqDTO);
    }

    private UserTypeEnum getUserType() {
        return UserTypeEnum.ADMIN;
    }


    @Override
    public String getMesJwtToken() {
        // 当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException(GlobalErrorCodeConstants.UNAUTHORIZED);
        }

        // 计算超时时间
        Instant now = Instant.now();
        long nbf = now.getEpochSecond();
        long exp = now.plus(jwtProperties.getMesTokenTtl()).getEpochSecond();

        // 生产token
        SecretKey secretKey = Keys.hmacShaKeyFor(jwtProperties.getMesSecret().getBytes(StandardCharsets.UTF_8));
        String aud = jwtProperties.getMesAud();
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        return Jwts.builder()
                .setHeaderParam(JwsHeader.ALGORITHM, signatureAlgorithm.getValue())
                .setHeaderParam(JwsHeader.KEY_ID, aud)
                .setHeaderParam(Header.TYPE, Header.JWT_TYPE)
                .claim("userId",loginUser.getId())
                .claim("companyId", loginUser.getOrganId())
                .claim("role","")
                .claim(Claims.AUDIENCE, aud)
                .claim(Claims.ISSUER, aud)
                .claim(Claims.NOT_BEFORE, nbf)
                .claim(Claims.EXPIRATION, exp)
                .signWith(secretKey, signatureAlgorithm)
                .compact();
    }
}
