<template>
	<a-modal :open="visible" :title="isEdit ? $t('common.editArea') : $t('common.addArea')" :width="600"
		:ok-text="$t('common.confirm')" :cancel-text="$t('common.cancel')" @ok="handleConfirm" @cancel="handleClose"
		:after-close="handleClose">
		<a-form ref="formRef" :model="formData" :label-col="{ span: 5 }">
			<a-form-item v-if="!isEdit" name="code" :label="$t('common.areaCode')"
				:rules="[{ required: true, message: $t('common.pleaseEnter') + $t('common.areaCode') }]">
				<a-input v-model:value="formData.code" :placeholder="$t('common.pleaseEnter')" :maxlength="20" />
			</a-form-item>

			<a-form-item name="title" :label="$t('common.areaName')"
				:rules="[{ required: true, message: $t('common.pleaseEnter') + $t('common.areaName') }]">
				<a-input v-model:value="formData.title" :placeholder="$t('common.pleaseEnter')" :maxlength="50" />
			</a-form-item>

			<a-form-item name="parent_code" :label="$t('common.parentArea')">
				<a-tree-select v-model:value="formData.parent_code" :tree-data="areaTreeData"
					:placeholder="$t('common.pleaseSelect')"
					:field-names="{ label: 'title', value: 'code', children: 'children' }" allow-clear show-search
					tree-default-expand-all />
			</a-form-item>

			<a-form-item name="status" :label="$t('common.status')"
				:rules="[{ required: true, message: $t('common.pleaseSelect') + $t('common.status') }]">
				<a-radio-group v-model:value="formData.status">
					<a-radio :value="1">{{ $t('common.enabled') }}</a-radio>
					<a-radio :value="0">{{ $t('common.disabled') }}</a-radio>
				</a-radio-group>
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import systemApi from '@/api/system'

// 定义组件名称
defineOptions({
	name: 'AreaModal',
})

const { t } = useI18n()

const props = defineProps({
	visible: {
		type: Boolean,
		default: false,
	},
	// 是否为编辑模式
	isEdit: {
		type: Boolean,
		default: false,
	},
	// 编辑时的初始数据
	initialData: {
		type: Object,
		default: () => ({}),
	},
})

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

const formRef = ref(null)
const areaTreeData = ref([])

// 表单数据
const formData = reactive({
	id: null,
	code: '',
	title: '',
	parent_code: null,
	status: 1,
})

// 获取地区树数据
const fetchAreaTree = async () => {
	try {
		const res = await systemApi.area.list.get({ pageSize: 1000 })
		if (res.code === 200) {
			const list = res.data.list || res.data || []
			areaTreeData.value = buildTree(list)
		}
	} catch (error) {
		console.error('获取地区树失败:', error)
	}
}

// 构建树结构
const buildTree = (list) => {
	const map = {}
	const roots = []

	// 创建映射，以 code 作为键
	list.forEach(item => {
		map[item.code] = { ...item, children: [] }
	})

	// 构建树，通过 parent_code 关联
	list.forEach(item => {
		if (item.parent_code && map[item.parent_code]) {
			map[item.parent_code].children.push(map[item.code])
		} else if (item.parent_code === '0' || !item.parent_code) {
			roots.push(map[item.code])
		}
	})

	return roots
}

// 监听弹窗显示和初始数据变化
watch(() => props.initialData, (newVal) => {
	if (props.isEdit && Object.keys(newVal).length > 0) {
		formData.id = newVal.id || null
		formData.code = newVal.code || ''
		formData.title = newVal.title || ''
		formData.parent_code = newVal.parent_code || null
		formData.status = newVal.status ?? 1
	}
}, { immediate: true })

// 监听弹窗打开，加载地区树数据
watch(() => props.visible, (newVal) => {
	if (newVal) {
		fetchAreaTree()
	}
})

// 监听弹窗关闭，重置表单
watch(() => props.visible, (newVal) => {
	if (!newVal) {
		handleClose()
	}
})

// 确认提交
const handleConfirm = async () => {
	try {
		const values = await formRef.value.validate()
		emit('confirm', values)
	} catch (error) {
		// 表单验证错误，不处理
	}
}

// 关闭弹窗并重置表单
const handleClose = () => {
	formRef.value?.resetFields()
	formData.id = null
	formData.code = ''
	formData.title = ''
	formData.parent_code = null
	formData.status = 1
	emit('update:visible', false)
}
</script>

<style scoped lang="scss">
// 弹窗样式可根据需要添加</style>
