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

import cn.hutool.core.util.ObjectUtil;
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.util.ServiceExceptionUtil;
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.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.api.social.dto.SocialUserRespDTO;
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.AuthSmsLoginReqVO;
import com.cf.imes.module.system.controller.admin.auth.vo.AuthSmsSendReqVO;
import com.cf.imes.module.system.controller.admin.auth.vo.AuthSocialLoginReqVO;
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.enums.sms.SmsSceneEnum;
import com.cf.imes.module.system.service.logger.LoginLogService;
import com.cf.imes.module.system.service.member.MemberService;
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.social.SocialUserService;
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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

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

import java.util.Objects;

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
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
@RefreshScope
public class AdminAuthServiceImpl implements AdminAuthService {

    @Resource
    private AdminUserService userService;
    @Resource
    private LoginLogService loginLogService;
    @Resource
    private OAuth2TokenService oauth2TokenService;
    @Resource
    private SocialUserService socialUserService;
    @Resource
    private MemberService memberService;
    @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;

    /**
     * 验证码的开关，默认为 true
     */
    @Value("${chenfeng.captcha.enable:true}")
    private Boolean captchaEnable;

    @Value("${chenfeng.gray.version:1.0.0}")
    private String grayVersion;

    @Value("${chenfeng.gray.default-version:1.0.0}")
    private String grayDefaultVersion;

    @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 ServiceExceptionUtil.exception(ErrorCodeConstants.AUTH_LOGIN_BAD_CREDENTIALS);
        }
        Long organId = user.getOrganId();
        // 校验机构有效性
        organFrameworkService.validOrgan(organId);
        // 校验部门有效性
        OrganContextHolder.setOrganId(organId);
        organFrameworkService.validDept(user.getDeptId());
        // 校验密码
        if (!userService.isPasswordMatch(password, user.getPassword())) {
            createLoginLog(user.getId(), username, null, organId, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.AUTH_LOGIN_BAD_CREDENTIALS);
        }
        // 校验是否禁用
        if (CommonStatusEnum.isDisable(user.getStatus())) {
            createLoginLog(user.getId(), username, null, organId, logTypeEnum, LoginResultEnum.USER_DISABLED);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.AUTH_LOGIN_USER_DISABLED);
        }
        return user;
    }


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

        // 使用账号密码，进行登录
        AdminUserDO user = authenticate(reqVO);
        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 {
            if (isManageEndPoint) {
                throw new ServiceException(ErrorCodeConstants.AUTH_MANAGEENDPOINT_LOGIN_PERMISSION_ERROR);
            }
            user.setUserType(UserTypeEnum.MEMBER);
        }

        Long organId = user.getOrganId();
        OrganizationDO organ = organService.getOrgan(organId);
        String dataSourceCode = organ.getDataSourceCode();
        // 校验机构数据源
        if (StringUtils.isBlank(dataSourceCode)) {
            throw exception(ORGAN_DATA_CODE_NOT_EXISTS);
        }
        if (CommonStatusEnum.ENABLE.getStatus().equals(organ.getGrayStatus())) {
            // 机构启用灰度、版本赋值到user
            user.setGrayVersion(grayVersion);
        } else {
            // 未启用灰度的机构需要默认版本号来做网关实例选择
            user.setGrayDefaultVersion(grayDefaultVersion);
        }
        // 创建 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 ServiceExceptionUtil.exception(ErrorCodeConstants.AUTH_MOBILE_NOT_EXISTS);
        }
        // 发送验证码
        smsCodeApi.sendSmsCode(AuthConvert.INSTANCE.convert(reqVO).setCreateIp(getClientIP()));
    }

    @Override
    public AuthLoginRespVO smsLogin(AuthSmsLoginReqVO reqVO) {
        // 校验验证码
        smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.ADMIN_MEMBER_LOGIN.getScene(), getClientIP()));

        // 获得用户信息
        AdminUserDO user = userService.getUserByMobile(reqVO.getMobile());
        if (user == null) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.USER_NOT_EXISTS);
        }
        Long organId = user.getOrganId();
        OrganizationDO organ = organService.getOrgan(organId);
        String dataSourceCode = organ.getDataSourceCode();
        if(StringUtils.isBlank(dataSourceCode)) {
            throw exception(ORGAN_DATA_CODE_NOT_EXISTS);
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, reqVO.getMobile(), LoginLogTypeEnum.LOGIN_MOBILE, dataSourceCode);
    }

    private 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 (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);
            }
        });
    }

    @Override
    public AuthLoginRespVO socialLogin(AuthSocialLoginReqVO reqVO) {
        // 使用 code 授权码，进行登录。然后，获得到绑定的用户编号
        SocialUserRespDTO socialUser = socialUserService.getSocialUserByCode(UserTypeEnum.ADMIN.getValue(), reqVO.getType(),
                reqVO.getCode(), reqVO.getState());
        if (socialUser == null || socialUser.getUserId() == null) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.AUTH_THIRD_LOGIN_NOT_BIND);
        }

        // 获得用户
        AdminUserDO user = userService.getUser(socialUser.getUserId());
        if (user == null) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.USER_NOT_EXISTS);
        }

        Long organId = user.getOrganId();
        OrganizationDO organ = organService.getOrgan(organId);
        String dataSourceCode = organ.getDataSourceCode();
        if(StringUtils.isBlank(dataSourceCode)) {
            throw exception(ORGAN_DATA_CODE_NOT_EXISTS);
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, user.getUsername(), LoginLogTypeEnum.LOGIN_SOCIAL, dataSourceCode);
    }

    @VisibleForTesting
    void validateCaptcha(AuthLoginReqVO reqVO) {
        // 如果验证码关闭，则不进行校验
        if (!captchaEnable) {
            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 ServiceExceptionUtil.exception(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 AuthLoginRespVO refreshToken(String refreshToken) {
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshAccessToken(refreshToken, OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        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.getUserType(), logType);
    }

    private void createLogoutLog(Long userId, 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(getUsername(userId));
        // 设置登录时通过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 String getUsername(Long userId) {
        if (userId == null) {
            return null;
        }
        AdminUserDO user = userService.getUser(userId);
        return user != null ? user.getUsername() : null;
    }

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

}
