package com.ecep.contract.ds.company.service;

import java.util.List;

import com.ecep.contract.SpringApp;
import com.ecep.contract.vo.CompanyVo;
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.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.constant.ServiceConstant;
import com.ecep.contract.ds.company.repository.CompanyExtendInfoRepository;
import com.ecep.contract.ds.company.model.Company;
import com.ecep.contract.ds.company.model.CompanyExtendInfo;
import com.ecep.contract.service.ServiceException;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.CompanyExtendInfoVo;
import com.fasterxml.jackson.databind.JsonNode;

/**
 * 公司文件服务
 */
@Lazy
@Service
@CacheConfig(cacheNames = "company-extend-info")
public class CompanyExtendInfoService implements IEntityService<CompanyExtendInfo>, QueryService<CompanyExtendInfoVo>, VoableService<CompanyExtendInfo, CompanyExtendInfoVo> {
    private static final Logger logger = LoggerFactory.getLogger(CompanyExtendInfoService.class);
    @Autowired
    private CompanyExtendInfoRepository repository;

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

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

    public Specification<CompanyExtendInfo> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return (root, query, builder) -> {
            return builder.or(
                    builder.like(root.get("businessScope"), "%" + searchText + "%"),
                    builder.like(root.get("taxRegistrationNumber"), "%" + searchText + "%"),
                    builder.like(root.get("legalPerson"), "%" + searchText + "%"));
        };
    }

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

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

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'byCompany-'+#p0.company.id")
    })
    public void delete(CompanyExtendInfo extendInfo) {
        repository.delete(extendInfo);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id", condition = "#p0.id != null"),
            @CacheEvict(key = "'byCompany-'+#p0.company.id", condition = "#p0.company != null")
    })
    @Override
    public CompanyExtendInfo save(CompanyExtendInfo extendInfo) {
        return repository.save(extendInfo);
    }

    @Cacheable(key = "'byCompany-'+#p0.id")
    public CompanyExtendInfoVo findByCompany(CompanyVo company) {
        List<CompanyExtendInfo> list = repository.findByCompanyId(company.getId());
        if (list.isEmpty()) {
            CompanyExtendInfo extendInfo = new CompanyExtendInfo();
            Company v1 = SpringApp.getBean(CompanyService.class).getById(company.getId());
            extendInfo.setCompany(v1);
            extendInfo.setDisableVerify(false);
            return repository.save(extendInfo).toVo();
        }
        return list.getFirst().toVo();
    }

    public CompanyExtendInfo findByCompany(Company company) {
        List<CompanyExtendInfo> list = repository.findByCompany(company);
        if (list.isEmpty()) {
            CompanyExtendInfo extendInfo = new CompanyExtendInfo();
            extendInfo.setCompany(company);
            extendInfo.setDisableVerify(false);
            return repository.save(extendInfo);
        }
        return list.getFirst();
    }

    @Override
    public void updateByVo(CompanyExtendInfo model, CompanyExtendInfoVo vo) throws ServiceException {
        if (model == null || vo == null) {
            throw new ServiceException("Model or VO cannot be null");
        }
        if (vo.getCompanyId() == null) {
            model.setCompany(null);
        } else {
            Company v1 = model.getCompany();
            if (v1 == null) {
                Company company = SpringApp.getBean(CompanyService.class).getById(vo.getCompanyId());
                model.setCompany(company);
            } else {
                if (!v1.getId().equals(vo.getCompanyId())) {
                    Company company = SpringApp.getBean(CompanyService.class).getById(vo.getCompanyId());
                    model.setCompany(company);
                }
            }
        }

        // 只更新VO中已有的字段
        model.setDisableVerify(vo.isDisableVerify());
    }

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