<template>
	<!-- 顶部导航栏 -->
	<custom-nav-bar :left="true" leftText="" @leftClick="" title="新增用户">
	</custom-nav-bar>
	
	<view class="create-container">
		<u--form labelPosition="left" :model="userForm" :rules="rules" ref="form">
			<u--image class="avatar" @click="onAvatarClick" :src="userForm.avatar?userForm.avatar:avatar" width="80px" height="80px"
				shape="circle" />
			<u-line color="#D2D2D2"></u-line>
			<u-form-item class="form-item" label="所属公司" prop="companyShortName" labelWidth="100px" required>
				<u--input v-model.trim="userForm.companyShortName" border="none" placeholder="" disabled class="custom-input"></u--input>
			</u-form-item>
			<u-line color="#D2D2D2"></u-line>
			<u-form-item class="form-item" label="用户姓名" prop="userName" labelWidth="100px" required>
				<u--input v-model.trim="userForm.userName" border="none" placeholder="请输入用户姓名" class="custom-input"></u--input>
			</u-form-item>
			<u-line color="#D2D2D2"></u-line>
			<u-form-item class="form-item" label="用户账号" prop="loginName" labelWidth="100px" required>
				<u--input v-model.trim="userForm.loginName" border="none" placeholder="请输入用户账号"
					maxlength="20" class="custom-input"></u--input>
			</u-form-item>
			<u-line color="#D2D2D2"></u-line>
			<u-form-item class="form-item" label="用户密码" v-show="!editFlag" prop="password" labelWidth="100px" required>
				<u--input v-model="userForm.password" border="none" password clearable placeholder="请输入用户密码" class="custom-input"></u--input>
			</u-form-item>
			<u-line color="#D2D2D2"></u-line>

			<u-form-item class="form-item" label="手机号码" prop="mobilePhone" labelWidth="100px" required>
				<u--input v-model="userForm.mobilePhone" border="none" type="number" maxlength="11"
					placeholder="请输入手机号码" class="custom-input"></u--input>
			</u-form-item>
			<u-line color="#D2D2D2"></u-line>
			<u-form-item class="form-item" label="用户性别" labelWidth="100px">
				<u-radio-group @change="onSexChange" v-model="userForm.sex">
					<u-radio activeColor="green" shape="square" :customStyle="{ marginRight: '50px' }" label="男"
						:name="0" />
					<u-radio activeColor="green" shape="square" :customStyle="{ marginRight: '50px' }" label="女"
						:name="1" />
				</u-radio-group>
			</u-form-item>
			<u-line color="#D2D2D2"></u-line>
			<u-form-item class="form-item" label="用户状态" labelWidth="100px">
				<u-radio-group @change="onStatusChange" v-model="userForm.status">
					<u-radio activeColor="green" shape="square" :customStyle="{ marginRight: '50px' }" label="启用"
						:name="0" />
					<u-radio activeColor="green" shape="square" label="禁用" :name="1" />
				</u-radio-group>
			</u-form-item>
			<u-line color="#D2D2D2"></u-line>
			<u-form-item class="form-item" label="临时账号" labelWidth="100px">
				<u-radio-group @change="onTempUserStatusChange" v-model="userForm.tempUserStatus">
					<u-radio activeColor="green" shape="square" :customStyle="{ marginRight: '50px' }" label="是"
						:name="0" />
					<u-radio activeColor="green" shape="square" label="否" :name="1" />
				</u-radio-group>
			</u-form-item>
			<u-line color="#D2D2D2"></u-line>
			<u-form-item class="form-item" label="用户角色" prop="roleName" labelWidth="100px" required >
				<u--input style=" background: white"  v-model="userForm.roleName"
					border="none" disabled placeholder="请选择角色" suffixIcon="arrow-right" class="custom-input" @click="onRolesOpen"></u--input>
			</u-form-item>
		</u--form>
		<u-action-sheet :show="showRoles" :actions="rolesActions" title="用户角色" description="" @close="showRoles = false"
			@select="onRolesSelect"></u-action-sheet>

		<view class="buttons">
			<u-button type="success" @click="submit">确认</u-button>
			<u-button @click="cancel">取消</u-button>
		</view>
	</view>
</template>

