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.constant.ServiceConstant;
import com.ecep.contract.ds.contract.repository.ContractItemRepository;
import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.ds.other.service.InventoryService;
import com.ecep.contract.ds.contract.model.Contract;
import com.ecep.contract.ds.contract.model.ContractItem;
import com.ecep.contract.model.Inventory;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.ContractItemVo;
import com.fasterxml.jackson.databind.JsonNode;

import jakarta.persistence.criteria.Path;

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

    @Lazy
    @Autowired
    private ContractItemRepository itemRepository;

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

    @Override
    @Cacheable(key = "#p0")
    public ContractItemVo findById(Integer id) {
        return itemRepository.findById(id).map(ContractItem::toVo).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<ContractItemVo> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<ContractItem> spec = null;
        if (paramsNode.has(ServiceConstant.KEY_SEARCH_TEXT)) {
            spec = getSpecification(paramsNode.get(ServiceConstant.KEY_SEARCH_TEXT).asText());
        }
        // field
        spec = SpecificationUtils.andParam(spec, paramsNode, "contract", "inventory", "creator", "updater");
        spec = SpecificationUtils.andFieldEqualParam(spec, paramsNode, "itemCode", "refId", "title", "specification");
        return findAll(spec, pageable).map(ContractItem::toVo);
    }

    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")
    })

    @Override
    public void updateByVo(ContractItem model, ContractItemVo vo) {
        // 更新基本属性
        model.setRefId(vo.getRefId());
        model.setItemCode(vo.getItemCode());
        model.setTitle(vo.getTitle());
        model.setSpecification(vo.getSpecification());
        model.setUnit(vo.getUnit());
        model.setExclusiveTaxPrice(vo.getExclusiveTaxPrice() != null ? vo.getExclusiveTaxPrice() : 0);
        model.setTaxRate(vo.getTaxRate() != null ? vo.getTaxRate() : 0);
        model.setTaxPrice(vo.getTaxPrice() != null ? vo.getTaxPrice() : 0);
        model.setQuantity(vo.getQuantity() != null ? vo.getQuantity() : 0);
        model.setStartDate(vo.getStartDate());
        model.setEndDate(vo.getEndDate());
        model.setRemark(vo.getRemark());

        // 处理关联对象
        if (vo.getContractId() == null) {
            model.setContract(null);
        } else {
            ContractService contractService = SpringApp.getBean(ContractService.class);
            if (model.getContract() == null || !model.getContract().getId().equals(vo.getContractId())) {
                model.setContract(contractService.getById(vo.getContractId()));
            }
        }

        if (vo.getInventoryId() == null) {
            model.setInventory(null);
        } else {
            InventoryService inventoryService = SpringApp.getBean(InventoryService.class);
            if (model.getInventory() == null || !model.getInventory().getId().equals(vo.getInventoryId())) {
                model.setInventory(inventoryService.getById(vo.getInventoryId()));
            }
        }

        if (vo.getCreatorId() == null) {
            model.setCreator(null);
        } else {
            EmployeeService employeeService = SpringApp.getBean(EmployeeService.class);
            if (model.getCreator() == null || !model.getCreator().getId().equals(vo.getCreatorId())) {
                model.setCreator(employeeService.getById(vo.getCreatorId()));
            }
        }

        if (vo.getUpdaterId() == null) {
            model.setUpdater(null);
        } else {
            EmployeeService employeeService = SpringApp.getBean(EmployeeService.class);
            if (model.getUpdater() == null || !model.getUpdater().getId().equals(vo.getUpdaterId())) {
                model.setUpdater(employeeService.getById(vo.getUpdaterId()));
            }
        }

        // 创建日期和更新日期通常由系统自动维护，这里不设置
    }

    @Override
    public ContractItem save(ContractItem item) {
        return itemRepository.save(item);
    }

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

}
