package com.ecep.contract.service;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.MyDateTimeUtils;
import com.ecep.contract.SpringApp;
import com.ecep.contract.VendorFileType;
import com.ecep.contract.constant.CompanyCustomerConstant;
import com.ecep.contract.constant.CompanyVendorConstant;
import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.CompanyVendorFileViewModel;
import com.ecep.contract.vo.ContractVo;
import com.ecep.contract.vo.VendorFileVo;
import com.ecep.contract.vo.VendorVo;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

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

@Service
public class VendorFileService extends QueryService<VendorFileVo, CompanyVendorFileViewModel> {
    public File getEvaluationFormTemplate() {
        SysConfService confService = SpringApp.getBean(SysConfService.class);
        String path = confService.getString(CompanyVendorConstant.KEY_EVALUATION_FORM_TEMPLATE);
        if (path == null) {
            return null;
        }
        return new File(path);
    }

    /**
     * 获取供应商下一个评价表的日期
     *
     * @param vendor 供应商
     * @param state  状态消费者
     * @return 下一个评价表的日期
     */
    public LocalDate getNextSignDate(VendorVo vendor, Consumer<String> state) {
        LocalDate miniContractDate = LocalDate.of(2022, 1, 1);

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

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

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

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

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

    public void verify(VendorVo companyVendor, LocalDate verifyDate, MessageHolder holder) {
        // 查询所有评价表
        List<VendorFileVo> files = findAllByVendorAndType(companyVendor, VendorFileType.EvaluationForm);
        if (files == null || files.isEmpty()) {
            holder.error("未见供应商评价");
            return;
        }

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

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

    public List<VendorFileVo> findAllByVendorAndType(VendorVo vendor, VendorFileType type) {
        return findAll(ParamUtils.builder()
                .equals("vendor", vendor.getId())
                .equals("type", type.name())
                .build(), Pageable.unpaged()).getContent();
    }
}
