<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" :disabled="mode==='show'" ref="formRef" label-width="100px">
			<el-form-item label="岗位名称" prop="post_name">
				<el-input type="text" v-model="form.post_name" placeholder="请输入岗位名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="岗位编码" prop="post_code">
				<pi-select v-model="form.post_code" :api="api.system.dict_data.option" :params="{key:'post_category'}"
						   :props="{label: 'dict_label', value: 'dict_value'}"></pi-select>
			</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-item label="是否启用" prop="status">
				<el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button v-if="mode!=='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script setup>
import {getCurrentInstance, ref} from 'vue'
import api from "@/api/index.js";

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

let mode = ref('add')
let titleMap = ref({
	add: '新增',
	edit: '编辑',
	show: '查看'
})
let visible = ref(false)
let isSaveing = ref(false)
let form = ref({
	post_id: '',
	post_name: '',
	status: 1,
	rank: 1
})
const rules = ref({
	post_name: [
		{required: true, message: '请填写岗位名称'}
	],
})

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

async function submit() {
	// 校验登录
	const validate = await formRef.value.validate().catch(() => {
	});
	if (!validate) {
		return false
	}
	isSaveing.value = true;
	const res = form.value.post_id ? await api.system.post.edit(form.value) : await api.system.post.add(form.value);
	isSaveing.value = false;
	emit('success')
	visible.value = false;
	proxy.$message.success(res.msg)
}
</script>
