jingrow.ui.form.on("Ai Agent", {
    refresh: function(frm) {
        // 如果当前是新建记录，则隐藏进度字段
        if (frm.is_new()) {
            frm.set_df_property('progress', 'hidden', 1);
        } else {
            // 否则显示进度字段，并更新进度条
            frm.set_df_property('progress', 'hidden', 0);
            updateCustomProgressBar(frm);
        }
        // 增加可视化节点编辑按钮（直接显示为主按钮，不放在下拉菜单）
        frm.add_custom_button(__('智能体编排'), function() {
            open_agent_flow_editor(frm);
        });
    }
});

function updateCustomProgressBar(frm) {
    let progress = frm.pg.progress || 0;
    let progressBarContainer = frm.fields_dict["progress"].$wrapper;
    
    // 动态调整父容器的样式，确保宽度为100%
    progressBarContainer.css({
        'max-width': '100%',
        'padding-right': '0'
    });
    
    // 清空容器内容
    progressBarContainer.empty();
    
    // 添加进度条
    let progressBar = $(`
        <div style="background-color: #f3f3f3; border-radius: 50px; overflow: hidden; width: 100%; margin-bottom:15px;">
            <div style="width: ${progress}%; background-color: #4caf50; border-radius: 50px; height: 10px;"></div>
        </div>
    `);
    
    progressBarContainer.append(progressBar);
}

function open_agent_flow_editor(frm) {
    loadAIAgentFlowBuilder().then(() => {
        let dialog = new jingrow.ui.Dialog({
            title: __('Ai Agent Builder'),
            size: 'extra-large',
            primary_action_label: __('Save'),
            primary_action: function() {
                save_agent_flow(frm, dialog);
            },
            secondary_action_label: __('Cancel'),
            secondary_action: function() {
                dialog.hide();
            }
        });
        dialog.$body.html('<div id="ai-agent-flow-builder-container" style="height: 600px;"></div>');
        dialog.show();
        setTimeout(() => {
            const container = dialog.$body.find('#ai-agent-flow-builder-container')[0];
            if (!container) return;
            
            // 直接使用当前表单的 agent_flow 数据
            let currentFlowData = frm.pg.agent_flow || {};
            
            // 如果是字符串，尝试解析为对象
            if (typeof currentFlowData === 'string') {
                try {
                    currentFlowData = JSON.parse(currentFlowData);
                } catch (e) {
                    currentFlowData = {};
                }
            }
            
            window.aiAgentFlowBuilder = new jingrow.ui.AIAgentFlowBuilder({
                wrapper: container,
                frm: frm,
                value: currentFlowData
            });
        }, 300);
    }).catch(error => {
        jingrow.msgprint({
            title: __('错误'),
            message: __('Ai Agent Flow Builder加载失败: ') + error.message,
            indicator: 'red'
        });
    });
}

function loadAIAgentFlowBuilder() {
    return new Promise((resolve, reject) => {
        if (jingrow.ui && jingrow.ui.AIAgentFlowBuilder) {
            resolve();
            return;
        }
        jingrow.require('ai_agent_flow_builder.bundle.js').then(() => {
            if (jingrow.ui && jingrow.ui.AIAgentFlowBuilder) {
                resolve();
            } else {
                reject(new Error('AIAgentFlowBuilder类未正确注册'));
            }
        }).catch(reject);
    });
}

function save_agent_flow(frm, dialog) {
    let flowData = null;
    if (window.aiAgentFlowBuilder && typeof window.aiAgentFlowBuilder.getFlowData === 'function') {
        try {
            flowData = window.aiAgentFlowBuilder.getFlowData();
        } catch (e) {}
    }
    if (!flowData) {
        jingrow.msgprint({
            title: __('错误'),
            message: __('无法获取流程数据'),
            indicator: 'red'
        });
        return;
    }
    
    // 格式化为多行美观JSON字符串
    const prettyJson = JSON.stringify(flowData, null, 2);
    frm.set_value('agent_flow', prettyJson);
    
    // 保存表单
    frm.save().then(() => {
        // 标记为已保存状态，系统会自动显示保存成功消息
        if (window.aiAgentFlowBuilder && window.aiAgentFlowBuilder.store) {
            window.aiAgentFlowBuilder.store.markClean();
        }
    }).catch((error) => {
        jingrow.msgprint({
            title: __('保存失败'),
            message: error.message || __('保存过程中发生错误'),
            indicator: 'red'
        });
    });
}
