package com.izouma.nineth.service;

import com.izouma.nineth.domain.*;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.AirDropType;
import com.izouma.nineth.enums.CollectionType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.*;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
@AllArgsConstructor
@Slf4j
public class AirDropService {

    private AirDropRepo       airDropRepo;
    private CouponRepo        couponRepo;
    private UserCouponRepo    userCouponRepo;
    private CollectionRepo    collectionRepo;
    private UserRepo          userRepo;
    private AssetService      assetService;
    private CollectionService collectionService;

    public Page<AirDrop> all(PageQuery pageQuery) {
        return airDropRepo.findAll(JpaUtils.toSpecification(pageQuery, AirDrop.class), JpaUtils.toPageRequest(pageQuery));
    }

    @Transactional
    public AirDrop create(AirDrop record) {
        if (AirDropType.coupon == record.getType()) {
            Coupon coupon = couponRepo.findById(record.getCouponId()).orElseThrow(new BusinessException("兑换券不存在"));
            record.getUserIds().stream().parallel().forEach(userId -> {
                UserCoupon userCoupon = new UserCoupon();
                BeanUtils.copyProperties(coupon, userCoupon);
                userCoupon.setId(null);
                userCoupon.setCouponId(coupon.getId());
                userCoupon.setUserId(userId);
                userCouponRepo.save(userCoupon);
            });
        } else {
            Collection collection = collectionRepo.findById(record.getCollectionId())
                    .orElseThrow(new BusinessException("藏品不存在"));
            if (collection.getStock() < record.getUserIds().size()) {
                throw new BusinessException("藏品库存不足");
            }
            List<User> users = userRepo.findByIdInAndDelFalse(record.getUserIds());
            for (User user : users) {
                try {
                    if (collection.getType() == CollectionType.BLIND_BOX) {
                        BlindBoxItem winItem = collectionService.draw(collection.getId());
                        assetService.createAsset(winItem, user, null, null, "空投", collectionService.getNextNumber(winItem.getCollectionId()));
                    } else {
                        assetService.createAsset(collection, user, null, null, "空投", collectionService.getNextNumber(collection.getId()));
                    }
                    collection.setStock(collection.getStock() - 1);
                    collection.setSale(collection.getSale() + 1);
                    collectionRepo.save(collection);
                } catch (Exception e) {
                    log.error("空投出错", e);
                }
            }
        }
        return airDropRepo.save(record);
    }
}
