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

import java.util.List;

import com.ecep.contract.QueryService;
import com.ecep.contract.util.SpecificationUtils;
import com.fasterxml.jackson.databind.JsonNode;
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.ds.project.repository.ProjectSaleTypeRepository;
import com.ecep.contract.model.ProjectSaleType;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.vo.ProjectSaleTypeVo;

@Lazy
@Service
@CacheConfig(cacheNames = "project-sale-type")
public class ProjectSaleTypeService implements IEntityService<ProjectSaleType>, QueryService<ProjectSaleTypeVo>,
        VoableService<ProjectSaleType, ProjectSaleTypeVo> {
    @Lazy
    @Autowired
    private ProjectSaleTypeRepository saleTypeRepository;

    public ProjectSaleType getById(Integer id) {
        return saleTypeRepository.findById(id).orElse(null);
    }

    @Cacheable(key = "#p0")
    public ProjectSaleTypeVo findById(Integer id) {
        ProjectSaleType entity = getById(id);
        if (entity != null) {
            return entity.toVo();
        }
        return null;
    }

    public ProjectSaleType findByName(String name) {
        return saleTypeRepository.findByName(name).orElse(null);
    }

    @Cacheable(key = "'code-'+#p0")
    public ProjectSaleTypeVo findByCode(String code) {
        ProjectSaleType entity = saleTypeRepository.findByCode(code).orElse(null);
        if (entity != null) {
            return entity.toVo();
        }
        return null;
    }

    @Cacheable(key = "'all'")
    public List<ProjectSaleTypeVo> findAll() {
        List<ProjectSaleType> entities = saleTypeRepository.findAll();
        return entities.stream().map(ProjectSaleType::toVo).toList();
    }

    public Page<ProjectSaleType> findAll(Specification<ProjectSaleType> spec, Pageable pageable) {
        return saleTypeRepository.findAll(spec, pageable);
    }

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

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

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'code-'+#p0.name"),
            @CacheEvict(key = "'all'"),
    })
    public ProjectSaleType save(ProjectSaleType type) {
        return saleTypeRepository.save(type);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'code-'+#p0.name"),
            @CacheEvict(key = "'all'"),
    })
    public void delete(ProjectSaleType type) {
        saleTypeRepository.delete(type);
    }

    @Override
    public void updateByVo(ProjectSaleType saleType, ProjectSaleTypeVo vo) {
        if (saleType == null || vo == null) {
            return;
        }

        // 映射基本属性
        saleType.setName(vo.getName());
        saleType.setCode(vo.getCode());
        saleType.setPath(vo.getPath());
        saleType.setDescription(vo.getDescription());
        saleType.setStoreByYear(vo.isStoreByYear());
        saleType.setCriticalProjectDecision(vo.isCriticalProjectDecision());
        saleType.setCriticalProjectLimit(vo.getCriticalProjectLimit() != null ? vo.getCriticalProjectLimit() : 0);
        saleType.setActive(vo.isActive());

        saleType.setCriticalProjectLimit(vo.getCriticalProjectLimit());

        saleType.setActive(vo.isActive());

        // ProjectSaleTypeVo中的created和version字段在ProjectSaleType实体中不存在，这里不做处理
        // 如果需要处理，可以添加日志记录或者其他逻辑
    }
}
