<template>
	<div>
		<el-dialog :title="(ruleForm.id ? $t('message.device.tableI18nAction.editCategory') : $t('message.device.tableI18nAction.addCategory'))" v-model="isShowDialog" width="600px">
			<el-form ref="formRef" :model="ruleForm" :rules="rules" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<!-- 上级分类 -->
						<el-form-item :label="$t('message.formI18nLabel.parentCategory')" :label-width="currentLocale == 'en' ? '120px' : '90px'">
							<el-cascader :options="deptData" :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name' }" :placeholder="$t('message.formI18nPlaceholder.parentCategory')" clearable class="w100" v-model="ruleForm.parentId">
								<template #default="{ node, data }">
									<span>{{ data.name }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="16" :lg="16" :xl="16">
						<!-- 分类名称 -->
						<el-form-item :label="$t('message.formI18nLabel.categoryName')" prop="name" :label-width="currentLocale == 'en' ? '120px' : '90px'">
							<el-input v-model="ruleForm.name" :placeholder="$t('message.formI18nPlaceholder.categoryName')" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
						<!-- 排序 -->
						<el-form-item :label="$t('message.formI18nLabel.sort')" prop="sort" label-width="40px">
							<el-input-number v-model="ruleForm.sort" :min="0" :max="100" step="1" step-strictly="true" controls-position="right" :placeholder="$t('message.formI18nPlaceholder.sort')" class="w100" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<!-- 分类标识 -->
						<el-form-item :label="$t('message.formI18nLabel.categoryKey')" prop="key" :label-width="currentLocale == 'en' ? '120px' : '90px'">
							<el-input v-model="ruleForm.key" :placeholder="$t('message.formI18nPlaceholder.categoryKey')" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<!-- 描述 -->
						<el-form-item :label="$t('message.formI18nLabel.desc')" prop="desc" :label-width="currentLocale == 'en' ? '120px' : '90px'">
							<el-input v-model="ruleForm.desc" type="textarea" :placeholder="$t('message.formI18nPlaceholder.desc')" maxlength="150"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel">{{ $t('message.tableI18nAction.cancel‌') }}</el-button>
					<el-button type="primary" @click="onSubmit" :loading="loading">{{ ruleForm.id ? $t('message.tableI18nAction.edit') : $t('message.tableI18nAction.add') }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, defineComponent, ref, unref, computed, defineEmits } from 'vue';
import api from '/@/api/device';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';

// 国际化
const { locale, t } = useI18n();

const currentLocale = computed(() => locale.value);	


const emit = defineEmits(['getCateList']);


interface RuleFormState {
	id?: number;
	parentId: number;
	name: string;
	key: string;
	desc: string;
	sort: number;
	children?: RuleFormState[];
}

const baseForm: RuleFormState = {
	parentId: 0, // 上级分类
	name: '', // 分类名称
	key: '',
	desc: '',
	sort: 0
};

		const formRef = ref<HTMLElement | null>(null);
		const loading = ref(false); // 添加loading状态'
		const isShowDialog = ref(false);
		const deptData = ref([]);// 分类数据
		const orgData = ref([]);// 组织数据
		// 使用computed自动响应语言变化
		const rules = computed(() => ({
				name: [{ required: true, message: t('message.formI18nPlaceholder.categoryName'), trigger: 'blur' }],
				key: [{ required: true, message: t('message.formI18nPlaceholder.categoryKey'), trigger: 'blur' }],
		}));
		const ruleForm = ref({
			...baseForm,
		})

		// // 打开弹窗
		const openDialog = (row?: RuleFormState | number) => {
			resetForm();
			api.category.getList({ status: 1 }).then((res: any) => {
				deptData.value = res.category || [];
			});


			if (row && typeof row === 'object') {
				ruleForm.value = row;
			} else if (row && typeof row === 'number') {
				ruleForm.value.parentId = row;
			}
			isShowDialog.value = true;
		};
		// 关闭弹窗
		const closeDialog = () => {
			isShowDialog.value = false;
		};
		// 取消
		const onCancel = () => {
			closeDialog();
		};
		// 新增
		const onSubmit = () => {
			const formWrap = unref(formRef) as any;
			if (!formWrap) return;
			formWrap.validate(async (valid: boolean) => {
				if (valid) {
					// 禁用按钮
					loading.value = true;
					if (!ruleForm.value.parentId) {
						ruleForm.value.parentId = 0;
					}
					if (!ruleForm.value.id) {
						//添加
						try {
							// 等待提交完成
							await api.category.add(ruleForm.value);
							ElMessage.success(t('message.tableI18nConfirm.addSuccess'));
							closeDialog(); // 关闭弹窗
							emit('getCateList');
						} catch (error) {
							ElMessage.error(t('message.tableI18nConfirm.addFailed'));
						}
					} else {
						//修改
						try {
							// 等待提交完成
							await api.category.edit(ruleForm.value);
							ElMessage.success(t('message.tableI18nConfirm.editSuccess'));
							closeDialog(); // 关闭弹窗
							emit('getCateList');
						} catch (error) { }
					}
					// 启用按钮
					loading.value = false;
				} else {
					// 表单验证失败时，启用按钮
					loading.value = false;
				}
			});
		};
		const resetForm = () => {
			ruleForm.value = {
				...baseForm,
			};
		};
defineExpose({ openDialog });
</script>
