package com.izouma.zhirongip.service.resource;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.izouma.zhirongip.converter.LongArrayConverter;
import com.izouma.zhirongip.domain.resource.Purchase;
import com.izouma.zhirongip.domain.supply.TechnologyProduct;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.resource.PurchaseRepo;
import com.izouma.zhirongip.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.List;

@Service
@AllArgsConstructor
public class PurchaseService {

    private final PurchaseRepo purchaseRepo;

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

    public Page<Purchase> all1(PageQuery pageQuery, String money) {
        return purchaseRepo.findAll(((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> and = JpaUtils.toPredicates(pageQuery, Purchase.class, root, criteriaQuery, criteriaBuilder);
            if (StrUtil.isNotBlank(money)) {
                LongArrayConverter lc = new LongArrayConverter();
                List<Long> money1 = lc.convertToEntityAttribute(money);
                if (money1.size() > 1) {
                    and.add(criteriaBuilder.between(root.get("expectedPrice"), money1.get(0), money1.get(1)));
                } else {
                    and.add(criteriaBuilder.greaterThanOrEqualTo(root.get("expectedPrice"), money1.get(0)));
                }
            }
            return criteriaBuilder.and(and.toArray(new Predicate[0]));
        }), JpaUtils.toPageRequest(pageQuery));
    }

    public Page<Purchase> recommend(Long id) {
        Purchase purchase = purchaseRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        PageRequest pageRequest = PageRequest.of(0, 3);
        Page<Purchase> purchases = purchaseRepo.findAllByPurchaseItemAndFieldAndIdNot(purchase.getPurchaseItem(), purchase
                .getField(), id, pageRequest);
        if (CollUtil.isNotEmpty(purchases.getContent())) {
            return purchases;
        }

        return purchaseRepo.findAllByPurchaseItemAndIdNot(purchase.getPurchaseItem(), id, pageRequest);
    }
}
