<template>
	<el-dialog
		:title="config.modalTitle" 
		:visible.sync="config.modalVisible" 
		:width="config.formLabelWidth" 
		@close="handleCancel">
		<div class="userMobile">
			<el-form label-width="80px" :model="form" :rules="rules" ref="from">
				<el-form-item label="角色名" prop="name">
					<el-input v-model="form.name"></el-input>
				</el-form-item>
				<el-form-item label="角色描述" prop="description">
					<el-input
					  type="textarea"
					  placeholder="请输入内容"
					  v-model="form.description"
					  maxlength="60"
					  show-word-limit
					></el-input>
				</el-form-item>
			</el-form>
		</div>
		<div slot="footer" class="dialog-footer">
			<el-button @click="handleCancel">取 消</el-button>
			<el-button type="primary" @click="submit">确 定</el-button>
		</div>
	</el-dialog>
</template>

<script>
	export default{
		name:'addeditMobiel',
		props:{
			modalTitle:{
				type:String
			},
			modalVisible:{
				type:Boolean
			},
			action:{
				type:String
			},
			editData:{
				type:Object,
				default:null
			}
		},
		watch:{
			modalTitle(newVal,oldVal){
				this.config.modalTitle = newVal
			},
			modalVisible(newVal,oldVal){
				this.config.modalVisible = newVal
			},
			action(newVal,oldVal){
				this.config.action = newVal
			},
			editData(newVal,oldVal){
				console.log(newVal)
				this.editDatas = newVal
			}
		},
		data(){
			return{
				config:{
					formLabelWidth:"520px",
					modalVisible:this.modalVisible,
					modalTitle:'角色管理',
					action:this.action
				},
				editDatas:null,
				rules:{
					name:[
						 { required: true, message: '角色名字不能为空!', trigger: 'blur' }
					],
					description:[
						{ required: true, message: '角色描述不能为空!', trigger: 'blur' }
					]
				},
				form:{}
			}
		},
		created(){
			if(this.config.action == 'edit'){
				console.log(this.editData)
				this.form = Object.assign({},this.editData)
			}
		},
		methods:{
			submit(){
				switch(this.config.action){
					case 'add':
						this.add()
						break;
					case 'edit':
						this.edit()
						break;
					default:
						break;
				}
			},
			add(){
				this.$refs.from.validate((valid) => {
					if (valid) {
						let params = this.form
						this.$port.addRole(params).then(res => {
							if(!res.code){
								this.config.modalVisible = false
								this.$emit('closeModal', true);
							}
						})
					}else {
						return false;
					}
				})
			},
			edit(){
				this.$refs.from.validate((valid) => {
					if (valid) {
						let params = {}
						params.id = this.form.id
						params.name = this.form.name
						params.description = this.form.description
						this.$port.updateRoleItem(params).then(res => {
							if(!res.code){
								this.config.modalVisible = false
								this.$emit('closeModal', true);
							}
						})
					}else {
						return false;
					}
				})
			},
			handleCancel(){
				this.config.modalVisible = false
				this.$emit('closeModal',false)
			}
		},
	}
</script>

<style>
</style>
