package com.njcn.user.service.impl;

import com.njcn.common.utils.PubUtils;
import com.njcn.redis.pojo.enums.RedisKeyEnum;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.user.enums.AppRoleEnum;
import com.njcn.user.pojo.vo.app.RoleReferralCodeVO;
import com.njcn.user.service.IReferralCodeService;
import com.njcn.user.service.IRoleService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.CaseInsensitiveMap;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 类的介绍：
 *
 * @author xuyang
 * @version 1.0.0
 * @createTime 2023/6/25 16:17
 */
@Slf4j
@Service
@AllArgsConstructor
public class ReferralCodeServiceImpl implements IReferralCodeService {

    private final RedisUtil redisUtil;

    private final IRoleService roleService;

    @Override
    public List<RoleReferralCodeVO> findReferralCode() {
        List<RoleReferralCodeVO> list = new ArrayList<>();
        Object object = redisUtil.getObjectByKey(RedisKeyEnum.ROLE_REFERRAL_CODE_KEY.getKey());
        if (Objects.isNull(object)){
            list = refreshReferralCode();
        } else {
            Map<String, String> map = ( Map<String, String>) redisUtil.getObjectByKey(RedisKeyEnum.ROLE_REFERRAL_CODE_KEY.getKey());
            for (Map.Entry<String, String> entry : map.entrySet()) {
                RoleReferralCodeVO vo = new RoleReferralCodeVO();
                vo.setRoleReferralCode(entry.getKey());
                vo.setRoleName(roleService.getRoleByCode(entry.getValue()).getName());
                list.add(vo);
            }
        }
        return list;
    }

    @Override
    public List<RoleReferralCodeVO> refreshReferralCode() {
        Map<String, String> result = new CaseInsensitiveMap();
        String code1 = PubUtils.getCode(6);
        String code2 = PubUtils.getCode(6);
        String code3 = PubUtils.getCode(6);
        result.put(code1,AppRoleEnum.MARKET_USER.getCode());
        result.put(code2,AppRoleEnum.ENGINEERING_USER.getCode());
        result.put(code3,AppRoleEnum.APP_VIP_USER.getCode());
        redisUtil.saveByKeyWithExpire("ROLE_REFERRAL_CODE",result,86400L);
        RoleReferralCodeVO vo1 = new RoleReferralCodeVO();
        vo1.setRoleName(roleService.getRoleByCode(AppRoleEnum.MARKET_USER.getCode()).getName());
        vo1.setRoleReferralCode(code1);
        RoleReferralCodeVO vo2 = new RoleReferralCodeVO();
        vo2.setRoleName(roleService.getRoleByCode(AppRoleEnum.ENGINEERING_USER.getCode()).getName());
        vo2.setRoleReferralCode(code2);
        RoleReferralCodeVO vo3 = new RoleReferralCodeVO();
        vo3.setRoleName(roleService.getRoleByCode(AppRoleEnum.APP_VIP_USER.getCode()).getName());
        vo3.setRoleReferralCode(code3);
        return Arrays.asList(vo1,vo2,vo3);
    }

}
