import { ref } from 'vue';
import { evaluateRules, getEnabledRules } from '/@/api/purchase/purchasingRuleConfig';

const RULE_CACHE_KEY = 'purchase_rule_cache';
const CACHE_EXPIRE_TIME = 5 * 60 * 1000;

interface RuleCache {
  data: any[];
  timestamp: number;
}

interface RuleResult {
  purchaseMode: string;
  purchaseSchool: string;
  bidTemplate: string;
  requiredFiles: { fieldName: string; fileTypeName: string; required: boolean }[];
  matchedRules: any[];
}

const ruleCache = ref<RuleCache | null>(null);

export function usePurchaseRules() {
  const loading = ref(false);
  const rules = ref<any[]>([]);

  const loadRules = async (forceRefresh = false) => {
    if (!forceRefresh && ruleCache.value) {
      const now = Date.now();
      if (now - ruleCache.value.timestamp < CACHE_EXPIRE_TIME) {
        rules.value = ruleCache.value.data;
        return;
      }
    }

    loading.value = true;
    try {
      const res = await getEnabledRules();
      rules.value = res.data || [];
      ruleCache.value = {
        data: rules.value,
        timestamp: Date.now()
      };
    } catch (e) {
      console.error('加载采购规则失败', e);
    } finally {
      loading.value = false;
    }
  };

  const evaluate = async (params: {
    budget: number;
    isCentralized?: string;
    isSpecial?: string;
    hasSupplier?: string;
    projectType?: string;
  }): Promise<RuleResult | null> => {
    try {
      const res = await evaluateRules(params);
      return res.data;
    } catch (e) {
      console.error('评估规则失败', e);
      return null;
    }
  };

  const getThresholds = () => {
    const thresholds: Record<string, number> = {
      deptPurchase: 0,
      feasibility: 0,
      publicSelect: 0,
      govPurchase: 0,
      deptSelfMeetingMinutes: 0
    };

    const getRuleAmount = (code: string, defaultVal?: number) => {
      const rule = rules.value.find(r => r.ruleCode === code);
      if (!rule) {
        if (defaultVal === undefined) {
          throw new Error(`采购规则配置缺失: ${code}，请在系统配置中维护`);
        }
        return defaultVal;
      }
      if (rule.amountMin !== undefined && rule.amountMin !== null) {
        return Number(rule.amountMin);
      }
      if (rule.amountMax !== undefined && rule.amountMax !== null) {
        return Number(rule.amountMax);
      }
      if (defaultVal === undefined) {
        throw new Error(`采购规则配置缺失: ${code}，请在系统配置中维护`);
      }
      return defaultVal;
    };

    thresholds.deptPurchase = getRuleAmount('DEPT_PURCHASE_THRESHOLD');
    thresholds.feasibility = getRuleAmount('FEASIBILITY_REPORT');
    thresholds.publicSelect = getRuleAmount('PUBLIC_BID_40W_100W');
    thresholds.govPurchase = getRuleAmount('GOV_PURCHASE_THRESHOLD');
    thresholds.deptSelfMeetingMinutes = getRuleAmount('DEPT_SELF_MEETING_MINUTES', 2000);

    return thresholds;
  };

  loadRules();

  return {
    loading,
    rules,
    loadRules,
    evaluate,
    getThresholds
  };
}

let globalRulesInstance: ReturnType<typeof usePurchaseRules> | null = null;

export function usePurchaseRulesSingleton() {
  if (!globalRulesInstance) {
    globalRulesInstance = usePurchaseRules();
  }
  return globalRulesInstance;
}