import { FlowTask, FlowTaskOptions, FieldSchema } from '../../flow.task'; // 假设FlowTask在同一目录下
import { getUserForm, FormField } from './get-user-form';

interface TaskUserFormOptions extends FlowTaskOptions {
    modalCtrl: any; // ModalController 类型
    fieldList: FormField[]; // 表单字段列表
}

export class TaskUserForm extends FlowTask {
    private modalCtrl: any;
    private fieldList: FormField[];

    constructor(options: TaskUserFormOptions) {
        super(options);
        this.modalCtrl = options.modalCtrl;
        this.fieldList = options.fieldList;
        // this.inputSchema = this.createInputSchema(); // 创建输入校验规则 此刻用户没有任何输入
        // this.outputSchema = this.createOutputSchema(); // 创建输出校验规则
    }

    override async handle(): Promise<void> {
        console.log("handle", this.modalCtrl, this.fieldList)
        const result = await getUserForm({
            modalCtrl: this.modalCtrl,
            fieldList: this.fieldList,
        });

        if (result) {
            console.log(result)
            // 将表单结果保存到任务数据中
            this.data = { ...this.data, ...result };
        } else {
            throw new Error('用户取消了表单');
        }
    }

    private createInputSchema(): FieldSchema[] {
        return this.fieldList.map(field => ({
            name: field.key,
            type: this.mapFieldType(field.type),
            required: field.required,
            description: field.name,
        }));
    }

    private createOutputSchema(): FieldSchema[] {
        return this.fieldList.map(field => ({
            name: field.key,
            type: this.mapFieldType(field.type),
            required: field.required,
            description: field.name,
        }));
    }

    private mapFieldType(type: string): any {
        switch (type.toLowerCase()) {
            case 'string':
                return 'string';
            case 'number':
                return 'number';
            case 'boolean':
                return 'boolean';
            case 'date':
                return 'object'; // 日期类型通常处理为对象
            case 'radio':
            case 'select':
            case 'checkbox':
                return 'array'; // 多选和单选可以处理为数组
            case 'textarea':
                return 'string'; // 多行文本处理为字符串
            default:
                throw new Error(`不支持的字段类型: ${type}`);
        }
    }
}