<template>
	<dc-drawer-header v-if="props.id" :detail="formState" />

	<a-form
		:label-align="useUpdateMethod.formLabelAlign"
		:label-col="useUpdateMethod.formLabelCol"
		:model="formState"
		:wrapper-col="useUpdateMethod.formWrapperCol"
		scrollToFirstError
		@finish="onFinish"
		@finishFailed="useUpdateMethod.formFail"
	>
		<base-form-item v-for="item of fieldList" :key="item.name" v-model:value="formState[item.name]" v-bind="item" />

		<a-form-item :wrapper-col="useUpdateMethod.formActionCol">
			<a-button html-type="submit" type="primary">提交</a-button>
			<a-button style="margin-left: 10px" @click="useUpdateMethod.handleCancel">关闭</a-button>
		</a-form-item>
	</a-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { SystemMenu } from '../../../entity/system/system-menu'
import requestMethod from '../../../api/system/menu'
import fields from './fields'
import { CascaderProps } from '../../../components/form-item/props'
import { messageMethod } from '../../../utils/message-util'
import { QueryObjectType } from '../../../http/request-model'
import BaseFormItem from '../../../components/form-item/BaseFormItem.vue'
import { updateMethod } from '../../../components/form/method'

// 操作页面的公用方法
const useUpdateMethod = updateMethod()

/**
 * 属性
 */
const props = defineProps<{ id?: string }>()
defineEmits<{ (e: 'cancel'): void; (e: 'refresh'): void }>()

const formState = reactive<Partial<SystemMenu>>({
	menuCode: '',
	menuName: '',
	isShow: 1,
	menuIds: []
})

/**
 * 如果是编辑，获取数据
 * 请求列表数据
 */
const fieldList = ref(fields)
onMounted(async () => {
	let { data } = await requestMethod.formSelect()

	// 挂载筛选数据
	const typeValue = fieldList.value.find(value => value.name == 'menuIds')?.typeValue
	if (typeValue) {
		const temp = typeValue as CascaderProps
		temp.options = data
	}

	if (props.id) {
		const { data } = await requestMethod.getById(props.id)

		// menu id处理
		data?.menuIds?.pop()

		Object.assign(formState, data)
		// formState.value = data
	}
})

/**
 * 提交表单
 * @param value
 */
const onFinish = async (value: SystemMenu) => {
	value.fkParentId = formState.menuIds?.slice().pop() || ''

	// 处理一下图标
	if (value.icon && value.icon.match(/-|\s/)) {
		value.icon = value.icon
			.split(/-|\s/g)
			.map(key => key.charAt(0).toUpperCase() + key.slice(1))
			.join('')
	}

	if (props.id) {
		// 如果有id， 说明是更新
		value.id = props.id
		value.version = formState.version ?? 1
		const { message } = await requestMethod.update({ ...(value as unknown as QueryObjectType) })
		messageMethod.success(message)
		useUpdateMethod.handleSave()
	} else {
		const { message } = await requestMethod.add({ ...(value as unknown as QueryObjectType) })
		messageMethod.success(message)
		useUpdateMethod.handleSave()
	}
}
</script>

<style lang="scss" scoped>
.form-grid {
	display: grid;
}
</style>
