/**
 * 表单设计器类型定义
 * 参考钉钉表单设计器风格
 */

// 字段类型枚举
export type FieldType =
  // 基础字段
  | 'text'
  | 'textarea'
  | 'number'
  | 'rating'
  | 'radio'
  | 'checkbox'
  | 'select'
  | 'multiSelect'
  | 'member'
  | 'department'
  | 'date'
  | 'dateRange'
  | 'datetime'
  | 'time'
  | 'image'
  | 'file'
  | 'email'
  | 'phone'
  | 'url'
  | 'money'
  | 'switch'
  // 高级字段
  | 'detail'        // 子表单
  | 'serialNumber'  // 流水号
  | 'relatedForm'   // 关联表单
  | 'relatedQuery'  // 关联查询
  | 'address'       // 地址
  | 'region'        // 国家/地区
  | 'location'      // 定位
  | 'cascade'       // 级联选择
  | 'signature'     // 手写签名
  | 'seal'          // 电子签章
  | 'richtext'      // 富文本
  | 'imageText'     // 图文展示
  | 'group'         // 分组
  | 'container'     // 布局容器
  | 'wordTemplate'  // Word 模板
  | 'currency';     // 金额（带货币类型）

// 字段宽度类型（基于栅格）
export type FieldWidth = 'full' | '1/2' | '1/3' | '2/3' | '1/4' | '3/4';

// 宽度映射到百分比
export const WIDTH_PERCENT: Record<FieldWidth, string> = {
  'full': '100%',
  '1/2': '50%',
  '1/3': '33.33%',
  '2/3': '66.67%',
  '1/4': '25%',
  '3/4': '75%',
};

// 宽度选项配置
export const WIDTH_OPTIONS: Array<{ value: FieldWidth; label: string }> = [
  { value: 'full', label: '整行' },
  { value: '1/2', label: '1/2' },
  { value: '1/3', label: '1/3' },
  { value: '2/3', label: '2/3' },
  { value: '1/4', label: '1/4' },
  { value: '3/4', label: '3/4' },
];

// 字段分类
export type FieldCategory = 'basic' | 'advanced' | 'layout' | 'business';

// 字段类型配置
export interface FieldTypeConfig {
  type: FieldType;
  label: string;
  icon: string;
  category: FieldCategory;
  description?: string;
  defaultProps: Partial<DesignField>;
}

// 设计字段（画布上的字段）
export interface DesignField {
  id: string;
  type: FieldType;
  name: string;
  label: string;
  placeholder?: string;
  description?: string;
  required?: boolean;
  disabled?: boolean;
  hidden?: boolean;
  // 布局属性
  width?: FieldWidth;
  // 验证规则
  validation?: {
    minLength?: number;
    maxLength?: number;
    min?: number;
    max?: number;
    pattern?: string;
    patternMessage?: string;
  };
  // 选项（用于 select, radio, checkbox）
  options?: Array<{
    label: string;
    value: string;
    color?: string;
  }>;
  // 文件配置
  accept?: string;
  maxSize?: number;
  maxCount?: number;
  // 日期配置
  dateFormat?: string;
  showTime?: boolean;
  // 数字配置
  precision?: number;
  prefix?: string;
  suffix?: string;
  // 金额配置（用于 currency 类型）
  currencyType?: string;           // 货币类型：CNY, USD, EUR, JPY 等
  showCurrencySelect?: boolean;    // 是否显示货币选择器
  allowedCurrencies?: string[];    // 允许选择的货币类型列表
  // 子表单配置（用于 detail 类型）
  children?: DesignField[];  // 子表单内的字段
  minRows?: number;          // 最少行数
  maxRows?: number;          // 最多行数
  // 默认值
  defaultValue?: unknown;    // 字段默认值，类型根据字段类型不同
  // 其他属性
  props?: Record<string, unknown>;
}

// 设计器状态
export interface DesignerState {
  fields: DesignField[];
  selectedFieldId: string | null;
  isDragging: boolean;
  history: DesignField[][];
  historyIndex: number;
}

// 设计器 Actions
export interface DesignerActions {
  addField: (field: DesignField, index?: number) => void;
  updateField: (id: string, updates: Partial<DesignField>) => void;
  removeField: (id: string) => void;
  moveField: (fromIndex: number, toIndex: number) => void;
  duplicateField: (id: string) => void;
  selectField: (id: string | null) => void;
  setDragging: (isDragging: boolean) => void;
  setFields: (fields: DesignField[]) => void;
  undo: () => void;
  redo: () => void;
  reset: () => void;
}

