package com.njcn.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.njcn.common.pojo.exception.BusinessException;
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.Role;
import com.njcn.user.pojo.po.UserRole;
import com.njcn.user.service.IAppInfoSetService;
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.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 IAppInfoSetService iAppInfoSetService;
    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);
        }
        Map<String, String> map;
        if (!(object instanceof Map)) {
            throw new BusinessException(UserResponseEnum.REFERRAL_CODE_LAPSE);
        } else {
            map = (Map<String, String>) object;
        }
        if (Objects.isNull(map.get(referralCode))) {
            throw new BusinessException(UserResponseEnum.REFERRAL_CODE_ERROR);
        }
        Role roleByCode = roleService.getRoleByCode(map.get(referralCode));
        //修改用户和角色的关系
        LambdaUpdateWrapper<UserRole> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(UserRole::getUserId, userId).set(UserRole::getRoleId, roleByCode.getId());
        userRoleService.update(lambdaUpdateWrapper);
//        if (Objects.equals(roleByCode.getCode(), AppRoleEnum.ENGINEERING_USER.getCode())) {
//            iAppInfoSetService.lambdaUpdate().
//                    eq(AppInfoSet::getUserId, userId).
//                    set(AppInfoSet::getExFactoryBug, 1).
//                    set(AppInfoSet::getFunctionBug, 1).
//                    update();
//        }
    }

}
