package com.qingyun.service.compare.factory;

import com.qingyun.common.exception.ServiceException;
import com.qingyun.service.compare.strategy.FileComparisonStrategy;
import com.qingyun.service.domain.ContractCompareTask;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

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

/**
 * 策略工厂（根据文件类型选择策略）
 */
@Component
public class FileComparisonStrategyFactory {

    private final List<FileComparisonStrategy> strategies;

    public FileComparisonStrategyFactory(List<FileComparisonStrategy> strategies) {
        this.strategies = strategies.stream()
            .sorted(Comparator.comparing(strategy -> {
                Order order = strategy.getClass().getAnnotation(Order.class);
                return order != null ? order.value() : Integer.MAX_VALUE;
            }))
            .collect(Collectors.toList());
    }

    /**
     * 根据任务中的文件扩展名选择合适的策略
     * @param task
     * @return
     */
    public FileComparisonStrategy getStrategy(ContractCompareTask task) {
        String ext1 = getFileExtension(task.getFirstContractUrl());
        String ext2 = getFileExtension(task.getSecondContractUrl());

        if (!ext1.equalsIgnoreCase(ext2)) {
            throw new ServiceException("两份文件类型不一致，无法对比");
        }

        for (FileComparisonStrategy strategy : strategies) {
            if (strategy.supports(ext1)) {
                return strategy;
            }
        }
        throw new ServiceException("不支持的文件类型: " + ext1);
    }

    /**
     * 获取文件扩展名
     * @param fileName 文件名
     * @return 文件扩展名
     */
    private String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf('.') == -1) return "";
        return fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
    }
}
