package com.ecep.contract.ds.contract.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ecep.contract.IEntityService;
import com.ecep.contract.QueryService;
import com.ecep.contract.ds.contract.repository.ContractPayPlanRepository;
import com.ecep.contract.model.Contract;
import com.ecep.contract.model.ContractPayPlan;
import com.ecep.contract.util.SpecificationUtils;
import com.fasterxml.jackson.databind.JsonNode;

/**
 * 合同支付计划服务
 */
@Lazy
@Service
@CacheConfig(cacheNames = "contract-pay-plan")
public class ContractPayPlanService implements IEntityService<ContractPayPlan>, QueryService<ContractPayPlan> {
    @Lazy
    @Autowired
    private ContractPayPlanRepository repository;

    @Cacheable(key = "#p0")
    @Override
    public ContractPayPlan findById(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public Specification<ContractPayPlan> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return (root, query, cb) -> {
            return cb.or(cb.like(root.get("payTerm"), "%" + searchText + "%"));
        };
    }

    @Override
    public Page<ContractPayPlan> findAll(Specification<ContractPayPlan> spec, Pageable pageable) {
        return repository.findAll(spec, pageable);
    }

    @Override
    public Page<ContractPayPlan> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<ContractPayPlan> spec = null;
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        // field
        spec = SpecificationUtils.andParam(spec, paramsNode, "contract");
        return findAll(spec, pageable);
    }

    public List<ContractPayPlan> findAllByContract(Contract contract) {
        return repository.findAllByContract(contract);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id")
    })
    @Override
    public void delete(ContractPayPlan entity) {
        repository.delete(entity);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id")
    })
    @Override
    public ContractPayPlan save(ContractPayPlan entity) {
        return repository.save(entity);
    }

}
