<script lang="ts" setup>
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { Close, Finished } from '@element-plus/icons-vue';
import * as api from '../api';
import { useResponse } from '/@/utils/useResponse';
import { hasPermission } from '/@/utils/hasPermission';

// 接口定义
interface RuleForm {
	status: string;
	platform_number: string;
	name: string;
}

interface Props {
	rowData?: {
		id: string | number;
		platform_number: string;
		name: string;
		status: string;
	};
}

// Props 和 Emits
const props = defineProps<Props>();
const emit = defineEmits<{
	refresh: [];
}>();

// 响应式数据
const btnLoading = ref(false);
const editOpen = defineModel({ default: false });
const editDrawer = useTemplateRef<any>('editDrawer');
const ruleFormRef = ref<FormInstance>();

// 表单数据初始化
const initFormData = (): RuleForm => ({
	platform_number: props.rowData?.platform_number ?? '',
	name: props.rowData?.name ?? '',
	status: props.rowData?.status ?? '',
});

const ruleForm = reactive<RuleForm>(initFormData());

// 表单验证规则
const rules = reactive<FormRules<RuleForm>>({
	name: [
		{ required: true, message: '请输入店铺名称', trigger: 'blur' },
		{ min: 2, max: 50, message: '店铺名称长度在 2 到 50 个字符', trigger: 'blur' },
	],
	platform_number: [
		{ required: true, message: '请输入平台编号', trigger: 'blur' },
		{ pattern: /^[A-Za-z0-9_-]+$/, message: '平台编号只能包含字母、数字、下划线和短横线', trigger: 'blur' },
	],
	status: [{ required: true, message: '请选择店铺状态', trigger: 'change' }],
});

// 店铺状态选项
const statusOptions = [
	{ label: '启用', value: 'open' },
	{ label: '关闭', value: 'closed' },
];

// 提交表单
const submitForm = async (formEl?: FormInstance) => {
	if (!formEl || !props.rowData?.id) return;

	try {
		const valid = await formEl.validate();
		if (!valid) return;

		btnLoading.value = true;

		const res = await useResponse(api.updateRow, { id: props.rowData.id, ...ruleForm }, btnLoading);

		if (res?.code === 2000) {
			editOpen.value = false;
			ElMessage.success({
				message: '编辑成功',
				plain: true,
				icon: 'Operation',
			});
			emit('refresh');
			resetForm();
		}
	} catch (error) {
		console.error('编辑失败:', error);
		ElMessage.error('编辑失败，请重试');
	} finally {
		btnLoading.value = false;
	}
};

// 重置表单
const resetForm = () => {
	ruleFormRef.value?.clearValidate();
	Object.assign(ruleForm, initFormData());
};

// 关闭抽屉
const closeDrawer = () => {
	editDrawer.value?.handleClose();
	resetForm();
};

// 监听抽屉打开状态，重新初始化表单数据
watch(editOpen, (newVal) => {
	if (newVal && props.rowData) {
		Object.assign(ruleForm, initFormData());
		nextTick(() => {
			ruleFormRef.value?.clearValidate();
		});
	}
});
</script>

<template>
	<div class="drawer-container">
		<el-drawer
			ref="editDrawer"
			v-model="editOpen"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			size="30%"
			title="市场店铺 - 编辑"
			destroy-on-close
		>
			<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="mx-2.5 mt-7" label-position="top" label-width="auto" status-icon>
				<el-form-item class="font-medium" label="店铺名称：" prop="name">
					<el-input v-model="ruleForm.name" placeholder="请输入店铺名称" maxlength="50" show-word-limit clearable />
				</el-form-item>

				<el-form-item class="font-medium" label="平台编号：" prop="platform_number">
					<el-input v-model="ruleForm.platform_number" placeholder="请输入平台编号" clearable />
				</el-form-item>

				<div v-if="hasPermission('shopStatusEdit')">
					<el-form-item class="font-medium" label="店铺状态：" prop="status">
						<el-select v-model="ruleForm.status" placeholder="请选择店铺状态" clearable class="w-full">
							<el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value" />
						</el-select>
					</el-form-item>
				</div>

				<el-form-item>
					<el-divider />
					<div class="flex flex-1 justify-end gap-3">
						<el-button :icon="Close" @click="closeDrawer"> 取 消 </el-button>
						<el-button :icon="Finished" :loading="btnLoading" type="primary" @click="submitForm(ruleFormRef)"> 确 定 </el-button>
					</div>
				</el-form-item>
			</el-form>
		</el-drawer>
	</div>
</template>

<style scoped>
.drawer-container :deep(.el-drawer__header) {
	border-bottom: none;
	font-weight: 500;
}

.drawer-container :deep(.el-drawer__title) {
	font-size: 18px;
}
</style>