<template>
	<a-modal v-model:open="visible" :title="title" :width="500" :confirm-loading="loading" @ok="handleOk" @cancel="handleCancel">
		<a-form ref="formRef" :model="formData" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
			<a-form-item label="城市名称" name="title">
				<a-input v-model:value="formData.title" placeholder="请输入城市名称" allow-clear />
			</a-form-item>

			<a-form-item label="城市编码" name="code">
				<a-input v-model:value="formData.code" placeholder="请输入城市编码" allow-clear :disabled="mode === 'edit'" />
			</a-form-item>

			<a-form-item v-if="mode === 'add'" label="父级城市" name="parent_code">
				<a-select v-model:value="formData.parent_code" placeholder="请选择父级城市" allow-clear show-search :filter-option="filterOption">
					<a-select-option :value="null">无（顶级城市）</a-select-option>
					<a-select-option v-for="city in flatCities" :key="city.code" :value="city.code"> {{ city.title }} ({{ city.code }}) </a-select-option>
				</a-select>
			</a-form-item>

			<a-form-item v-if="mode === 'edit' && formData.parent_code" label="父级城市" name="parent_code">
				<a-input v-model:value="parentCityTitle" disabled />
			</a-form-item>
		</a-form>
	</a-modal>
</template>

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

const props = defineProps({
	visible: {
		type: Boolean,
		default: false,
	},
	cityData: {
		type: Object,
		default: () => ({}),
	},
	mode: {
		type: String,
		default: 'add',
	},
})

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

const formRef = ref(null)
const loading = ref(false)
const flatCities = ref([])
const parentCityTitle = ref('')

const formData = reactive({
	title: '',
	code: '',
	parent_code: null,
})

const rules = {
	title: [
		{ required: true, message: '请输入城市名称', trigger: 'blur' },
		{ max: 100, message: '城市名称不能超过100个字符', trigger: 'blur' },
	],
	code: [
		{ required: true, message: '请输入城市编码', trigger: 'blur' },
		{ max: 50, message: '城市编码不能超过50个字符', trigger: 'blur' },
		{
			pattern: /^[A-Za-z0-9_-]+$/,
			message: '城市编码只能包含字母、数字、下划线和横线',
			trigger: 'blur',
		},
	],
}

const title = computed(() => {
	const titles = {
		add: '新增城市',
		edit: '编辑城市',
	}
	return titles[props.mode] || '城市'
})

const visible = computed({
	get: () => props.visible,
	set: (val) => emit('update:visible', val),
})

// 加载所有城市（用于父级选择）
const loadAllCities = async () => {
	try {
		const res = await api.city.list.get({ page_size: 1000 })
		if (res.code === 200) {
			flatCities.value = res.data.list || []
		}
	} catch (error) {
		console.error('加载城市列表失败', error)
	}
}

// 搜索过滤
const filterOption = (input, option) => {
	return option.children[0].children.toLowerCase().includes(input.toLowerCase())
}

// 重置表单
const resetForm = () => {
	formData.title = ''
	formData.code = ''
	formData.parent_code = null
	parentCityTitle.value = ''
	formRef.value?.clearValidate()
}

// 监听 cityData 变化
watch(
	() => props.cityData,
	(val) => {
		if (val && props.visible) {
			formData.title = val.title || ''
			formData.code = val.code || ''
			formData.parent_code = val.parent_code || null

			if (props.mode === 'edit' && val.parent_code) {
				// 查找父级城市名称
				const parentCity = flatCities.value.find((city) => city.code === val.parent_code)
				parentCityTitle.value = parentCity ? `${parentCity.title} (${parentCity.code})` : val.parent_code
			}
		}
	},
	{ immediate: true, deep: true },
)

// 监听弹窗打开
watch(
	() => props.visible,
	(val) => {
		if (val) {
			loadAllCities()
		} else {
			resetForm()
		}
	},
)

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

		const data = {
			title: formData.title,
			code: formData.code,
		}

		if (props.mode === 'add' && formData.parent_code) {
			data.parent_code = formData.parent_code
		}

		let res
		if (props.mode === 'add') {
			res = await api.city.add.post(data)
		} else if (props.mode === 'edit') {
			res = await api.city.edit.put(props.cityData.id, data)
		}

		if (res.code === 200) {
			message.success(props.mode === 'edit' ? '更新成功' : '创建成功')
			emit('success')
			handleCancel()
		}
	} catch (error) {
		if (error.errorFields) {
			// 表单验证错误，不提示
		} else {
			message.error(error.message || '操作失败')
		}
	} finally {
		loading.value = false
	}
}

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