import { deviceDetection } from '@pureadmin/utils';
import { addDialog } from '@/components/BaseDialog/index';
import ${originalName}Dialog from '${dialogPath}';
import { use${originalName}Store } from '${storePath}';
import { h, ref } from 'vue';
import { messageBox } from '@/utils/message';
import type { FormItemProps } from '${typesPath}';
import { $t } from '@/plugins/i18n';

export const formRef = ref();
// 删除ids
export const deleteIds = ref([]);
const ${lowercaseName}Store = use${originalName}Store();

/**
 * * 搜索初始化${classTitle}
 */
export async function onSearch() {
	${lowercaseName}Store.loading = true;
	await ${lowercaseName}Store.get${originalName}List();
	${lowercaseName}Store.loading = false;
}

/**
 * * 添加${classTitle}
 */
export function onAdd() {
	addDialog({
        title: `$leftBrace $t("add_new")}$leftBrace$t("${lowercaseName}")}`,
		width: '30%',
		props: {
			formInline: {
#foreach($item in $addFormList)
    $!{item}: undefined,
#end
			},
		},
		draggable: true,
		fullscreenIcon: true,
		closeOnClickModal: false,
		contentRenderer: () => h(${originalName}Dialog, { ref: formRef }),
		beforeSure: (done, { options }) => {
			const form = options.props.formInline as FormItemProps;
			formRef.value.formRef.validate(async (valid: any) => {
				if (!valid) return;

				const result = await ${lowercaseName}Store.add${originalName}(form);
				if (!result) return;
				done();
				await onSearch();
			});
		},
	});
}

/**
 * * 更新${classTitle}
 * @param row
 */
export function onUpdate(row: any) {
	addDialog({
		title: `$leftBrace$t("modify")}$leftBrace$t("${lowercaseName}")}`,
		width: '30%',
		props: {
		formInline: {
#foreach($item in $addFormList)
    $!{item}: row.$!{item},
#end
	}
},
		draggable: true,
		fullscreenIcon: true,
		closeOnClickModal: false,
		contentRenderer: () => h(${originalName}Dialog, { ref: formRef }),
		beforeSure: (done, { options }) => {
			const form = options.props.formInline as FormItemProps;
			formRef.value.formRef.validate(async (valid: any) => {
				if (!valid) return;

				const result = await ${lowercaseName}Store.update${originalName}({ ...form, id: row.id });
				if (!result) return;
				done();
				await onSearch();
			});
		},
	});
}

/**
 * * 删除${classTitle}
 */
export const onDelete = async (row: any) => {
	const id = row.id;

	// 是否确认删除
	const result = await messageBox({
		title: $t('confirm_delete'),
		showMessage: false,
		confirmMessage: undefined,
		cancelMessage: $t("cancel_delete"),
	});
	if (!result) return;

	// 删除数据
	await ${lowercaseName}Store.delete${originalName}([id]);
	await onSearch();
};

/**
 * 批量删除
 */
export const onDeleteBatch = async () => {
	const ids = deleteIds.value;

	// 是否确认删除
	const result = await messageBox({
		title: $t('confirm_delete'),
		showMessage: false,
		confirmMessage: undefined,
		cancelMessage: $t('cancel_delete'),
	});
	if (!result) return;

	// 删除数据
	await ${lowercaseName}Store.delete${originalName}(ids);
	await onSearch();
};