// 字段类型配置列表 - 按照钉钉风格排列
export const FIELD_TYPES: FieldTypeConfig[] = [
  // ============= 基础字段（按图中顺序）=============
  // 第1行：单行文本、多行文本
  {
    type: 'text',
    label: '单行文本',
    icon: 'Type',
    category: 'basic',
    defaultProps: {
      placeholder: '请输入',
      width: 'full',
    },
  },
  {
    type: 'textarea',
    label: '多行文本',
    icon: 'AlignLeft',
    category: 'basic',
    defaultProps: {
      placeholder: '请输入',
      width: 'full',
    },
  },
  // 第2行：数值、评分
  {
    type: 'number',
    label: '数值',
    icon: 'Hash',
    category: 'basic',
    defaultProps: {
      placeholder: '请输入',
      width: '1/2',
    },
  },
  {
    type: 'rating',
    label: '评分',
    icon: 'Star',
    category: 'basic',
    defaultProps: {
      width: '1/2',
    },
  },
  // 第3行：单选、复选
  {
    type: 'radio',
    label: '单选',
    icon: 'Circle',
    category: 'basic',
    defaultProps: {
      width: 'full',
      options: [
        { label: '选项1', value: 'option1' },
        { label: '选项2', value: 'option2' },
      ],
    },
  },
  {
    type: 'checkbox',
    label: '复选',
    icon: 'CheckSquare',
    category: 'basic',
    defaultProps: {
      width: 'full',
      options: [
        { label: '选项1', value: 'option1' },
        { label: '选项2', value: 'option2' },
      ],
    },
  },
  // 第4行：下拉单选、下拉复选
  {
    type: 'select',
    label: '下拉单选',
    icon: 'ChevronDown',
    category: 'basic',
    defaultProps: {
      placeholder: '请选择',
      width: '1/2',
      options: [
        { label: '选项1', value: 'option1' },
        { label: '选项2', value: 'option2' },
        { label: '选项3', value: 'option3' },
      ],
    },
  },
  {
    type: 'multiSelect',
    label: '下拉复选',
    icon: 'ListChecks',
    category: 'basic',
    defaultProps: {
      placeholder: '请选择',
      width: '1/2',
      options: [
        { label: '选项1', value: 'option1' },
        { label: '选项2', value: 'option2' },
        { label: '选项3', value: 'option3' },
      ],
    },
  },
  // 第5行：成员、部门
  {
    type: 'member',
    label: '成员',
    icon: 'User',
    category: 'basic',
    defaultProps: {
      placeholder: '请选择',
      width: '1/2',
    },
  },
  {
    type: 'department',
    label: '部门',
    icon: 'Building',
    category: 'basic',
    defaultProps: {
      placeholder: '请选择',
      width: '1/2',
    },
  },
  // 第6行：日期、日期区间
  {
    type: 'date',
    label: '日期',
    icon: 'Calendar',
    category: 'basic',
    defaultProps: {
      placeholder: '请选择',
      width: '1/2',
    },
  },
  {
    type: 'dateRange',
    label: '日期区间',
    icon: 'CalendarRange',
    category: 'basic',
    defaultProps: {
      width: 'full',
    },
  },
  // 第7行：图片上传、附件
  {
    type: 'image',
    label: '图片上传',
    icon: 'Image',
    category: 'basic',
    defaultProps: {
      accept: 'image/*',
      maxCount: 9,
      width: 'full',
    },
  },
  {
    type: 'file',
    label: '附件',
    icon: 'Paperclip',
    category: 'basic',
    defaultProps: {
      accept: '*/*',
      maxCount: 5,
      width: 'full',
    },
  },

  // ============= 高级字段（按图中顺序）=============
  // 第1行：子表单、布局容器
  {
    type: 'detail',
    label: '子表单',
    icon: 'Table',
    category: 'advanced',
    defaultProps: {
      width: 'full',
    },
  },
  {
    type: 'container',
    label: '布局容器',
    icon: 'Layout',
    category: 'advanced',
    defaultProps: {
      width: 'full',
    },
  },
  // 分组（可折叠容器，包含一组字段）
  {
    type: 'group',
    label: '分组',
    icon: 'FolderOpen',
    category: 'advanced',
    defaultProps: {
      width: 'full',
      label: '分组标题',
      props: {
        collapsible: true,
        defaultCollapsed: false,
        fields: [],
      },
    },
  },
  // 第2行：流水号、关联表单
  {
    type: 'serialNumber',
    label: '流水号',
    icon: 'Hash',
    category: 'advanced',
    defaultProps: {
      width: '1/2',
    },
  },
  // 第2行：关联表单、关联查询
  {
    type: 'relatedForm',
    label: '关联表单',
    icon: 'FileText',
    category: 'advanced',
    defaultProps: {
      placeholder: '请选择',
      width: '1/2',
    },
  },
  {
    type: 'relatedQuery',
    label: '关联查询',
    icon: 'Search',
    category: 'advanced',
    defaultProps: {
      width: '1/2',
    },
  },
  // 第3行：地址、国家/地区
  {
    type: 'address',
    label: '地址',
    icon: 'MapPin',
    category: 'advanced',
    defaultProps: {
      placeholder: '请输入地址',
      width: 'full',
    },
  },
  {
    type: 'region',
    label: '国家/地区',
    icon: 'Globe',
    category: 'advanced',
    defaultProps: {
      placeholder: '请选择',
      width: '1/2',
    },
  },
  // 第4行：定位、级联选择
  {
    type: 'location',
    label: '定位',
    icon: 'Navigation',
    category: 'advanced',
    defaultProps: {
      width: '1/2',
    },
  },
  {
    type: 'cascade',
    label: '级联选择',
    icon: 'GitBranch',
    category: 'advanced',
    defaultProps: {
      placeholder: '请选择',
      width: '1/2',
    },
  },
  // 第5行：手写签名、电子签章
  {
    type: 'signature',
    label: '手写签名',
    icon: 'PenTool',
    category: 'advanced',
    defaultProps: {
      width: '1/2',
    },
  },
  {
    type: 'seal',
    label: '电子签章',
    icon: 'Stamp',
    category: 'advanced',
    defaultProps: {
      width: '1/2',
    },
  },
  // 第6行：富文本、图文展示
  {
    type: 'richtext',
    label: '富文本',
    icon: 'FileText',
    category: 'advanced',
    defaultProps: {
      width: 'full',
    },
  },
  {
    type: 'imageText',
    label: '图文展示',
    icon: 'Image',
    category: 'advanced',
    defaultProps: {
      width: 'full',
    },
  },
  // 第8行：Word 模板
  {
    type: 'wordTemplate',
    label: 'Word 模板',
    icon: 'FileText',
    category: 'advanced',
    defaultProps: {
      width: 'full',
    },
  },
  // 第9行：金额
  {
    type: 'currency',
    label: '金额',
    icon: 'Banknote',
    category: 'advanced',
    description: '支持填写金额和选择货币类型',
    defaultProps: {
      width: '1/2',
      precision: 2,
      currencyType: 'CNY',
      showCurrencySelect: true,
      allowedCurrencies: ['CNY', 'USD', 'EUR', 'JPY', 'GBP', 'HKD'],
    },
  },
];

