<!-- 用户管理详情 -->
<template>
	<div class='consumerDetails'>
		<div style="">
			<el-row :gutter="20">
				<el-col :span="5">
					<div class="leftImg">
						<img src="../assets/images/xq-tx-1.png"/>
						<!--<img src="../assets/images/xq-tx-2.png"/>-->
					</div>
				</el-col>
				<el-col :span="19">
					<div>
						<el-form :model="userForm" :rules="rules" ref="userForm" 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="userForm.username"></el-input>
									</el-form-item>
									<el-form-item class="first" label="身份证" prop="idCard">
										<el-input v-model="userForm.idCard"></el-input>
									</el-form-item>
									<el-form-item class="first" prop="email" label="邮箱">
										<el-input v-model="userForm.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="userForm.phone1" autocomplete="off"></el-input>
									</el-form-item>
									<el-form-item class="first" label="地址" prop="address">
										<el-input v-model="userForm.address"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item class="first" label="电话2" prop="phone2">
										<el-input v-model="userForm.phone2"></el-input>
									</el-form-item>
									<el-form-item class="first" label="入职时间" prop="entryTime">
										<el-date-picker type="date" placeholder="选择日期" v-model="userForm.entryTime" style="width: 100%;"></el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
							<div class="roleDiv first" style="width: 100%;">
								<el-form-item class="first" label="部门" prop="departmentIds">
									<!--<el-input v-model="userForm.departmentId"></el-input>-->
									<el-select v-model="userForm.departmentIds" multiple placeholder="请选择">
										<el-option
														v-for="item in deOptions"
														:key="item.id"
														:label="item.name"
														:value="item.id">
										</el-option>
									</el-select>
								</el-form-item>
								<el-form-item class="first" label="岗位" prop="job">
									<el-input v-model="userForm.jobs"></el-input>
								</el-form-item>
								<el-form-item label="角色" prop="roles">
									<el-select v-model="userForm.roles" @change="roleChange" multiple placeholder="请选择角色">
										<el-option
														v-for="item in roleList"
														:key="item.id"
														:label="item.name"
														:disabled="item.disabled"
														:value="item.id">
										</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: 45%;">
			<el-button type="primary" @click="submitForm('userForm')" style="margin-right: 30px;">修改</el-button>
			<el-button type="primary" @click="deleteUSer('userForm')">删除</el-button>
		</div>
	</div>
</template>

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

	export default {
		name: "ConsumerDetails",
//import引入的组件需要注入到对象中才能使用
		components: {},
		data () {
			var checkPhone = (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('电话号码格式不正确'))
					}
				} else {
					callback()
				}
			};
//这里存放数据
			return {
				paramsData: '',
				userForm:{
					username: '',
					phone1: '',
					phone2: '',
					idCard: '',
					address: '',
					jobs: '',
					departmentId: '',
					// department2: '',
					// department3: '',
					email: '',
					entryTime: '',
					roles: [],
				},
				rules:{
					username: [
						{ required: true, message: '请输入用户名', trigger: 'blur' },
					],
					phone1: [
						{required: true, validator: checkPhone, trigger: 'blur' }
					],
					phone2: [
						{required: true, validator: checkPhone, 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' },
					],
					departmentId: [
						{ 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: [],
				deOptions: []
			};
		},
//监听属性 类似于data概念
		computed: {},
//监控data中的数据变化
		watch: {},
//方法集合
		methods: {
			getRoles() {
				this.$axios.getRole().then((res) => {
					console.log(res.data)
					if (res.request.status === 200) {
						let obj = {authorities:[],
							departmentId: '',
							description: "",
							id: "",
							isLeader: "",
							name: "无"}
						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;
					}
				})

			},
			submitForm(formName) {
				console.log(this.userForm)
				this.$refs[formName].validate((valid) => {
					if (valid) {
						console.log(this.userForm)
						let obj = JSON.parse(JSON.stringify(this.userForm));
						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.putUsers(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;
							}
						});
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			deleteUSer(formName) {
				this.$axios.deleteUsers(this.userForm.id).then((res) => {
					console.log(res);
					if (res.request.status === 200) {
						this.$message({
							message: '删除用户成功!',
							type: 'success'
						});
						this.$refs[formName].resetFields();
						this.$router.push({name: 'consumerManage'});
					}
				})
			},
			roleChange(val) {
				console.log(val)
				console.log(val[0]);
				let data = JSON.parse(JSON.stringify(this.roleList));
				if (val.length > 0) {
					console.log(111)
					if (val[0] !== '') {
						data.forEach((v, i) => {
							// console.log(v)
							if (v.id !== '') {
								v.disabled = false;
							} else {
								v.disabled = true;
							}
						})
					} else {
						data.forEach((v, i) => {
							// console.log(v)
							if (v.id !== '') {
								v.disabled = true;
							} else {
								v.disabled = false;
							}
						})
					}
				} else {
					data.forEach((v, i) =>{
						v.disabled = false;
					})
				}
				console.log(data)
				this.roleList = JSON.parse(JSON.stringify(data));
			}
		},
//生命周期 - 创建完成（可以访问当前this实例）
		created () {

		},
//生命周期 - 挂载完成（可以访问DOM元素）
		mounted () {
			this.getRoles();
			this.postDepartmentList();
			let that = this;
			setTimeout(function () {
				console.log(that.$Base64.decode(localStorage.getItem('adminUser')))
				let data = JSON.parse(that.$Base64.decode(localStorage.getItem('adminUser')));
				console.log(data)
				that.userForm = data;
				let roles = [];
				data.roles.forEach((v, i) => {
					roles.push(v.id);
				})
				if (roles.length === 0) {
					roles = [''];
					that.roleChange(roles)
				}
				that.userForm.roles = roles;
			}, 300)
		},
		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;
	}
</style>
