package com.vctgo.auth.service;

import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.vctgo.auth.form.LoginBody;
import com.vctgo.auth.form.LoginRequest;
import com.vctgo.common.core.constant.CacheConstants;
import com.vctgo.common.core.constant.Constants;
import com.vctgo.common.core.constant.SecurityConstants;
import com.vctgo.common.core.constant.UserConstants;
import com.vctgo.common.core.domain.R;
import com.vctgo.common.core.enums.UserStatus;
import com.vctgo.common.core.exception.CaptchaException;
import com.vctgo.common.core.exception.ServiceException;
import com.vctgo.common.core.text.Convert;
import com.vctgo.common.core.utils.StrUtils;
import com.vctgo.common.core.utils.ip.IpUtils;
import com.vctgo.common.redis.service.RedisService;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.RemoteUserService;
import com.vctgo.system.api.domain.SysUser;
import com.vctgo.system.api.domain.SysUserTempalte;
import com.vctgo.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * 登录校验方法
 *
 * @author vctgo
 */
@Slf4j
@Component
public class SysLoginService {
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private CaptchaRedisService captchaRedisService;

    /**
     * 登录
     */
    public LoginUser login(String loginType, String username, String password) {
        // 用户名或密码为空 错误
        if (StrUtils.isAnyBlank(username, password)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = "1".equals(loginType) || "3".equals(loginType) ?
                remoteUserService.getPlatformUserInfo(username, SecurityConstants.INNER) :
                remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StrUtils.isNotNull(userResult) && userResult.getCode() == 409) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException(userResult.getMsg());
        }

