package com.ecep.contract.ds.customer.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.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.customer.repository.CompanyCustomerEntityRepository;
import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.ds.customer.model.CompanyCustomer;
import com.ecep.contract.ds.customer.model.CompanyCustomerEntity;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.CompanyCustomerEntityVo;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "company-customer-entity")
public class CompanyCustomerEntityService implements IEntityService<CompanyCustomerEntity>, QueryService<CompanyCustomerEntityVo>, VoableService<CompanyCustomerEntity, CompanyCustomerEntityVo> {
    @Lazy
    @Autowired
    private CompanyCustomerEntityRepository repository;

    @Autowired
    private CustomerService companyCustomerService;

    @Autowired
    private CustomerCatalogService customerCatalogService;

    @Autowired
    private EmployeeService employeeService;

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

    @Cacheable(key = "#p0")
    @Override
    public CompanyCustomerEntityVo findById(Integer id) {
        return repository.findById(id).map(CompanyCustomerEntity::toVo).orElse(null);
    }

    @Override
    public Specification<CompanyCustomerEntity> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return SpecificationUtils.andWith(searchText, this::buildSearchSpecification);
    }

    protected Specification<CompanyCustomerEntity> buildSearchSpecification(String searchText) {
        return (root, query, builder) -> {
            return builder.or(
                    builder.like(root.get("name"), "%" + searchText + "%"),
                    builder.like(root.get("abbName"), "%" + searchText + "%"),
                    builder.like(root.get("code"), "%" + searchText + "%"));
        };
    }

    public List<CompanyCustomerEntity> search(String searchText) {
        Specification<CompanyCustomerEntity> spec = getSpecification(searchText);
        return repository.findAll(spec, Pageable.ofSize(10)).getContent();
    }

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

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

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'code-'+#p0.code")
    })
    @Override
    public void delete(CompanyCustomerEntity entity) {
        repository.delete(entity);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'code-'+#p0.code")
    })
    @Override
    public CompanyCustomerEntity save(CompanyCustomerEntity entity) {
        return repository.save(entity);
    }

    public List<CompanyCustomerEntity> findAllByCustomer(CompanyCustomer companyCustomer) {
        return repository.findByCustomer(companyCustomer);
    }

    @Cacheable(key = "'code-'+#p0")
    public CompanyCustomerEntityVo findByCustomerCode(String customerCode) {
        return repository.findByCode(customerCode).map(CompanyCustomerEntity::toVo).orElse(null);
    }

    public void resetTo(CompanyCustomer from, CompanyCustomer to) {
        List<CompanyCustomerEntity> entities = repository.findByCustomer(from);
        for (CompanyCustomerEntity entity : entities) {
            entity.setCustomer(to);
        }
        repository.saveAll(entities);
    }

    @Override
    public void updateByVo(CompanyCustomerEntity entity, CompanyCustomerEntityVo vo) {
        // 优化关联实体处理逻辑 - 客户关联
        if (vo.getCustomerId() == null) {
            entity.setCustomer(null);
        } else {
            // 添加实体匹配检查
            if (entity.getCustomer() == null || !entity.getCustomer().getId().equals(vo.getCustomerId())) {
                // 使用getById方法替代findById
                entity.setCustomer(companyCustomerService.getById(vo.getCustomerId()));
            }
        }

        // 映射基本属性
        entity.setName(vo.getName());
        entity.setAbbName(vo.getAbbName());
        entity.setCode(vo.getCode());

        // 优化关联实体处理逻辑 - 客户分类关联
        if (vo.getCustomerCatalogId() == null) {
            entity.setCatalog(null);
        } else {
            // 添加实体匹配检查
            if (entity.getCatalog() == null || !entity.getCatalog().getId().equals(vo.getCustomerCatalogId())) {
                // 使用getById方法替代findById
                entity.setCatalog(customerCatalogService.getById(vo.getCustomerCatalogId()));
            }
        }

        // 优化关联实体处理逻辑 - 创建者关联
        if (vo.getCreatorId() == null) {
            entity.setCreator(null);
        } else {
            // 添加实体匹配检查
            if (entity.getCreator() == null || !entity.getCreator().getId().equals(vo.getCreatorId())) {
                // 使用getById方法替代findById
                entity.setCreator(employeeService.getById(vo.getCreatorId()));
            }
        }

        // 优化关联实体处理逻辑 - 修改者关联
        if (vo.getModifierId() == null) {
            entity.setModifier(null);
        } else {
            // 添加实体匹配检查
            if (entity.getModifier() == null || !entity.getModifier().getId().equals(vo.getModifierId())) {
                // 使用getById方法替代findById
                entity.setModifier(employeeService.getById(vo.getModifierId()));
            }
        }

        // 映射其他属性
        entity.setModifyDate(vo.getModifyDate());
        entity.setDevelopDate(vo.getDevelopDate());
        entity.setUpdatedDate(vo.getUpdatedDate());
        entity.setFetchedTime(vo.getFetchedTime());
    }

}
