package com.izouma.zhirongip.service.demand;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.zhirongip.domain.Setting;
import com.izouma.zhirongip.domain.demand.Funding;
import com.izouma.zhirongip.domain.supply.TechnicalManager;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.SettingRepo;
import com.izouma.zhirongip.repo.demand.FundingRepo;
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 FundingService {

    private final FundingRepo fundingRepo;
    private final SettingRepo settingRepo;

    public Page<Funding> all(PageQuery pageQuery, Long field) {
//        return fundingRepo.findAll(JpaUtils.toSpecification(pageQuery, Funding.class), JpaUtils.toPageRequest(pageQuery));
        Map<Long, String> settingMap = settingRepo.findAllByFlag(5)
                .stream()
                .collect(Collectors.toMap(Setting::getId, Setting::getName));

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

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

    public Funding get(Long id) {

        Map<Long, String> settingMap = settingRepo.findAllByFlag(5)
                .stream()
                .collect(Collectors.toMap(Setting::getId, Setting::getName));
        Funding funding = fundingRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        funding.setPurposeName(funding.getPurpose()
                .stream()
                .map(settingMap::get)
                .collect(Collectors.toList()));

        return funding;
    }
}
