<template>
	<div>
		<div class="content-head">
			<dataBreadcrumb :breads="breads"></dataBreadcrumb>
			<h3>新建角色</h3>
			<h5>新建角色</h5>
		</div>
		<div class="content">
			<div class="message">
				<el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm">
					<el-form-item label="角色名称" prop="roleName">
						<el-input v-model.trim="form.roleName"></el-input>
					</el-form-item>
					<el-form-item label="权限" prop="menuPOList">
						<el-tree :data="data" :default-checked-keys="[1]"  :default-expanded-keys="[1]" :props="defaultProps" show-checkbox @check-change="handleCheckChange" node-key="id" ref="tree">
						</el-tree>
					</el-form-item>
				</el-form>
			</div>
		</div>
		<div class="centerButton">
			<el-button @click="back">返回</el-button>
			<el-button @click="add">添加</el-button>
		</div>
	</div>
</template>

<script>
	import {
		roleMenus,roleadd
	} from '@api/purchaser/organization'
	import dataBreadcrumb from '@components/dataBreadcrumb.vue'
	export default {
		components: {
			dataBreadcrumb
		},
		data() {
			let check = async (rule, value, callback) => {
				console.log("1")
				console.log(this.form.menuPOList.length)
				if (this.form.menuPOList.length == 0) {
					console.log("空")
					return callback(new Error('请选择权限'));
				} else {
					callback();
				}
			};
			return {
				breads: ['系统管理', '权限管理'],
				data: [],
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				form: {
					roleName: "",
					menuPOList: []
				},
				rules: {
					roleName: [{
						required: true,
						message: '请填写',
						trigger: 'blur'
					}],
					menuPOList: [{
						required: true,
						validator: check,
						trigger: 'change'
					}],
				}
			}
		},
		methods: {
			back() {
				this.$router.go(-1)
			},
			async getroleMenus() {
				const {
					data,
					code
				} = await roleMenus(1)
				data[0].disabled=true
				this.data = data
			},
		
			handleCheckChange() {
				this.form.menuPOList = this.$refs.tree.getCheckedKeys()
			},
			async add() {
				try {
					const valid = await this.$refs['form'].validate()
					if (valid) {
						let form = this.form
						const {
							code,
							msg
						} = await roleadd(form)
						if (code === 200) {
							this.$message({
								message: msg,
								type: 'success',
								duration: 1500
							})
							setTimeout(() => {
								this.$router.go(-1)
							}, 1500)
						}else{
							this.$message.error(msg)
						}
					}
				} catch (e) {
					console.log(e)
				}
			}
		},
		created() {
			this.getroleMenus()
		}
	}
</script>


<style scoped>
	.message {
		width: 60%;
		margin-left: 50px;
		margin-top: 20px;
	}

	.message>div {
		margin-bottom: 30px;
	}
</style>