        if (StrUtils.isNull(userResult) || StrUtils.isNull(userResult.getData())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUserTempalte user = userResult.getData().getSysUserTempalte();


        // 按照登录类型判断 1 平台端 2 幼儿园端 3 专家端
        if ("1".equals(loginType) && 9999 != user.getTenantId()) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            log.error("平台端---登录用户：" + username + " 不存在");
            throw new ServiceException("登录用户：" + username + " 不存在,请核查核对后再试");
        } else if ("2".equals(loginType) && 9999 == user.getTenantId()) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            log.error("幼儿园端---登录用户：" + username + " 不存在");
            throw new ServiceException("登录用户：" + username + " 不存在,请核对后再试");
        } else if ("3".equals(loginType) && (9999 != user.getTenantId() || !"1".equals(user.getIsExpert()))) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            log.error("专家端---登录用户：" + username + " 不存在");
            throw new ServiceException("登录用户：" + username + " 不存在,请核对后再试");
        }

        //线程塞入租户ID
        SecurityUtils.setTenantId(Convert.toStr(user.getTenantId()));
        SecurityUtils.setTenantType(Convert.toStr(userInfo.getTenantType()));
        SecurityUtils.setTenantName(userInfo.getTenantName());
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }


        String status = ("1".equals(loginType) || "3".equals(loginType)) ? user.getStatus() : user.getAccountStatus();
        if ("1".equals(status)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被禁用");
            throw new ServiceException("对不起，您的账号：" + username + " 已被禁用");
        } else if ("2".equals(status)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号未启用");
            throw new ServiceException("对不起，您的账号：" + username + " 未启用");
        }

        //先查询是否被停用了租户
        if (userInfo.getTenantStatus() != null && UserStatus.DISABLE.getCode().equals(userInfo.getTenantStatus().toString())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "当前租户已经被停用，请联系管理员");
            throw new ServiceException("当前租户已经被停用");
        }
        if (userInfo.getTenantEndDate() != null && userInfo.getTenantEndDate().compareTo(new Date()) < 0) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "当前租户已超过租赁日期，请联系管理员");
            throw new ServiceException("当前租户已超过租赁日期");
        }

        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    public void logout(String loginName) {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    public void register(String username, String password) {
        // 用户名或密码为空 错误
        if (StrUtils.isAnyBlank(username, password)) {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setUserAccount(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }

    /**
     * 验证码二次校验校验
     *
     * @param code
     * @return
     */
    public void verification(String code) {
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaVerification(code);
        ResponseModel response = captchaService.verification(captchaVO);
        if (!response.isSuccess()) {
            throw new CaptchaException("登录失败");
        }
    }


    /**
     * 评选小程序登录
     */
    public LoginUser programLogin(LoginRequest form) {
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.recordLogininfor(form.getAccount(), Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        if ("1".equals(form.getLoginType())) {
            String cachedCode = captchaRedisService.getSmsCode(form.getAccount());
            if (cachedCode == null || cachedCode.equals(form.getCode())) {
                throw new ServiceException("验证码无效或已过期");
            }
            //查询用户
            LoginUser user = remoteUserService.getAppUserInfo(form.getAccount()).getData();
            recordLogService.recordLogininfor(user.getUsername(), Constants.LOGIN_SUCCESS, "登录成功");
            return user;
        } else if ("3".equals(form.getLoginType())) {
            LoginUser user = remoteUserService.getUserInfoByOpenId(form.getWxCode()).getData();
            recordLogService.recordLogininfor(user.getUsername(), Constants.LOGIN_SUCCESS, "登录成功");
            return user;
        }
        throw new ServiceException("暂不支持该登录方式");
    }

    /**
     * 登录
     */
    public LoginUser voteLogin(String loginType, String username, String password) {
        // 用户名或密码为空 错误
        if (StrUtils.isAnyBlank(username, password)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getVoteUserInfo(username, SecurityConstants.INNER);

        if (StrUtils.isNotNull(userResult) && userResult.getCode() == 409) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException(userResult.getMsg());
        }

        if (StrUtils.isNull(userResult) || StrUtils.isNull(userResult.getData())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUserTempalte user = userResult.getData().getSysUserTempalte();


        // 按照登录类型判断 1 平台端 2 幼儿园端 3 专家端
//        if ("1".equals(loginType) && 9999 != user.getTenantId()) {
//            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
//            log.error("平台端---登录用户：" + username + " 不存在");
//            throw new ServiceException("登录用户：" + username + " 不存在,请核查核对后再试");
//        } else if ("2".equals(loginType) && 9999 == user.getTenantId()) {
//            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
//            log.error("幼儿园端---登录用户：" + username + " 不存在");
//            throw new ServiceException("登录用户：" + username + " 不存在,请核对后再试");
//        } else if ("3".equals(loginType) && (9999 != user.getTenantId() || !"1".equals(user.getIsExpert()))) {
//            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
//            log.error("专家端---登录用户：" + username + " 不存在");
//            throw new ServiceException("登录用户：" + username + " 不存在,请核对后再试");
//        }

        //线程塞入租户ID
        SecurityUtils.setTenantId(Convert.toStr(user.getTenantId()));
        SecurityUtils.setTenantType(Convert.toStr(userInfo.getTenantType()));
        SecurityUtils.setTenantName(userInfo.getTenantName());
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }


//        String status = ("1".equals(loginType) || "3".equals(loginType)) ? user.getStatus() : user.getAccountStatus();
//        if ("1".equals(status)) {
//            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被禁用");
//            throw new ServiceException("对不起，您的账号：" + username + " 已被禁用");
//        } else if ("2".equals(status)) {
//            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号未启用");
//            throw new ServiceException("对不起，您的账号：" + username + " 未启用");
//        }

//        //先查询是否被停用了租户
//        if (userInfo.getTenantStatus() != null && UserStatus.DISABLE.getCode().equals(userInfo.getTenantStatus().toString())) {
//            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "当前租户已经被停用，请联系管理员");
//            throw new ServiceException("当前租户已经被停用");
//        }
//        if (userInfo.getTenantEndDate() != null && userInfo.getTenantEndDate().compareTo(new Date()) < 0) {
//            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "当前租户已超过租赁日期，请联系管理员");
//            throw new ServiceException("当前租户已超过租赁日期");
//        }

        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }
}
