package com.bonus.zlpt.auth.service;

import com.bonus.zlpt.common.core.utils.DateUtils;
import com.bonus.zlpt.system.api.constants.RedisConstants;
import io.micrometer.core.instrument.util.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.bonus.zlpt.common.core.constant.CacheConstants;
import com.bonus.zlpt.common.core.constant.Constants;
import com.bonus.zlpt.common.core.constant.SecurityConstants;
import com.bonus.zlpt.common.core.constant.UserConstants;
import com.bonus.zlpt.common.core.domain.R;
import com.bonus.zlpt.common.core.enums.UserStatus;
import com.bonus.zlpt.common.core.exception.ServiceException;
import com.bonus.zlpt.common.core.text.Convert;
import com.bonus.zlpt.common.core.utils.StringUtils;
import com.bonus.zlpt.common.core.utils.ip.IpUtils;
import com.bonus.zlpt.common.redis.service.RedisService;
import com.bonus.zlpt.common.security.utils.SecurityUtils;
import com.bonus.zlpt.system.api.RemoteUserService;
import com.bonus.zlpt.system.api.domain.SysUser;
import com.bonus.zlpt.system.api.model.LoginUser;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    /**
     * 登录
     */
    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黑名单校验
        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.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.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();
        SysUser user = userResult.getData().getSysUser();
        //新增逻辑   如果用户点击账户注销 那么修改用户账号状态为已删除，并设置最后的登录时间 一周之内可以登录并且可以撤销注销状态，如果一周之内没有撤销，那么将该账号数据物理删除
        Date loginDate = DateUtils.addDays(user.getLoginDate(), 7);
        //如果是删除状态，并且超出一周
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()) && loginDate.after(new Date()))
        {
            //删除用户
            removeUser(user.getUserId());
            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 void logout(String loginName)
    {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    public void register(String phonenumber,String code,String username, String password)
    {




        if (StringUtils.isAnyBlank(phonenumber,code,username, password))
        {
            throw new ServiceException("用户/密码必须填写");
        }

        checkCode(phonenumber,code);

        String mobileRegEx = "^1[3,4,5,6,7,8,9][0-9]{9}$";
        Pattern pattern = Pattern.compile(mobileRegEx);
        Matcher matcher = pattern.matcher(phonenumber);

        if (!matcher.matches()) {
            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.setLoginDate(new Date());
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

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


    /**
     * 根据用户id删除用户
     * @param id
     */
    public void removeUser(Long id){

        remoteUserService.remove(new Long[]{id});
    }

    /**
     * 用户注销或者撤销注销
     * @param user
     */
    public void logOff(SysUser user) {

        remoteUserService.edit(user);
    }



    /**
     * 判断验证码是否存在Redis中
     *
     * @param phone 手机号码
     * @param code  验证码
     * @return 校验结果
     * @throws ServiceException 异常信息
     */
    public boolean checkCode(String phone, String code) {

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



}
