package com.izouma.zhirongip.service.supply;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.zhirongip.domain.Setting;
import com.izouma.zhirongip.domain.supply.ServiceProvider;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.repo.SettingRepo;
import com.izouma.zhirongip.repo.supply.ServiceProviderRepo;
import com.izouma.zhirongip.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class ServiceProviderService {

    private final ServiceProviderRepo serviceProviderRepo;
    private final SettingRepo         settingRepo;

    public Page<ServiceProvider> all(PageQuery pageQuery, Long field) {
        Map<Long, String> settingMap = settingRepo.findAllByFlag(6)
                .stream()
                .collect(Collectors.toMap(Setting::getId, Setting::getName));

        return serviceProviderRepo.findAll(((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> and = JpaUtils.toPredicates(pageQuery, ServiceProvider.class, root, criteriaQuery, criteriaBuilder);
            if (ObjectUtil.isNotNull(field)) {
                Expression<Long> function = criteriaBuilder.function("FIND_IN_SET", Long.class, criteriaBuilder.literal(field), root
                        .get("field"));
                and.add(criteriaBuilder.greaterThan(function, 0L));
            }

            return criteriaBuilder.and(and.toArray(new Predicate[0]));
        }), JpaUtils.toPageRequest(pageQuery))
                .map(manager -> {
                    manager.setFieldName(manager.getField()
                            .stream()
                            .map(settingMap::get)
                            .collect(Collectors.toList()));
                    return manager;
                });
    }
}
