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

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

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.VendorFileType;
import com.ecep.contract.VendorType;
import com.ecep.contract.constant.ServiceConstant;
import com.ecep.contract.ds.vendor.repository.VendorFileTypeLocalRepository;
import com.ecep.contract.model.VendorFileTypeLocal;
import com.ecep.contract.service.ServiceException;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.VendorFileTypeLocalVo;
import com.fasterxml.jackson.databind.JsonNode;

/**
 * 供应商文件类型服务类
 * 提供对供应商文件类型的查询、创建、更新和删除操作
 */
@Lazy
@Service
@CacheConfig(cacheNames = "vendor-file-type")
public class VendorFileTypeService implements IEntityService<VendorFileTypeLocal>, QueryService<VendorFileTypeLocalVo>,
        VoableService<VendorFileTypeLocal, VendorFileTypeLocalVo> {
    @Lazy
    @Autowired
    private VendorFileTypeLocalRepository repository;

    @Override
    public Page<VendorFileTypeLocalVo> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<VendorFileTypeLocal> 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"),
                    VendorType.valueOf(paramsNode.get("type").asText())));
        }

        // field
        spec = SpecificationUtils.andFieldEqualParam(spec, paramsNode, "lang", "value");
        return findAll(spec, pageable).map(VendorFileTypeLocal::toVo);
    }

    @Cacheable(key = "#p0")
    @Override
    public VendorFileTypeLocalVo findById(Integer id) {
        return repository.findById(id).map(VendorFileTypeLocal::toVo).orElse(null);
    }

    public VendorFileTypeLocal getById(Integer id) {
        return repository.findById(id).orElse(null);
    }

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

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

    @Override
    public Specification<VendorFileTypeLocal> 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 = "#p0.id"),
            @CacheEvict(key = "'all-'+#p0.getLang()")
    })
    @Override
    public void delete(VendorFileTypeLocal entity) {
        repository.delete(entity);
    }

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

    @Override
    public void updateByVo(VendorFileTypeLocal entity, VendorFileTypeLocalVo vo) throws ServiceException {
        if (entity == null) {
            throw new ServiceException("VendorFileTypeLocal entity cannot be null");
        }
        if (vo == null) {
            throw new ServiceException("VendorFileTypeLocalVo cannot be null");
        }

        // 映射基本属性
        entity.setLang(vo.getLang());
        entity.setValue(vo.getValue());
        entity.setType(vo.getType());
    }
}
