package com.izouma.nineth.service;

import com.izouma.nineth.domain.Asset;
import com.izouma.nineth.domain.UserAssetSummary;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.CollectionType;
import com.izouma.nineth.repo.AssetRepo;
import com.izouma.nineth.repo.UserAssetSummaryRepo;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@AllArgsConstructor
@Slf4j
public class UserAssetSummaryService {

    private AssetRepo assetRepo;

    private UserAssetSummaryRepo userAssetSummaryRepo;

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

    public void calculateNum(Long userId) {
        log.info("开始重新计算用户：{}的资产数量", userId);
        List<UserAssetSummary> userAssetSummaries = new ArrayList<>();
        // 查询盲盒数量
        List<Asset> blindBoxAssets = assetRepo.findAllByUserIdAndTypeAndOpened(userId, CollectionType.BLIND_BOX, Boolean.FALSE);
        blindBoxAssets.forEach(asset -> {
            userAssetSummaries.add(new UserAssetSummary(asset));
        });
        // 查询非盲盒数量
        List<UserAssetSummary> notBlindBoxAssets = userAssetSummaryRepo.find(userId);
        notBlindBoxAssets.forEach(userAssetSummary -> {
            UserAssetSummary newUserAssetSummary = new UserAssetSummary();
            BeanUtils.copyProperties(userAssetSummary, newUserAssetSummary);
            newUserAssetSummary.setId(null);
            userAssetSummaries.add(newUserAssetSummary);
        });
        List<UserAssetSummary> isExist = userAssetSummaryRepo.findByUserId(userId);
        if (CollectionUtils.isNotEmpty(isExist)) {
            userAssetSummaryRepo.deleteByUserId(userId);
        }
        userAssetSummaryRepo.saveAll(userAssetSummaries);
    }

}
