/**
 * 栅格布局字段预览组件
 * 用于在表单预览模式下渲染栅格及其子字段
 */

import React from 'react';
import { Row, Col, Form } from 'antd';
import type { Rule } from 'antd/es/form';
import type { FieldConfig, FormConfig, ValidationRule } from '../types';
import FieldRenderer from './FieldRenderer';

interface GridFieldPreviewProps {
  field: FieldConfig;
  formData?: Record<string, any>;
  onFieldChange?: (name: string, value: any) => void;
  formConfig?: FormConfig;
}

const GridFieldPreview: React.FC<GridFieldPreviewProps> = ({ 
  field, 
  formData = {}, 
  onFieldChange,
  formConfig 
}) => {
  const columns = field.columns || 2;
  const children = field.children || Array(columns).fill([]);
  
  // 使用自定义列宽度或平均分配
  const getColSpan = (colIndex: number) => {
    if (field.columnSpans && field.columnSpans.length > colIndex) {
      return field.columnSpans[colIndex];
    }
    return 24 / columns; // 平均分配
  };

  // 将验证规则转换为Ant Design的Rule数组（和FormPreview保持一致）
  const convertValidationRules = (validationRules?: ValidationRule[]): Rule[] => {
    if (!validationRules || validationRules.length === 0) return [];

    return validationRules.map(rule => {
      const antdRule: Rule = {
        type: rule.type === 'email' ? 'email' : rule.type === 'url' ? 'url' : undefined,
        message: rule.message || `请输入正确的${rule.type}`,
      };

      switch (rule.type) {
        case 'required':
          antdRule.required = true;
          break;
        case 'pattern':
          if (rule.value) {
            antdRule.pattern = new RegExp(rule.value);
          }
          break;
        case 'min':
          antdRule.type = 'number';
          antdRule.min = rule.value;
          break;
        case 'max':
          antdRule.type = 'number';
          antdRule.max = rule.value;
          break;
        case 'minLength':
          antdRule.min = rule.value;
          break;
        case 'maxLength':
          antdRule.max = rule.value;
          break;
        case 'phone':
          antdRule.pattern = /^1[3-9]\d{9}$/;
          break;
        case 'idCard':
          antdRule.pattern = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dX]$/;
          break;
      }

      return antdRule;
    });
  };

  const renderFieldItem = (childField: FieldConfig) => {
    // 布局组件直接渲染，不需要 Form.Item
    if (['text', 'divider', 'grid'].includes(childField.type)) {
      return (
        <div key={childField.id} style={{ marginBottom: 8 }}>
          <FieldRenderer field={childField} isPreview={true} />
        </div>
      );
    }

    // 根据表单配置决定布局方式
    const isVertical = formConfig?.labelAlign === 'top';
    
    // 合并基础验证规则和自定义验证规则（和FormPreview保持一致）
    const customRules = convertValidationRules(childField.validationRules);
    
    // 🐛 调试：打印验证规则
    if (childField.validationRules && childField.validationRules.length > 0) {
      console.log(`📋 [GridFieldPreview] 字段 "${childField.label}" 的验证规则:`, childField.validationRules);
      console.log(`✅ [GridFieldPreview] 转换后的规则:`, customRules);
    }
    
    // 检查自定义验证规则中是否已经包含必填验证
    const hasRequiredRule = childField.validationRules?.some(rule => rule.type === 'required');
    
    // 基础规则：只有在没有自定义必填验证时，才使用字段属性中的"是否必填"
    const baseRules: Rule[] = [];
    if (childField.required && !hasRequiredRule) {
      baseRules.push({
        required: true,
        message: `请输入${childField.label}`,
      });
    }
    
    const allRules = [...baseRules, ...customRules];
    
    // 🐛 调试：打印最终规则
    if (allRules.length > 0) {
      console.log(`🎯 [GridFieldPreview] 字段 "${childField.label}" 最终验证规则:`, allRules);
    }
    
    // 普通表单字段用 Form.Item 包裹
    // 栅格内字段：根据对齐方式使用不同的布局
    return (
      <Form.Item
        key={childField.id}
        label={childField.label}
        name={childField.name}
        colon={true}
        labelCol={isVertical ? { span: 24 } : { span: 8 }}
        wrapperCol={isVertical ? { span: 24 } : { span: 16 }}
        rules={allRules}
      >
        <FieldRenderer
          field={childField}
          value={formData[childField.name]}
          onChange={(value) => onFieldChange?.(childField.name, value)}
          isPreview={true}
        />
      </Form.Item>
    );
  };

  return (
    <div style={{ marginBottom: 16 }}>
      <Row gutter={field.gutter || 16}>
        {children.map((columnFields, colIndex) => {
          const colSpan = getColSpan(colIndex);
          return (
            <Col key={colIndex} span={colSpan}>
              {columnFields.map((childField: FieldConfig) => renderFieldItem(childField))}
            </Col>
          );
        })}
      </Row>
    </div>
  );
};

export default GridFieldPreview;

