package com.ecep.contract.service;

import java.io.File;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.ecep.contract.CustomerFileType;
import com.ecep.contract.MessageHolder;
import com.ecep.contract.SpringApp;
import com.ecep.contract.constant.CompanyCustomerConstant;
import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.CustomerFileViewModel;
import com.ecep.contract.vo.CustomerFileVo;
import com.ecep.contract.vo.CustomerVo;
import com.ecep.contract.vo.CompanyVo;
import com.ecep.contract.vo.ContractVo;

@Service
@CacheConfig(cacheNames = "customer-file")
public class CompanyCustomerFileService extends QueryService<CustomerFileVo, CustomerFileViewModel> {

    public File getEvaluationFormTemplate() {
        SysConfService confService = SpringApp.getBean(SysConfService.class);
        String path = confService.getString(CompanyCustomerConstant.KEY_EVALUATION_FORM_TEMPLATE);
        if (path == null) {
            return null;
        }
        return new File(path);
    }

    @Cacheable
    @Override
    public CustomerFileVo findById(Integer id) {
        return super.findById(id);
    }

    public LocalDate getNextSignDate(CustomerVo companyCustomer, MessageHolder holder) {
        LocalDate miniContractDate = LocalDate.of(2022, 1, 1);
        Integer companyId = companyCustomer.getCompanyId();

        CompanyService companyService = SpringApp.getBean(CompanyService.class);
        CompanyVo company = companyService.findById(companyId);
        ContractService contractService = SpringApp.getBean(ContractService.class);
        Map<String, Object> params = ParamUtils.builder().equals("company", company.getId()).build();
        long count = contractService.count(params);
        if (count == 0) {
            holder.info("未发现已登记的合同");
            return null;
        }

        // 检索评估表
        List<CustomerFileVo> files = findAllByCustomerAndType(companyCustomer,
                CustomerFileType.EvaluationForm);
        CustomerFileVo latestFile = files.stream()
                .filter(v -> v.getSignDate() != null && v.isValid())
                .max(Comparator.comparing(CustomerFileVo::getSignDate))
                .orElse(null);
        if (latestFile == null) {
            // 没有有效的评估表的评价日期
            holder.warn("未发现有效的评估表");
            // 返回最早的合同日期
            ContractVo firstContract = contractService.findAll(params, Pageable.unpaged()).stream()
                    .filter(v -> v.getSetupDate() != null && !v.getSetupDate().isBefore(miniContractDate))
                    .min(Comparator.comparing(ContractVo::getSetupDate))
                    .orElse(null);
            if (firstContract == null) {
                holder.warn("最早的合同不存在?");
                return null;
            }

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

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

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

    public List<CustomerFileVo> findAllByCustomer(CustomerVo companyCustomer) {
        return findAll(ParamUtils.builder().equals("customer", companyCustomer).build(), Pageable.unpaged())
                .getContent();
    }

    public List<CustomerFileVo> findAllByCustomerAndType(CustomerVo customer, CustomerFileType type) {
        return findAll(ParamUtils.builder()
                .equals("customer", customer.getId())
                .equals("type", type.name())
                .build(), Pageable.unpaged()).getContent();
    }

    @CacheEvict(allEntries = true)
    @Override
    public CustomerFileVo save(CustomerFileVo entity) {
        return super.save(entity);
    }
}
