package com.ecep.contract.ds.contract.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.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.company.service.CompanyService;
import com.ecep.contract.ds.contract.repository.ContractBidVendorRepository;
import com.ecep.contract.ds.contract.repository.ContractFileRepository;
import com.ecep.contract.ds.company.model.Company;
import com.ecep.contract.ds.contract.model.Contract;
import com.ecep.contract.ds.contract.model.ContractBidVendor;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.ContractBidVendorVo;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "contract-ven-bid")
public class ContractBidVendorService implements IEntityService<ContractBidVendor>, QueryService<ContractBidVendorVo>, VoableService<ContractBidVendor, ContractBidVendorVo> {
    @Lazy
    @Autowired
    private ContractBidVendorRepository repository;

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

    @Cacheable(key = "#p0")
    @Override
    public ContractBidVendorVo findById(Integer id) {
        ContractBidVendor entity = getById(id);
        if (entity != null) {
            return entity.toVo();
        }
        return null;
    }

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

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

    @Cacheable(key = "'allbycontract-'+#p0.id")
    public List<ContractBidVendorVo> findByContract(Contract contract) {
        return repository.findByContractId(contract.getId()).stream().map(ContractBidVendor::toVo).toList();
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'allbycontract-'+#p0.contract.id")
    })
    public ContractBidVendor save(ContractBidVendor bidVendor) {
        return repository.save(bidVendor);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'allbycontract-'+#p0.contract.id")
    })
    @Override
    public void delete(ContractBidVendor bidVendor) {
        repository.delete(bidVendor);
    }

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

    @Caching(evict = {
            @CacheEvict(key = "#p0.id")
    })
    public void deleteById(int id) {
        repository.deleteById(id);
    }

    public List<ContractBidVendor> findByContractAndCompany(Contract contract, Company company) {
        return repository.findByContractIdAndCompanyId(contract.getId(), company.getId());
    }

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

    @Override
    public void updateByVo(ContractBidVendor model, ContractBidVendorVo vo) {
        // 处理关联对象
        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.getCompanyId() == null) {
            model.setCompany(null);
        } else {
            CompanyService companyService = SpringApp.getBean(CompanyService.class);
            if (model.getCompany() == null || !model.getCompany().getId().equals(vo.getCompanyId())) {
                model.setCompany(companyService.getById(vo.getCompanyId()));
            }
        }

        if (vo.getQuotationSheetFileId() == null) {
            model.setQuotationSheet(null);
        } else {
            if (model.getQuotationSheet() == null || !model.getQuotationSheet().getId().equals(vo.getQuotationSheetFileId())) {
                model.setQuotationSheet(SpringApp.getBean(ContractFileRepository.class).findById(vo.getQuotationSheetFileId()).orElse(null));
            }
        }
    }
}
