package com.izouma.nineth.service;

import com.izouma.nineth.config.RedisKeys;
import com.izouma.nineth.domain.Asset;
import com.izouma.nineth.domain.AssetSellLimit;
import com.izouma.nineth.domain.Collection;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.AssetRepo;
import com.izouma.nineth.repo.AssetSellLimitRepo;
import com.izouma.nineth.repo.CollectionRepo;
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.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.time.ZoneId;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@AllArgsConstructor
@Slf4j
public class AssetSellLimitService {

    private AssetSellLimitRepo assetSellLimitRepo;

    private CollectionRepo collectionRepo;

    private AssetRepo assetRepo;

    private RedisTemplate redisTemplate;

    public Page<AssetSellLimit> all(PageQuery pageQuery) {
        pageQuery.getQuery().put("del", false);
        return assetSellLimitRepo.findAll(JpaUtils.toSpecification(pageQuery, AssetSellLimit.class), JpaUtils.toPageRequest(pageQuery));
    }

    @Transactional
    public AssetSellLimit save(AssetSellLimit assetSellLimit){
        Long collectionId = assetSellLimit.getCollectionId();
        Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
        assetSellLimit.setCollectionName(collection.getName());
        assetSellLimit.setProjectId(collection.getProjectId());
        if(assetSellLimit.getId() != null){
            AssetSellLimit oldValue = assetSellLimitRepo.findById(assetSellLimit.getId()).orElseThrow(new BusinessException("记录不存在"));
            BeanUtils.copyProperties(assetSellLimit,oldValue, "createdAt", "createdBy", "del");
            assetSellLimit = oldValue;
        }

        assetSellLimitRepo.save(assetSellLimit);

        return assetSellLimit;
    }


    @Transactional
    public void softDelete(Long assetSellLimitId){
        AssetSellLimit assetSellLimit = assetSellLimitRepo.findById(assetSellLimitId).orElseThrow(new BusinessException("记录不存在"));
        assetSellLimit.setDel(true);
        assetSellLimitRepo.save(assetSellLimit);

        //解除限制
        List<Asset> limitAssets = assetRepo.findLimitPriceAsset(assetSellLimit.getCollectionId(), assetSellLimit.getMinPrice());
        //解除藏品的限制
        limitAssets.forEach(asset -> {
            String key = RedisKeys.ASSET_SHELL_LIMIT_KEY + asset.getId();
            redisTemplate.delete(key);
        });

    }



}
