
package org.tio.sitexxx.service.service.atom;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.sitexxx.service.cache.CacheConfig;
import org.tio.sitexxx.service.cache.Caches;
import org.tio.sitexxx.service.model.main.User;
import org.tio.sitexxx.service.service.base.RegisterService;
import org.tio.sitexxx.service.service.base.UserService;

import java.util.Random;

public class RegisterAtom extends AbsAtom {

	private static Logger log = LoggerFactory.getLogger(RegisterAtom.class);

	private User user;

	public RegisterAtom(User user) {
		this.user = user;
	}

	public static String getRandomNickname(int length) {
		StringBuilder val = new StringBuilder();
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			val.append(random.nextInt(10));
		}
		return val.toString();
	}

	@Override
	public boolean run() {
		user.setInvFlag(false);
		if (RegisterService.me.isLoginnameExists(user.getLoginname())) {
			msg = "该账号已注册，如忘记密码，请找回";
			log.error(msg + ",loginname:{},nick:{},pwd:{}", user.getLoginname(), user.getNick(), user.getPwd());
			return false;
		}

		if (UserService.ME.save(user) == null) {
			msg = "账号注册失败：账号信息有误";
			log.error(msg + ",loginname:{},nick:{},pwd:{}", user.getLoginname(), user.getNick(), user.getPwd());
			return false;
		}
		user.setUserno(getRandomNickname(10));
		user.update();

		boolean baseResult = RegisterService.me.initBaseInfo(user);
		if (!baseResult) {
			msg = "账号注册失败：基础数据初始化失败";
			log.error(msg + ",loginname:{},nick:{},pwd:{}", user.getLoginname(), user.getNick(), user.getPwd());
			return false;
		}
		boolean coinResult = RegisterService.me.initCoinInfo(user);
		if (!coinResult) {
			msg = "账号注册失败：财务初始化失败";
			log.error(msg + ",loginname:{},nick:{},pwd:{}", user.getLoginname(), user.getNick(), user.getPwd());
			return false;
		}

		RegisterService.me.initWx(user);

		//清空当前用户数
		Caches.getCache(CacheConfig.USER_COUNT).clear();

		if (StrUtil.isBlank(msg)) {
			msg = "注册成功";
		}
		return true;
	}
}
