package cn.wisenergy.service.app.impl;

import cn.wisenergy.common.utils.Constants;
import cn.wisenergy.common.utils.R;
import cn.wisenergy.common.utils.RedisUtils;
import cn.wisenergy.common.utils.ShareCodeUtil;
import cn.wisenergy.mapper.UsersMapper;
import cn.wisenergy.model.app.User;
import cn.wisenergy.model.vo.UserRegisterVo;
import cn.wisenergy.service.app.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author 86187
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public R<Boolean> userRegister(UserRegisterVo userVo) {
        log.info("shop-mall[]LoginServiceImpl[]userRegister[]input.param.userVo:" + userVo);
        if (null == userVo || StringUtils.isBlank(userVo.getUserId()) || StringUtils.isBlank(userVo.getSms())) {
            return R.error("入参不能为空!");
        }

        //判断phone是否符合输入类型
        if (!userVo.getUserId().matches(Constants.RegConstant.PHONE_REGSTR)) {
            return R.error("手机号码格式不正确!");
        }

        //1、检验验证码是否正确
        String key = "";
        String redisCode = redisUtils.getValue(key);
        if (!userVo.getSms().equals(redisCode) || StringUtils.isBlank(redisCode)) {
            return R.error("验证码错误!");
        }

        //2、检验手机号是否已经被注册
        boolean bool = checkPhone(userVo.getUserId());
        if (!bool) {
            return R.error("该用户已存在，请直接登录!");
        }

        //3、初始化用户信息
        User user = new User();
        user.setUserId(userVo.getUserId());
        user.setHeadImage(Constants.Common.HEAD_POTRAIT);
        user.setUserLevel(0);
        if (StringUtils.isBlank(userVo.getBeInvitedCode())) {
            user.setBeInvitedCode("1");
        } else {
            //判断推荐人邀请码信息是否正确
            User userCode = usersMapper.queryByInviteCode(userVo.getBeInvitedCode());
            if (null == userCode) {
                return R.error("邀请码填写无效,邀请人不存在,请重新填写!");
            }
            user.setBeInvitedCode(userVo.getBeInvitedCode());
        }

        //todo 当id大于千万级别是 邀请码的位数会大于六位
        String inviteCode = ShareCodeUtil.idToCode("");
        user.setInviteCode(inviteCode);
        return null;
    }

    private Boolean checkPhone(String userId) {
        //根据userId，获取用户信息
        User user = usersMapper.getByUserId(userId);
        return null == user;
    }
}
