import { FormCollectorComponent } from './form-collector/form-collector.component';

export interface FormField {
    type: string;
    key: string;
    name: string;
    required?: boolean;
    options?: { label: string; value: any }[];
    min?: number;
    max?: number;
    pattern?: string;
    placeholder?: string;
    validator?: any;
    default?: any;
}

/**
 * 表单采集函数
 * @param params.modalCtrl Ionic ModalController 实例
 * @param params.fieldList 表单字段定义
 * @returns Promise 解析用户提交的数据，如果取消则返回 undefined
 */
export async function getUserForm(params: {
    modalCtrl: any; // Ionic ModalController 类型
    fieldList: FormField[];
}): Promise<Record<string, any> | undefined> {
    const { modalCtrl, fieldList } = params;

    if (!modalCtrl || typeof modalCtrl.create !== 'function') {
        throw new Error('modalCtrl parameter must be an instance of Ionic ModalController');
    }

    const modal = await modalCtrl.create({
        component: FormCollectorComponent,
        componentProps: {
            fieldList
        }
    });

    await modal.present();

    const { data } = await modal.onWillDismiss();
    return data;
}

/**
 * 表单采集类形式
 */
export class FormCollector {
    constructor(private modalCtrl: any) {
        if (!modalCtrl || typeof modalCtrl.create !== 'function') {
            throw new Error('modalCtrl parameter must be an instance of Ionic ModalController');
        }
    }

    async getForm(fieldList: FormField[]): Promise<Record<string, any> | undefined> {
        return getUserForm({ modalCtrl: this.modalCtrl, fieldList });
    }
}