package com.easyproject.core.web.service;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.easyproject.common.core.domain.AjaxClientResult;
import com.easyproject.common.core.domain.entity.ClientMember;
import com.easyproject.common.core.domain.model.LoginMember;
import com.easyproject.common.utils.*;
import com.easyproject.common.utils.ip.IpUtils;
import com.easyproject.service.mapper.member.ClientMemberMapper;
import com.easyproject.clientbus.service.member.IMemberInviteService;
import com.easyproject.clientbus.service.member.IClientMemberService;
import com.easyproject.clientbus.service.config.IClientConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.easyproject.common.constant.CacheConstants;
import com.easyproject.common.constant.Constants;
import com.easyproject.common.constant.UserConstants;
import com.easyproject.common.core.domain.model.RegisterBody;
import com.easyproject.common.core.redis.RedisCache;
import com.easyproject.common.exception.user.CaptchaException;
import com.easyproject.common.exception.user.CaptchaExpireException;
import com.easyproject.core.manager.AsyncManager;
import com.easyproject.core.manager.factory.AsyncFactory;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 注册校验方法
 *
 * @author java001
 */
@Slf4j
@Component
public class MemberRegisterService {
    @Autowired
    private IClientMemberService memberService;

    @Autowired
    private IClientConfigService configService;

    @Resource
    private RedisCache redisCache;
    @Resource
    private ClientMemberMapper clientMemberMapper;

    @Resource
    private IMemberInviteService memberInviteService;

    @Resource
    private IClientMemberService clientMemberService;
    @Resource
    private MemberTokenService tokenService;


    /**
     * 方法说明: 注册-账号+密码
     *
     * @param
     * @return
     * @author java-101
     * @date 2024-07-03 14:49:32
     */
    public AjaxClientResult register(RegisterBody registerBody) {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        ClientMember member = new ClientMember();
        member.setMemberName(username);

        // 注册验证码开关
        boolean captchaEnabled = configService.selectRegisterCaptchaEnabled();
        if (captchaEnabled) {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }

        //组装token信息（登录信息）
        LoginMember loginMember = new LoginMember();
        Map<String,Object> map = new HashMap<>();

        if (StringUtils.isEmpty(username)) {
            return AjaxClientResult.error(MessageUtils.message("member.register.002"));
        } else if (StringUtils.isEmpty(password)) {
            return AjaxClientResult.error(MessageUtils.message("member.register.003"));
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            return AjaxClientResult.error(MessageUtils.message("member.register.004"));
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            return AjaxClientResult.error(MessageUtils.message("member.register.005"));
        } else if (UserConstants.NOT_UNIQUE.equals(memberService.checkUserNameUnique(member))) {
            return AjaxClientResult.error(MessageUtils.message("member.register.006"));
        } else {
            //生成当前注册用户邀请码
            // 新增
            String code = RandomUtil.randomStringUpper(6);
            //检查邀请码是否存在
            long count = memberService.selectCountByCode(code);
            if (count > 0) {
                code = RandomUtil.randomStringUpper(6);
            }

            member.setNickName(username);
            member.setPassword(SecurityUtils.encryptPassword(password));
            member.setMemberNum(null);
            member.setAvatarUrl(null);
            member.setMemberAddress(null);
            member.setStatus("0");
            member.setInviteCode(code);
            boolean regFlag = memberService.registerMember(member);
            if (!regFlag) {
                return AjaxClientResult.error(MessageUtils.message("member.register.007"));
            } else {//注册成功

                //用户唯一编号 也就是 用户UID，用于显示与IM登录
                String memberNum = String.valueOf(BigDecimal.valueOf(member.getId()).add(new BigDecimal("22421800")));

                //处理MemberNum（IM使用 平台唯一）
                LambdaUpdateWrapper<ClientMember> update = Wrappers.<ClientMember>lambdaUpdate();
                update.set(ClientMember::getMemberNum, memberNum);
                update.eq(ClientMember::getId, member.getId());
                clientMemberMapper.update(null, update);

                //添加注册日志
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("member.register.success")));

                //添加登录日志
                recordLoginInfo(member.getId());

                //注册成功及登录成功
                loginMember.setMember(member);//用户信息
                loginMember.setUserId(member.getId());//用户ID
                // 生成本系统APP登录状态的token
                String token = tokenService.createToken(loginMember);

                //组装返回值
                map.put(Constants.TOKEN, token);
                map.put("userId",memberNum);
            }
        }
        return AjaxClientResult.success(map);
    }

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

    /**
     * 记录登录信息
     *
     * @param memberId 用户ID
     */
    public void recordLoginInfo(Long memberId) {
        ClientMember clientMember = new ClientMember();
        clientMember.setId(memberId);
        clientMember.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        clientMember.setLoginDate(DateUtils.getNowDate());
        clientMemberService.updateUserProfile(clientMember);
    }
}
