package com.cyksj.service.user.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.util.StringUtil;
import com.cyksj.mapper.UserMapper;
import com.cyksj.model.entity.User;
import com.cyksj.service.user.UserCommonService;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

/**
 * 项目名: yhlxj2
 * 文件名: UserCommonServiceImpl
 * 创建者: JavaZou
 * 创建时间:2025/4/18 14:09
 */
@Service
@RequiredArgsConstructor
public class UserCommonServiceImpl implements UserCommonService {
	private final UserMapper userMapper;

	@Override
	public User insertUser(String account, Boolean isPhone) {
		User user = new User();
		//默认头像
		user.setHeadimgurl(Constant.DEFAULT_HEAD_IMG);
		user.setNickname(Constant.DEFAULT_NAME + RandomUtil.randomString(6));
		user.setRegisterEnv(User.RegisterEnv.pc.name());
		//手机号
		if (isPhone) user.setLoginPhone(account);
		else user.setEmail(account);
		userMapper.insert(user);
		//推广id
		user.setShowId(getUserShowId(user.getId()));
		return user;
	}

	@Override
	public String getUserShowId(Long userId) {
		Integer update = 0;
		String showId = null;
		while (update != 1) {
			showId = StringUtil.randomString(5);
			try {
				update = userMapper.update(null, Wrappers.lambdaUpdate(User.class)
						.set(User::getShowId, showId)
						.eq(User::getId, userId));
			} catch (DuplicateKeyException e) {
				update = 0;
			}
		}
		return showId;
	}
}
