<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
			<el-form-item label="上级" prop="parent_id">
				<el-cascader ref="categoryRef" v-model="form.parent_id" :options="menu" :props="menuProps" clearable
							 style="width: 100%;"></el-cascader>
			</el-form-item>
			<el-form-item label="名称" prop="category_name">
				<el-input v-model="form.category_name" placeholder="请输入分类名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="排序" prop="rank">
				<el-input-number v-model="form.rank" controls-position="right" :min="1" :max="9999"
								 style="width: 100%;"></el-input-number>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script setup>
import assetConfig from "@/config/asset"
import {getCurrentInstance, ref} from "vue"

defineExpose({
	setType,
	open
})

const emit = defineEmits(['success', 'closed'])
const formRef = ref(null)
const categoryRef = ref(null)
const {proxy} = getCurrentInstance()

let mode = ref("add")
const titleMap = ref({
	add: '新增',
	edit: '编辑'
})
let visible = ref(false)
let isSaveing = ref(false)

let form = ref({
	category_id: null,
	category_name: "",
	parent_id: 0,
	rank: 1,
	type: ""
})
let rules = ref({
	category_name: [
		{required: true, message: '请输入分类名称'}
	]
})
let menu = ref([])
let menuProps = ref({
	value: "category_id",
	label: "category_name",
	checkStrictly: true
})

function open(_mode = 'add', data = null, parent_id = null) {
	mode.value = _mode;
	visible.value = true;
	if (parent_id) {
		form.value.parent_id = parent_id
	}
	if (data) {
		Object.assign(form.value, data)
	}
}

function setType(type) {
	form.value.type = type
	return {open, setMenu};
}

function setMenu(_menu) {
	menu.value = _menu
	return {open, setType};
}

async function submit() {
	// 校验登录
	const validate = await formRef.value.validate().catch(() => {
	});
	if (!validate) {
		return false
	}
	let data = Object.assign({}, form.value)
	// 部门获取最后一项
	if (categoryRef.value.getCheckedNodes().length > 0) {
		data.parent_id = categoryRef.value.getCheckedNodes()[0].value
	}
	isSaveing.value = true;
	const res = data.category_id ? await assetConfig.menuEditObj(data) : await assetConfig.menuAddObj(data);
	isSaveing.value = false;
	emit('success', data, mode.value)
	visible.value = false;
	proxy.$message.success(res.msg)
}

</script>

<style scoped>
.el-form-item {
	margin-bottom: 18px;
}
</style>
