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

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.domain.Sort;
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.contract.repository.PurchaseOrderItemRepository;
import com.ecep.contract.ds.other.service.InventoryService;
import com.ecep.contract.ds.vendor.model.PurchaseOrderItem;
import com.ecep.contract.service.ServiceException;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.PurchaseOrderItemVo;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "contract-purchase-order-item")
public class PurchaseOrderItemService implements IEntityService<PurchaseOrderItem>, QueryService<PurchaseOrderItemVo>,
        VoableService<PurchaseOrderItem, PurchaseOrderItemVo> {
    private static final Logger logger = LoggerFactory.getLogger(PurchaseOrderItemService.class);
    @Lazy
    @Autowired
    private PurchaseOrderItemRepository repository;

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

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

    @Cacheable(key = "'refId-'+#p0")
    public PurchaseOrderItemVo findByRefId(Integer itemRefId) {
        List<PurchaseOrderItem> list = repository.findAllByRefId(itemRefId);
        if (list.isEmpty()) {
            return null;
        }
        while (list.size() > 1) {
            PurchaseOrderItem item = list.removeLast();
            repository.delete(item);
            if (logger.isInfoEnabled()) {
                logger.info("Duplicate PurchaseOrderItem, Delete {}", item);
            }
        }
        return list.getFirst().toVo();
    }

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

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

    @Override
    public Page<PurchaseOrderItemVo> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<PurchaseOrderItem> spec = null;
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        // field
        spec = SpecificationUtils.andParam(spec, paramsNode, "order", "inventory");
        return findAll(spec, pageable).map(PurchaseOrderItem::toVo);
    }

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

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

    public List<PurchaseOrderItem> findAll(Specification<PurchaseOrderItem> spec, Sort sort) {
        return repository.findAll(spec, sort);
    }

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

        model.setRefId(vo.getRefId());
        model.setQuantity(vo.getQuantity());
        model.setPrice(vo.getPrice());
        model.setTaxRate(vo.getTaxRate());
        model.setExclusiveTaxPrice(vo.getExclusiveTaxPrice());
        model.setArriveDate(vo.getArriveDate());
        model.setDescription(vo.getDescription());

        if (vo.getOrder() == null) {
            model.setOrder(null);
        } else {
            model.setOrder(SpringApp.getBean(PurchaseOrdersService.class).getById(vo.getOrder()));
        }

        if (vo.getInventoryId() == null) {
            model.setInventory(null);
        } else {
            model.setInventory(SpringApp.getBean(InventoryService.class).getById(vo.getInventoryId()));
        }
    }
}
