/**
 * 表单预览组件
 * 预览设计好的表单效果
 */

import React, { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import { Form, message } from 'antd';
import type { Rule } from 'antd/es/form';
import dayjs from 'dayjs';
import type { FieldConfig, FormConfig, ValidationRule, LinkageRule } from '../types';
import FieldRenderer from './FieldRenderer';
import GridFieldPreview from './GridFieldPreview';
import '../styles.css';

interface FormPreviewProps {
  fields: FieldConfig[];
  formConfig: FormConfig;
}

export interface FormPreviewRef {
  submit: () => Promise<void>;
  reset: () => void;
}

const FormPreview = forwardRef<FormPreviewRef, FormPreviewProps>(({ fields, formConfig }, ref) => {
  const [form] = Form.useForm();
  const [formData, setFormData] = useState<Record<string, any>>({});
  const [fieldStates, setFieldStates] = useState<Record<string, {
    visible?: boolean;
    disabled?: boolean;
    required?: boolean;
  }>>({});

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      console.log('表单提交数据:', values);
      setFormData(values);
      message.success('表单提交成功！请查看控制台');
    } catch (error) {
      message.error('请填写必填项');
    }
  };

  const handleReset = () => {
    form.resetFields();
    setFormData({});
    message.info('表单已重置');
  };

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    submit: handleSubmit,
    reset: handleReset,
  }));

  // 将验证规则转换为Ant Design的Rule数组
  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}`,
        // 注意：不设置 trigger，或者不仅仅设置为 blur，这样提交时也会触发验证
        // 如果用户指定了 trigger，我们也在提交时触发
      };

      switch (rule.type) {
        case 'required':
          antdRule.required = true;
          // 必填验证始终在提交时触发，不管用户选择了什么 trigger
          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 evaluateCondition = (condition: any, 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;
    }
  };

  // 处理联动规则
  useEffect(() => {
    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;
    };

    const allFields = flattenFields(fields);
    const newFieldStates: Record<string, any> = {};

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

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

            switch (rule.type) {
              case 'visible':
                newFieldStates[field.name].visible = rule.action;
                break;
              case 'disabled':
                newFieldStates[field.name].disabled = rule.action;
                break;
              case 'required':
                newFieldStates[field.name].required = rule.action;
                break;
              case 'value':
                // 值联动需要直接设置表单值
                form.setFieldValue(field.name, rule.action);
                break;
            }
          }
        });
      }
    });

    setFieldStates(newFieldStates);
  }, [formData, fields, form]);

  // 设置默认值
  useEffect(() => {
    const defaultValues: Record<string, any> = {};
    
    const collectDefaultValues = (fieldList: FieldConfig[]) => {
      fieldList.forEach(field => {
        if (field.defaultValue !== undefined && field.name) {
          // 🔧 日期字段需要转换为 dayjs 对象
          if (field.type === 'date' && typeof field.defaultValue === 'string') {
            defaultValues[field.name] = dayjs(field.defaultValue);
          } else {
            defaultValues[field.name] = field.defaultValue;
          }
        }
        if (field.type === 'grid' && field.children) {
          field.children.forEach(columnFields => {
            collectDefaultValues(columnFields);
          });
        }
      });
    };

    collectDefaultValues(fields);
    form.setFieldsValue(defaultValues);
    setFormData(prev => ({ ...prev, ...defaultValues }));
  }, [fields, form]);

  // 递归渲染字段（包括栅格布局内的字段）
  const renderFields = (fieldList: FieldConfig[]): React.ReactNode => {
    return fieldList.map((field) => {
      // 布局组件：文本、分割线
      if (field.type === 'text' || field.type === 'divider') {
        return (
          <div key={field.id}>
            <FieldRenderer field={field} isPreview={true} />
          </div>
        );
      }

      // 栅格布局：使用专门的预览组件，自动处理内部字段的 Form.Item
      if (field.type === 'grid') {
        return (
          <GridFieldPreview
            key={field.id}
            field={field}
            formData={formData}
            onFieldChange={(name, value) => setFormData(prev => ({ ...prev, [name]: value }))}
            formConfig={formConfig}
          />
        );
      }

      // 获取字段状态（联动规则影响）
      const fieldState = fieldStates[field.name] || {};
      const isVisible = fieldState.visible !== false;  // 默认显示
      const isDisabled = fieldState.disabled || field.disabled || false;
      const isRequired = fieldState.required !== undefined ? fieldState.required : field.required;

      // 如果字段被隐藏，不渲染
      if (!isVisible) {
        return null;
      }

      // 合并基础验证规则和自定义验证规则
      const customRules = convertValidationRules(field.validationRules);
      
      // 🐛 调试：打印验证规则
      if (field.validationRules && field.validationRules.length > 0) {
        console.log(`📋 字段 "${field.label}" 的验证规则:`, field.validationRules);
        console.log(`✅ 转换后的规则:`, customRules);
      }
      
      // 检查自定义验证规则中是否已经包含必填验证
      const hasRequiredRule = field.validationRules?.some(rule => rule.type === 'required');
      
      // 基础规则：只有在没有自定义必填验证时，才使用字段属性中的"是否必填"
      const baseRules: Rule[] = [];
      if (isRequired && !hasRequiredRule) {
        baseRules.push({
          required: true,
          message: `请输入${field.label}`,
        });
      }
      
      const allRules = [...baseRules, ...customRules];
      
      // 🐛 调试：打印最终规则
      if (allRules.length > 0) {
        console.log(`🎯 字段 "${field.label}" 最终验证规则:`, allRules);
      }

      // 普通表单组件使用 Form.Item 包裹
      return (
        <Form.Item
          key={field.id}
          label={field.label}
          name={field.name}
          colon={true}
          rules={allRules}
        >
          <FieldRenderer
            field={{ ...field, disabled: isDisabled }}
            value={formData[field.name]}
            onChange={(value) => setFormData(prev => ({ ...prev, [field.name]: value }))}
            isPreview={true}
          />
        </Form.Item>
      );
    });
  };

  if (fields.length === 0) {
    return (
      <div style={{ padding: 40, textAlign: 'center', color: '#8c8c8c' }}>
        表单为空
      </div>
    );
  }

  const formLayout = formConfig.labelAlign === 'top' ? 'vertical' : 'horizontal';
  const labelColSpan = formConfig.labelAlign === 'left' ? 6 : formConfig.labelAlign === 'right' ? 6 : undefined;
  const wrapperColSpan = formConfig.labelAlign === 'left' || formConfig.labelAlign === 'right' ? 18 : undefined;

  return (
    <div style={{ padding: '24px 40px' }}>
      <Form
        form={form}
        layout={formLayout}
        size={formConfig.size}
        colon={true}
        labelAlign={formConfig.labelAlign === 'top' ? undefined : formConfig.labelAlign}
        labelCol={labelColSpan ? { span: labelColSpan } : undefined}
        wrapperCol={wrapperColSpan ? { span: wrapperColSpan } : undefined}
      >
        {formConfig.title && (
          <h3 style={{ marginBottom: 24 }}>{formConfig.title}</h3>
        )}

        {renderFields(fields)}
      </Form>

      {Object.keys(formData).length > 0 && (
        <div style={{ marginTop: 24, padding: 16, background: '#f5f5f5', borderRadius: 4 }}>
          <h4>表单数据：</h4>
          <pre>{JSON.stringify(formData, null, 2)}</pre>
        </div>
      )}
    </div>
  );
});

FormPreview.displayName = 'FormPreview';

export default FormPreview;

