package com.dcsoft.auth.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.dcsoft.auth.form.LoginBody;
import com.dcsoft.auth.form.RegisterBody;
import com.dcsoft.common.core.constant.CacheConstants;
import com.dcsoft.common.core.constant.Constants;
import com.dcsoft.common.core.constant.SecurityConstants;
import com.dcsoft.common.core.constant.UserConstants;
import com.dcsoft.common.core.domain.R;
import com.dcsoft.common.core.enums.UserStatus;
import com.dcsoft.common.core.exception.ServiceException;
import com.dcsoft.common.core.text.Convert;
import com.dcsoft.common.core.utils.SmsUtils;
import com.dcsoft.common.core.utils.StringUtils;
import com.dcsoft.common.core.utils.bean.BeanUtils;
import com.dcsoft.common.core.utils.ip.IpUtils;
import com.dcsoft.common.core.utils.uuid.IdUtils;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.redis.service.RedisService;
import com.dcsoft.common.security.utils.SecurityUtils;
import com.dcsoft.common.sms.config.properties.SmsProperties;
import com.dcsoft.system.api.RemoteUserService;
import com.dcsoft.system.api.domain.SmsDTO;
import com.dcsoft.system.api.domain.SysUser;
import com.dcsoft.system.api.model.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 *
 * @author dcsoft
 */
@Component
public class SysLoginService
{
    private static final Logger log = LoggerFactory.getLogger(SysLoginService.class);
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SmsProperties smsProperties;

    @Value("${visitor.deptId}")
    private Long deptId;

    @Value("${visitor.roleId}")
    private Long roleId;

    private static final String USER_REGISTER = "USER_REGISTER:";
    private static final String USER_REGISTER_TIME = "USER_REGISTER_TIME:";

    private static final long CASH_TIMEOUT = 60 * 5;

