package com.ecep.contract.ds.company.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.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.ds.company.repository.CompanyContactRepository;
import com.ecep.contract.model.Company;
import com.ecep.contract.model.CompanyContact;
import com.ecep.contract.util.MyStringUtils;
import com.ecep.contract.util.SpecificationUtils;
import com.fasterxml.jackson.databind.JsonNode;

/**
 * 公司联系人服务
 */
@Lazy
@Service
@CacheConfig(cacheNames = "company-contact")
public class CompanyContactService implements IEntityService<CompanyContact>, QueryService<CompanyContact> {
    private static final Logger logger = LoggerFactory.getLogger(CompanyContactService.class);

    @Autowired
    private CompanyContactRepository companyContactRepository;

    public CompanyContact save(CompanyContact contact) {
        return companyContactRepository.save(contact);
    }

    public void resetTo(Company from, Company to) {
        // 曾用名 关联到 updater
        List<CompanyContact> list = companyContactRepository.findAllByCompany(from);
        if (list.isEmpty()) {
            return;
        }
        for (CompanyContact oldName : list) {
            oldName.setMemo(MyStringUtils.appendIfAbsent(oldName.getMemo(), "转自 " + from.getId()));
            oldName.setCompany(to);
        }
        companyContactRepository.saveAll(list);
    }

    public void deleteByCompany(Company company) {
        int deleted = companyContactRepository.deleteAllByCompany(company);
        if (deleted > 0) {
            if (logger.isInfoEnabled()) {
                logger.info("Delete {} records by company:#{}", deleted, company.getId());
            }
        }
    }

    public void delete(CompanyContact entity) {
        companyContactRepository.delete(entity);
    }

    public CompanyContact findFirstByCompany(Company company) {
        return companyContactRepository.findFirstByCompany(company).orElse(null);
    }

    public CompanyContact findById(Integer id) {
        return companyContactRepository.findById(id).orElse(null);
    }

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

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

    public List<CompanyContact> searchByCompany(Company company, String userText) {
        Specification<CompanyContact> spec = SpecificationUtils.and((root, query, builder) -> {
            return builder.equal(root.get("company"), company);
        }, getSpecification(userText));
        return companyContactRepository.findAll(spec);
    }

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

    public List<CompanyContact> findAllByCompanyAndName(Company company, String contactName) {
        return companyContactRepository.findAllByCompanyAndName(company, contactName);
    }

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