import { createApp } from "vue";
import { createPinia } from "pinia";
import AIAgentFlowBuilderComponent from "./AIAgentFlowBuilder.vue";
import { useFlowStore } from "./store/flowStore";
import '@vue-flow/core/dist/style.css';
import '@vue-flow/core/dist/theme-default.css';

class AIAgentFlowBuilder {
	constructor({ wrapper, frm, value }) {
		this.$wrapper = wrapper instanceof jQuery ? wrapper : $(wrapper);
		this.frm = frm;
		this.page = frm.page;
		this.pagetype = frm.pagetype;
		this.initialValue = value;
		this.init();
	}

	init() {
		// 设置全局智能体信息，供执行器使用
		this.setup_global_agent_info();
		this.setup_app();
		this.watch_changes();
	}

	setup_global_agent_info() {
		// 设置全局变量，让执行器能够获取到智能体信息
		if (this.frm && this.frm.doc && this.frm.doc.name) {
			window.current_agent_name = this.frm.doc.name;
		}
	}

	setup_app() {
		// 创建 Pinia 实例
		let pinia = createPinia();

		// 创建 Vue 应用
		let app = createApp(AIAgentFlowBuilderComponent);
		
		// 设置 Jingrow 全局属性
		SetVueGlobals(app);
		app.use(pinia);

		// 创建 store 并传递必要的上下文
		this.store = useFlowStore();
		this.store.frm = this.frm;
		this.store.page = this.page;
		this.store.pagetype = this.pagetype;

		// 挂载应用
		this.$flow_builder = app.mount(this.$wrapper.get(0));
		
		// 加载现有数据
		this.load_agent_flow();
	}

	async load_agent_flow() {
		try {
			
			// 直接使用传入的初始值
			if (this.initialValue) {
				this.store.loadFlowData(this.initialValue);
			} else {
				// 如果没有初始值，加载空的流程数据
				this.store.loadFlowData({});
			}
		} catch (error) {
		}
	}

	watch_changes() {
		// 监听 store 变化，标记表单为脏状态
		this.store.$subscribe((mutation, state) => {
			if (state.hasUnsavedChanges) {
				this.frm.dirty();
			}
		});
	}

	// 为外部调用提供 getFlowData 方法
	getFlowData() {
		return this.store.getFlowData();
	}
}

// 注册到 Jingrow 框架
jingrow.provide("jingrow.ui");
jingrow.ui.AIAgentFlowBuilder = AIAgentFlowBuilder;
export default AIAgentFlowBuilder; 