    /**
     * 登录
     */
    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("用户不存在/密码错误");
        }

        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 void logout(String loginName)
    {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    public void register(String username, String password)
    {
        // 用户名或密码为空 错误
        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));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

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

    /**
     * 注册(小程序注册都是一键注册)
     */
    public LoginUser appRegister(RegisterBody registerBody) {
        if (ObjectUtil.isNull(registerBody)) {
            throw new ServiceException("请校验注册信息！");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        //如果有openId,从微信一键登录过来的
        if (StringUtils.isNotBlank(registerBody.getOpenid())) {
            sysUser.setOpenid(registerBody.getOpenid());
            //查询该手机的用户信息是否绑定了openId，没有则绑定openId
            R<LoginUser> userInfo = remoteUserService.getUserInfos(registerBody.getPhone(), SecurityConstants.INNER);
            if (null != userInfo && 200 == userInfo.getCode()) {
                //如果没有openId，更新该手机号的openId
                if (ObjectUtil.isNotEmpty(userInfo.getData())
                        && ObjectUtil.isNotEmpty(userInfo.getData().getSysUser())
                        && StringUtils.isBlank(userInfo.getData().getSysUser().getOpenid())) {
                    SysUser sysUser1 = new SysUser();
                    sysUser1.setUserId(userInfo.getData().getSysUser().getUserId());
                    sysUser1.setOpenid(registerBody.getOpenid());
                    remoteUserService.updateOpenId(sysUser1, SecurityConstants.INNER);
                    return remoteUserService.getWxUserInfo(sysUser.getOpenid(), SecurityConstants.INNER).getData();
                }
            } else {
                throw new ServiceException("微信登录注册异常！");
            }
        }

        //如果是手机号验证码登录一键注册
        if(StringUtils.isNotBlank(registerBody.getSmsCode())) {
            //获取短信验证码
            Object smsCode = redisService.getCacheObject(USER_REGISTER + registerBody.getPhone());
            if (ObjectUtil.isNull(smsCode) && StringUtils.isBlank(String.valueOf(smsCode))) {
                throw new ServiceException("验证码已过期，请重新获取");
            }
            if (!StringUtils.equals(registerBody.getSmsCode(), String.valueOf(smsCode))) {
                throw new ServiceException("验证码不正确，请重新填写");
            }
            sysUser.setUserName(registerBody.getPhone());
            sysUser.setPhonenumber(registerBody.getPhone());
        }

        sysUser.setUserName(registerBody.getPhone());
        sysUser.setPhonenumber(registerBody.getPhone());
        sysUser.setNickName(registerBody.getPhone());
        //密码初始化
        if (StringUtils.isBlank(registerBody.getPassword())) {
            AjaxResult result = remoteUserService.selectConfigByKey("sys.user.initPassword");
            String password = "123456";
            if (result.isSuccess()) {
                password = result.get("msg").toString();
            }
            registerBody.setPassword(password);
        }

        sysUser.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
        sysUser.setDeptId(deptId);
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

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

        //查询新增的访客信息
        R<LoginUser> userResult = null;
        if (StringUtils.isNotBlank(registerBody.getOpenid())) {
            userResult = remoteUserService.getWxUserInfo(sysUser.getOpenid(), SecurityConstants.INNER);
        } else {
            userResult = remoteUserService.getUserInfo(sysUser.getUserName(), SecurityConstants.INNER);
        }
        //给访客设置对应角色
        SysUser sysUser1 = new SysUser();
        sysUser1.setUserId(userResult.getData().getSysUser().getUserId());
        sysUser1.setRoleId(roleId);
        remoteUserService.insertVisitor(sysUser1, SecurityConstants.INNER);

        recordLogService.recordLogininfor(sysUser.getOpenid(), Constants.REGISTER, "注册成功");

        if (StringUtils.isNotBlank(sysUser.getOpenid())) {
            return remoteUserService.getWxUserInfo(sysUser.getOpenid(), SecurityConstants.INNER).getData();
        } else {
            return remoteUserService.getUserInfo(sysUser.getUserName(), SecurityConstants.INNER).getData();
        }
    }

    /**
     * 登录
     */
    public LoginUser Smslogin(LoginBody login) {
        // 用户名不在指定范围内 错误
        if (login.getUsername().length() < UserConstants.USERNAME_MIN_LENGTH
                || login.getUsername().length() > UserConstants.USERNAME_MAX_LENGTH) {
            recordLogService.recordLogininfor(login.getUsername(), 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(login.getUsername(), Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }

        //获取短信验证码
        Object cashSmsCode = redisService.getCacheObject(USER_REGISTER + login.getUsername());
        if (ObjectUtil.isNull(login.getSmsCode()) && StringUtils.isBlank(String.valueOf(login.getSmsCode()))) {
            throw new ServiceException("验证码已过期，请重新获取");
        }
        if (!StringUtils.equals(login.getSmsCode(), String.valueOf(cashSmsCode))) {
            throw new ServiceException("验证码不正确，请重新填写");
        }

        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfos(login.getUsername(), SecurityConstants.INNER);

        //没查到用户则注册
        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            RegisterBody registerBody = new RegisterBody();
            BeanUtils.copyProperties(login, registerBody);
            registerBody.setPhone(login.getUsername());
            registerBody.setOpenid(null);
            return this.appRegister(registerBody);
        }

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

        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(login.getUsername(), Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + login.getUsername() + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.recordLogininfor(login.getUsername(), Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + login.getUsername() + " 已停用");
        }
        if (user.getUserName().contains("WX_")) {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(user.getUserId());
            sysUser.setUserName(login.getUsername());
            sysUser.setNickName(login.getUsername());
            sysUser.setPhonenumber(login.getUsername());
            remoteUserService.updateByUserId(sysUser, SecurityConstants.INNER);
        }

        // 查询用户信息
        R<LoginUser> userResultNew = remoteUserService.getUserInfo(login.getUsername(), SecurityConstants.INNER);
        recordLogService.recordLogininfor(login.getUsername(), Constants.LOGIN_SUCCESS, "登录成功");
        return userResultNew.getData();
    }

    public void updateOpenId(LoginUser userInfo, LoginBody form) {
        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser = userInfo.getSysUser();
        sysUser.setUserName(form.getUsername());
        sysUser.setOpenid(form.getOpenid());
        R<?> registerResult = remoteUserService.updateOpenId(sysUser, SecurityConstants.INNER);
        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
    }

    public R<LoginUser> getWxUserInfo(LoginBody form) {
        R<LoginUser> registerResult = remoteUserService.getWxUserInfo(form.getOpenid(), SecurityConstants.INNER);
        return registerResult;
    }

    /**
     * 发送短信
     *
     * @param register
     */
    public R<String> sendSms(RegisterBody register) {
        if (StringUtils.isBlank(register.getPhone())) {
            return R.fail("手机号不能为空!");
        }

        //生成六位验证码
        String smsCode = SmsUtils.generateSmsCode();
        log.info("{}短信二维码{}", register.getPhone(), smsCode);

        SmsDTO smsDTO = new SmsDTO();
        smsDTO.setTemplateId(smsProperties.getTemplate11());
        smsDTO.setCaptcha(smsCode);
        smsDTO.setPhone(register.getPhone());
        AjaxResult ajaxResult = remoteUserService.sendMessage(smsDTO, SecurityConstants.INNER);
        if (!ajaxResult.isSuccess()) {
            throw new ServiceException(ajaxResult.get("msg").toString());
        }

        //缓存次数
        int i = 1;
        Integer time = redisService.getCacheObject(USER_REGISTER_TIME + register.getPhone());
        //如果已经达到10次则达到单日上限
        if (null != time) {
            i = time + 1;
            if(time == 10) {
                throw new ServiceException("发送短信验证码次数已达到单日上限");
            }
        }
        // 获取当天的结束时间点
        Date endOfDay = DateUtil.endOfDay(new Date());
        // 获取当前时间至当天结束的毫秒数
        long cashTime = (endOfDay.getTime() - System.currentTimeMillis()) / 1000;
        redisService.setCacheObject(USER_REGISTER_TIME + register.getPhone(), i, cashTime, TimeUnit.SECONDS);

        //缓存短信
        redisService.setCacheObject(USER_REGISTER + register.getPhone(), smsCode, CASH_TIMEOUT, TimeUnit.SECONDS);
        return R.ok();
    }
}
