package com.ecep.contract.ds.customer.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.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.constant.ServiceConstant;
import com.ecep.contract.ds.customer.repository.CompanyCustomerEvaluationFormFileRepository;
import com.ecep.contract.ds.customer.model.CompanyCustomer;
import com.ecep.contract.ds.customer.model.CompanyCustomerEvaluationFormFile;
import com.ecep.contract.ds.customer.model.CompanyCustomerFile;
import com.ecep.contract.service.ServiceException;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.CompanyCustomerEvaluationFormFileVo;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "company-customer-evaluation-form-file")
public class CompanyCustomerEvaluationFormFileService
        implements IEntityService<CompanyCustomerEvaluationFormFile>, QueryService<CompanyCustomerEvaluationFormFile>,
        VoableService<CompanyCustomerEvaluationFormFile, CompanyCustomerEvaluationFormFileVo> {
    private static final Logger logger = LoggerFactory.getLogger(CompanyCustomerEvaluationFormFileService.class);

    @Lazy
    @Autowired
    private CompanyCustomerEvaluationFormFileRepository repository;

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

    @Cacheable(key = "#p0")
    @Override
    public CompanyCustomerEvaluationFormFile findById(Integer id) {
        return getById(id);
    }

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

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
    })
    @Override
    public void delete(CompanyCustomerEvaluationFormFile formFile) {
        repository.delete(formFile);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
    })
    @Override
    public CompanyCustomerEvaluationFormFile save(CompanyCustomerEvaluationFormFile formFile) {
        return repository.save(formFile);
    }

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

    @Override
    public Page<CompanyCustomerEvaluationFormFile> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<CompanyCustomerEvaluationFormFile> spec = null;
        if (paramsNode.has(ServiceConstant.KEY_SEARCH_TEXT)) {
            spec = getSpecification(paramsNode.get(ServiceConstant.KEY_SEARCH_TEXT).asText());
        }

        if (paramsNode.has("customer")) {
            CompanyCustomer customer = new CompanyCustomer();
            customer.setId(paramsNode.get("customer").asInt());
            spec = SpecificationUtils.and(spec,
                    (root, query, builder) -> builder.equal(root.get("customerFile").get("customer"), customer));
        }

        spec = SpecificationUtils.andParam(spec, paramsNode, "customerFile");
        spec = SpecificationUtils.andFieldEqualParam(spec, paramsNode, "catalog", "level");

        return findAll(spec, pageable);
    }

    /**
     * 根据客户查询所有评估表文件
     * 
     * @param customer 客户实体
     * @return 评估表文件列表
     */
    public List<CompanyCustomerEvaluationFormFile> findAllByCustomer(CompanyCustomer customer) {
        return repository.findAllByCustomerFileCustomer(customer);
    }

    /**
     * 根据客户ID和文件类型查询评估表文件
     * 
     * @param companyCustomerId 客户ID
     * @param type              文件类型
     * @return 评估表文件列表
     */
    public List<CompanyCustomerEvaluationFormFile> findAllByCustomerIdAndType(int companyCustomerId, String type) {
        return repository.findAllByCustomerAndType(companyCustomerId, type);
    }

    /**
     * 根据客户文件查询评估表文件
     * 
     * @param customerFile 客户文件实体
     * @return 评估表文件列表
     */
    public CompanyCustomerEvaluationFormFile findByCustomerFile(CompanyCustomerFile customerFile) {
        return repository.findByCustomerFile(customerFile);
    }

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

        // 映射基本属性
        model.setCatalog(vo.getCatalog());
        model.setLevel(vo.getLevel());
        model.setCreditLevel(vo.getCreditLevel());

        model.setScore1(vo.getScore1());
        model.setScore2(vo.getScore2());
        model.setScore3(vo.getScore3());
        model.setScore4(vo.getScore4());
        model.setScore5(vo.getScore5());

        model.setScoreTemplateVersion(vo.getScoreTemplateVersion());

        // 优化关联实体处理逻辑
        if (vo.getCustomerFile() == null) {
            model.setCustomerFile(null);
        } else {
            CompanyCustomerFileService service = SpringApp.getBean(CompanyCustomerFileService.class);
            // 添加实体匹配检查
            if (model.getCustomerFile() == null || !model.getCustomerFile().getId().equals(vo.getCustomerFile())) {
                // 使用getById方法替代findById
                model.setCustomerFile(service.getById(vo.getCustomerFile()));
            }
        }
    }
}