<script>
	import store from "@/store"
	import plugin from "@/plugins"
	// 默认头像
	import avatar from "../../../static/images/mine/userAvatar.png"
	export default {
		data() {
			return {
				form: null,
				showRoles: false,
				rolesActions: [],
				userForm: {},
				companyObj:{},
				avatar:"",
				rules: {
					avatar: {
						type: "string",
						required: true,
						message: "请上传图像",
						trigger: ["change"]
					},
					userName: [{
							type: "string",
							required: true,
							message: "请填写用户姓名",
							trigger: ["blur", "change"]
						},
						{
							min: 2,
							max: 20,
							message: "长度在2-20个字符之间"
						}
					],
					loginName: [{
							type: "string",
							required: true,
							message: "请输入用户账号",
							trigger: ["blur", "change"]
						},
						{
							pattern: /^[0-9a-zA-Z]*$/g,
							// 正则检验前先将值转为字符串
							transform(value) {
								return String(value)
							},
							message: "只能包含字母或数字"
						},
						{
							min: 5,
							max: 20,
							message: "长度在5-20个字符之间"
						}
					],
					password: [{
							type: "string",
							required: true,
							message: "请输入用户密码",
							trigger: ["blur", "change"]
						},
						{
							min: 5,
							max: 20,
							message: "长度在5-20个字符之间"
						}
					],
					mobilePhone: [{
						type: "string",
						required: true,
						len: 11,
						message: "请输入11位手机号码",
						trigger: ["blur", "change"]
					}],
					roleName: {
						type: "string",
						required: true,
						message: "请选择用户角色",
						trigger: ["change"]
					}
				},
				editFlag: false
			}
		},
		created() {
			this.reset();
			this.getRolesList();
		},
		onLoad(options) {
			this.avatar = avatar;
			uni.$on("setAvatar", function(options) {
				user.value.avatar = options
			})
			// 判断是否从用户列表的编辑过来的
			if (options.edit) {
				this.editFlag = true;
				this.getUserInfo(options.id);
				uni.setNavigationBarTitle({
					title: "修改用户"
				})
			} else {
				this.companyObj = JSON.parse(decodeURIComponent(options.companyObj));
				this.userForm.companyId =this.companyObj.rootCompanyId; 
				this.userForm.companyGroupId = this.companyObj.companyId;
				this.userForm.companyShortName = this.companyObj.companyFullName;
			}
		},
		methods: {
			getUserInfo(userId) {
				if (!this.editFlag) return
				//获取用户列表
				store
					.dispatch("getUser", userId)
					.then(res => {
						this.userForm = res.data;
						this.userForm.status = parseInt(res.data.status) ;
						if(res.data.role){
							this.userForm.roleId = res.data.role.roleId;
							this.userForm.roleName = res.data.role.roleName;
						}
						if(res.data.companyGroup){
							this.userForm.companyShortName = res.data.companyGroup.companyFullName;
						}
					})
					.catch(error => {
						plugin.modal.msgError("获取准备修改的用户的信息失败," + error)
					})
					.finally(() => {
						plugin.modal.closeLoading()
					})
			},
			getRolesList() {
				store
					.dispatch("getRoleList")
					.then(res => {
						this.rolesActions = res.data.map(item => {
							return {
								name: item.roleName,
								id: item.roleId
							}
						})
						// 只有在不是编辑的情况下默认角色是使用者,否则等这个api返回来的时候可能会无意修改了用户的角色
						if (!this.editFlag) {
							let defaultRole = this.rolesActions.find(item => item.name.indexOf("使用者") != -1)
							if (defaultRole) {
								this.userForm.roleId = defaultRole.id
								this.userForm.roleName = defaultRole.name
							}
						}
					})
					.catch(error => {
						plugin.modal.msgError("获取角色数据失败," + error)
					})
					.finally(() => {
						plugin.modal.closeLoading()
					})
			},
			reset() {
				this.userForm = {
					userId: null,
					companyId: null,
					companyGroupId: null,
					loginName: null,
					password: null,
					userName: null,
					userType:1,
					mobilePhone: null,
					tempUserStatus:1,
					expirationTime: null,
					avatar: null,
					sex:0,
					status:0,
					remark: "",
					postIds: [],
					roleId: null,
					roleIds: null,
					companyShortName: ""
				};
			},
			onSexChange(e) {
				this.userForm.sex = e;
			},
			onStatusChange(e) {
				this.userForm.status = e;
			},
			onAvatarClick() {
				if(!this.userForm.avatar){
					this.userForm.avatar = avatar;
				}
				plugin.tab.navigateTo(
					`/pages/mine/avatar/index?userId=${this.userForm.userId}&avatar=${this.userForm.avatar}`
				)
			},
			onRolesSelect(e) {
				this.userForm.roleId = e.id;
				this.userForm.roleName = e.name;
			},
			onRolesOpen() {
				this.showRoles = true;
			},
			onTempUserStatusChange(e) {
				this.userForm.tempUserStatus = e;
			},
			submit() {
				//编辑用户信息
				this.userForm.roleIds=[];
				this.userForm.roleIds.push(this.userForm.roleId);
				if (this.editFlag) {
					this.userForm.password = "888888";
					this.$refs["form"]
						.validate()
						.then(res => {
							this.updateUserInfo();
						})
						.catch(errors => {
							uni.$u.toast("请补充用户信息")
						})
				} else {
					console.log(this.userForm)
					// 新增用户
					this.$refs["form"]
						.validate()
						.then(res => {
							store.dispatch("addUser", this.userForm).then(res => {
								plugin.modal.showToast("用户添加成功")
								plugin.tab.navigateBack()
							})
						})
						.catch(errors => {
							uni.$u.toast("请补充用户信息")
						})
				}
			},
			updateUserInfo() {
				this.userForm.password = "";
				store
					.dispatch("updateUser", this.userForm)
					.then(res => {
						plugin.modal.showToast("用户信息修改成功")
						plugin.tab.navigateBack()
					})
					.catch(error => {
						plugin.modal.msgError("用户修改信息失败," + error)
					})
					.finally(() => {
						plugin.modal.closeLoading()
					})
			},
			cancel() {
				plugin.tab.navigateBack();
			}
		}
	}
</script>
<style lang="scss">
	.create-container {
		background-color: #FFF;
		.custom-input {
		  width: 280px;
		}
		.avatar {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 20px;
		}

		.form-item {
			width: 100%;
			margin-left: 20px;
			display: flex;
			justify-content: center;
			align-items: flex-start;
		}

		.buttons {
			margin: 10px 50px;
			display: flex;
			justify-content: space-between;

			button {
				margin: 0px 20px;
			}
		}
	}
</style>