package com.supServer.framework.security.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.supServer.common.constant.Constants;
import com.supServer.common.constant.UserConstants;
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.redis.RedisCache;
import com.supServer.framework.security.mode.RegisterBody;
import com.supServer.project.entity.BizCompanyInfo;
import com.supServer.project.entity.BizVerify;
import com.supServer.project.entity.UserInfo;
import com.supServer.project.service.BizCompanyInfoService;
import com.supServer.project.service.IBizVerifyService;
import com.supServer.project.service.SmsService;
import com.supServer.project.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

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

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private BizCompanyInfoService bizCompanyInfoService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private IBizVerifyService bizVerifyService;



    public String register(RegisterBody registerBody) throws IOException {
        String msg = "",username = registerBody.getUserName(),password = registerBody.getPassword();
        //校验短信验证码
//        boolean code = smsService.validateCode(registerBody.getPhone(), registerBody.getSmsCode());
//        if(code){
//            msg = "验证码错误";
//        }
//        else
        if (StringUtils.isEmpty(username)) {
            msg = "姓名不能为空";
        }
        else if (username.contains(" "))
        {
            msg = "姓名格式有误";
        }
        else if (StringUtils.isEmpty(registerBody.getSex()))
        {
            msg = "请选择用户性别";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (StringUtils.isEmpty(registerBody.getEmail()))
        {
            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
        {
            Integer num=bizCompanyInfoService.selectBycode(registerBody.getCreditCode());
            if (ObjectUtil.equal(0,num)){
                msg= "保存用户'" + username + "'失败,该企业审批中";
                return msg;
            }
            if (ObjectUtil.equal(1,num)){
                msg= "保存用户'" + username + "'失败,该企业已被注册";
                return msg;
            }
            if(ObjectUtil.equal(2,num)){
                //驳回修改企业信息
                BizCompanyInfo bizcompanyInfoId=bizCompanyInfoService.selectCompanyInfo(registerBody.getCreditCode());
                bizcompanyInfoId.setCompanyName(registerBody.getCompanyName());
                bizcompanyInfoId.setCreditCode(registerBody.getCreditCode());
                bizcompanyInfoId.setLegalPerson(registerBody.getLegalPerson());
                bizcompanyInfoId.setRegisteredCapital(registerBody.getRegisteredCapital());
                bizcompanyInfoId.setRegisteredDate(DateUtil.parse(registerBody.getRegisteredDate()));
                bizcompanyInfoId.setRegisteredAddress(registerBody.getRegisteredAddress());
                bizcompanyInfoId.setAddressDetail(registerBody.getAddressDetail());
                bizcompanyInfoId.setBriefing(registerBody.getBriefing());
                bizcompanyInfoId.setLicenseUrl(registerBody.getLicenseUrl());
                bizcompanyInfoId.setCardUrl(registerBody.getCardUrl());
                bizcompanyInfoId.setCatId(registerBody.getCatId());
                bizcompanyInfoId.setFileUrl(registerBody.getFileUrl());
                bizcompanyInfoId.setSource("0");
                bizcompanyInfoId.setFileName(registerBody.getFileName());
                bizCompanyInfoService.updateCompany(bizcompanyInfoId);
                BizVerify bizVerify = new BizVerify();
                bizVerify.setCreditCode(registerBody.getCreditCode());
                bizVerify.setStatus(3);
                bizVerify.setReviewStatus(0);
                bizVerify.setCreateTime(LocalDateTime.now());
                bizVerifyService.insert(bizVerify);
            }
            if(null==num){
                //添加用户信息
                UserInfo userInfo = new UserInfo();
                String userId = IdUtils.fastSimpleUUID();
                userInfo.setUserId(userId);
                userInfo.setUserName(username);
                userInfo.setSex(registerBody.getSex());
                userInfo.setAccount(registerBody.getPhone());
                userInfo.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
                userInfo.setPhone(registerBody.getPhone());
                userInfo.setType("0");
                userInfo.setEmail(registerBody.getEmail());
                userInfo.setProvinceCode(registerBody.getProvinceCode());
                userInfo.setCityCode(registerBody.getCityCode());
                userInfo.setAreaCode(registerBody.getAreaCode());
                userInfo.setAccountStatus("0");
                //添加企业信息
                BizCompanyInfo companyInfo = new BizCompanyInfo();
                companyInfo.setUserId(userId);
                companyInfo.setCompanyName(registerBody.getCompanyName());
                companyInfo.setCreditCode(registerBody.getCreditCode());
                companyInfo.setLegalPerson(registerBody.getLegalPerson());
                companyInfo.setRegisteredCapital(registerBody.getRegisteredCapital());
                companyInfo.setRegisteredDate(DateUtil.parse(registerBody.getRegisteredDate()));
                companyInfo.setRegisteredAddress(registerBody.getRegisteredAddress());
                companyInfo.setAddressDetail(registerBody.getAddressDetail());
                companyInfo.setBriefing(registerBody.getBriefing());
                companyInfo.setLicenseUrl(registerBody.getLicenseUrl());
                companyInfo.setCardUrl(registerBody.getCardUrl());
                companyInfo.setCatId(registerBody.getCatId());
                companyInfo.setFileUrl(registerBody.getFileUrl());
                companyInfo.setSource("0");
                companyInfo.setContacts(registerBody.getUserName());
                companyInfo.setPhone(registerBody.getPhone());
                companyInfo.setFileName(registerBody.getFileName());
                companyInfo.setContacts(username);
                companyInfo.setPhone(registerBody.getPhone());
                //添加审批信息
                BizVerify bizVerify = new BizVerify();
                bizVerify.setCreditCode(registerBody.getCreditCode());
                bizVerify.setStatus(3);
                bizVerify.setReviewStatus(0);
                int i = userInfoService.registerUser(userInfo);
                if (i <= 0 ) {
                    msg = "注册失败,请联系系统管理人员";
                }
                int biz=bizCompanyInfoService.insertCompany(companyInfo);
                bizVerifyService.insert(bizVerify);
            }

        }
        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) {
        System.out.println(DateUtil.parse("2003-12-29 00:00:00"));
    }

}
