package com.ecep.contract.ds.customer.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.CustomerFileType;
import com.ecep.contract.IEntityService;
import com.ecep.contract.QueryService;
import com.ecep.contract.constant.ServiceConstant;
import com.ecep.contract.ds.customer.repository.CustomerFileTypeLocalRepository;
import com.ecep.contract.model.CustomerFileTypeLocal;
import com.ecep.contract.util.SpecificationUtils;
import com.fasterxml.jackson.databind.JsonNode;

import com.ecep.contract.service.ServiceException;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.vo.CustomerFileTypeLocalVo;

@Lazy
@Service
@CacheConfig(cacheNames = "customer-file-type")
public class CustomerFileTypeService implements IEntityService<CustomerFileTypeLocal>, QueryService<CustomerFileTypeLocalVo>,
        VoableService<CustomerFileTypeLocal, CustomerFileTypeLocalVo> {
    @Lazy
    @Autowired
    private CustomerFileTypeLocalRepository repository;

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

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

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

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

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

    @Cacheable(key = "'all-'+#p0.toLanguageTag()")
    public Map<CustomerFileType, CustomerFileTypeLocalVo> 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<CustomerFileTypeLocal> 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(CustomerFileTypeLocal entity) {
        repository.delete(entity);
    }

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

    @Override
    public void updateByVo(CustomerFileTypeLocal model, CustomerFileTypeLocalVo vo) {
        if (model == null) {
            throw new ServiceException("实体对象不能为空");
        }
        if (vo == null) {
            throw new ServiceException("VO对象不能为空");
        }

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