import FcDesigner from 'form-create-designer';
import {listDicData, listDicUrl} from "/@/api/jsonflow/common";
import {validateNull} from "/@/utils/validate";
import request from '/@/utils/request';

export function initFcDesignerFetch(formRef, formData, globalData) {
    // 配置表单请求拦截器
    FcDesigner.designerForm.fetch = FcDesigner.formCreate.fetch = async (options: any) => {
        // 发起请求
        let res
        if (options.method === 'GET') {
            res = await listDicUrl(options.action, options.query);
        } else {
            if (options.file) {
                res = await handleHttpUpload(options)
                options.onSuccess(res);
                return
            } else {
                res = await listDicData(options.action, options.data);
            }
        }
        if (validateNull(res.data)) return
        options.onSuccess(res.data);
    };
}


const handleHttpUpload = async (options) => {
    let formData = new FormData();
    formData.append('file', options.file);
    try {
        return await request({
            url: options.action,
            method: 'post',
            headers: {
                'Content-Type': 'multipart/form-data',
                'Enc-Flag': 'false',
            },
            data: formData,
        });
    } catch (error) {
        options.onError(error as any);
    }
};
