package com.ruoyi.cai.manager;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.cai.domain.Rank;
import com.ruoyi.cai.domain.User;
import com.ruoyi.cai.domain.UserInfo;
import com.ruoyi.cai.enums.SystemConfigEnum;
import com.ruoyi.cai.enums.account.AccountChangeCodeEnum;
import com.ruoyi.cai.executor.ExecutorConstant;
import com.ruoyi.cai.mapper.AccountMapper;
import com.ruoyi.cai.service.AccountChangeLogService;
import com.ruoyi.cai.service.RankService;
import com.ruoyi.cai.service.UserInfoService;
import com.ruoyi.cai.service.UserService;
import com.ruoyi.cai.util.CaiDateUtil;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;

@Component
@Slf4j
public class AwardManager {

    @Autowired
    private SystemConfigManager systemConfigManager;
    @Resource
    private AccountMapper accountMapper;
    @Autowired
    private AccountChangeLogService accountChangeLogService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RankService rankService;

    public void giveRegisterAsync(Long userId){
        AwardManager bean = SpringUtil.getBean(AwardManager.class);
        ExecutorConstant.COMMON_EXECUTOR.execute(() -> {
            bean.giveRegister(userId);
        });
    }

    public void giveRegister(Long userId){
        Long price = systemConfigManager.getSystemConfigOfLong(SystemConfigEnum.REGISTER_AWARD);
        if(price == 0){
            return;
        }
        User user = userService.getById(userId);
        if(user == null){
            log.error("注册奖励领取失败 用户不存在 userId={}",userId);
            return;
        }
        accountMapper.incsIncomeCoin(userId,price);
        accountChangeLogService.saveLogNoAdmin(user.getId(),user.getUsercode(), AccountChangeCodeEnum.REGISTER_AWARD,price,null);
    }

    public void giveFastPayAsync(Long userId, Long traceId){
        AwardManager bean = SpringUtil.getBean(AwardManager.class);
        ExecutorConstant.COMMON_EXECUTOR.execute(() -> {
            bean.giveFastPay(userId,traceId);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    public void giveFastPay(Long userId,Long traceId){
        Long price = systemConfigManager.getSystemConfigOfLong(SystemConfigEnum.FAST_PAY_AWARD);
        if(price == 0){
            return;
        }
        User user = userService.getById(userId);
        if(user == null){
            log.error("首充奖励领取失败 用户不存在 userId={}",userId);
            return;
        }
        UserInfo userInfo = userInfoService.getByUserId(userId);
        if(userInfo == null || BooleanUtils.isNotFalse(userInfo.getFastPay())){
            log.warn("首充奖励领取失败 用户已领取 85 userId={}",userId);
            return;
        }
        boolean update = userInfoService.update(Wrappers.lambdaUpdate(UserInfo.class)
                .eq(UserInfo::getId, userInfo.getId())
                .eq(UserInfo::getFastPay, false)
                .set(UserInfo::getFastPay, true));
        if(!update){
            log.warn("首充奖励领取失败 用户已领取 93 userId={}",userId);
            return;
        }
        accountMapper.incsIncomeCoin(userId,price);
        accountChangeLogService.saveLogNoAdmin(user.getId(),user.getUsercode(), AccountChangeCodeEnum.FAST_PAY_AWARD,price,traceId);
    }


    public void giveRank(Long rankId,Long userId){
        Rank rank = rankService.getById(rankId);
        if(rank == null){
            throw new ServiceException("领取失败,奖励不存在");
        }
        if(!rank.getUserId().equals(userId)){
            throw new ServiceException("只能领取自己的奖励哦");
        }
        if(rank.getOrderRank() > 10){
            throw new ServiceException("只有前10名可以领取奖励");
        }
        if(rank.getDataType().equals(1)){ // 日榜
            LocalDate lastDay = LocalDate.now().plusDays(-1);
            if(!rank.getRankBeginTime().equals(lastDay)){
                throw new ServiceException("领奖时间已过");
            }
            rankService.giveRank(rankId);
        }else if(rank.getDataType().equals(2)){ // 周榜
            LocalDate date = CaiDateUtil.getLastWeekOne(LocalDate.now());
            if(!rank.getRankBeginTime().equals(date)){
                throw new ServiceException("领奖时间已过");
            }
            rankService.giveRank(rankId);
        }
    }
}
