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

import java.math.BigDecimal;
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.SpringApp;
import com.ecep.contract.ds.contract.service.ContractPayPlanService;
import com.ecep.contract.ds.project.repository.ProjectFundPlanRepository;
import com.ecep.contract.ds.contract.model.ContractPayPlan;
import com.ecep.contract.ds.project.model.Project;
import com.ecep.contract.ds.project.model.ProjectFundPlan;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.ProjectFundPlanVo;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "project-fund-plan")
public class ProjectFundPlanService implements IEntityService<ProjectFundPlan>, QueryService<ProjectFundPlanVo>,
        VoableService<ProjectFundPlan, ProjectFundPlanVo> {
    @Lazy
    @Autowired
    private ProjectFundPlanRepository repository;

    @Override
    public ProjectFundPlan getById(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Cacheable(key = "#p0")
    @Override
    public ProjectFundPlanVo findById(Integer id) {
        ProjectFundPlan fundPlan = getById(id);
        if (fundPlan != null) {
            return fundPlan.toVo();
        }
        return null;
    }

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

    @Override
    public Page<ProjectFundPlanVo> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<ProjectFundPlan> spec = null;
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        // field
        spec = SpecificationUtils.andParam(spec, paramsNode, "project");
        Page<ProjectFundPlan> page = findAll(spec, pageable);
        return page.map(ProjectFundPlan::toVo);
    }

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

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
    })
    public ProjectFundPlan save(ProjectFundPlan fundPlan) {
        return repository.save(fundPlan);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
    })
    public void delete(ProjectFundPlan fundPlan) {
        repository.delete(fundPlan);
    }

    public List<ProjectFundPlan> findByProject(Project project) {
        return repository.findAllByProject(project);
    }

    public BigDecimal calculateAmountByProject(Project project) {
        List<ProjectFundPlan> plans = findByProject(project);
        if (plans.isEmpty()) {
            return BigDecimal.ZERO;
        }
        // 转换为BigDecimal
        return BigDecimal.valueOf(plans.stream().mapToDouble(ProjectFundPlan::getPayCurrency).sum());
        // return plans.stream()
        //         .map(ProjectFundPlan::getAmount)
        //         .filter(Optional::isPresent)
        //         .map(Optional::get)
        //         .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    @Override
    public void updateByVo(ProjectFundPlan model, ProjectFundPlanVo vo) {
        // 基本字段映射
        model.setPayRatio(vo.getPayRatio());
        model.setPayCurrency(vo.getPayCurrency());
        model.setPayTerm(vo.getPayTerm());
        model.setUpdateDate(vo.getUpdateDate());

        // 处理关联实体
        if (vo.getContractPayPlanId() != null) {
            ContractPayPlan contractPayPlan = SpringApp.getBean(ContractPayPlanService.class).getById(vo.getContractPayPlanId());
            model.setContractPayPlan(contractPayPlan);
        }else{
            model.setContractPayPlan(null);
        }
    }
}
