import { createApp, watchEffect } from "vue";
import { createPinia } from "pinia";
import { useSchemaStore } from "./store";
import SchemaBuilderComponent from "./SchemaBuilder.vue";
import { registerGlobalComponents } from "./globals.js";
import naive from 'naive-ui';
import { t } from '@/shared/i18n';

class SchemaBuilder {
	constructor({ wrapper, frm, pagetype, customize }) {
		this.$wrapper = $(wrapper);
		this.frm = frm;
		this.page = frm.page;
		this.pagetype = pagetype;
		this.customize = customize;
		this.read_only = false;

		this.init();
	}

	init(refresh) {
		// 使用全局 t() 设置标题
		this.page.set_title(t(this.pagetype));
		!refresh && this.setup_app();
		refresh && this.update_store();
		this.watch_changes();
	}


	setup_app() {
		// create a pinia instance
		let pinia = createPinia();

		// create a vue instance
		let app = createApp(SchemaBuilderComponent);
		// 全局 i18n 已通过直接 import { t } 使用，无需注入占位 $t
		app.use(pinia);
		app.use(naive);

		// create a store
		this.store = useSchemaStore();
		this.update_store();

		// register global components
		registerGlobalComponents(app);

		// mount the app
		this.$schema_builder = app.mount(this.$wrapper.get(0));
	}

	update_store() {
		this.store.pagetype = this.pagetype;
		this.store.is_customize_form = this.customize;
		this.store.page = this.page;
		this.store.frm = this.frm;
	}

	watch_changes() {
		watchEffect(() => {
			if (this.store.dirty || this.frm.is_dirty()) {
				this.frm.dirty();
			} else {
				this.page.clear_indicator();
			}

			if (this.store.read_only) {
				// 使用 t() 翻译指示信息
				let message = this.store.preview ? t("Preview Mode") : t("Read Only");
				this.page.set_indicator(message, "orange");
			}
		});
	}
	
	// 获取 Schema 数据的方法（参考 aiAgentFlowBuilder.getFlowData）
	getSchemaData() {
		if (this.store && this.store.schema) {
			// 确保 schema 是最新的
			this.store.updateSchema();
			return this.store.schema;
		}
		return null;
	}
	
	// 保存 Schema 到表单字段
	saveSchemaToForm() {
		const schemaData = this.getSchemaData();
		if (schemaData && this.frm) {
			// 设置表单字段值
			this.frm.set_value('node_schema', JSON.stringify(schemaData, null, 2));
			// 保存表单
			this.frm.save().then(() => {
				// 移除多余的提示，只保留系统自动的"已保存"提示
			}).catch(error => {
				console.error(`保存失败: ${error.message}`);
			});
		} else {
		}
	}
	
	// 触发保存事件，让父组件知道需要保存
	triggerSave() {
		// 触发自定义事件
		if (this.$wrapper && this.$wrapper[0]) {
			const saveEvent = new CustomEvent('schema-save', {
				detail: { schemaData: this.getSchemaData() }
			});
			this.$wrapper[0].dispatchEvent(saveEvent);
		}
	}
}

// 提供全局SchemaBuilder类
if (typeof window !== 'undefined') {
	if (!window.jingrow) {
		window.jingrow = {};
	}
	if (!window.jingrow.ui) {
		window.jingrow.ui = {};
	}
	window.jingrow.ui.SchemaBuilder = SchemaBuilder;
}

export default SchemaBuilder;
