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.ds.contract.repository.ContractItemRepository;
import com.ecep.contract.model.Contract;
import com.ecep.contract.model.ContractItem;
import com.ecep.contract.model.Inventory;
import com.ecep.contract.util.SpecificationUtils;
import com.fasterxml.jackson.databind.JsonNode;

import jakarta.persistence.criteria.Path;

@Lazy
@Service
@CacheConfig(cacheNames = "contract-item")
public class ContractItemService implements IEntityService<ContractItem>, QueryService<ContractItem> {
    private static final Logger logger = LoggerFactory.getLogger(ContractItemService.class);

    @Lazy
    @Autowired
    private ContractItemRepository itemRepository;

    @Override
    @Cacheable(key = "#p0")
    public ContractItem findById(Integer id) {
        return itemRepository.findById(id).orElse(null);
    }

    @Override
    public Specification<ContractItem> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return (root, query, builder) -> {
            Path<Inventory> inventory = root.get("inventory");
            return builder.or(
                    builder.like(root.get("itemCode"), "%" + searchText + "%"),
                    builder.like(root.get("title"), "%" + searchText + "%"),
                    builder.like(root.get("specification"), "%" + searchText + "%"),
                    builder.like(root.get("unit"), "%" + searchText + "%"),
                    builder.like(root.get("remark"), "%" + searchText + "%"),
                    builder.and(
                            inventory.isNotNull(), builder.or(
                                    builder.like(inventory.get("name"), "%" + searchText + "%"),
                                    builder.like(inventory.get("code"), "%" + searchText + "%"),
                                    builder.like(inventory.get("specification"), "%" + searchText + "%"))));
        };
    }

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

    @Override
    public Page<ContractItem> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<ContractItem> spec = null;
        // TODO 完成参数处理
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        // field
        spec = SpecificationUtils.andParam(spec, paramsNode, "contract");
        logger.warn("Unsupported paramsNode: {}", paramsNode);
        return findAll(spec, pageable);
    }

    public List<ContractItem> findAllByContract(Contract contract) {
        return itemRepository.findByContractId(contract.getId());
    }

    public List<ContractItem> findAllByInventory(Inventory inventory) {
        return itemRepository.findByInventoryId(inventory.getId());
    }

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

    @Caching(evict = {
            @CacheEvict(key = "#p0.id")
    })
    public ContractItem save(ContractItem item) {
        return itemRepository.save(item);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id")
    })
    @Override
    public void delete(ContractItem item) {
        itemRepository.delete(item);
    }

}
