package com.izouma.zhirongip.service.resource;

import cn.hutool.core.util.StrUtil;
import com.izouma.zhirongip.converter.LongArrayConverter;
import com.izouma.zhirongip.domain.resource.SuccessCase;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.repo.resource.SuccessCaseRepo;
import com.izouma.zhirongip.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

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

@Service
@AllArgsConstructor
public class SuccessCaseService {

    private final SuccessCaseRepo successCaseRepo;

    public Page<SuccessCase> all(PageQuery pageQuery, String money) {
        return successCaseRepo.findAll(((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> and = JpaUtils.toPredicates(pageQuery, SuccessCase.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("soldPrice"), money1.get(0), money1.get(1)));
                } else {
                    and.add(criteriaBuilder.greaterThanOrEqualTo(root.get("soldPrice"), money1.get(0)));
                }
            }
            return criteriaBuilder.and(and.toArray(new Predicate[0]));
        }), JpaUtils.toPageRequest(pageQuery));
    }
}
