package com.bonus.sgzb.auth.service;

import com.bonus.sgzb.auth.form.RegisterBody;
import com.bonus.sgzb.common.core.constant.CacheConstants;
import com.bonus.sgzb.common.core.constant.Constants;
import com.bonus.sgzb.common.core.constant.SecurityConstants;
import com.bonus.sgzb.common.core.constant.UserConstants;
import com.bonus.sgzb.common.core.domain.R;
import com.bonus.sgzb.common.core.enums.UserStatus;
import com.bonus.sgzb.common.core.exception.ServiceException;
import com.bonus.sgzb.common.core.text.Convert;
import com.bonus.sgzb.common.core.utils.StringUtils;
import com.bonus.sgzb.common.core.utils.ip.IpUtils;
import com.bonus.sgzb.common.redis.service.RedisService;
import com.bonus.sgzb.common.security.service.TokenService;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.system.api.RemoteUserService;
import com.bonus.sgzb.system.api.domain.SysUser;
import com.bonus.sgzb.system.api.model.LoginUser;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    @Resource
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private TokenService tokenService;


    /**
     * 用户名密码登录
     */
    public LoginUser login(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.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黑名单校验
        isBlackIp(username);
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("用户名不存在/密码错误");
        }

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

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    /**
     * 手机号验证码登录
     */
    public LoginUser loginCode(String phone, String code) {
        // 手机号或验证码为空 错误
        if (StringUtils.isAnyBlank(phone, code)) {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "手机号/验证码必须填写");
            throw new ServiceException("手机号/验证码必须填写");
        }
        // 验证码不在指定范围内 错误
        if (code.length() != UserConstants.CODE_MIN_LENGTH_LOGIN) {
            recordLogService.recordLogininfor(code, Constants.LOGIN_FAIL, "验证码长度不在指定范围");
            throw new ServiceException("验证码长度不在指定范围");
        }
        // 手机号码不在指定范围内 错误
        if (phone.length() != UserConstants.PHONE_DEFAULT_LENGTH_LOGIN) {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "手机号码长度不在指定范围");
            throw new ServiceException("手机号码长度不在指定范围");
        }
        // IP黑名单校验
        isBlackIp(phone);
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfoByPhone(phone, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "登录手机号不存在");
            throw new ServiceException("登录手机号：" + phone + " 不存在");
        }

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

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + phone + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + phone + " 已停用");
        }
        if (remoteUserService.checkCode(phone, code).getCode() != Constants.SUCCESS) {
            throw new ServiceException("对不起，您输入的验证码：" + code + " 不存在");
        } else {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_SUCCESS, "登录成功");
            return userInfo;
        }
    }

    public boolean checkCode(String phone, String code) {
        String a = "_";
        String redisCode = redisService.getCacheObject("code_" + phone);
        if (StringUtils.isEmpty(redisCode)) {
            throw new ServiceException("验证码失效", 403);
        }
        if (!StringUtils.equals(redisCode.split(a)[0], code)) {
            throw new ServiceException("验证码错误", 401);
        } else {
            redisService.deleteObject("code_" + phone);
            return true;
        }
    }

    /**
     * 根据手机号码重置密码，判断Redis中是否有验证码，如果有则通过验证，并删除key
     *
     * @param phone    手机号码
     * @param password 密码
     * @param code     验证码
     */
    private void resetPassword(String phone, String code, Long userId, String password) {
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("密码长度必须在6到19个字符之间");
        }
        if (code.length() != UserConstants.CODE_MIN_LENGTH_LOGIN) {
            throw new ServiceException("验证码长度需为6位");
        }
        if (phone.length() != UserConstants.PHONE_DEFAULT_LENGTH_LOGIN) {
            throw new ServiceException("手机号码长度不在指定范围");
        }
        if (remoteUserService.checkCode(phone, code).getCode() != Constants.SUCCESS) {
            throw new ServiceException("对不起，您输入的验证码：" + code + " 不存在,请输入有效的验证码");
        } else {
            // 已验证过的验证码需要清除
            redisService.deleteObject("code_" + phone);

            // 执行重置密码操作
            SysUser user = new SysUser();
            user.setUserId(userId);
            user.setPassword(SecurityUtils.encryptPassword(password));
        }
    }

    private void isBlackIp(String phone) {
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
    }

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

    /**
     * 注册
     */
    public void register(RegisterBody registerBody) {
        String username = registerBody.getUsername();
        // 随机生成一个10位数密码
        String password = generateRandomPassword(10);
        String phone = registerBody.getPhone();
        // 用户名或密码为空 错误
        if (StringUtils.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.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        sysUser.setPhonenumber(phone);
        sysUser.setDeptId(100L);
        List<Long> list = new ArrayList<>();
        list.add(105L);
        Long[] longArray = new Long[list.size()];
        for (int i = 0; i < list.size(); i++) {
            longArray[i] = list.get(i);
        }
        sysUser.setRoleIds(longArray);
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

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


    public Map loginByMall(LoginUser loginUser) {
        String username = loginUser.getUsername();
        HashMap hashMap = new HashMap();
        String token = loginUser.getToken();
        // 表示商城登录该系统的标识
        if (StringUtils.isNotBlank(token)) {
            R<LoginUser> userInfo = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
            if (ObjectUtils.isNotEmpty(userInfo.getData()) && userInfo.getCode() == 200) {
                return tokenService.createToken(userInfo.getData());
            } else {
                hashMap.put("status", "1");
                return hashMap;
            }
        } else {
            hashMap.put("status", "2");
            return hashMap;
        }
    }


    // 生成一个随机length位数密码
    public static String generateRandomPassword(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();


        StringBuilder password = new StringBuilder();

        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            password.append(characters.charAt(index));
        }
        return password.toString();
    }

    /**
     * 根据用户名查询用户信息
     * @param username
     * @return
     */
    public LoginUser selectByName(String username) {
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
        return userResult.getData();
    }
}
