package com.ruoyi.framework.web.service;

import com.ruoyi.common.enums.AccessFromType;
import com.ruoyi.common.enums.BoolValues;
import com.ruoyi.common.enums.RoleType;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.utils.PhoneUtils;
import com.ruoyi.mxjb.service.IMxjbSelectedGroupService;
import com.ruoyi.system.service.ShortMessageService;
import com.ruoyi.syzy.domain.BBusiWishLocationSubmits;
import com.ruoyi.syzy.service.IBBusiWishLocationSubmitsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * 注册校验方法
 * 
 * @author voluntary
 */
@Component
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ShortMessageService shortMessageService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserCommonService userCommonService;


    @Autowired
    private IMxjbSelectedGroupService selectedGroupService;
    @Autowired
    private IBBusiWishLocationSubmitsService wishLocationSubmitsService;
    /**
     * 注册
     */
    public String register(RegisterBody registerBody)
    {
        String msg = StringUtils.EMPTY, code = registerBody.getCode(),
                username = registerBody.getUsername(),
                password = registerBody.getPassword(),
                provinceName = registerBody.getProvinceName();
        //delFlag=2的用户先删除
        SysUser existUser = userService.selectUserByUserNameOrPhone(username);
        if(null!=existUser&& UserStatus.DISABLE.getCode().equals(existUser.getStatus())){
            userService.deleteUserPhysicalById(existUser.getUserId());
        }
        SysUser user = new SysUser();
        user.setUserName(username);
        user.setPhonenumber(username);

        if (StringUtils.isEmpty(username))
        {
            msg = "手机号不能为空";
        }
        if(!PhoneUtils.isPhoneNumber(username)) {
            msg = "手机号不正确";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }

        else if (StringUtils.isEmpty(provinceName))
        {
            msg = "省份不能为空";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            msg = "手机号'" + username + "'已存在，注册失败";
        }else if(!shortMessageService.checkCode(username,code)){
            // 验证码
            msg = "手机验证码错误";
        }else {
            //默认为front注册
            user.setUserType(String.valueOf(AccessFromType.front.getValue()));
            user.setPhonenumber(username);
            user.setPassword(SecurityUtils.encryptPassword(password));
            user.setPassword2(password);
            user.setIsBind(BoolValues.no.getValue());
            user.setProvinceName(registerBody.getProvinceName());
            Long[] roleIds = new Long[]{RoleType.frontCommon.getValue()};
            user.setRoleIds(roleIds);
            user.setCustomSchoolName(registerBody.getCustomSchoolName());
            user.setCustomClassName(registerBody.getCustomClassName());
            user.setExamMajor(registerBody.getExamMajor());

            Map<String, String> examMajorMap = wishLocationSubmitsService.examMajors(user.getProvinceName()).stream().collect(Collectors.toMap(BBusiWishLocationSubmits::getCourse, BBusiWishLocationSubmits::getCourseName));
            user.setExamMajorName(examMajorMap.get(registerBody.getExamMajor()));

            user.setExamType(registerBody.getExamType());
            user.setGaokaoYear(registerBody.getGaokaoYear());
            //处理是否锁定成绩（主要用于补充：如06-20开启，用户06-21注册的情况）
            if(userCommonService.isInIntervalDate(user)){
                user.setScoreLock(BoolValues.yes.getValue());//初始化时在时间范围内直接将其置为中间状态
            }else {
                user.setScoreLock(BoolValues.no.getValue());
            }

            user.setNickName(registerBody.getName());
            //锁分阶段不允许修改分数及组合
            user.setScore(registerBody.getScore());
            //组合
            Integer groupId= selectedGroupService.selectGroupIdByMode(registerBody.getMode());
            user.setGroupId(groupId);
            user.setSex(registerBody.getSex());

            int row = userService.insertUser(user);
            if (row<1)
            {
                msg = "注册失败,请联系系统管理人员";
            }else{
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(user,username, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }

        return msg;
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }
}
