import React, { Component, useState, useEffect, useRef } from 'react'; import { Form, Input, Select, Button, Message, Radio, Dialog, Overlay, Search } from '@alifd/next'; import { IPublicModelSettingField } from '@alilc/lowcode-types'; import fetchRequest from '@/utils/request'; import { useGetFields } from '@/hooks/use-get-fields'; import { IGetField } from '@/types'; import Editor from './components/editor'; import { EditorRefType, FormFieldType } from '@/constants'; import classNames from 'classnames'; import './index.less'; const { Popup } = Overlay; interface FetchSetterProps extends IGetField { value: any; onChange: (val: any) => void; } interface HeaderItem { key: string; value: string; paramType: string; // 新增参数类型字段 } interface ProcessFunction { name: string; code: string; } const FetchSetterFC: React.FC = (props) => { const { value = {}, onChange } = props; const [visible, setVisible] = useState(false); const [popVisible, setPopVisible] = useState(false); const [searchValue, setSearchValue] = useState(''); const editorRef = useRef(null); // 从value中获取初始值,如果没有则使用默认值 const [fetchConfig, setFetchConfig] = useState({ type: 'fetch', dataSourceId: value.dataSourceId || '', url: value.url || '', method: value.method || 'GET', timeout: value.timeout || 5000, headers: value.headers || [], params: value.params || [], paramType: value.paramType || 'custom', // 参数类型 queryFilterFields: value.queryFilterFields || [], // 查询头字段 processFunctions: value.processFunctions || [], // 数据处理函数 }); const { fieldList, getFieldList } = useGetFields(props); // Content-Type 选项 const contentTypeOptions = [ { label: 'application/json', value: 'application/json' }, { label: 'application/x-www-form-urlencoded', value: 'application/x-www-form-urlencoded' }, { label: 'multipart/form-data', value: 'multipart/form-data' }, { label: 'text/plain', value: 'text/plain' }, { label: 'text/html', value: 'text/html' }, ]; // 组件初始化时,如果没有请求头,添加默认的 Content-Type useEffect(() => { if (fetchConfig.headers.length === 0) { updateConfig('headers', [{ key: 'Content-Type', value: 'application/json' }]); } }, []); const formatFieldListOptions = (options: any[]) => { return options.map((item: any) => ({ label: `${item.name}(${item.fieldId})`, value: `${item.parentId}(${item.fieldId})`, })); }; // 添加请求头 const addHeader = (preset?: { key: string; value: string }) => { const newHeaders = [...fetchConfig.headers]; if (preset) { newHeaders.push(preset); } else { newHeaders.push({ key: '', value: '' }); } updateConfig('headers', newHeaders); }; // 删除请求头 const removeHeader = (index: number) => { const newHeaders = [...fetchConfig.headers]; newHeaders.splice(index, 1); updateConfig('headers', newHeaders); }; // 更新请求头 const updateHeader = (index: number, field: 'key' | 'value', value: string) => { const newHeaders = [...fetchConfig.headers]; newHeaders[index][field] = value; updateConfig('headers', newHeaders); }; // 添加请求参数 const addParam = () => { const newParams = [...fetchConfig.params]; newParams.push({ key: '', value: '', paramType: 'custom' }); updateConfig('params', newParams); }; // 删除请求参数 const removeParam = (index: number) => { const newParams = [...fetchConfig.params]; newParams.splice(index, 1); updateConfig('params', newParams); }; // 更新请求参数 const updateParam = (index: number, field: 'key' | 'value' | 'paramType', value: string) => { const newParams = [...fetchConfig.params]; newParams[index][field] = value; updateConfig('params', newParams); }; // 更新配置并触发onChange const updateConfig = (key: string, value: any) => { const newConfig = { ...fetchConfig, [key]: value }; setFetchConfig(newConfig); onChange(newConfig); }; // 数据处理函数 const processFunctionOptions = [ { label: '是否发起请求的计算函数', value: 'shouldFetch' }, { label: '请求前对参数的处理函数', value: 'beforeFetch' }, { label: '请求成功后的结果处理函数', value: 'onSuccess' }, { label: '请求失败后的处理函数', value: 'onError' }, ]; // 添加数据处理函数 const addProcessFunction = (type: string) => { const existingIndex = fetchConfig.processFunctions.findIndex( (fn: ProcessFunction) => fn.name === type, ); if (existingIndex !== -1) { return; } let defaultCode = ''; switch (type) { case 'shouldFetch': defaultCode = 'function() { return true; }'; break; case 'beforeFetch': defaultCode = 'function(params) { return params; }'; break; case 'onSuccess': defaultCode = 'function(response) { return response; }'; break; case 'onError': defaultCode = 'function(error) { console.error(error); }'; break; default: defaultCode = 'function() {}'; } const newProcessFunctions = [ ...fetchConfig.processFunctions, { name: type, code: defaultCode }, ]; updateConfig('processFunctions', newProcessFunctions); }; // 删除数据处理函数 const removeProcessFunction = (index: number) => { const newProcessFunctions = [...fetchConfig.processFunctions]; newProcessFunctions.splice(index, 1); updateConfig('processFunctions', newProcessFunctions); }; // 更新数据处理函数代码 const updateProcessFunctionCode = (index: number, code: string) => { const newProcessFunctions = [...fetchConfig.processFunctions]; newProcessFunctions[index].code = code; updateConfig('processFunctions', newProcessFunctions); }; // 测试连接 const testConnection = async () => { const url = editorRef?.current?.getValue(); if (!url) { Message.error('请输入请求地址'); return; } try { const shouldFetchFn = fetchConfig.processFunctions.find( (fn: ProcessFunction) => fn.name === 'shouldFetch', ); // 执行是否发起请求的计算函数 if (shouldFetchFn) { try { // eslint-disable-next-line no-new-func const execShouldFetch = new Function(`return ${shouldFetchFn.code}`)(); const shouldProceed = execShouldFetch(); if (!shouldProceed) { console.log('根据计算函数结果,不发起请求'); return; } } catch (error) { console.error( `计算函数执行出错: ${error instanceof Error ? error.message : String(error)}`, ); return; } } // 根据不同的参数类型构建请求参数 let requestParams: Record = {}; if (fetchConfig.paramType === 'custom') { // 自定义参数 fetchConfig.params.forEach((param: HeaderItem) => { if (param.key && param.value) { requestParams[param.key] = param.value; } }); } else if (fetchConfig.paramType === 'queryFilter') { // 查询头字段 fetchConfig.queryFilterFields.forEach((field: string) => { requestParams[field] = `模拟${field}值`; }); } // 查找请求前参数处理函数 const beforeFetchFn = fetchConfig.processFunctions.find( (fn: ProcessFunction) => fn.name === 'beforeFetch', ); if (beforeFetchFn) { try { // eslint-disable-next-line no-new-func const execBeforeFetch = new Function(`return ${beforeFetchFn.code}`)(); const processedParams = execBeforeFetch(requestParams); if (processedParams) { requestParams = processedParams; } } catch (error) { console.error( `参数处理函数执行出错: ${error instanceof Error ? error.message : String(error)}`, ); return; } } // 构建请求头 const headers: Record = {}; fetchConfig.headers.forEach((header: HeaderItem) => { if (header.key && header.value) { headers[header.key] = header.value; } }); // 使用 fetchRequest 发送请求 const res = await fetchRequest(url, { method: fetchConfig.method, headers, // 只在 POST 请求时添加请求体 ...(fetchConfig.method === 'POST' ? { body: JSON.stringify(requestParams) } : {}), timeout: fetchConfig.timeout, }); if (res.success) { // 请求成功后的处理函数 const onSuccessFn = fetchConfig.processFunctions.find( (fn: ProcessFunction) => fn.name === 'onSuccess', ); let processedData = res.data; if (onSuccessFn) { try { // eslint-disable-next-line no-new-func const execOnSuccess = new Function(`return ${onSuccessFn.code}`)(); const result = execOnSuccess(processedData); if (result !== undefined) { processedData = result; } } catch (error) { Message.error( `成功处理函数执行出错: ${error instanceof Error ? error.message : String(error)}`, ); return; } } Message.success('连接成功'); Dialog.show({ title: '请求结果', content: (
{JSON.stringify(processedData, null, 2)}
), }); } else { // 查找请求失败后的处理函数 const onErrorFn = fetchConfig.processFunctions.find( (fn: ProcessFunction) => fn.name === 'onError', ); // 请求失败后的处理函数 if (onErrorFn) { try { // eslint-disable-next-line no-new-func const execOnError = new Function(`return ${onErrorFn.code}`)(); execOnError(res); } catch (error) { console.error( `失败处理函数执行出错: ${error instanceof Error ? error.message : String(error)}`, ); return; } } Message.error(res.msg || '请求失败'); } } catch (error) { // 请求失败后的处理函数 const onErrorFn = fetchConfig.processFunctions.find( (fn: ProcessFunction) => fn.name === 'onError', ); if (onErrorFn) { try { // eslint-disable-next-line no-new-func const execOnError = new Function(`return ${onErrorFn.code}`)(); execOnError(error); } catch (fnError) { Message.error( `失败处理函数执行出错: ${fnError instanceof Error ? fnError.message : String(fnError)}`, ); return; } } Message.error(`请求出错: ${error instanceof Error ? error.message : String(error)}`); } }; // 打开配置对话框 const openConfigDialog = () => { getFieldList(); setVisible(true); }; // 关闭配置对话框 const closeConfigDialog = () => { setVisible(false); }; // 确认配置 const confirmConfig = () => { // 获取编辑器中的URL值 const editorValue = editorRef?.current?.getValue(); // 创建新的配置对象 const newConfig = { ...fetchConfig, url: editorValue || fetchConfig.url, }; // 更新状态并触发onChange setFetchConfig(newConfig); onChange(newConfig); // 关闭对话框 setVisible(false); }; // url 添加字段 const handleUrlItemClick = (item: any) => { editorRef?.current?.insertText( `${JSON.stringify({ fieldId: item.fieldId, parentId: item.parentId, name: item.name, })}`, ); setPopVisible(false); }; const filterFieldList = (list: any[]): any[] => { if (!searchValue) return list; return list.filter((item) => { const name = item.name?.toLowerCase() || ''; const fieldId = item.fieldId?.toLowerCase() || ''; const keywords = searchValue.toLowerCase() || ''; return name.includes(keywords) || fieldId.includes(keywords); }); }; // 渲染表单内容 const renderFormContent = () => { return (
updateConfig('dataSourceId', value)} placeholder="请输入数据源 ID" /> updateConfig('method', value)} > GET POST { setSearchValue(''); setPopVisible(true); }} > } align="tc tc" triggerType="click" visible={popVisible} target={document.getElementById('editor-container')} onVisibleChange={(visible) => setPopVisible(false)} >
setSearchValue(keywords)} className="fetch-search" />
{filterFieldList(fieldList).map((item) => { return (
handleUrlItemClick(item)} > {item.name}({item.fieldId}) {FormFieldType[item.type]?.text}
); })}
{/* updateConfig('url', value)} placeholder="请输入请求地址" /> */}
{fetchConfig.method === 'POST' && (
{fetchConfig.params.map((param: HeaderItem, index: number) => (
updateParam(index, 'key', value as string)} placeholder="name" style={{ width: '20%', marginRight: '8px' }} /> : {param.paramType === 'custom' && ( updateParam(index, 'value', value as string)} placeholder="value" style={{ width: '30%', marginRight: '8px' }} /> )} {param.paramType === 'queryFilter' && ( updateParam(index, 'paramType', value as string)} dataSource={[ { label: '自定义参数', value: 'custom' }, { label: '查询头字段', value: 'queryFilter' }, ]} style={{ width: '30%', marginRight: '8px' }} />
))}
)} {/* updateConfig('timeout', value)} min={1000} step={1000} /> */}
{/* 第一行固定为 Content-Type */}
: updateHeader(actualIndex, 'key', value as string)} placeholder="key" style={{ width: '40%', marginRight: '8px' }} /> : updateHeader(actualIndex, 'value', value as string)} placeholder="value" style={{ width: '40%', marginRight: '8px' }} />
); }, )}