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

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.ds.vendor.repository.VendorGroupRepository;
import com.ecep.contract.model.VendorGroup;
import com.ecep.contract.service.ServiceException;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.VendorGroupVo;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "vendor-group")
public class VendorGroupService
        implements IEntityService<VendorGroup>, QueryService<VendorGroupVo>, VoableService<VendorGroup, VendorGroupVo> {
    @Lazy
    @Autowired
    private VendorGroupRepository vendorGroupRepository;

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

    public VendorGroup getById(Integer id) {
        return vendorGroupRepository.findById(id).orElse(null);
    }

    public VendorGroup findByName(String name) {
        return vendorGroupRepository.findByName(name).orElse(null);
    }

    @Cacheable(key = "'code-'+#p0")
    public VendorGroupVo findByCode(String code) {
        return vendorGroupRepository.findByCode(code).map(VendorGroup::toVo).orElse(null);
    }

    @Cacheable(key = "'all'")
    public List<VendorGroup> findAll() {
        return vendorGroupRepository.findAll();
    }

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

    @Override
    public Page<VendorGroupVo> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<VendorGroup> spec = null;
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        // 添加额外的参数过滤
        spec = SpecificationUtils.andFieldEqualParam(spec, paramsNode, "active", "name", "code");
        return findAll(spec, pageable).map(entity -> entity.toVo());
    }

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

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'code-'+#p0.name"),
            @CacheEvict(key = "'all'"),
    })
    public VendorGroup saveEntity(VendorGroup group) {
        return vendorGroupRepository.save(group);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'code-'+#p0.name"),
            @CacheEvict(key = "'all'"),
    })
    public void deleteEntity(VendorGroup entity) {
        vendorGroupRepository.delete(entity);
    }

    public VendorGroup newInstance() {
        VendorGroup group = new VendorGroup();
        group.setCode("");
        group.setName("");
        group.setDescription("");
        group.setActive(true);
        group.setPriceComparison(true);
        group.setRequireQuotationSheetForBid(true);
        group.setCanPrePurchase(false);
        return group;
    }

    @Override
    public void updateByVo(VendorGroup model, VendorGroupVo vo) {
        if (model == null) {
            throw new ServiceException("VendorGroup cannot be null");
        }
        if (vo == null) {
            throw new ServiceException("VendorGroupVo cannot be null");
        }
        // Map properties from VO to entity
        model.setName(vo.getName());
        model.setCode(vo.getCode());
        model.setDescription(vo.getDescription());
        model.setActive(vo.isActive());
        model.setPriceComparison(vo.isPriceComparison());
        model.setRequireQuotationSheetForBid(vo.isRequireQuotationSheetForBid());
        model.setCanPrePurchase(vo.isCanPrePurchase());
    }


    @Override
    public VendorGroup save(VendorGroup entity) {
        return saveEntity(entity);
    }

    @Override
    public void delete(VendorGroup entity) {
        deleteEntity(entity);
    }
}
