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.SpringApp;
import com.ecep.contract.ds.company.repository.CompanyContactRepository;
import com.ecep.contract.ds.company.model.Company;
import com.ecep.contract.ds.company.model.CompanyContact;
import com.ecep.contract.service.ServiceException;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.MyStringUtils;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.CompanyContactVo;
import com.ecep.contract.vo.CompanyVo;
import com.fasterxml.jackson.databind.JsonNode;

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

    @Autowired
    private CompanyContactRepository repository;

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

    @Override
    public CompanyContact save(CompanyContact contact) {
        return repository.save(contact);
    }

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

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

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

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

    public CompanyContactVo findFirstByCompany(CompanyVo company) {
        return repository.findFirstByCompanyId(company.getId()).map(CompanyContact::toVo).orElse(null);
    }

    @Override
    public CompanyContactVo findById(Integer id) {
        return repository.findById(id).map(CompanyContact::toVo).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 repository.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 repository.findAll(spec);
    }

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

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

    @Override
    public Page<CompanyContactVo> 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).map(CompanyContact::toVo);
    }

    @Override
    public void updateByVo(CompanyContact model, CompanyContactVo vo) {
        if (model == null) {
            throw new ServiceException("CompanyContact cannot be null");
        }
        if (vo == null) {
            throw new ServiceException("CompanyContactVo cannot be null");
        }

        // 基本属性映射
        model.setName(vo.getName());
        model.setPhone(vo.getPhone());
        model.setEmail(vo.getEmail());
        model.setAddress(vo.getAddress());
        model.setPosition(vo.getPosition());
        model.setU8Code(vo.getU8Code());
        model.setMemo(vo.getMemo());
        model.setCreated(vo.getCreated());

        // 处理关联关系 - 公司
        if (vo.getCompanyId() != null) {
            model.setCompany(SpringApp.getBean(CompanyService.class).getById(vo.getCompanyId()));
        } else {
            model.setCompany(null);
        }

        // 注意：
        // 1. CompanyContact实体类中没有primary字段，所以不需要设置
        // 2. CompanyContact实体类中没有active字段，所以不需要设置
    }

}
