/**
 * 表单联动规则工具
 * 处理字段之间的联动逻辑
 */

import type { FieldConfig, LinkageCondition } from '../types';

/**
 * 评估联动条件
 * @param condition 联动条件
 * @param formValues 表单值
 * @returns 条件是否满足
 */
export const evaluateCondition = (
  condition: LinkageCondition,
  formValues: Record<string, any>
): boolean => {
  const fieldValue = formValues[condition.field];
  const compareValue = condition.value;

  switch (condition.operator) {
    case '==':
      return fieldValue == compareValue;
    case '!=':
      return fieldValue != compareValue;
    case '>':
      return Number(fieldValue) > Number(compareValue);
    case '<':
      return Number(fieldValue) < Number(compareValue);
    case '>=':
      return Number(fieldValue) >= Number(compareValue);
    case '<=':
      return Number(fieldValue) <= Number(compareValue);
    case 'includes':
      return Array.isArray(fieldValue) 
        ? fieldValue.includes(compareValue) 
        : String(fieldValue).includes(compareValue);
    case 'notIncludes':
      return Array.isArray(fieldValue) 
        ? !fieldValue.includes(compareValue) 
        : !String(fieldValue).includes(compareValue);
    default:
      return false;
  }
};

/**
 * 扁平化字段列表（包括栅格内的字段）
 * @param fieldList 字段列表
 * @returns 扁平化后的字段数组
 */
export const flattenFields = (fieldList: FieldConfig[]): FieldConfig[] => {
  const result: FieldConfig[] = [];
  
  fieldList.forEach(field => {
    // 排除布局组件
    if (field.type !== 'divider' && field.type !== 'text') {
      result.push(field);
    }
    
    // 递归处理栅格布局内的字段
    if (field.type === 'grid' && field.children) {
      field.children.forEach(columnFields => {
        result.push(...flattenFields(columnFields));
      });
    }
  });
  
  return result;
};

/**
 * 字段状态接口
 */
export interface FieldState {
  visible?: boolean;
  disabled?: boolean;
  required?: boolean;
}

/**
 * 计算字段联动状态
 * @param fields 字段列表
 * @param formData 表单数据
 * @returns 字段状态映射
 */
export const calculateLinkageStates = (
  fields: FieldConfig[],
  formData: Record<string, any>
): Record<string, FieldState> => {
  const allFields = flattenFields(fields);
  const fieldStates: Record<string, FieldState> = {};

  allFields.forEach(field => {
    if (field.linkageRules && field.linkageRules.length > 0) {
      field.linkageRules.forEach(rule => {
        // 检查所有条件是否都满足
        const allConditionsMet = rule.conditions.every(condition =>
          evaluateCondition(condition, formData)
        );

        if (allConditionsMet) {
          if (!fieldStates[field.name]) {
            fieldStates[field.name] = {};
          }

          switch (rule.type) {
            case 'visible':
              fieldStates[field.name].visible = rule.action;
              break;
            case 'disabled':
              fieldStates[field.name].disabled = rule.action;
              break;
            case 'required':
              fieldStates[field.name].required = rule.action;
              break;
            // 'value' 类型需要在调用方处理，因为需要访问 form 实例
          }
        }
      });
    }
  });

  return fieldStates;
};

