package com.ecep.contract.cloud.tyc;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
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.MessageHolder;
import com.ecep.contract.cloud.CloudInfo;
import com.ecep.contract.constant.CloudServiceConstant;
import com.ecep.contract.model.CloudTyc;
import com.ecep.contract.model.Company;
import com.ecep.contract.util.MyStringUtils;

@Lazy
@Service
public class CloudTycService implements IEntityService<CloudTyc> {
    private static final Logger logger = LoggerFactory.getLogger(CloudTycService.class);

    /**
     * 天眼查报告，文件名中必须包含 天眼查 字样
     *
     * @param fileName 文件名
     * @return 是否是天眼查报告
     */
    public static boolean isTycReport(String fileName) {
        // 文件名中包含 天眼查 字样
        return fileName.contains(CloudServiceConstant.TYC_NAME);
    }

    @Autowired
    private CloudTycRepository cloudTycRepository;

    public CloudTyc getOrCreateCloudTyc(CloudInfo info) {
        Optional<CloudTyc> optional = cloudTycRepository.findById(info.getId());
        return optional.orElseGet(() -> getOrCreateCloudTyc(info.getCompany()));
    }

    public CloudTyc getOrCreateCloudTyc(Company company) {
        Integer companyId = company.getId();
        List<CloudTyc> list = cloudTycRepository.findAllByCompanyId(companyId);
        if (list.isEmpty()) {
            CloudTyc tyc = new CloudTyc();
            tyc.setCompany(company);
            tyc.setScore(-1);
            tyc.setCloudLatest(null);
            return cloudTycRepository.save(tyc);
        }
        if (list.size() == 1) {
            return list.getFirst();
        }

        // 查询有 CloudId 的记录
        List<CloudTyc> hasCouldIdList = list.stream()
                .filter(v -> {
                    return StringUtils.hasText(v.getCloudId())
                            && MyStringUtils.isAllDigit(v.getCloudId());
                })
                .collect(Collectors.toList());

        // 没有匹配到一条时
        if (hasCouldIdList.isEmpty()) {
            // 保留第一条，其他删除
            CloudTyc rk = list.removeFirst();
            cloudTycRepository.deleteAll(list);
            return rk;
        }

        // 只有匹配到一条有 CloudId 的记录
        if (hasCouldIdList.size() == 1) {
            // 保留匹配的记录，其他删除
            CloudTyc rk = hasCouldIdList.removeFirst();
            list.remove(rk);
            cloudTycRepository.deleteAll(list);
            return rk;
        }

        // 查询有 Score 的记录
        List<CloudTyc> hasLatestList = hasCouldIdList.stream().filter(v -> {
            return v.getScore() != null && v.getScore() > 0;
        }).collect(Collectors.toList());
        // 没有匹配到一条时
        if (hasLatestList.isEmpty()) {
            // 保留第一条，其他删除
            CloudTyc rk = hasCouldIdList.removeFirst();
            list.remove(rk);
            cloudTycRepository.deleteAll(list);
            return rk;
        }

        // 只有匹配到一条有 CloudId 的记录
        if (hasLatestList.size() == 1) {
            // 保留匹配的记录，其他删除
            CloudTyc rk = hasLatestList.removeFirst();
            list.remove(rk);
            cloudTycRepository.deleteAll(list);
            return rk;
        }

        return hasLatestList.getFirst();

    }

    public CloudTyc save(CloudTyc cloudTyc) {
        return cloudTycRepository.save(cloudTyc);
    }

    @Override
    public void delete(CloudTyc entity) {
        cloudTycRepository.delete(entity);
    }


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

    public void resetTo(Company from, Company to) {
        List<CloudTyc> list = cloudTycRepository.findAllByCompanyId(from.getId());
        for (CloudTyc item : list) {
            item.setCompany(to);
        }
        cloudTycRepository.saveAll(list);
    }

    public CloudTyc findById(Integer id) {
        return cloudTycRepository.findById(id).orElse(null);
    }

    public Page<CloudTyc> findAll(Specification<CloudTyc> spec, PageRequest pageable) {
        return cloudTycRepository.findAll(spec, pageable);
    }

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

    @Override
    public Specification<CloudTyc> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return (root, query, builder) -> {
            return builder.like(root.get("cloudId"), "%" + searchText + "%");
        };
    }

    public void syncCompany(Company company, MessageHolder holder) {
        // TODO 从天眼查同步公司信息
        holder.warn("TODO 未实现");
    }
}
