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

import com.ecep.contract.CompanyFileType;
import com.ecep.contract.constant.ServiceConstant;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
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 com.ecep.contract.IEntityService;
import com.ecep.contract.QueryService;
import com.ecep.contract.ds.company.repository.CompanyFileTypeLocalRepository;
import com.ecep.contract.model.CompanyFileTypeLocal;
import com.ecep.contract.vo.CompanyFileTypeLocalVo;
import com.fasterxml.jackson.databind.JsonNode;

import jakarta.annotation.Resource;
import org.springframework.util.StringUtils;

import java.util.Locale;
import java.util.Map;
import java.util.Optional;

@Lazy
@Service
@CacheConfig(cacheNames = "company-file-type")
public class CompanyFileTypeService
        implements IEntityService<CompanyFileTypeLocal>, QueryService<CompanyFileTypeLocalVo>,
        VoableService<CompanyFileTypeLocal, CompanyFileTypeLocalVo> {

    @Resource
    private CompanyFileTypeLocalRepository repository;

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

    @Cacheable(key = "#id")
    @Override
    public CompanyFileTypeLocalVo findById(Integer id) {
        Optional<CompanyFileTypeLocal> optional = repository.findById(id);
        return optional.map(CompanyFileTypeLocal::toVo).orElse(null);
    }

    @Override
    public Page<CompanyFileTypeLocalVo> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<CompanyFileTypeLocal> spec = null;
        if (paramsNode.has(ServiceConstant.KEY_SEARCH_TEXT)) {
            spec = getSpecification(paramsNode.get(ServiceConstant.KEY_SEARCH_TEXT).asText());
        }

        if (paramsNode.has("type")) {
            spec = SpecificationUtils.and(spec, (root, query, builder) -> builder.equal(root.get("type"),
                    CompanyFileType.valueOf(paramsNode.get("type").asText())));
        }
        // field
        return findAll(spec, pageable).map(CompanyFileTypeLocal::toVo);
    }

    @Cacheable(key = "'all-'+#locale.toLanguageTag()")
    public Map<CompanyFileType, CompanyFileTypeLocalVo> findAll(Locale locale) {
        return repository.getCompleteMapByLocal(locale.toLanguageTag()).entrySet().stream()
                .collect(java.util.stream.Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().toVo()));
    }

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

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

    @Caching(evict = {
            @CacheEvict(key = "#entity.id"),
            @CacheEvict(key = "'all-'+#entity.getLang()")
    })
    @Override
    public void delete(CompanyFileTypeLocal entity) {
        repository.delete(entity);
    }

    @Caching(evict = {
            @CacheEvict(key = "#entity.id"),
            @CacheEvict(key = "'all-'+#entity.getLang()")
    })
    @Override
    public CompanyFileTypeLocal save(CompanyFileTypeLocal entity) {
        return repository.save(entity);
    }

    @Override
    public void updateByVo(CompanyFileTypeLocal model, CompanyFileTypeLocalVo vo) {
        // 映射基本属性
        model.setId(vo.getId());
        model.setType(vo.getType());
        model.setLang(vo.getLang());
        model.setValue(vo.getValue());
        // 实体中没有active字段，不需要映射
    }
}
