package com.njcn.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.PubUtils;
import com.njcn.redis.pojo.enums.RedisKeyEnum;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.user.enums.UserResponseEnum;
import com.njcn.user.pojo.po.UserRole;
import com.njcn.user.service.IAppRoleService;
import com.njcn.user.service.IRoleService;
import com.njcn.user.service.IUserRoleService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 类的介绍：
 *
 * @author xuyang
 * @version 1.0.0
 * @createTime 2023/6/25 18:32
 */
@Service
@AllArgsConstructor
public class AppRoleServiceImpl implements IAppRoleService {

    private final RedisUtil redisUtil;

    private final IRoleService roleService;

    private final IUserRoleService userRoleService;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void roleUpdate(String userId, String referralCode, String devCode) {
        Object object = redisUtil.getObjectByKey(RedisKeyEnum.ROLE_REFERRAL_CODE_KEY.getKey());
        if (Objects.isNull(object)){
            throw new BusinessException(UserResponseEnum.REFERRAL_CODE_LAPSE);
        }
        LinkedHashMap<String,String> map = (LinkedHashMap<String,String>) object;
        if (Objects.isNull(map.get(referralCode))){
            throw new BusinessException(UserResponseEnum.REFERRAL_CODE_ERROR);
        }
        //修改用户和角色的关系
        LambdaUpdateWrapper<UserRole> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(UserRole::getUserId,userId).set(UserRole::getRoleId,roleService.getRoleByCode(map.get(referralCode)).getId());
        userRoleService.update(lambdaUpdateWrapper);
        //重新生成新的推荐码
        LinkedHashMap<String,String> roleMap = new LinkedHashMap<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (Objects.equals(entry.getKey(),referralCode)){
                roleMap.put(PubUtils.getCode(6),entry.getValue());
            } else {
                roleMap.put(entry.getKey(),entry.getValue());
            }
        }
        redisUtil.saveByKeyWithExpire("ROLE_REFERRAL_CODE",roleMap,120L);
    }

}
