<template>
	<a-modal v-model:visible="openAddModel" :title="title" ok-text="提交" cancel-text="取消" @ok="sumbitForm"
		@cancel="cancelModal" width="50%">
		<a-form :model="createForm" :label-col="{span: 4}" labelAlign="right" style="margin-top: 20px;">
			<a-row gutter="20">
				<a-col span="24">
					<a-form-item required label="角色名" name="name">
						<a-input v-model:value="createForm.name" placeholder="请输入角色名" />
					</a-form-item>
				</a-col>
				<a-col span="24">
					<a-form-item required label="角色代码" name="code">
						<a-input v-model:value="createForm.code" placeholder="请输入角色代码" />
					</a-form-item>
				</a-col>
				<a-col span="24">
					<a-form-item required label="描述" name="description">
						<a-input v-model:value="createForm.description" placeholder="请描述角色" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
	</a-modal>
</template>

<script setup lang="ts">
	import { ref, onMounted, computed, defineProps, watch, defineEmits } from 'vue';
	import { PostRoleAdd, PostRoleEdit } from '@/apis/models';
	import { dataForm, otherDataForm, reset } from '@/views/permission/role/add/data.ts';
	import { useCommon } from '@/hooks/useCommon';
	let { store, openAddModel, hideModal, message, } = useCommon();
	const emit = defineEmits();
	let props = defineProps(['edit_record']);
	let title = ref<String>('新增角色');
	let createForm = ref<companyDepartmentType.addFormType>(dataForm)

	const sumbitForm = () => {
		if (createForm.value.name && createForm.value.code && createForm.value.description) {
			if (!createForm.value.id) {
				PostRoleAdd(createForm.value).then(res => {
					message.success('新增角色成功');
					hideModal();
					resetForm();
					emit('successAdd');
				}).catch(err => {
				})
			} else {
				PostRoleEdit(createForm.value).then(res => {
					message.success('修改角色成功');
					hideModal();
					resetForm();
					emit('successAdd');
				}).catch(err => {
				})
			}
		} else {
			message.warning('请补充完整信息');
		}

	}

	const resetForm = () => {
		createForm.value = reset().dataForm;
	}
	const cancelModal = () => {
		emit('closeAdd');
		resetForm();
		hideModal();
	}


	openAddModel = computed(() => {
		return store.state.openAddModel;
	})

	watch(() => props.edit_record, (newVal) => {
		if (newVal) {
			title.value = "编辑角色";
			createForm.value = {
				id: newVal.id,
				name: newVal.name,
				code: newVal.code,
				description: newVal.description
			}
		} else {
			title.value = "新增角色"
		}
	})
</script>

<style>

</style>