<template>
	<el-dialog title="分配角色" v-model="visible" draggable :width="500">
		<el-form :model="form" :rules="rules" :disabled="mode==='show'" ref="dialogForm" label-width="100px"
				 label-position="right">
			<el-form-item label="头像" prop="avatar">
				<ossImgUpload @parentParams="parentParams" :url="form.avatar" />
			</el-form-item>
			<el-form-item label="登录账号" prop="login_name">
				<el-input v-model="form.login_name" placeholder="用于登录系统" clearable :disabled="show"></el-input>
				<div class="el-form-item-msg">账号信息用于登录，系统不允许修改</div>
			</el-form-item>
			<el-form-item label="姓名" prop="name">
				<el-input v-model="form.name" placeholder="请输入完整的真实姓名" clearable :disabled="show"></el-input>
			</el-form-item>
			<el-form-item label="所属角色" prop="role_ids">
				<el-select v-model="form.role_ids" multiple filterable style="width: 100%">
					<el-option v-for="item in groups" :key="item.id" :label="item.label" :value="item.id"/>
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button v-if="mode!=='show'" type="primary" :loading="isSave" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>
export default {
	emits: ['success', 'closed'],
	data() {
		return {
			show: false,
			isSave: false,
			visible: false,
			form: {
				avatar:"",
				user_id: "",
				login_name: "",
				name: "",
				role_ids: []
			},

			rules: {
				role_ids: [
					{required: true, message: '请选择所属角色', trigger: 'change'}
				]
			},
			groups: [],
			groupsProps: {
				value: "id",
				multiple: true,
				checkStrictly: true
			},
		}
	},
	mounted() {
		this.getGroup()
	},
	methods: {
		open() {
			this.visible = true;
			this.show = true;
			return this
		},
		async getGroup() {
			const res = await this.$API.system.role.list.get();
			if(res.code == 200){
				this.groups = res.data.rows;
			}
		},
		// 图片上传成功回调
		parentParams(files){
			this.form.avatar = files;
		},
		submit() {
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSave = true;
					const res = await this.$API.system.user.allocatRole.post(this.form);
					if (res.code === 200) {
						this.$emit('success', this.form, this.mode)
						this.visible = false;
						this.$message.success("分配成功")
					}
					this.isSave = false;
				} else {
					this.isSave = false;
					return false;
				}
			})
		},
		setData(data) {
			this.form.user_id = data.id
			this.form.avatar = data.avatar;
			this.form.login_name = data.login_name
			this.form.name = data.name
			this.form.role_ids = data.group?data.group.role_ids:[]
			this.form.mobile = data.mobile
		}
	}
}
</script>

<style scoped>

</style>
