<!-- 用户新增修改弹框 -->
<template>
	<div class='consumerDialog'>
		<el-dialog title="" :show-close="false" :append-to-body="true" :close-on-click-modal="false" :close-on-press-escape="false" :lock-scroll="true" :visible.sync="dialogConsumerVisible">
			<div slot="title" class="header-title">
				<span class="dialogHeader">{{doName}}</span>
				<img @click="closeDialog('createForm')" class="dialogHeaderClose" src="../assets/images/dialogClose.png" />
			</div>
			<div class="">
					<div class="elDiv">
						<el-form :model="createForm" :rules="rules" ref="createForm" label-width="130px" class="demo-ruleForm">
							<!--<div class="detailTop">-->
								<!--<div class="imgAndName">-->


								<!--</div>-->
							<!--</div>-->
							<el-row :gutter="100">
								<el-col :span="12">
									<div class="imgDiv">
										<img class="pic" src="../assets/images/photoDefault.png"/>
										<img v-show="createForm.status === '2'" class="statusImg" src="../assets/images/statusBusy.png"/>
										<img v-show="createForm.status === '1'" class="statusImg" src="../assets/images/statusNormal.png"/>
										<img v-show="createForm.status === '0'" class="statusImg" src="../assets/images/statusIdle.png"/>
									</div>
									<el-form-item class="leftFirst" label="身份证" prop="idCard">
										<el-input v-model="createForm.idCard" placeholder="请输入身份证"></el-input>
									</el-form-item>
									<el-form-item class="first" label="电话1" prop="phone1">
										<el-input v-model.number="createForm.phone1" autocomplete="off" placeholder="请输入电话"></el-input>
									</el-form-item>
									<el-form-item class="first selectStyle" label="部门" prop="departmentIds">
										<el-select style="width: 100%;" v-model="createForm.departmentIds" multiple placeholder="请选择">
											<el-option
															v-for="item in departmentList"
															:key="item.id"
															:label="item.name"
															:value="item.id">
											</el-option>
										</el-select>
										<!--<el-select v-model="selectTree" placeholder="请选择" multiple collapse-tags @change="selectChange">-->
											<!--<el-option  :value="createForm.departmentIds" style="height: auto">//option展开高度太小，把height设置为auto就好啦-->
												<!--<el-tree :data="deOptions" show-checkbox node-key="id" ref="tree" highlight-current :props="defaultProps" @check-change="handleCheckChange"></el-tree>-->
											<!--</el-option>-->
										<!--</el-select>-->
									</el-form-item>
									<el-form-item class="first" label="地址" prop="address">
										<el-input v-model="createForm.address" placeholder="请输入地址"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<div class="nameDiv">
										<el-form-item class="first" label="姓名" prop="username">
											<el-input v-model="createForm.username" placeholder="请输入姓名"></el-input>
										</el-form-item>
										<el-form-item class="" label="岗位" prop="jobs">
											<el-input v-model="createForm.jobs" placeholder="请输入岗位"></el-input>
										</el-form-item>
									</div>
									<el-form-item class="rightFirst" prop="email" label="邮箱">
										<el-input v-model="createForm.email" placeholder="请输入邮箱"></el-input>
									</el-form-item>
									<el-form-item class="first" label="电话2" prop="phone2">
										<el-input v-model="createForm.phone2" placeholder="请输入电话"></el-input>
									</el-form-item>
									<el-form-item label="角色" class="first" prop="roles">
										<el-select style="width: 100%;" v-model="createForm.roles" @change="roleChange" multiple placeholder="请选择角色">
											<el-option
															v-for="item in roleLists"
															:key="item.id"
															:label="item.name"
															:value="item.id"
															:disabled="item.disabled">
											</el-option>
										</el-select>
									</el-form-item>
									<el-form-item class="first" label="入职时间" prop="entryTime">
										<el-date-picker value-format="yyyy-MM-dd" type="date" placeholder="请选择入职时间" v-model="createForm.entryTime" style="width: 100%;"></el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form>
					</div>
				<div class="btnStyle">
					<el-button type="primary" @click="submitForm('createForm')">保存</el-button>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
	//例如：import 《组件名称》 from '《组件路径》';

	export default {
		name: "consumerDialog",
//import引入的组件需要注入到对象中才能使用
		components: {},
		props: ['showConsumerDialog', 'editConsumer', 'doName', 'roleList', 'departmentList'],
		data () {
			let checkPhone1 = (rule, value, callback) => {
				const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/;
				console.log(value)
				if (value !== '') {
					console.log(value)
					if (phoneReg.test(value)) {
						callback()
					} else {
						callback(new Error('电话1号码格式不正确'))
					}
				} else {
					return callback(new Error('电话1号码不能为空'))
				}
			};
			let checkPhone2 = (rule, value, callback) => {
				const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/;
				console.log(value)
				if (value !== '') {
					console.log(value)
					if (phoneReg.test(value)) {
						callback()
					} else {
						callback(new Error('电话2号码格式不正确'))
					}
				} else {
					return callback(new Error('电话2号码不能为空'))
				}
			};
//这里存放数据
			return {
				dialogConsumerVisible: false,
				roleLists: [],
				// deOptions: [],
				selectTree: '',
				createForm: {
					username: '',
					phone1: '',
					phone2: '',
					idCard: '',
					address: '',
					jobs: '',
					departmentIds: [],
					email: '',
					entryTime: '',
					roles: []
				},
				rules: {
					username: [
						{required: true, message: '请输入姓名', trigger: 'blur'},
					],
					phone1: [
						{required: true, validator: checkPhone1, trigger: 'blur'}
					],
					phone2: [
						{required: true, validator: checkPhone2, trigger: 'blur'}
					],
					idCard: [
						{required: true, message: '请填写证件号码', trigger: 'blur'},
						{
							pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
							message: '证件号码格式有误！',
							trigger: 'blur'
						}
					],
					address: [
						{required: true, message: '请输入地址', trigger: 'blur'},
					],
					jobs: [
						{required: true, message: '请输入岗位', trigger: 'blur'},
					],
					departmentIds: [
						{type: 'array', required: true, message: '请选择部门', trigger: 'change'}
						// { required: true, message: '请输入部门1', trigger: 'blur' },
					],
					email: [
						{required: true, message: '请输入邮箱地址', trigger: 'blur'},
						{type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
					],
					entryTime: [
						{required: true, message: '请选择入职时间', trigger: 'change'}
					],
					roles: [
						{type: 'array', required: true, message: '请选择角色', trigger: 'change'},
					],
				}
			}
		},
//监听属性 类似于data概念
		computed: {},
//监控data中的数据变化
		watch: {
			showConsumerDialog:{
				immediate: true,
				handler(showConsumerDialog) {
					this.dialogConsumerVisible = showConsumerDialog;
				}
			},
			roleList: {
				handler(val) {
					console.log(val)
					this.roleLists = val;
				}
			},
			editConsumer: {
				handler(editConsumer) {
					if (JSON.stringify(editConsumer) !== '{}') {
						let data = JSON.parse(JSON.stringify(editConsumer));
						let roles = [];
						data.roles.forEach((v, i) => {
							roles.push(v.id);
						})
						if (roles.length === 0) {
							roles = [''];
							this.roleChange(roles)
						}
						data.roles = roles;
						this.createForm = data;
					}
				}
			}
		},
//方法集合
		methods: {
			closeDialog(formName, val) {
				this.$refs[formName].resetFields();
				this.createForm.username = '';
				this.createForm.phone1 = '';
				this.createForm.phone2 = '';
				this.createForm.idCard = '';
				this.createForm.address = '';
				this.createForm.jobs = '';
				this.createForm.departmentIds = [];
				this.createForm.email = '';
				this.createForm.entryTime = '';
				this.createForm.roles = [];
				this.$emit('close', val);
			},
			// selectChange(e){
			// 	var arrNew = [];
			// 	var dataLength = this.mineStatusValue.length;
			// 	var eleng = e.length;
			// 	for(let i = 0; i< dataLength ;i++){
			// 		for(let j = 0; j < eleng; j++){
			// 			if(e[j] === this.mineStatusValue[i].label){
			// 				arrNew.push(this.mineStatusValue[i])
			// 			}
			// 		}
			// 	}
			// 	this.$refs.tree.setCheckedNodes(arrNew);//设置勾选的值
			// },
			// handleCheckChange() {
			// 	let res = this.$refs.tree.getCheckedNodes(true, true); //这里两个true，1. 是否只是叶子节点 2. 是否包含半选节点（就是使得选择的时候不包含父节点）
			// 	let arrLabel = [];
			// 	let arr = [];
			// 	res.forEach(item => {
			// 		arrLabel.push(item.label);
			// 		arr.push(item);
			// 	});
			// 	this.mineStatusValue = arr;
			// 	this.mineStatus = arrLabel;
			// 	console.log('arr:'+JSON.stringify(arr))
			// 	console.log('arrLabel:'+arrLabel)
			// },
			submitForm(formName) {
				console.log(this.createForm)
				let obj = JSON.parse(JSON.stringify(this.createForm));
				console.log(obj.roles, this.roleLists)
				let newArr = [];
				if (obj.roles.length > 0 && obj.roles[0] !== '') {
					for (let i = 0; i < this.roleLists.length; i++) {
						for (let j = 0; j < obj.roles.length; j++) {
							if(obj.roles[j] === this.roleLists[i].id){
								newArr.push(this.roleList[i]);
							}
						}
					}
					console.log(newArr)
					obj.roles = newArr;
				} else {
					obj.roles =null;
				}
				obj.phone1 = obj.phone1 + '';
				obj.phone2 = obj.phone2 + '';
				console.log(obj)
				this.$refs[formName].validate((valid) => {
					if (valid) {
						console.log(this.doName)
						if (this.doName === '修改用户') {
							this.$axios.putUsers(obj).then((res) => {
								console.log(res)
								this.$message({
									message: `${this.doName}成功!`,
									type: 'success'
								});
								this.$refs[formName].resetFields();
								this.closeDialog('createForm', this.doName);
							})
						} else {
							this.$axios.postUser(obj).then((res) => {
								console.log(res)
								this.$message({
									message: `${this.doName}成功!`,
									type: 'success'
								});
								this.$refs[formName].resetFields();
								this.closeDialog('createForm', this.doName);
							})
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			roleChange(val) {
				console.log(val)
				console.log(val[0]);
				let data = JSON.parse(JSON.stringify(this.roleLists));
				console.log(data)
				if (val.length > 0) {
					if (val[0] !== '') {
						data.forEach((v, i) => {
							if (v.id !== '') {
								v.disabled = false;
							} else {
								v.disabled = true;
							}
						})
					} else {
						data.forEach((v, i) => {
							if (v.id !== '') {
								v.disabled = true;
							} else {
								v.disabled = false;
							}
						})
					}
				} else {
					data.forEach((v, i) =>{
						v.disabled = false;
					})
				}
				this.roleLists = data;
			},
		},
//生命周期 - 创建完成（可以访问当前this实例）
		created () {

		},
//生命周期 - 挂载完成（可以访问DOM元素）
		mounted () {
		},
		beforeCreate () {
		}, //生命周期 - 创建之前
		beforeMount () {
		}, //生命周期 - 挂载之前
		beforeUpdate () {
		}, //生命周期 - 更新之前
		updated () {
		}, //生命周期 - 更新之后
		beforeDestroy () {
		}, //生命周期 - 销毁之前
		destroyed () {
		}, //生命周期 - 销毁完成
		activated () {
		}, //如果页面有keep-alive缓存功能，这个函数会触发
	}
</script>
<style scoped>
	.detailTop{
		height: 230px;
		margin-top: 20px;
		/*line-height: 320px;*/
	}

	.leftFirst{
		margin-top: 80px;
	}

	.first{
		margin-top: 40px;
	}

	.rightFirst{
		margin-top: 40px;
	}

	.imgAndName{
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.imgDiv{
		margin-left: 100px;
		width: 215px;
		height: 160px;
		background-image: url("../assets/images/personPhoto.png");
		background-repeat: no-repeat;
		background-size: 100% 100%;
		margin-right: 90px;
		position: relative;
	}

	.imgDiv .pic{
		width: 155px;
		margin: 30px 0 0 30px;
	}

	.imgDiv .statusImg{
		width: 45px;
		position: absolute;
		top: 0px;
		right: 0px;
	}

	.nameDiv{
		height: 155px;
		text-align: center;
	}

	.nameStyle{
		color: #5059D5;
		font-size: 30px;
	}

	.jobStyle{
		color: #19152C;
		font-size: 20px;
		margin-top: 30px;
	}

	.elDiv{
		margin: 40px 100px 20px 100px;
	}

	.elDiv li{
		height: 40px;
		margin-top: 50px;
		font-size: 18px;
	}

	.titleDiv{
		color: #787682;
	}

	.contentDiv{
		color: #19152c;
		margin-top: 5px;
		font-weight: bold;
	}

	.btnStyle{
		text-align: center;
		margin-top: 50px;
	}

	/deep/ .el-input__inner{
		border-color: #a8acea;/*no*/
		font-size: 18px;
	}

	/deep/ .el-input__inner:hover {
		border-color: #5059d5;
	}

	/deep/ .el-input.is-active .el-input__inner, .el-input__inner:focus {
		border-color: #5059d5;
		outline: 0;
	}

	/deep/ .el-textarea__inner{
		border-color: #a8acea;
	}

	/deep/ .el-textarea__inner:hover {
		border-color: #5059d5;
	}

	/deep/ .el-textarea__inner:focus {
		outline: 0;
		border-color: #5059d5;
	}

	/deep/ .el-form-item__label {
		text-align: right;
		/*width: 120px !important;*/
		font-size: 18px;
		line-height: 40px;
		color: #787682;
	}

	/deep/ .el-form-item__content {
		line-height: 40px;
		font-size: 18px;
		color: #19152c;
	}
.selectStyle /deep/ .el-input__inner {
	background-color: #FFF;
	background-image: none;
	border-radius: 20px; /*no*/
	border: 1px solid #a8acea; /*no*/
	-webkit-box-sizing: border-box;
	box-sizing: border-box;
	color: #606266;
	display: inline-block;
	font-size: 18px;
	height: 40px;
	line-height: 40px;
	outline: 0;
	padding: 0 15px;
	-webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);
	transition: border-color .2s cubic-bezier(.645,.045,.355,1);
	width: 100%;
}

	/deep/ .el-tag--small {
		height: 26px;
		padding: 0 10px;
		border-radius: 20px;
		line-height: 26px;
		font-size: 16px;
	}

	/deep/ .el-tag .el-icon-close {
		font-size: 16px;
		height: 16px;
		width: 16px;
		line-height: 16px;
		vertical-align: middle;
		top: -1px;
		right: -5px;
	}
</style>
