package com.easyproject.clientbus.service.member.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.easyproject.common.core.domain.entity.ClientMember;
import com.easyproject.service.domain.member.MemberInvite;
import com.easyproject.service.mapper.member.MemberInviteMapper;
import com.easyproject.service.mapper.member.ClientMemberMapper;
import com.easyproject.clientbus.service.member.IMemberInviteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* 方法说明: 用户邀请关系
* 传入参数:
* 返回的值:
* 作者: java-002
* 日期: 2025/8/23 0023
*/
@Slf4j
@Service
public class MemberInviteServiceImpl implements IMemberInviteService {
    Snowflake snowflake = IdUtil.getSnowflake(1, 6);

    @Resource
    private MemberInviteMapper memberInviteMapper;
    @Resource
    private ClientMemberMapper clientMemberMapper;
    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    /**
     * 方法说明: 绑定用户关系
     * 传入参数: registerMemberId 注册用户ID
     * 传入参数: inviteCode 注册用户填写的上级邀请码
     * 返回的值:
     * 作者: java-002
     * 日期: 2025/8/23 0023
     */
    @Async("threadPoolTaskExecutor")
    @Transactional(rollbackFor={RuntimeException.class, Exception.class})
    @Override
    public void addMemberInvite(Long registerMemberId, String inviteCode) {
        log.info("绑定用户关系，注册用户ID={}，上级用户邀请码={}",registerMemberId,inviteCode);

        String lockKey = "register_add_member_invite_"+inviteCode;
        String value = UUID.randomUUID().toString();
        Boolean flag = false;
        do{
            flag = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, value, 60, TimeUnit.SECONDS);//60秒后自动解锁
        }while (!flag);
        log.info("新用户注册，绑定用户关系，加锁成功");

        try {
            if(ObjectUtil.isEmpty(registerMemberId)){
                return;
            }
            if(ObjectUtil.isEmpty(inviteCode)){
                return;
            }
            //查询上级用户信息
            ClientMember inviteCodeMember = clientMemberMapper.selectOne(Wrappers.<ClientMember>lambdaQuery().eq(ClientMember::getInviteCode,inviteCode));
            if(ObjectUtil.isEmpty(inviteCodeMember)){
                log.error("绑定用户关系，邀请码对应用户不存在，注册用户ID={}，上级用户邀请码={}",registerMemberId,inviteCode);
                return;
            }

            //查询父级用户邀请关系数据，在用户关系表中的数据
            MemberInvite parentMemberInvite = memberInviteMapper.selectOne(Wrappers.<MemberInvite>lambdaQuery().eq(MemberInvite::getMemberId,inviteCodeMember.getId()));
            if(ObjectUtil.isEmpty(parentMemberInvite)){//不存在，上级用户还没有拥有过下级
                parentMemberInvite = new MemberInvite();
                parentMemberInvite.setMemberId(inviteCodeMember.getId());
                parentMemberInvite.setPid(0L);
                parentMemberInvite.setHeightNo(0L);
                parentMemberInvite.setLeftNo(1L);
                parentMemberInvite.setRightNo(2L);
                parentMemberInvite.setGroupNo(snowflake.nextIdStr());
                Date date = DateUtil.date();
                parentMemberInvite.setCreateTime(date);
                parentMemberInvite.setUpdateTime(date);
                parentMemberInvite.setRemark("顶级");
                int result = memberInviteMapper.insert(parentMemberInvite);
                if(result>0){
                    //添加下一级
                    addNextLevel(parentMemberInvite,registerMemberId);
                }
            }else{
                //添加下一级
                addNextLevel(parentMemberInvite,registerMemberId);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (value.equals(stringRedisTemplate.opsForValue().get(lockKey))) {
                //删除锁
                stringRedisTemplate.delete(lockKey);
                log.info("新用户注册，绑定用户关系，删除锁成功");
            }
        }

    }

    /**
    * 方法说明: 添加下一级
    * 传入参数:
    * 返回的值:
    * 作者: java-002
    * 日期: 2025/8/23 0023
    */
    public boolean addNextLevel(MemberInvite parentMemberInvite,Long registerMemberId){

        //处理父节点其他节点左值 左序大于当前节点右序的左序号都自增2
        memberInviteMapper.updatOtherNodeLeft(parentMemberInvite.getRightNo(),parentMemberInvite.getGroupNo());
        //处理父节点其他节点右值 右序大于等于当前节点右序的右序号都自增2
        memberInviteMapper.updatOtherNodeRight(parentMemberInvite.getRightNo(),parentMemberInvite.getGroupNo());


        MemberInvite registerMemberInvite = new MemberInvite();//注册用户关系数据
        registerMemberInvite.setMemberId(registerMemberId);
        registerMemberInvite.setPid(parentMemberInvite.getMemberId());
        registerMemberInvite.setHeightNo(parentMemberInvite.getHeightNo()+1);
        registerMemberInvite.setLeftNo(parentMemberInvite.getRightNo());
        registerMemberInvite.setRightNo(parentMemberInvite.getRightNo()+1);
        registerMemberInvite.setGroupNo(parentMemberInvite.getGroupNo());
        Date date = DateUtil.date();
        registerMemberInvite.setCreateTime(date);
        registerMemberInvite.setUpdateTime(date);
        int result = memberInviteMapper.insert(registerMemberInvite);
        if(result>0){
            return true;
        }else{
            return false;
        }
    }

}
