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.SpringApp;
import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.ds.vendor.repository.VendorEntityRepository;
import com.ecep.contract.ds.vendor.model.Vendor;
import com.ecep.contract.ds.vendor.model.VendorEntity;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.VendorEntityVo;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "company-vendor-entity")
public class VendorEntityService implements IEntityService<VendorEntity>, QueryService<VendorEntityVo>,
        VoableService<VendorEntity, VendorEntityVo> {
    @Lazy
    @Autowired
    private VendorEntityRepository repository;

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

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

    /**
     * 因为 code 具有唯一性，所以不需要增加 CompanyVendor 加以区分
     *
     * @param code 供应商编号
     * @return CompanyVendorEntity
     */
    @Cacheable(key = "'code-'+#p0")
    public VendorEntityVo findByCode(String code) {
        return repository.findByCode(code).map(VendorEntity::toVo).orElse(null);
    }

    @Override
    public Specification<VendorEntity> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return SpecificationUtils.andWith(searchText, this::buildSearchSpecification);
    }

    protected Specification<VendorEntity> buildSearchSpecification(String searchText) {
        return (root, query, builder) -> {
            return builder.or(
                    builder.like(root.get("name"), "%" + searchText + "%"),
                    builder.like(root.get("abbName"), "%" + searchText + "%"),
                    builder.like(root.get("code"), "%" + searchText + "%"));
        };
    }

    @Override
    public List<VendorEntity> search(String searchText) {
        Specification<VendorEntity> spec = getSpecification(searchText);
        return repository.findAll(spec, Pageable.ofSize(10)).getContent();
    }

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

    @Override
    public Page<VendorEntityVo> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<VendorEntity> spec = null;
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        // 添加额外的参数过滤s
        spec = SpecificationUtils.andParam(spec, paramsNode, "vendor");
        return findAll(spec, pageable).map(VendorEntity::toVo);
    }

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

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

    public List<VendorEntity> findAllByVendor(Vendor vendor) {
        return repository.findByVendor(vendor);
    }

    @Override
    public void updateByVo(VendorEntity model, VendorEntityVo vo) {
        // 处理关联对象
        if (vo.getVendorId() == null) {
            model.setVendor(null);
        } else {
            model.setVendor(SpringApp.getBean(VendorService.class).getById(vo.getVendorId()));
        }

        // 更新基本属性
        model.setName(vo.getName());
        model.setAbbName(vo.getAbbName());
        model.setCode(vo.getCode());
        model.setModifyDate(vo.getModifyDate());
        model.setDevelopDate(vo.getDevelopDate());
        model.setUpdatedDate(vo.getUpdatedDate());
        model.setFetchedTime(vo.getFetchedTime());

        if (vo.getCatalogId() == null) {
            model.setCatalog(null);
        } else {
            model.setCatalog(SpringApp.getBean(VendorCatalogService.class).getById(vo.getCatalogId()));
        }

        EmployeeService employeeService = SpringApp.getBean(EmployeeService.class);
        if (vo.getCreatorId() == null) {
            model.setCreator(null);
        } else {
            model.setCreator(employeeService.getById(vo.getCreatorId()));
        }
        if (vo.getModifierId() == null) {
            model.setModifier(null);
        } else {
            model.setModifier(employeeService.getById(vo.getModifierId()));
        }
    }
}