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

import java.io.File;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;

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.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ecep.contract.CompanyVendorFileType;
import com.ecep.contract.IEntityService;
import com.ecep.contract.MessageHolder;
import com.ecep.contract.MyDateTimeUtils;
import com.ecep.contract.SpringApp;
import com.ecep.contract.ds.company.service.CompanyBasicService;
import com.ecep.contract.ds.contract.service.ContractFileService;
import com.ecep.contract.ds.contract.service.ContractService;
import com.ecep.contract.ds.vendor.repository.CompanyVendorFileRepository;
import com.ecep.contract.model.CompanyVendor;
import com.ecep.contract.model.CompanyVendorFile;
import com.ecep.contract.model.Contract;


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

    @Autowired
    private CompanyVendorFileRepository repository;
    @Autowired
    private ContractFileService contractFileService;

    public CompanyVendorFile findById(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public Specification<CompanyVendorFile> getSpecification(String searchText) {
        return (root, query, builder) -> {
            return builder.or(builder.like(root.get("filePath"), "%" + searchText + "%"));
        };
    }

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

    public List<CompanyVendorFile> findAllByVendor(CompanyVendor companyVendor) {
        return repository.findAllByVendorId(companyVendor.getId());
    }

    public void delete(CompanyVendorFile file) {
        repository.delete(file);
    }

    public void deleteById(int id) {
        repository.deleteById(id);
    }

    public void saveAll(List<CompanyVendorFile> files) {
        repository.saveAll(files);
    }

    public CompanyVendorFile save(CompanyVendorFile file) {
        return repository.save(file);
    }

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

    public List<CompanyVendorFile> findAllByVendorAndType(CompanyVendor vendor, CompanyVendorFileType type) {
        return repository.findAllByVendorAndType(vendor, type);
    }

    /**
     * 验证供应商文件
     *
     * @param companyVendor 供应商
     * @param verifyDate    验证日期
     * @param holder        状态输出
     */
    public void verify(CompanyVendor companyVendor, LocalDate verifyDate, MessageHolder holder) {
        // 验证最早日期，之前属于历史问题，不做处理
        LocalDate minDate = LocalDate.of(2022, 1, 1);
        if (verifyDate.isBefore(minDate)) {
            return;
        }

        // 查询所有评价表
        List<CompanyVendorFile> files = findAllByVendorAndType(companyVendor, CompanyVendorFileType.EvaluationForm);
        if (files == null || files.isEmpty()) {
            holder.error("未见供应商评价");
            return;
        }

        // 检索 验证日期最近一年内的有效评价表，日期宽限7天
        LocalDate begin = verifyDate.plusYears(-1);
        CompanyVendorFile vendorFile = files.stream()
                .filter(v -> v.getSignDate() != null && v.isValid())
                .filter(v -> MyDateTimeUtils.dateValidFilter(v.getSignDate(), begin, verifyDate, 7))
                .findFirst().orElse(null);
        if (vendorFile == null) {
            // 检索最后一个有效评价表
            CompanyVendorFile latestFile = files.stream()
                    .filter(v -> v.getSignDate() != null && v.isValid())
                    .max(Comparator.comparing(CompanyVendorFile::getSignDate))
                    .orElse(null);

            if (latestFile == null) {
                holder.error("未匹配的供应商评价");
                return;
            }
            // 提示评价表已过期
            holder.error("供应商评价已过期：" + latestFile.getSignDate() + ", 检测日期：" + verifyDate);
        }
    }

    /**
     * 根据合同 和 评价表情况计算下一个评价日期
     *
     * @param companyVendor 供应商
     * @return 下一个评价日期
     */
    public LocalDate getNextSignDate(CompanyVendor companyVendor, Consumer<String> state) {
        LocalDate miniContractDate = LocalDate.of(2022, 1, 1);

        // 检索全部合同
        ContractService contractService = SpringApp.getBean(ContractService.class);
        List<Contract> contractList = contractService.findAllByCompanyVendor(companyVendor, null, null);
        if (contractList.isEmpty()) {
            state.accept("未发现已登记的合同");
            return null;
        }
        // 检索评价表
        List<CompanyVendorFile> files = findAllByVendorAndType(companyVendor, CompanyVendorFileType.EvaluationForm);
        CompanyVendorFile latestFile = files.stream()
                .filter(v -> v.getSignDate() != null && v.isValid())
                .max(Comparator.comparing(CompanyVendorFile::getSignDate))
                .orElse(null);

        // 没有有效的评价表的评价日期
        if (latestFile == null) {
            state.accept("未发现有效的评价表");
            // 返回最早的合同日期
            Contract firstContract = contractList.stream()
                    .filter(v -> v.getSetupDate() != null && !v.getSetupDate().isBefore(miniContractDate))
                    .min(Comparator.comparing(Contract::getSetupDate))
                    .orElse(null);
            if (firstContract == null) {
                state.accept("最早的合同不存在?");
                return null;
            }

            LocalDate setupDate = firstContract.getSetupDate();
            state.accept("依据合同 " + firstContract.getCode() + " 的日期 " + setupDate + " 推算");
            return CompanyBasicService.adjustToWorkDay(setupDate.plusDays(-7));
        }

        // 检查失效日期起的第一个合同
        LocalDate nextInValidDate = latestFile.getSignDate().plusYears(1);
        File file = new File(latestFile.getFilePath());
        state.accept("依据 " + file.getName() + " 的失效期 " + nextInValidDate + " 检索合同");
        List<Contract> matchedContracts = contractList.stream()
                .filter(v -> v.getSetupDate().isAfter(nextInValidDate)).toList();
        // 没有在失效日期后的合同时，使用失效日期
        if (matchedContracts.isEmpty()) {
            state.accept("未发现失效期 " + nextInValidDate + " 后的合同");
            return null;
        }
        state.accept("发现匹配合同 " + matchedContracts.size() + " 个");

        // 按时间取最早一个
        Contract firstContract = matchedContracts.stream()
                .min(Comparator.comparing(Contract::getSetupDate))
                .orElse(null);
        LocalDate setupDate = firstContract.getSetupDate();
        state.accept("匹配失效期 " + nextInValidDate + " 后的第一个合同 " + firstContract.getCode());
        state.accept("依据合同 " + firstContract.getCode() + " 的日期 " + setupDate + " 推算");
        return CompanyBasicService.adjustToWorkDay(setupDate.plusDays(-7));
    }


}
