<!-- 新增用户 -->
<template>
	<div class='createConsumer'>
		<div style="">
			<el-row :gutter="20">
				<el-col :span="5">
					<div class="leftImg">
						<!--<el-upload-->
										<!--style="margin-top: 50px;"-->
										<!--ref="uploads"-->
										<!--class="avatar-uploader"-->
										<!--action="https://jsonplaceholder.typicode.com/posts/"-->
										<!--:show-file-list="false"-->
										<!--:on-change="imgPreview"-->
										<!--:auto-upload="false">-->
							<!--&lt;!&ndash;:before-upload="beforeAvatarUpload"&ndash;&gt;-->
							<!--<img v-if="imageUrl" :src="imageUrl" class="avatar">-->
							<!--<i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
						<!--</el-upload>-->
						<img class="leftImgs" src="../assets/images/xq-tx-1.png"/>
					</div>
				</el-col>
				<el-col :span="19">
					<div>
						<el-form :model="createForm" :rules="rules" ref="createForm" label-width="100px" class="demo-ruleForm">
							<el-row :gutter="10">
								<el-col :span="8">
									<el-form-item class="first" label="姓名" prop="username">
										<el-input v-model="createForm.username"></el-input>
									</el-form-item>
									<el-form-item class="first" label="身份证" prop="idCard">
										<el-input v-model="createForm.idCard"></el-input>
									</el-form-item>
									<el-form-item class="first" prop="email" label="邮箱">
										<el-input v-model="createForm.email"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item class="first" label="电话1" prop="phone1">
										<el-input v-model.number="createForm.phone1" autocomplete="off"></el-input>
									</el-form-item>
									<el-form-item class="first" label="地址" prop="address">
										<el-input v-model="createForm.address"></el-input>
									</el-form-item>
									<!--<el-form-item class="first" label="部门2" prop="department2">-->
										<!--<el-input v-model="createForm.department2"></el-input>-->
									<!--</el-form-item>-->
									<!--<el-form-item class="first" label="入职时间" prop="entryTime">-->
										<!--<el-date-picker type="date" placeholder="选择日期" v-model="createForm.entryTime" style="width: 100%;"></el-date-picker>-->
									<!--</el-form-item>-->
								</el-col>
								<el-col :span="8">
									<el-form-item class="first" label="电话2" prop="phone2">
										<el-input v-model="createForm.phone2"></el-input>
									</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-form-item class="first" label="部门3" prop="department3">-->
										<!--<el-input v-model="createForm.department3"></el-input>-->
									<!--</el-form-item>-->
								</el-col>
							</el-row>
							<div class="roleDiv " style="width: 100%;">
								<el-form-item class="first" label="部门" prop="departmentIds">
									<el-select v-model="createForm.departmentIds" multiple placeholder="请选择">
										<el-option
														v-for="item in deOptions"
														:key="item.id"
														:label="item.name"
														:value="item.id">
										</el-option>
									</el-select>
									<!--<el-input v-model="createForm.department"></el-input>-->
									<!--<el-select v-model="createForm.department" placeholder="请选择"  collapse-tags @change="selectChange">-->
									<!--<el-option  :value="mineStatusValue" style="height: auto">-->
									<!--&lt;!&ndash;//option展开高度太小，把height设置为auto就好啦&ndash;&gt;-->
									<!--<el-tree :data="data" 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="jobs">
									<el-input v-model="createForm.jobs"></el-input>
								</el-form-item>
								<el-form-item label="角色" prop="roles">
									<el-select v-model="createForm.roles" @change="roleChange" multiple placeholder="请选择角色">
										<el-option
														v-for="item in roleList"
														:key="item.id"
														:label="item.name"
														:value="item.id"
														:disabled="item.disabled">
										</el-option>
									</el-select>
								</el-form-item>
							</div>
						</el-form>
					</div>
				</el-col>
			</el-row>
		</div>
		<div style="text-align: center;position: absolute;bottom: 40px;left: 49%;">
			<el-button type="primary" @click="submitForm('createForm')" style="margin-right: 30px;">保存</el-button>
		</div>
	</div>
