<template>
	<a-modal :title="title" :open="visible" :width="500" :destroy-on-close="true" @cancel="handleCancel">
		<a-form :model="form" :rules="rules" ref="dialogForm" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
			<a-form-item label="角色名称" name="name">
				<a-input v-model:value="form.name" placeholder="请输入新角色名称" allow-clear />
			</a-form-item>
			<a-form-item label="角色编码" name="code">
				<a-input v-model:value="form.code" placeholder="请输入新角色编码" allow-clear />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-space>
				<a-button @click="handleCancel">取 消</a-button>
				<a-button type="primary" :loading="loading" @click="handleOk">确 定</a-button>
			</a-space>
		</template>
	</a-modal>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import authApi from '@/api/auth'

const emit = defineEmits(['success', 'closed'])

const visible = ref(false)
const loading = ref(false)
const sourceId = ref(null)
const sourceName = ref('')
const sourceCode = ref('')

// 表单数据
const form = reactive({
	name: '',
	code: '',
})

// 标题
const title = computed(() => (sourceId.value ? '复制角色' : '批量复制'))

// 表单引用
const dialogForm = ref()

// 验证规则
const rules = {
	name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
	code: [
		{ required: true, message: '请输入角色编码', trigger: 'blur' },
		{
			pattern: /^[a-zA-Z0-9_]+$/,
			message: '角色编码只能包含字母、数字和下划线',
			trigger: 'blur',
		},
	],
}

// 打开对话框
const open = (data = null) => {
	if (data && data.id) {
		// 单个复制
		sourceId.value = data.id
		sourceName.value = data.name
		sourceCode.value = data.code
		form.name = `${data.name}_副本`
		form.code = `${data.code}_copy`
	} else {
		// 批量复制（暂不支持自定义名称，直接在后端处理）
		sourceId.value = null
		sourceName.value = ''
		sourceCode.value = ''
		form.name = ''
		form.code = ''
	}
	visible.value = true
	return {
		open,
		close,
	}
}

// 关闭对话框
const close = () => {
	visible.value = false
}

// 处理取消
const handleCancel = () => {
	emit('closed')
	visible.value = false
}

// 处理确定
const handleOk = async () => {
	try {
		if (sourceId.value) {
			// 单个复制
			await dialogForm.value.validate()
			loading.value = true
			const res = await authApi.role.copy.post(sourceId.value, {
				name: form.name,
				code: form.code,
			})
			loading.value = false

			if (res.code === 200) {
				emit('success')
				visible.value = false
				message.success('复制成功')
			} else {
				message.error(res.message || '复制失败')
			}
		} else {
			// 批量复制（通过外部传入的 ids）
			emit('success')
			visible.value = false
		}
	} catch (error) {
		console.error('复制失败:', error)
		loading.value = false
	}
}

// 暴露方法给父组件
defineExpose({
	open,
	close,
})
</script>
