package com.supServer.framework.security.service;

import com.supServer.common.constant.Constants;
import com.supServer.common.constant.UserConstants;
import com.supServer.common.exception.ServiceException;
import com.supServer.common.exception.user.CaptchaException;
import com.supServer.common.exception.user.CaptchaExpireException;
import com.supServer.common.utils.SecurityUtils;
import com.supServer.common.utils.StringUtils;
import com.supServer.common.utils.uuid.IdUtils;
import com.supServer.framework.manager.AsyncManager;

import com.supServer.framework.redis.RedisCache;
import com.supServer.framework.security.mode.RegisterBody;

import com.supServer.project.entity.UserInfo;
import com.supServer.project.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @description：
 * @Author: ly
 * @Date: 2022/3/29 11:15
 */
@Component
public class UserRegisterService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserInfoService userInfoService;


    public String register(RegisterBody registerBody) throws IOException {
        String msg = "",username = registerBody.getUserName(),password = registerBody.getPassword();
        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (username.contains(" "))
        {
            msg = "用户名格式有误";
        }
        else if (StringUtils.isEmpty(registerBody.getType()))
        {
            msg = "请选择用户类型";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在4到8个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在8到12个字符之间";
        }
        else if (UserConstants.NOT_UNIQUE.equals(userInfoService.checkUserNameUnique(username)))
        {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        }
        else if (UserConstants.NOT_UNIQUE.equals(userInfoService.checkUserPhoneUnique(registerBody.getPhone())))
        {
            msg = "保存用户'" + username + "'失败，手机号已被使用";
        }
        else
        {
            // 消息关联标示
            String identifier = IdUtils.fastSimpleUUID();
            UserInfo userInfo = new UserInfo();
            String userId = IdUtils.fastSimpleUUID();
            userInfo.setUserId(userId);
            userInfo.setUserName(username);
            userInfo.setAccount(username);
            if ("0".equals(registerBody.getType())){
                //个人用户
                userInfo.setType(registerBody.getType());
                userInfo.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
                userInfo.setEmail(registerBody.getEmail());
                userInfo.setPhone(registerBody.getPhone());
                userInfo.setProvinceCode(registerBody.getProvinceCode());
                userInfo.setCityCode(registerBody.getCityCode());
                userInfo.setAreaCode(registerBody.getAreaCode());
                userInfo.setAccountStatus("1");
                int i = userInfoService.registerUser(userInfo);
                if (i <= 0 ) {
                    msg = "注册失败,请联系系统管理人员";
                }
            }else {
                if (!registerBody.getIdCardName().equals(registerBody.getLegalPersonName()))
                {
                    throw new ServiceException("保存用户'" + username + "'失败,法人身份证与企业不符");
                }
                //企业用户
                userInfo.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
                userInfo.setPhone(registerBody.getPhone());
                userInfo.setEmail(registerBody.getEmail());
                userInfo.setProvinceCode(registerBody.getProvinceCode());
                userInfo.setCityCode(registerBody.getCityCode());
                userInfo.setAreaCode(registerBody.getAreaCode());
                userInfo.setAccountStatus("0");
                userInfo.setType(registerBody.getType());
                int i = userInfoService.registerUser(userInfo);
                if (i > 0){
                    //添加企业用户认证记录


                }else {
                    msg = "注册失败,请联系系统管理人员";
                }
            }
        }
        return msg;

    }

    /**
     * 校验验证码
     *
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String code, String uuid)
    {
        String verifyKey = Constants.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();
        }
    }

    public static void main(String[] args) {
        String[] companyNames = new String[]{"registerBody.getCompanyName()"};
        System.out.println(companyNames[0]);
    }

}