</template>

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

	export default {
		name: "CreateConsumer",
//import引入的组件需要注入到对象中才能使用
		components: {},
		data () {
			var 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号码不能为空'))
				}
			};
			var 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 {
				imageUrl: '',
				file: '',
				createForm:{
					username: '',
					phone1: '',
					phone2: '',
					idCard: '',
					address: '',
					jobs: '',
					departmentIds: [],
					// department2: '',
					// department3: '',
					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' },
					],
					// department2: [
					// 	{ required: true, message: '请输入部门2', trigger: 'blur' },
					// ],
					// department3: [
					// 	{ required: true, message: '请输入部门3', 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' },
					],
				},
				roleList: [],
				mineStatus: "",
				mineStatusValue: [],
				data: [],
				defaultProps: {
					children: "departments",
					label: "name"
				},
				deOptions: [],
				disabledRole: false
			};
		},
//监听属性 类似于data概念
		computed: {},
//监控data中的数据变化
		watch: {},
//方法集合
		methods: {
			getRoles() {
				this.$axios.getRole().then((res) => {
					console.log(res.data)
					if (res.request.status === 200) {
						res.data.forEach((v, i) => {
							v.disabled = false;
						})
						let obj = {authorities:[],
							departmentId: '',
							description: "",
							id: "",
							isLeader: "",
							name: "无",
							disabled: false}
						res.data.push(obj)
						this.roleList = res.data;
					}
				})
			},
			postDepartmentList() {
				// this.$axios.postDepartmentList().then((res) => {
				// 	console.log(res)
				// 	if (res.request.status === 200) {
				// 		this.data = res.data;
				// 	}
				// })
				this.$axios.getAllDepartment().then((res) => {
					console.log(res)
					if (res.request.status === 200) {
						// this.data = res.data;
						this.deOptions = res.data;
					}
				})

			},
			imgPreview (file) {
				// this.$refs.uploads.clearFiles();
				console.log(file)
				// 图片显示前做一下判断
				const IMG_ALLOWD = ['jpeg', 'jpg', 'gif', 'png']
				const imgType = file.raw.type.split('/')[1]
				// 判断图片格式
				if (IMG_ALLOWD.indexOf(imgType) === -1) {
					this.$message.warning('上传图片格式错误')
					this.imageUrl = null;
				} else {
					// 成功
					this.file = file;
					this.imageUrl = URL.createObjectURL(file.raw)
				}
			},
			submitForm(formName) {
				console.log(this.createForm)
				let obj = JSON.parse(JSON.stringify(this.createForm));
				console.log(obj.roles, this.roleList)
				let newArr = [];
				if (obj.roles.length > 0 && obj.roles[0] !== '') {
					for (let i = 0; i < this.roleList.length; i++) {
						for (let j = 0; j < obj.roles.length; j++) {
							if(obj.roles[j] === this.roleList[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) {
						this.$axios.postUser(obj).then((res) => {
							console.log(res)
							this.$message({
								message: '新增用户成功!',
								type: 'success'
							});
							this.$refs[formName].resetFields();
							this.$router.push({name: 'consumerManage'});
						})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			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.createForm.department = arrLabel;
				console.log('arr:'+JSON.stringify(arr))
				console.log('arrLabel:'+arrLabel)
			},
			roleChange(val) {
				console.log(val)
				console.log(val[0]);
				let data = JSON.parse(JSON.stringify(this.roleList));
				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.roleList = data;
			}
		},
//生命周期 - 创建完成（可以访问当前this实例）
		created () {

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

	.leftImg{
		text-align: center;
	}

	/*.leftImg img{*/
		/*width: 300px;*/
		/*height: 420px;*/
		/*margin-top: 40px;*/
	/*}*/

	.roleDiv /deep/ .el-select {
		display: inline-block;
		position: relative;
		width: 100%;
	}

	.first {
		margin-top: 50px;
	}

	.leftImg /deep/ .avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}
	.leftImg /deep/ .avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}
	.leftImg /deep/ .avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 250px;
		height: 350px;
		line-height: 350px;
		text-align: center;
	}
	.leftImg /deep/ .avatar {
		width: 250px;
		height: 350px;
		display: block;
	}

	.leftImgs{
		margin-top: 100px;
		width: 295px;
		height: 413px;
	}
</style>
