<template>
	<a-modal :open="dialogVisible" :title="isEdit ? '编辑配置项' : '新增配置项'" @cancel="handleCancel" :width="600" :confirm-loading="loading" @ok="handleOk">
		<a-form ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
			<a-form-item label="配置名称" name="name">
				<a-input v-model:value="formData.name" placeholder="请输入配置名称" />
			</a-form-item>

			<a-form-item v-if="!isEdit" label="配置键" name="key">
				<a-input v-model:value="formData.key" :placeholder="isEdit ? '' : '请输入配置键，如: site_name'">
					<template #prefix>
						<key-outlined />
					</template>
				</a-input>
				<div class="form-tip">建议使用小写字母、下划线命名</div>
			</a-form-item>

			<a-form-item v-if="!isEdit" label="分组" name="group">
				<a-select v-model:value="formData.group" placeholder="请选择分组" :options="groupOptions" show-search :filter-option="filterOption" />
			</a-form-item>

			<a-form-item v-if="!isEdit" label="配置类型" name="type">
				<a-select v-model:value="formData.type" placeholder="请选择配置类型" @change="handleTypeChange">
					<a-select-option value="string">字符串</a-select-option>
					<a-select-option value="text">文本</a-select-option>
					<a-select-option value="number">数字</a-select-option>
					<a-select-option value="boolean">布尔值</a-select-option>
					<a-select-option value="select">下拉选择</a-select-option>
					<a-select-option value="radio">单选</a-select-option>
					<a-select-option value="checkbox">多选</a-select-option>
					<a-select-option value="file">文件</a-select-option>
					<a-select-option value="json">JSON</a-select-option>
				</a-select>
			</a-form-item>

			<a-form-item v-if="!isEdit && ['select', 'radio', 'checkbox'].includes(formData.type)" label="选项配置" name="options">
				<div class="options-editor">
					<div v-for="(option, index) in formData.options" :key="index" class="option-item">
						<a-input v-model:value="option.label" placeholder="选项标签" style="flex: 1; margin-right: 8px" />
						<a-input v-model:value="option.value" placeholder="选项值" style="flex: 1; margin-right: 8px" />
						<a-button type="text" danger :disabled="formData.options.length <= 1" @click="removeOption(index)">
							<delete-outlined />
						</a-button>
					</div>
					<a-button type="dashed" block @click="addOption" style="margin-top: 8px"> <plus-outlined /> 添加选项 </a-button>
				</div>
			</a-form-item>

			<a-form-item label="配置值" name="value">
				<a-textarea v-if="['string', 'text', 'json'].includes(formData.type)" v-model:value="formData.value" :placeholder="getValuePlaceholder(formData.type)" :rows="formData.type === 'json' ? 6 : 3" />
				<a-input-number v-else-if="formData.type === 'number'" v-model:value="formData.value" placeholder="请输入数字" style="width: 100%" />
				<a-switch v-else-if="formData.type === 'boolean'" v-model:checked="formData.value" checked-children="是" un-checked-children="否" />
				<span v-else-if="formData.type === 'file'">{{ formData.value || '未选择文件' }}</span>
				<span v-else>{{ getDisplayValue(formData.value) }}</span>
			</a-form-item>

			<a-form-item label="默认值" name="default_value">
				<a-textarea v-if="['string', 'text', 'json'].includes(formData.type)" v-model:value="formData.default_value" :placeholder="getValuePlaceholder(formData.type)" :rows="formData.type === 'json' ? 6 : 3" />
				<a-input-number v-else-if="formData.type === 'number'" v-model:value="formData.default_value" placeholder="请输入默认值" style="width: 100%" />
				<a-switch v-else-if="formData.type === 'boolean'" v-model:checked="formData.default_value" checked-children="是" un-checked-children="否" />
				<span v-else>{{ getDisplayValue(formData.default_value) }}</span>
			</a-form-item>

			<a-form-item v-if="!isEdit" label="验证规则" name="validation">
				<a-input v-model:value="formData.validation" placeholder="如: required|email|max:100" />
				<div class="form-tip">可选，使用 Laravel 验证规则语法</div>
			</a-form-item>

			<a-form-item label="描述" name="description">
				<a-textarea v-model:value="formData.description" placeholder="请输入配置描述" :rows="2" />
			</a-form-item>

			<a-form-item v-if="!isEdit" label="排序" name="sort">
				<a-input-number v-model:value="formData.sort" :min="0" :max="9999" style="width: 100%" />
				<div class="form-tip">数字越小排序越靠前</div>
			</a-form-item>

			<a-form-item v-if="!isEdit" label="状态" name="status">
				<a-switch v-model:checked="formData.status" checked-children="启用" un-checked-children="禁用" />
			</a-form-item>

			<a-form-item v-if="record?.is_system" label="系统配置">
				<a-tag color="orange">系统配置项 - 仅可修改配置值</a-tag>
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import { KeyOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { useDictionaryStore } from '@/stores/modules/dictionary'
import systemApi from '@/api/system'

// Props
const props = defineProps({
	visible: {
		type: Boolean,
		default: false,
	},
	record: {
		type: Object,
		default: null,
	},
	defaultGroup: {
		type: String,
		default: '',
	},
	groups: {
		type: Array,
		default: () => [],
	},
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// Refs
const formRef = ref(null)
const loading = ref(false)

// 字典 store
const dictionaryStore = useDictionaryStore()

// 对话框可见性
const dialogVisible = computed({
	get: () => props.visible,
	set: (value) => emit('update:visible', value),
})

// 是否为编辑模式
const isEdit = computed(() => !!props.record)

// 表单数据
const formData = reactive({
	name: '',
	key: '',
	group: '',
	type: 'string',
	options: [],
	value: '',
	default_value: '',
	validation: '',
	description: '',
	sort: 0,
	status: true,
})

// 获取值的占位符
const getValuePlaceholder = (type) => {
	if (type === 'json') {
		return '{\"key\": \"value\"}'
	}
	return '请输入配置值'
}

// 表单验证规则
const formRules = computed(() => ({
	name: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
	key: [
		{
			required: !isEdit.value,
			message: '请输入配置键',
			trigger: 'blur',
		},
		{
			pattern: /^[a-z][a-z0-9_]*$/i,
			message: '只能包含字母、数字、下划线，且以字母开头',
			trigger: 'blur',
		},
	],
	group: [{ required: true, message: '请选择分组', trigger: 'change' }],
	type: [{ required: true, message: '请选择配置类型', trigger: 'change' }],
}))

// 分组选项
const groupOptions = computed(() => {
	return props.groups.map((item) => ({
		label: item.label,
		value: item.value,
	}))
})

// 过滤选项
const filterOption = (input, option) => {
	return option.label.toLowerCase().includes(input.toLowerCase())
}

// 监听 visible 变化
watch(
	() => props.visible,
	(val) => {
		if (val) {
			if (isEdit.value && props.record) {
				// 编辑模式：填充表单数据
				Object.keys(formData).forEach((key) => {
					if (props.record[key] !== undefined) {
						formData[key] = props.record[key]
					}
				})

				// 处理 options
				if (typeof formData.options === 'string' && formData.options) {
					try {
						formData.options = JSON.parse(formData.options)
					} catch (e) {
						formData.options = []
					}
				}

				// 确保 options 是数组
				if (!Array.isArray(formData.options)) {
					formData.options = []
				}

				// 如果 options 为空，初始化一个默认选项
				if (['select', 'radio', 'checkbox'].includes(formData.type) && formData.options.length === 0) {
					formData.options = [{ label: '选项1', value: 'option1' }]
				}
			} else {
				// 新增模式：重置表单数据
				Object.keys(formData).forEach((key) => {
					if (key === 'status') {
						formData[key] = true
					} else if (key === 'sort') {
						formData[key] = 0
					} else if (key === 'options') {
						formData[key] = []
					} else {
						formData[key] = ''
					}
				})

				// 设置默认分组
				if (props.defaultGroup) {
					formData.group = props.defaultGroup
				}
			}
		}
	},
)

// 类型改变时处理
const handleTypeChange = (type) => {
	// 重置值和默认值
	formData.value = ''
	formData.default_value = ''

	// 如果是选择类型，初始化选项
	if (['select', 'radio', 'checkbox'].includes(type)) {
		if (!formData.options || formData.options.length === 0) {
			formData.options = [{ label: '选项1', value: 'option1' }]
		}
	} else {
		formData.options = []
	}
}

// 添加选项
const addOption = () => {
	const index = formData.options.length + 1
	formData.options.push({
		label: `选项${index}`,
		value: `option${index}`,
	})
}

// 移除选项
const removeOption = (index) => {
	formData.options.splice(index, 1)
}

// 获取显示值
const getDisplayValue = (value) => {
	if (['select', 'radio'].includes(formData.type)) {
		const option = formData.options.find((opt) => opt.value === value)
		return option ? option.label : value
	}

	if (formData.type === 'checkbox') {
		if (typeof value === 'string') {
			try {
				const values = JSON.parse(value)
				return values
					.map((v) => {
						const option = formData.options.find((opt) => opt.value === v)
						return option ? option.label : v
					})
					.join(', ')
			} catch (e) {
				return value
			}
		}
		return value
	}

	return value || '-'
}

// 确认
const handleOk = async () => {
	try {
		await formRef.value.validate()

		// 验证选项配置
		if (['select', 'radio', 'checkbox'].includes(formData.type) && formData.options.length === 0) {
			message.error('请至少添加一个选项')
			return
		}

		// 处理 options
		const submitData = { ...formData }
		if (['select', 'radio', 'checkbox'].includes(formData.type)) {
			submitData.options = JSON.stringify(formData.options)
		} else {
			submitData.options = null
		}

		// 处理值
		if (formData.type === 'checkbox') {
			if (Array.isArray(submitData.value)) {
				submitData.value = JSON.stringify(submitData.value)
			}
			if (Array.isArray(submitData.default_value)) {
				submitData.default_value = JSON.stringify(submitData.default_value)
			}
		}

		loading.value = true

		let res
		if (isEdit.value) {
			// 编辑
			res = await systemApi.config.edit.put(props.record.id, submitData)
		} else {
			// 新增
			res = await systemApi.config.add.post(submitData)
		}

		if (res.code === 200) {
			message.success(isEdit.value ? '编辑成功' : '新增成功')
			emit('success')
		} else {
			message.error(res.message || (isEdit.value ? '编辑失败' : '新增失败'))
		}
	} catch (error) {
		console.error(isEdit.value ? '编辑配置项失败:' : '新增配置项失败:', error)
		message.error(isEdit.value ? '编辑失败' : '新增失败')
	} finally {
		loading.value = false
	}
}

// 取消
const handleCancel = () => {
	emit('update:visible', false)
}
</script>

<style scoped lang="scss">
.options-editor {
	.option-item {
		display: flex;
		align-items: center;
		margin-bottom: 8px;
	}
}

.form-tip {
	font-size: 12px;
	color: #8c8c8c;
	margin-top: 4px;
}
</style>
