package cn.iocoder.yudao.module.system.service.auth;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
import cn.iocoder.yudao.framework.common.util.string.StrUtils;
import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.module.system.api.logger.dto.LoginLogCreateReqDTO;
import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserBindReqDTO;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserRespDTO;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.*;
import cn.iocoder.yudao.module.system.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialUserBindDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.social.SocialUserBindMapper;
import cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum;
import cn.iocoder.yudao.module.system.enums.logger.LoginResultEnum;
import cn.iocoder.yudao.module.system.enums.oauth2.OAuth2ClientConstants;
import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum;
import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum;
import cn.iocoder.yudao.module.system.oa.SslSkippingRestTemplate;
import cn.iocoder.yudao.module.system.service.logger.LoginLogService;
import cn.iocoder.yudao.module.system.service.member.MemberService;
import cn.iocoder.yudao.module.system.service.oauth2.OAuth2TokenService;
import cn.iocoder.yudao.module.system.service.social.SocialUserService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.module.system.util.DingtalkUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.google.common.annotations.VisibleForTesting;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * Auth Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Slf4j
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 SocialUserBindMapper socialUserBindMapper;
    @Value("${oa.ssoToken}")
    private String ssoToken;

    @Value("${pms.ssoToken}")
    private String pmsSsoToken;

    @Value("${pms.secret}")
    private String pmsSecret;

    @Value("${oa.secret}")
    private String oaSecret;

    @Value("${zentao.code}")
    private String zentaoCode;

    @Value("${zentao.secret}")
    private String zentaoSecret;

    /**
     * 验证码的开关，默认为 true
     */
    @Value("${yudao.captcha.enable:true}")
    @Setter // 为了单测：开启或者关闭验证码
    private Boolean captchaEnable;

    @Override
    public AdminUserDO authenticate(String username, String password) {
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME;
        // 校验账号是否存在
        AdminUserDO user = userService.getUserByUsername(username);
        if (user == null) {
            createLoginLog(null, username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        if (!userService.isPasswordMatch(password, user.getPassword())) {
            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        // 校验是否禁用
        if (CommonStatusEnum.isDisable(user.getStatus())) {
            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.USER_DISABLED);
            throw exception(AUTH_LOGIN_USER_DISABLED);
        }
        return user;
    }

    @Override
    @DataPermission(enable = false)
    public AuthLoginRespVO login(AuthLoginReqVO reqVO) {
        // 校验验证码
        validateCaptcha(reqVO);

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

        // 如果 socialType 非空，说明需要绑定社交用户
        if (reqVO.getSocialType() != null) {
            socialUserService.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }
        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);
    }

    @Override
    public void sendSmsCode(AuthSmsSendReqVO reqVO) {
        // 如果是重置密码场景，需要校验图形验证码是否正确
        if (Objects.equals(SmsSceneEnum.ADMIN_MEMBER_RESET_PASSWORD.getScene(), reqVO.getScene())) {
            ResponseModel response = doValidateCaptcha(reqVO);
            if (!response.isSuccess()) {
                throw exception(AUTH_REGISTER_CAPTCHA_CODE_ERROR, response.getRepMsg());
            }
        }

        // 登录场景，验证是否存在
        if (userService.getUserByMobile(reqVO.getMobile()) == null) {
            throw exception(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 exception(USER_NOT_EXISTS);
        }

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

    private void createLoginLog(Long userId, String username,
                                LoginLogTypeEnum logTypeEnum, LoginResultEnum loginResult) {
        // 插入登录日志
        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(ServletUtils.getClientIP());
        reqDTO.setResult(loginResult.getResult());
        loginLogService.createLoginLog(reqDTO);
        // 更新最后登录时间
        if (userId != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult())) {
            userService.updateUserLogin(userId, ServletUtils.getClientIP());
        }
    }

    @Override
    public AuthLoginRespVO socialLogin(AuthSocialLoginReqVO reqVO) {
        // 使用 code 授权码，进行登录。然后，获得到绑定的用户编号
        SocialUserRespDTO socialUser = socialUserService.getSocialUserByCode(UserTypeEnum.ADMIN.getValue(), reqVO.getType(),
                reqVO.getCode(), reqVO.getState());
        if (socialUser == null ) {
            throw exception(AUTH_THIRD_LOGIN_NOT_BIND);
        }
        try {
            // 获得绑定用户
            SocialUserBindDO socialUserBind = socialUserBindMapper.selectByUserTypeAndSocialUserId(UserTypeEnum.ADMIN.getValue(),
                    socialUser.getUserId());
            AdminUserDO user;
            if (Objects.isNull(socialUserBind)) {
                String userId = DingtalkUtil.getUserIdByUnion(socialUser.getUnionId());
                OapiV2UserGetResponse.UserGetResponse userDetail = DingtalkUtil.getUserDetail(userId);
                user = userService.getUserByUsername(userDetail.getJobNumber());
                if (user == null) {
                    throw new ServiceException(new ErrorCode(1,"请联系管理员在门户系统中开户"));
                }
                // 绑定钉钉
                SocialUserBindDO newSocialUserBind = SocialUserBindDO.builder()
                        .userId(user.getId()).userType(UserTypeEnum.ADMIN.getValue())
                        .socialUserId(socialUser.getUserId()).socialType(SocialTypeEnum.DINGTALK.getType()).build();
                socialUserBindMapper.insert(newSocialUserBind);
            } else {
                user = userService.getUser(socialUserBind.getUserId());
            }
            // 获得用户
            if (user == null) {
                throw exception(USER_NOT_EXISTS);
            }
            // 创建 Token 令牌，记录登录日志
            return createTokenAfterLoginSuccess(user.getId(), user.getUsername(), LoginLogTypeEnum.LOGIN_SOCIAL);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @VisibleForTesting
    void validateCaptcha(AuthLoginReqVO reqVO) {
        ResponseModel response = doValidateCaptcha(reqVO);
        // 校验验证码
        if (!response.isSuccess()) {
            // 创建登录失败日志（验证码不正确)
            createLoginLog(null, reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME, LoginResultEnum.CAPTCHA_CODE_ERROR);
            throw exception(AUTH_LOGIN_CAPTCHA_CODE_ERROR, response.getRepMsg());
        }
    }

    private ResponseModel doValidateCaptcha(CaptchaVerificationReqVO reqVO) {
        // 如果验证码关闭，则不进行校验
        if (!captchaEnable) {
            return ResponseModel.success();
        }
        ValidationUtils.validate(validator, reqVO, CaptchaVerificationReqVO.CodeEnableGroup.class);
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaVerification(reqVO.getCaptchaVerification());
        return captchaService.verification(captchaVO);
    }

    private AuthLoginRespVO createTokenAfterLoginSuccess(Long userId, String username, LoginLogTypeEnum logType) {
        // 插入登陆日志
        createLoginLog(userId, username, logType, LoginResultEnum.SUCCESS);
        // 创建访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.createAccessToken(userId, getUserType().getValue(),
                OAuth2ClientConstants.CLIENT_ID_DEFAULT, null);
        // 构建返回结果
        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) {
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logType);
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(userType);
        if (ObjectUtil.equal(getUserType().getValue(), userType)) {
            reqDTO.setUsername(getUsername(userId));
        } else {
            reqDTO.setUsername(memberService.getMemberUserMobile(userId));
        }
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(ServletUtils.getClientIP());
        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;
    }

    @Override
    public AuthLoginRespVO register(AuthRegisterReqVO registerReqVO) {
        // 1. 校验验证码
        validateCaptcha(registerReqVO);

        // 2. 校验用户名是否已存在
        Long userId = userService.registerUser(registerReqVO);

        // 3. 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(userId, registerReqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);
    }

    @VisibleForTesting
    void validateCaptcha(AuthRegisterReqVO reqVO) {
        ResponseModel response = doValidateCaptcha(reqVO);
        // 验证不通过
        if (!response.isSuccess()) {
            throw exception(AUTH_REGISTER_CAPTCHA_CODE_ERROR, response.getRepMsg());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(AuthResetPasswordReqVO reqVO) {
        AdminUserDO userByMobile = userService.getUserByMobile(reqVO.getMobile());
        if (userByMobile == null) {
            throw exception(USER_MOBILE_NOT_EXISTS);
        }

        smsCodeApi.useSmsCode(new SmsCodeUseReqDTO()
                .setCode(reqVO.getCode())
                .setMobile(reqVO.getMobile())
                .setScene(SmsSceneEnum.ADMIN_MEMBER_RESET_PASSWORD.getScene())
                .setUsedIp(getClientIP())
        );

        userService.updateUserPassword(userByMobile.getId(), reqVO.getPassword());
    }

    @Override
    public String oaSsoToken(AuthOaLoginReqVO reqVO) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        RestTemplate restTemplate = SslSkippingRestTemplate.createRestTemplate();
        // 使用 MultiValueMap 而不是 HashMap
        MultiValueMap<String, String> params1 = new LinkedMultiValueMap<>();
        params1.add("appid", oaSecret);
        params1.add("loginid", reqVO.getUsername());
        HttpEntity<MultiValueMap<String, String>> requestEntityOut = new HttpEntity<>(params1, headers);
        String result = restTemplate.postForObject(ssoToken, requestEntityOut, String.class);
        // JSONObject jsonObject = JSON.parseObject(result);
        // String token = String.valueOf(jsonObject.get("token"));
        System.out.println("result token:" + result);
        return result;
    }

    @Override
    public String pmsSsoToken(AuthOaLoginReqVO reqVO) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("tenant-id", "1");
        RestTemplate restTemplate = SslSkippingRestTemplate.createRestTemplate();
        // 使用 MultiValueMap 而不是 HashMap
        Map<String, String> params1 = new HashMap<>();
        params1.put("appid", pmsSecret);
        params1.put("username", reqVO.getUsername());
        HttpEntity<Map<String, String>> requestEntityOut = new HttpEntity<>(params1, headers);
        String result = restTemplate.postForObject(pmsSsoToken, requestEntityOut, String.class);
        JSONObject jsonObject = JSON.parseObject(result);
        String token = String.valueOf(jsonObject.get("data"));
        System.out.println("result token:" + token);
        return token;
    }

    @Override
    public String crmGetUser(String token) {
        // 根据token 获取当前登录人的信息 userId...
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.checkAccessToken(token);
        //
        if (ObjUtil.isEmpty(accessTokenDO)) {
            return StrUtil.EMPTY;
        }
        Long userId = accessTokenDO.getUserId();
        if (ObjUtil.isEmpty(userId)) {
            return StrUtil.EMPTY;
        }
        AdminUserDO user = userService.getUser(userId);
        if (ObjUtil.isEmpty(user)) {
            return StrUtil.EMPTY;
        }
        // 查询 userId 对应的员工工号
        return user.getUsername();
    }

    @Override
    public AuthLoginRespVO h5SocialLogin(AuthSocialLoginReqVO reqVO) {
        // h5页面获取免登录授权码code 后台通过code查询用户信息
        String validCode = StrUtils.xssEncode(reqVO.getCode());
        try {
            // 钉钉用户id
            String userId = DingtalkUtil.getUserIdByAuthCode(validCode);
            if (StrUtil.isBlank(userId)) {
                // 查询不到用户详情 返回 登录失败
                throw exception(USER_NOT_EXISTS);
            }
            // 根据钉钉用户id 查询用户详情
            OapiV2UserGetResponse.UserGetResponse userDetail = DingtalkUtil.getUserDetail(userId);
            if (ObjUtil.isEmpty(userDetail)) {
                // 查询不到用户详情 返回 登录失败
                throw exception(USER_NOT_EXISTS);
            }
            // 工号
            String jobNumber = userDetail.getJobNumber();
            // 手机号
            String mobile = userDetail.getMobile();
            if (StrUtil.isBlank(mobile)) {
                throw exception(USER_NOT_EXISTS);
            }
            // 查询当前用户表中 此手机号 是否存在
            AdminUserDO user = userService.getUserByMobile(mobile);
            if (ObjUtil.isEmpty(user)) {
                throw exception(USER_NOT_EXISTS);
            }
            // 创建 Token 令牌，记录登录日志 h5钉钉微应用登录
            return createTokenAfterLoginSuccess(user.getId(), user.getUsername(), LoginLogTypeEnum.LOGIN_DING_H5);
        } catch (Exception e) {
            // 调用钉钉接口报错 提示 登录失败
            e.printStackTrace();
            throw exception(USER_NOT_EXISTS);
        }
    }

    @Override
    public AuthZentaoLoginRespVO zentaoSsoToken(AuthOaLoginReqVO reqVO) {
        AuthZentaoLoginRespVO respVO = new AuthZentaoLoginRespVO();
        try {
            respVO.setCode(zentaoCode);
            LocalDateTime currentDate = LocalDateTime.now();
            Long currentDateMilli = LocalDateTimeUtil.toEpochMilli(currentDate);
            respVO.setTimestamp(currentDateMilli);
            // 跳转链接 http://project.deepoil.cc/zentao/api.php?m=user&f=apilogin&account=0033777&code=Deep0ilPortal&time=1775199774917&token=43f484e18659a1898cded87e6fd8e40c
            // md5 加密 code+应用密钥+时间戳  得到 token
            String token = SecureUtil.md5(zentaoCode + zentaoSecret + currentDateMilli);
            respVO.setToken(token);
            // h5页面获取免登录授权码code 后台通过code查询用户信息
            // String validCode = StrUtils.xssEncode(reqVO.getCode());
            // 根据工号查询用户是否存在
            AdminUserDO user = userService.getUserByUsername(reqVO.getUsername());
            if (ObjUtil.isEmpty(user)) {
                throw exception(USER_NOT_EXISTS);
            }
            respVO.setJobNumber(user.getUsername());
            // 钉钉用户id
            // String userId = DingtalkUtil.getUserIdByAuthCode(validCode);
            // if (StrUtil.isBlank(userId)) {
                // 查询不到用户详情 返回 登录失败
                // throw exception(USER_NOT_EXISTS);
            // }
            // 根据钉钉用户id 查询用户详情
            // OapiV2UserGetResponse.UserGetResponse userDetail = DingtalkUtil.getUserDetail(userId);
            // if (ObjUtil.isEmpty(userDetail)) {
                // 查询不到用户详情 返回 登录失败
                // throw exception(USER_NOT_EXISTS);
            // }
            // 工号
            // String jobNumber = userDetail.getJobNumber();
            // respVO.setJobNumber(jobNumber);
            // 手机号
            // String mobile = userDetail.getMobile();
            // if (StrUtil.isBlank(mobile)) {
                // throw exception(USER_NOT_EXISTS);
            // }
            // 查询当前用户表中 此手机号 是否存在
            // AdminUserDO user = userService.getUserByMobile(mobile);
            // if (ObjUtil.isEmpty(user)) {
                // throw exception(USER_NOT_EXISTS);
            // }
            return respVO;
        } catch (Exception e) {
            // 调用钉钉接口报错 提示 登录失败
            e.printStackTrace();
            throw exception(USER_NOT_EXISTS);
        }
    }

}