// 分类配置
export const FIELD_CATEGORIES: Array<{ key: FieldCategory; label: string; icon: string }> = [
  { key: 'basic', label: '基础控件', icon: 'Layers' },
  { key: 'advanced', label: '高级控件', icon: 'Sparkles' },
  { key: 'business', label: '业务控件', icon: 'Briefcase' },
  { key: 'layout', label: '布局控件', icon: 'Layout' },
];

// 生成唯一 ID
export function generateId(): string {
  return `field_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}

// 生成随机字母标识（小写字母）
function generateRandomLetters(length: number): string {
  const chars = 'abcdefghijklmnopqrstuvwxyz';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

// 字母递增（如 'aaaaaaaa' -> 'aaaaaaab', 'aaaaaaaz' -> 'aaaaaaba'）
function incrementLetters(str: string): string {
  const chars = str.split('');
  let i = chars.length - 1;
  
  while (i >= 0) {
    if (chars[i] === 'z') {
      chars[i] = 'a';
      i--;
    } else {
      chars[i] = String.fromCharCode(chars[i].charCodeAt(0) + 1);
      break;
    }
  }
  
  // 如果全部溢出（如 'zzzzzzzz' -> 重新随机）
  if (i < 0) {
    return generateRandomLetters(str.length);
  }
  
  return chars.join('');
}

// 递归收集所有字段名（包括容器和子表单内的字段）
function collectAllFieldNames(fields: DesignField[]): string[] {
  const names: string[] = [];
  
  for (const field of fields) {
    names.push(field.name);
    
    // 检查布局容器内的字段
    if (field.type === 'container' && field.props?.columns) {
      const columns = field.props.columns as Array<{ id: string; fields: DesignField[] }>;
      for (const column of columns) {
        if (column.fields) {
          names.push(...collectAllFieldNames(column.fields));
        }
      }
    }
    
    // 检查分组内的字段
    if (field.type === 'group' && field.props?.fields) {
      const groupFields = field.props.fields as DesignField[];
      names.push(...collectAllFieldNames(groupFields));
    }
    
    // 检查子表单内的字段
    if (field.type === 'detail' && field.children) {
      names.push(...collectAllFieldNames(field.children));
    }
  }
  
  return names;
}

// 获取同类型字段的最大后缀（用于递增）
function getMaxSuffixForType(type: FieldType, fields: DesignField[]): string | null {
  const allNames = collectAllFieldNames(fields);
  const prefix = `${type}_`;
  
  // 找出所有同类型的字段后缀
  const suffixes = allNames
    .filter(name => name.startsWith(prefix))
    .map(name => name.slice(prefix.length))
    .filter(suffix => /^[a-z]{8}$/.test(suffix)); // 只匹配8位字母的后缀
  
  if (suffixes.length === 0) {
    return null;
  }
  
  // 按字母顺序排序，取最大的
  suffixes.sort();
  return suffixes[suffixes.length - 1];
}

// 生成字段名（格式：类型_8位字母标识，同类型递增）
export function generateFieldName(type: FieldType, fields: DesignField[]): string {
  const prefix = type;
  const existingNames = new Set(collectAllFieldNames(fields));
  
  // 检查是否已有同类型字段
  const maxSuffix = getMaxSuffixForType(type, fields);
  
  let suffix: string;
  if (maxSuffix) {
    // 已有同类型字段，从最大后缀递增
    suffix = incrementLetters(maxSuffix);
  } else {
    // 没有同类型字段，生成新的8位随机字母
    suffix = generateRandomLetters(8);
  }
  
  let candidateName = `${prefix}_${suffix}`;
  
  // 确保唯一（极端情况下的后备）
  let attempts = 0;
  const maxAttempts = 100;
  
  while (existingNames.has(candidateName) && attempts < maxAttempts) {
    suffix = incrementLetters(suffix);
    candidateName = `${prefix}_${suffix}`;
    attempts++;
  }
  
  return candidateName;
}

// 创建新字段
export function createField(config: FieldTypeConfig, fields: DesignField[]): DesignField {
  const name = generateFieldName(config.type, fields);
  return {
    id: generateId(),
    type: config.type,
    name,
    label: config.label,
    required: false,
    ...config.defaultProps,
  };
}

// 转换为 JSON Schema
export function toJSONSchema(fields: DesignField[]): {
  schema: Record<string, unknown>;
  uiSchema: Record<string, unknown>;
} {
  const properties: Record<string, unknown> = {};
  const required: string[] = [];
  const uiSchema: Record<string, unknown> = {};
  
  // 布局信息
  const layout: Array<{ field: string; width: string }> = [];

  fields.forEach((field) => {
    // 跳过纯布局组件（分隔线、描述）
    if (['divider', 'description'].includes(field.type)) {
      layout.push({ field: field.name, width: WIDTH_PERCENT[field.width || 'full'] });
      return;
    }

    // 处理分组 - 可折叠容器，包含一组字段
    if (field.type === 'group') {
      const groupFields = (field.props?.fields as DesignField[]) || [];
      
      // 递归转换分组内的字段
      const innerResult = toJSONSchema(groupFields);
      
      // 创建分组的 schema（作为特殊的 object 类型）
      const groupSchema: Record<string, unknown> = {
        type: 'object',
        title: field.label,
        'x-type': 'group',
        'x-collapsible': field.props?.collapsible !== false,
        'x-defaultCollapsed': field.props?.defaultCollapsed === true,
        'x-icon': field.props?.icon || undefined,  // 分组图标
        properties: innerResult.schema.properties || {},
        required: innerResult.schema.required || [],
      };
      
      properties[field.name] = groupSchema;
      
      // 合并 UI Schema（添加到分组下）
      uiSchema[field.name] = innerResult.uiSchema;
      
      // 添加分组布局信息
      layout.push({ 
        field: field.name, 
        width: WIDTH_PERCENT[field.width || 'full'],
      });
      
      return;
    }

    // 处理布局容器 - 特殊类型，用于多列布局
    if (field.type === 'container') {
      const containerLayout = (field.props?.layout as { ratios: number[]; gap?: number }) || { ratios: [1, 1] };
      const containerColumns = (field.props?.columns as Array<{ id: string; fields: DesignField[] }>) || [];
      
      // 将布局容器作为一个特殊的对象类型
      const containerSchema: Record<string, unknown> = {
        type: 'object',
        'x-type': 'container', // 标记为布局容器
        'x-layout': containerLayout,
        properties: {},
      };
      
      const containerProperties: Record<string, unknown> = {};
      const containerRequired: string[] = [];
      
      // 处理每列的字段
      containerColumns.forEach((column, colIndex) => {
        column.fields.forEach((childField) => {
          const childSchema: Record<string, unknown> = {
            title: childField.label,
            'x-column': colIndex, // 标记所属列
          };
          
          // 根据子字段类型设置 schema
          switch (childField.type) {
            case 'text':
            case 'textarea':
            case 'email':
            case 'phone':
            case 'url':
              childSchema.type = 'string';
              break;
            case 'number':
            case 'money':
              childSchema.type = 'number';
              break;
            case 'select':
            case 'radio':
              childSchema.type = 'string';
              if (childField.options) {
                childSchema.enum = childField.options.map(o => o.value);
                childSchema.enumNames = childField.options.map(o => o.label);
              }
              break;
            case 'multiSelect':
            case 'checkbox':
              childSchema.type = 'array';
              childSchema.items = { type: 'string' };
              if (childField.options) {
                (childSchema.items as Record<string, unknown>).enum = childField.options.map(o => o.value);
              }
              break;
            case 'date':
            case 'datetime':
            case 'time':
              childSchema.type = 'string';
              childSchema.format = childField.type === 'datetime' ? 'date-time' : childField.type;
              break;
            case 'switch':
              childSchema.type = 'boolean';
              break;
            default:
              childSchema.type = 'string';
          }
          
          // ✅ 保存默认值
          if (childField.defaultValue !== undefined) {
            childSchema.default = childField.defaultValue;
          }
          
          // ✅ 保存 UI 相关属性（使用 x- 扩展字段）
          if (childField.placeholder) childSchema['x-placeholder'] = childField.placeholder;
          if (childField.description) childSchema['x-description'] = childField.description;
          if (childField.disabled) childSchema['x-disabled'] = true;
          if (childField.hidden) childSchema['x-hidden'] = true;
          
          // ✅ 保存验证规则
          if (childField.validation?.minLength) childSchema.minLength = childField.validation.minLength;
          if (childField.validation?.maxLength) childSchema.maxLength = childField.validation.maxLength;
          if (childField.validation?.min) childSchema.minimum = childField.validation.min;
          if (childField.validation?.max) childSchema.maximum = childField.validation.max;
          if (childField.validation?.pattern) childSchema.pattern = childField.validation.pattern;
          
          // ✅ 保存额外配置
          if (childField.precision !== undefined) childSchema['x-precision'] = childField.precision;
          if (childField.prefix) childSchema['x-prefix'] = childField.prefix;
          if (childField.suffix) childSchema['x-suffix'] = childField.suffix;
          if (childField.maxCount) childSchema['x-maxCount'] = childField.maxCount;
          if (childField.accept) childSchema['x-accept'] = childField.accept;
          if (childField.dateFormat) childSchema['x-dateFormat'] = childField.dateFormat;
          if (childField.showTime) childSchema['x-showTime'] = childField.showTime;
          if (childField.currencyType) childSchema['x-currencyType'] = childField.currencyType;
          if (childField.showCurrencySelect !== undefined) childSchema['x-showCurrencySelect'] = childField.showCurrencySelect;
          if (childField.allowedCurrencies) childSchema['x-allowedCurrencies'] = childField.allowedCurrencies;
          
          containerProperties[childField.name] = childSchema;
          
          if (childField.required) {
            containerRequired.push(childField.name);
          }
        });
      });
      
      containerSchema.properties = containerProperties;
      if (containerRequired.length > 0) {
        containerSchema.required = containerRequired;
      }
      
      properties[field.name] = containerSchema;
      layout.push({ field: field.name, width: '100%' });
      return;
    }

    // 构建字段 schema
    const fieldSchema: Record<string, unknown> = {
      title: field.label,
    };

    // 根据类型设置
    switch (field.type) {
      case 'text':
      case 'email':
      case 'phone':
      case 'url':
        fieldSchema.type = 'string';
        if (field.type === 'email') fieldSchema.format = 'email';
        if (field.type === 'url') fieldSchema.format = 'uri';
        break;
      case 'textarea':
        fieldSchema.type = 'string';
        break;
      case 'number':
      case 'money':
        fieldSchema.type = 'number';
        if (field.validation?.min !== undefined) fieldSchema.minimum = field.validation.min;
        if (field.validation?.max !== undefined) fieldSchema.maximum = field.validation.max;
        break;
      case 'rating':
        fieldSchema.type = 'number';
        fieldSchema.minimum = 0;
        fieldSchema.maximum = (field.props?.maxStars as number) || 5;
        fieldSchema['x-maxStars'] = (field.props?.maxStars as number) || 5;
        break;
      case 'serialNumber':
        fieldSchema.type = 'string';
        fieldSchema['x-readonly'] = true;
        if (field.props?.serialPrefix) fieldSchema['x-serialPrefix'] = field.props.serialPrefix;
        if (field.props?.serialPadding) fieldSchema['x-serialPadding'] = field.props.serialPadding;
        break;
      case 'region':
        fieldSchema.type = 'string';
        break;
      case 'address':
        fieldSchema.type = 'object';
        fieldSchema.properties = {
          province: { type: 'string' },
          city: { type: 'string' },
          district: { type: 'string' },
          detail: { type: 'string' },
        };
        break;
      case 'cascade':
        fieldSchema.type = 'array';
        fieldSchema.items = { type: 'string' };
        if (field.props?.cascadeOptions) {
          fieldSchema['x-cascadeOptions'] = field.props.cascadeOptions;
        }
        break;
      case 'signature':
        fieldSchema.type = 'string';
        fieldSchema.format = 'data-url';
        break;
      case 'richtext':
        fieldSchema.type = 'string';
        fieldSchema['x-format'] = 'html';
        break;
      case 'currency':
        // 金额字段：存储为对象 { amount: number, currency: string }
        fieldSchema.type = 'object';
        fieldSchema.properties = {
          amount: { type: 'number' },
          currency: { type: 'string' },
        };
        if (field.validation?.min !== undefined) {
          (fieldSchema.properties as Record<string, unknown>).amount = {
            type: 'number',
            minimum: field.validation.min,
          };
        }
        if (field.validation?.max !== undefined) {
          const amountSchema = (fieldSchema.properties as Record<string, Record<string, unknown>>).amount;
          amountSchema.maximum = field.validation.max;
        }
        break;
      case 'date':
      case 'datetime':
        fieldSchema.type = 'string';
        fieldSchema.format = field.type === 'datetime' ? 'date-time' : 'date';
        break;
      case 'dateRange':
        fieldSchema.type = 'array';
        fieldSchema.items = { type: 'string', format: 'date' };
        break;
      case 'time':
        fieldSchema.type = 'string';
        fieldSchema.format = 'time';
        break;
      case 'select':
      case 'radio':
        fieldSchema.type = 'string';
        if (field.options) {
          fieldSchema.enum = field.options.map((o) => o.value);
          fieldSchema.enumNames = field.options.map((o) => o.label);
        }
        break;
      case 'multiSelect':
      case 'checkbox':
        fieldSchema.type = 'array';
        fieldSchema.items = { type: 'string' };
        if (field.options) {
          fieldSchema.items = {
            type: 'string',
            enum: field.options.map((o) => o.value),
            enumNames: field.options.map((o) => o.label),
          };
        }
        break;
      case 'switch':
        fieldSchema.type = 'boolean';
        break;
      case 'file':
      case 'image':
        fieldSchema.type = 'array';
        fieldSchema.items = { type: 'string', format: 'data-url' };
        break;
      case 'member':
      case 'department':
        fieldSchema.type = 'string';
        break;
      case 'location':
        fieldSchema.type = 'object';
        fieldSchema.properties = {
          address: { type: 'string' },
          lat: { type: 'number' },
          lng: { type: 'number' },
        };
        break;
      case 'detail':
        fieldSchema.type = 'array';
        // 将子表单的 children 转换为 items.properties
        if (field.children && field.children.length > 0) {
          const itemProperties: Record<string, Record<string, unknown>> = {};
          const itemRequired: string[] = [];
          // ✅ 保存列顺序
          const columnOrder: string[] = [];
          
          field.children.forEach((child) => {
            const childSchema: Record<string, unknown> = {
              title: child.label,
            };
            
            // 根据子字段类型设置 schema
            switch (child.type) {
              case 'text':
              case 'textarea':
              case 'email':
              case 'phone':
              case 'url':
                childSchema.type = 'string';
                break;
              case 'number':
              case 'money':
                childSchema.type = 'number';
                break;
              case 'select':
              case 'radio':
                childSchema.type = 'string';
                if (child.options) {
                  childSchema.enum = child.options.map(o => o.value);
                  childSchema.enumNames = child.options.map(o => o.label);
                }
                break;
              case 'multiSelect':
              case 'checkbox':
                childSchema.type = 'array';
                childSchema.items = { type: 'string' };
                if (child.options) {
                  (childSchema.items as Record<string, unknown>).enum = child.options.map(o => o.value);
                }
                break;
              case 'date':
              case 'datetime':
              case 'time':
                childSchema.type = 'string';
                childSchema.format = child.type === 'datetime' ? 'date-time' : child.type;
                break;
              case 'switch':
                childSchema.type = 'boolean';
                break;
              case 'member':
              case 'department':
                childSchema.type = 'string';
                break;
              case 'file':
              case 'image':
                childSchema.type = 'array';
                childSchema.items = { type: 'string' };
                break;
              default:
                childSchema.type = 'string';
            }
            
            // ✅ 保存默认值
            if (child.defaultValue !== undefined) {
              childSchema.default = child.defaultValue;
            }
            
            // ✅ 保存 UI 相关属性（使用 x- 扩展字段）
            if (child.placeholder) childSchema['x-placeholder'] = child.placeholder;
            if (child.description) childSchema['x-description'] = child.description;
            if (child.disabled) childSchema['x-disabled'] = true;
            if (child.hidden) childSchema['x-hidden'] = true;
            
            // ✅ 保存验证规则
            if (child.validation?.minLength) childSchema.minLength = child.validation.minLength;
            if (child.validation?.maxLength) childSchema.maxLength = child.validation.maxLength;
            if (child.validation?.min) childSchema.minimum = child.validation.min;
            if (child.validation?.max) childSchema.maximum = child.validation.max;
            if (child.validation?.pattern) childSchema.pattern = child.validation.pattern;
            
            // ✅ 保存额外配置
            if (child.precision !== undefined) childSchema['x-precision'] = child.precision;
            if (child.prefix) childSchema['x-prefix'] = child.prefix;
            if (child.suffix) childSchema['x-suffix'] = child.suffix;
            if (child.maxCount) childSchema['x-maxCount'] = child.maxCount;
            if (child.accept) childSchema['x-accept'] = child.accept;
            if (child.dateFormat) childSchema['x-dateFormat'] = child.dateFormat;
            if (child.showTime) childSchema['x-showTime'] = child.showTime;
            if (child.currencyType) childSchema['x-currencyType'] = child.currencyType;
            if (child.showCurrencySelect !== undefined) childSchema['x-showCurrencySelect'] = child.showCurrencySelect;
            if (child.allowedCurrencies) childSchema['x-allowedCurrencies'] = child.allowedCurrencies;
            
            itemProperties[child.name] = childSchema;
            columnOrder.push(child.name); // ✅ 记录顺序
            
            if (child.required) {
              itemRequired.push(child.name);
            }
          });
          
          fieldSchema.items = {
            type: 'object',
            properties: itemProperties,
            required: itemRequired.length > 0 ? itemRequired : undefined,
            'x-column-order': columnOrder, // ✅ 保存列顺序
          };
        } else {
          fieldSchema.items = { type: 'object', properties: {} };
        }
        break;
    }

    // 字符串验证
    if (field.validation?.minLength) fieldSchema.minLength = field.validation.minLength;
    if (field.validation?.maxLength) fieldSchema.maxLength = field.validation.maxLength;
    if (field.validation?.pattern) fieldSchema.pattern = field.validation.pattern;

    // 默认值
    if (field.defaultValue !== undefined) {
      fieldSchema.default = field.defaultValue;
    }

    properties[field.name] = fieldSchema;

    // 必填
    if (field.required) {
      required.push(field.name);
    }

    // 构建 UI Schema
    const fieldUI: Record<string, unknown> = {};
    if (field.placeholder) fieldUI['ui:placeholder'] = field.placeholder;
    if (field.description) fieldUI['ui:help'] = field.description;
    if (field.disabled) fieldUI['ui:disabled'] = true;
    if (field.hidden) fieldUI['ui:hidden'] = true;

    // 布局宽度
    if (field.width) {
      fieldUI['ui:width'] = WIDTH_PERCENT[field.width];
    }

    // 特殊 widget
    const widgetMap: Record<string, string> = {
      textarea: 'textarea',
      switch: 'switch',
      radio: 'radio',
      rating: 'rating',
      serialNumber: 'serialNumber',
      region: 'region',
      address: 'address',
      cascade: 'cascade',
      signature: 'signature',
      richtext: 'richtext',
      checkbox: 'checkboxes',
      date: 'date',
      datetime: 'datetime',
      time: 'time',
      dateRange: 'dateRange',
      money: 'money',
      file: 'file',
      image: 'image',
      member: 'member',
      department: 'department',
      location: 'location',
      currency: 'currency',
    };
    if (widgetMap[field.type]) {
      fieldUI['ui:widget'] = widgetMap[field.type];
    }

    // 额外配置
    if (field.precision !== undefined) fieldUI['ui:precision'] = field.precision;
    if (field.prefix) fieldUI['ui:prefix'] = field.prefix;
    if (field.suffix) fieldUI['ui:suffix'] = field.suffix;
    if (field.maxCount) fieldUI['ui:maxCount'] = field.maxCount;
    if (field.accept) fieldUI['ui:accept'] = field.accept;
    if (field.dateFormat) fieldUI['ui:dateFormat'] = field.dateFormat;
    
    // 金额字段配置
    if (field.currencyType) fieldUI['ui:currencyType'] = field.currencyType;
    if (field.showCurrencySelect !== undefined) fieldUI['ui:showCurrencySelect'] = field.showCurrencySelect;
    if (field.allowedCurrencies) fieldUI['ui:allowedCurrencies'] = field.allowedCurrencies;

    if (Object.keys(fieldUI).length > 0) {
      uiSchema[field.name] = fieldUI;
    }

    // 添加到布局
    layout.push({ field: field.name, width: WIDTH_PERCENT[field.width || 'full'] });
  });

  // 字段顺序
  uiSchema['ui:order'] = fields.map((f) => f.name);
  // 布局信息
  uiSchema['ui:layout'] = layout;

  return {
    schema: {
      type: 'object',
      properties,
      required,
    },
    uiSchema,
  };
}

// 从列数反推宽度
function percentToWidth(percent: string): FieldWidth {
  for (const [width, p] of Object.entries(WIDTH_PERCENT)) {
    if (p === percent) return width as FieldWidth;
  }
  return 'full';
}

// 从 JSON Schema 解析
export function fromJSONSchema(
  schema: Record<string, unknown>,
  uiSchema: Record<string, unknown> = {},
  fallbackLabels: {
    group?: string;
    container?: string;
    detail?: string;
  } = {}
): DesignField[] {
  const fields: DesignField[] = [];
  const properties = (schema.properties || {}) as Record<string, Record<string, unknown>>;
  const required = (schema.required || []) as string[];
  const order = (uiSchema['ui:order'] || Object.keys(properties)) as string[];

  order.forEach((fieldName) => {
    const fieldSchema = properties[fieldName];
    if (!fieldSchema) return;

    const fieldUI = (uiSchema[fieldName] || {}) as Record<string, unknown>;

    // 处理分组
    if (fieldSchema.type === 'object' && fieldSchema['x-type'] === 'group') {
      const groupFields = fromJSONSchema(
        { properties: fieldSchema.properties, required: fieldSchema.required } as Record<string, unknown>,
        fieldUI as Record<string, unknown>,
        fallbackLabels
      );
      
      const groupField: DesignField = {
        id: generateId(),
        type: 'group',
        name: fieldName,
        label: (fieldSchema.title as string) || fallbackLabels.group || '分组',
        width: 'full',
        props: {
          collapsible: fieldSchema['x-collapsible'] !== false,
          defaultCollapsed: fieldSchema['x-defaultCollapsed'] === true,
          icon: fieldSchema['x-icon'] as string | undefined,
          fields: groupFields,
        },
      };
      
      fields.push(groupField);
      return;
    }

    // 处理布局容器
    if (fieldSchema.type === 'object' && fieldSchema['x-type'] === 'container') {
      const containerLayout = fieldSchema['x-layout'] as { ratios: number[]; gap?: number } | undefined;
      const containerProps = fieldSchema.properties as Record<string, Record<string, unknown>> || {};
      
      // 按列分组字段
      const ratios = containerLayout?.ratios || [1, 1];
      const columns: Array<{ id: string; fields: DesignField[] }> = ratios.map((_, i) => ({
        id: `col-${generateId()}`,
        fields: [],
      }));
      
      Object.entries(containerProps).forEach(([childName, childSchema]) => {
        const colIndex = (childSchema['x-column'] as number) || 0;
        if (colIndex < columns.length) {
          // 递归解析子字段
          const childField = parseFieldFromSchema(childName, childSchema, {}, []);
          if (childField) {
            columns[colIndex].fields.push(childField);
          }
        }
      });
      
      const containerField: DesignField = {
        id: generateId(),
        type: 'container',
        name: fieldName,
        label: fallbackLabels.container || '布局容器',
        width: 'full',
        props: {
          layout: containerLayout || { ratios: [1, 1], gap: 16 },
          columns,
        },
      };
      
      fields.push(containerField);
      return;
    }

    // 处理子表单
    if (fieldSchema.type === 'array' && fieldSchema.items) {
      const itemSchema = fieldSchema.items as Record<string, unknown>;
      if (itemSchema.type === 'object' && itemSchema.properties) {
        // ✅ 使用 x-column-order 保持列顺序
        const columnOrder = (itemSchema['x-column-order'] || []) as string[];
        const detailUiSchema: Record<string, unknown> = {};
        if (columnOrder.length > 0) {
          detailUiSchema['ui:order'] = columnOrder;
        }
        
        const detailFields = fromJSONSchema(
          { properties: itemSchema.properties, required: itemSchema.required } as Record<string, unknown>,
          detailUiSchema,
          fallbackLabels
        );
        
        const detailField: DesignField = {
          id: generateId(),
          type: 'detail',
          name: fieldName,
          label: (fieldSchema.title as string) || fallbackLabels.detail || '子表单',
          width: 'full',
          children: detailFields,
        };
        
        fields.push(detailField);
        return;
      }
    }

    // 普通字段
    const field = parseFieldFromSchema(fieldName, fieldSchema, fieldUI, required);
    if (field) {
      fields.push(field);
    }
  });

  return fields;
}

// 从 schema 解析单个字段
function parseFieldFromSchema(
  fieldName: string,
  fieldSchema: Record<string, unknown>,
  fieldUI: Record<string, unknown>,
  required: string[]
): DesignField | null {
  // 确定字段类型
  let type: FieldType = 'text';
  const schemaType = fieldSchema.type as string;
  const format = fieldSchema.format as string | undefined;
  const widget = fieldUI['ui:widget'] as string | undefined;

  if (schemaType === 'boolean') {
    type = widget === 'switch' ? 'switch' : 'checkbox';
  } else if (schemaType === 'number' || schemaType === 'integer') {
    if (widget === 'rating') type = 'rating';
    else if (widget === 'money') type = 'money';
    else type = 'number';
  } else if (schemaType === 'array') {
    if (widget === 'checkboxes') type = 'checkbox';
    else if (widget === 'file') type = 'file';
    else if (widget === 'image') type = 'image';
    else if (widget === 'dateRange') type = 'dateRange';
    else if (widget === 'cascade') type = 'cascade';
    else type = 'multiSelect';
  } else if (schemaType === 'object') {
    if (widget === 'location') type = 'location';
    else if (widget === 'currency') type = 'currency';
    else if (widget === 'address') type = 'address';
  } else if (schemaType === 'string') {
    if (widget === 'serialNumber') type = 'serialNumber';
    else if (widget === 'region') type = 'region';
    else if (widget === 'signature') type = 'signature';
    else if (widget === 'richtext') type = 'richtext';
    else if (format === 'email') type = 'email';
    else if (format === 'uri') type = 'url';
    else if (format === 'date') type = 'date';
    else if (format === 'date-time') type = 'datetime';
    else if (format === 'time') type = 'time';
    else if (widget === 'textarea') type = 'textarea';
    else if (widget === 'radio') type = 'radio';
    else if (widget === 'member') type = 'member';
    else if (widget === 'department') type = 'department';
    else if (fieldSchema.enum) type = 'select';
  }

  const field: DesignField = {
    id: generateId(),
    type,
    name: fieldName,
    label: (fieldSchema.title as string) || fieldName,
    // ✅ 优先从 uiSchema 读取，其次从 x- 扩展字段读取（用于子表单列）
    placeholder: (fieldUI['ui:placeholder'] || fieldSchema['x-placeholder']) as string | undefined,
    description: (fieldUI['ui:help'] || fieldSchema['x-description']) as string | undefined,
    required: required.includes(fieldName),
    disabled: (fieldUI['ui:disabled'] || fieldSchema['x-disabled']) as boolean | undefined,
    hidden: (fieldUI['ui:hidden'] || fieldSchema['x-hidden']) as boolean | undefined,
  };

  // 布局宽度
  if (fieldUI['ui:width']) {
    field.width = percentToWidth(fieldUI['ui:width'] as string);
  }

  // 选项
  if (fieldSchema.enum) {
    const enumValues = fieldSchema.enum as string[];
    const enumNames = (fieldSchema.enumNames || enumValues) as string[];
    field.options = enumValues.map((value, i) => ({
      value,
      label: enumNames[i] || value,
    }));
  }

  // 验证规则
  if (fieldSchema.minLength || fieldSchema.maxLength || fieldSchema.minimum || fieldSchema.maximum || fieldSchema.pattern) {
    field.validation = {};
    if (fieldSchema.minLength) field.validation.minLength = fieldSchema.minLength as number;
    if (fieldSchema.maxLength) field.validation.maxLength = fieldSchema.maxLength as number;
    if (fieldSchema.minimum) field.validation.min = fieldSchema.minimum as number;
    if (fieldSchema.maximum) field.validation.max = fieldSchema.maximum as number;
    if (fieldSchema.pattern) field.validation.pattern = fieldSchema.pattern as string;
  }

  // 额外配置（优先从 uiSchema 读取，其次从 x- 扩展字段读取）
  if (fieldUI['ui:precision'] || fieldSchema['x-precision']) 
    field.precision = (fieldUI['ui:precision'] || fieldSchema['x-precision']) as number;
  if (fieldUI['ui:prefix'] || fieldSchema['x-prefix']) 
    field.prefix = (fieldUI['ui:prefix'] || fieldSchema['x-prefix']) as string;
  if (fieldUI['ui:suffix'] || fieldSchema['x-suffix']) 
    field.suffix = (fieldUI['ui:suffix'] || fieldSchema['x-suffix']) as string;
  if (fieldUI['ui:maxCount'] || fieldSchema['x-maxCount']) 
    field.maxCount = (fieldUI['ui:maxCount'] || fieldSchema['x-maxCount']) as number;
  if (fieldUI['ui:accept'] || fieldSchema['x-accept']) 
    field.accept = (fieldUI['ui:accept'] || fieldSchema['x-accept']) as string;
  if (fieldUI['ui:dateFormat'] || fieldSchema['x-dateFormat']) 
    field.dateFormat = (fieldUI['ui:dateFormat'] || fieldSchema['x-dateFormat']) as string;
  if (fieldUI['ui:showTime'] || fieldSchema['x-showTime']) 
    field.showTime = (fieldUI['ui:showTime'] || fieldSchema['x-showTime']) as boolean;
  
  // 金额字段配置（优先从 uiSchema 读取，其次从 x- 扩展字段读取）
  if (fieldUI['ui:currencyType'] || fieldSchema['x-currencyType']) 
    field.currencyType = (fieldUI['ui:currencyType'] || fieldSchema['x-currencyType']) as string;
  if (fieldUI['ui:showCurrencySelect'] !== undefined || fieldSchema['x-showCurrencySelect'] !== undefined) 
    field.showCurrencySelect = (fieldUI['ui:showCurrencySelect'] || fieldSchema['x-showCurrencySelect']) as boolean;
  if (fieldUI['ui:allowedCurrencies'] || fieldSchema['x-allowedCurrencies']) 
    field.allowedCurrencies = (fieldUI['ui:allowedCurrencies'] || fieldSchema['x-allowedCurrencies']) as string[];

  // 默认值
  if (fieldSchema.default !== undefined) {
    field.defaultValue = fieldSchema.default;
  }

  if (type === 'rating' && fieldSchema['x-maxStars']) {
    field.props = { ...(field.props || {}), maxStars: fieldSchema['x-maxStars'] as number };
  }

  if (type === 'serialNumber') {
    const sp: Record<string, unknown> = { ...(field.props || {}) };
    if (fieldSchema['x-serialPrefix']) sp.serialPrefix = fieldSchema['x-serialPrefix'];
    if (fieldSchema['x-serialPadding']) sp.serialPadding = fieldSchema['x-serialPadding'];
    field.props = sp;
  }

  if (type === 'cascade' && fieldSchema['x-cascadeOptions']) {
    field.props = { ...(field.props || {}), cascadeOptions: fieldSchema['x-cascadeOptions'] };
  }

  return field;
}
