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

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
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 com.ecep.contract.IEntityService;
import com.ecep.contract.QueryService;
import com.ecep.contract.SpringApp;
import com.ecep.contract.ds.company.service.CompanyOldNameService;
import com.ecep.contract.ds.vendor.repository.VendorApprovedItemRepository;
import com.ecep.contract.ds.company.model.Company;
import com.ecep.contract.ds.company.model.CompanyOldName;
import com.ecep.contract.ds.vendor.model.Vendor;
import com.ecep.contract.model.VendorApproved;
import com.ecep.contract.ds.vendor.model.VendorApprovedItem;
import com.ecep.contract.service.ServiceException;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.VendorApprovedItemVo;
import com.fasterxml.jackson.databind.JsonNode;

import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;

@Lazy
@Service
public class VendorApprovedItemService
        implements IEntityService<VendorApprovedItem>, QueryService<VendorApprovedItemVo>,
        VoableService<VendorApprovedItem, VendorApprovedItemVo> {

    @Lazy
    @Autowired
    private VendorApprovedItemRepository repository;
    @Lazy
    @Autowired
    private CompanyOldNameService companyOldNameService;

    public VendorApprovedItemService() {
    }

    @Override
    public VendorApprovedItemVo findById(Integer id) {
        return repository.findById(id).map(VendorApprovedItem::toVo).orElse(null);
    }

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

    @Override
    public Specification<VendorApprovedItem> getSpecification(String searchText) {
        return (root, query, builder) -> {
            Path<Vendor> vendor = root.get("vendor");
            Path<Company> company = vendor.get("company");

            List<CompanyOldName> oldNames = companyOldNameService.search(searchText);
            Predicate companyPredicate = oldNames.isEmpty() ? builder.like(company.get("name"), "%" + searchText + "%")
                    : builder.or(
                            builder.like(company.get("name"), "%" + searchText + "%"),
                            company.get("id").in(
                                    oldNames.stream().map(CompanyOldName::getCompanyId).collect(Collectors.toList())));
            return builder.or(
                    builder.and(
                            vendor.isNotNull(),
                            builder.and(
                                    company.isNotNull(),
                                    companyPredicate)),
                    builder.like(root.get("vendorName"), "%" + searchText + "%"),
                    builder.like(root.get("description"), "%" + searchText + "%"));
        };
    }

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

    @Override
    public void delete(VendorApprovedItem entity) {
        repository.delete(entity);
    }

    @Override
    public VendorApprovedItem save(VendorApprovedItem entity) {
        return repository.save(entity);
    }

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

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

    public List<VendorApprovedItem> findAllByListAndVendor(VendorApproved approvedList, Vendor vendor) {
        return repository.findAllByListAndVendor(approvedList, vendor);
    }

    @Override
    public void updateByVo(VendorApprovedItem entity, VendorApprovedItemVo vo) throws ServiceException {
        if (entity == null) {
            throw new ServiceException("VendorApprovedItem entity cannot be null");
        }
        if (vo == null) {
            throw new ServiceException("VendorApprovedItemVo cannot be null");
        }

        // 映射基本属性
        entity.setVendorName(vo.getVendorName());
        entity.setType(vo.getType());
        entity.setDescription(vo.getDescription());

        // 处理关联实体
        if (vo.getListId() != null) {
            VendorApprovedService vendorApprovedService = SpringApp.getBean(VendorApprovedService.class);
            VendorApproved vendorApproved = vendorApprovedService.getById(vo.getListId());
            if (vendorApproved != null) {
                entity.setList(vendorApproved);
            }
        }

        if (vo.getVendorId() != null) {
            VendorService vendorService = SpringApp.getBean(VendorService.class);
            Vendor vendor = vendorService.getById(vo.getVendorId());
            if (vendor != null) {
                entity.setVendor(vendor);
            }
        }
    }
}
