package top.continew.admin.business.service.Impl;

import cn.dev33.satoken.stp.StpUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.continew.admin.business.model.entity.AirdropRecord;
import top.continew.admin.business.model.entity.TgUser;
import top.continew.admin.business.model.req.AirdropManagerReq;
import top.continew.admin.business.service.AirdropManagerService;
import top.continew.admin.business.service.IAirdropRecordService;
import top.continew.admin.business.service.ITgUserService;
import top.continew.starter.core.validation.CheckUtils;

import java.time.LocalDateTime;

@Service
@AllArgsConstructor
@Slf4j
public class AirdropManagerServiceImpl implements AirdropManagerService {
    private final IAirdropRecordService recordService;
    private final ITgUserService userService;

    @Override
    @Transactional
    public void airdropManager(AirdropManagerReq req) {
        Object loginId = StpUtil.getLoginId();
        TgUser user = userService.getById(req.getTargetUser());
        CheckUtils.throwIfNull(user, "空投目标用户为空");

        Integer goldCoinNum = req.getGoldCoinNum();
        Integer airdropCoin = user.getAirdropCoin();
        Integer preDropNum = user.getAirdropCoin();

        //用户表新增或者减去空投金币数量
        if (req.getOperationType().equals(1)) {
            airdropCoin -= goldCoinNum;
        } else {
            airdropCoin += goldCoinNum;
        }
        user.setAirdropCoin(airdropCoin);
        //记录操作日志
        AirdropRecord record = new AirdropRecord();
        record.setAirdropTime(LocalDateTime.now());
        record.setTargetUser(user.getId());
        record.setPreDropNum(preDropNum);
        record.setPostDropNum(airdropCoin);
        record.setGoldCoinNum(goldCoinNum);
        record.setCreatedBy(String.valueOf(loginId));
        record.setCreatedTime(LocalDateTime.now());
        //同时更新
        userService.updateById(user);
        recordService.save(record);
    }
}
