import { Interface, LEVEL_ENUM, LogicItem } from '../..';

/**
 * 根据接口参数列表生成 CallInterParam 列表
 * @param itface 接口
 */
function getCallParamsOfInterface(itface: Interface): Array<Partial<LogicItem>> {
    const res = (itface?.logic?.params || []).map((param) => ({
        level: LEVEL_ENUM.param,
        type: 'CallInterParam',
        logicId: itface.logic.id,
        callInterParam: `#/${itface.logic.id}/${param.id}`,
        refTarget: param,
        callInterParamValue: null,
    }));

    return res;
}

export function getSelectedCallParamsOfInterface(itface: Interface, params: Array<Partial<LogicItem>> = []) {
    let res = getCallParamsOfInterface(itface).filter((item) => item.refTarget.required
        && params.every((param) => param.callInterParam !== `#/${item.refTarget.id}`));
    res = [...params, ...res];
    return res;
}

export function getRequiredCallParamsOfInterface(itface: Interface) {
    return getCallParamsOfInterface(itface).filter((item) => item.refTarget.required);
}

export function getOptionalCallParamsOfInterface(itface: Interface) {
    return getCallParamsOfInterface(itface).filter((item) => !item.refTarget.required);
}

/**
 * 生成调用接口
 * @param itface 接口实例
 * @param params 输入参数
 */
export function genCallInterface(itface: Interface, params: Array<Partial<LogicItem>> = []) {
    if (itface.entityId) {
        const identifier = itface.logicId ? itface.logicId : itface.name;
        return {
            level: 'logicNode',
            type: 'CallLogic',
            label: '调用逻辑',
            callee: identifier,
            calleeCode: `callInterface_${identifier}`,
            params,
        };
    }

    const res = {
        level: 'logicNode',
        type: 'CallInterface',
        label: '调用接口',
        interfaceKey: '',
        params,
    };
    if (itface) {
        res.interfaceKey = itface.key;
    }

    return res;
}

export default genCallInterface;

export function genCallInterfaceFromTempInterface(itface: any, params: Array<Partial<LogicItem>> = []) {
    if (itface.entityId) {
        return {
            level: 'logicNode',
            type: 'CallLogic',
            label: '调用逻辑',
            callee: itface.name,
            calleeCode: 'callInterface_',
            params,
        };
    }
    return {
        level: 'logicNode',
        type: 'CallInterface',
        label: '调用接口',
        interfaceKey: itface.name,
        params,
    };
}
