<template>
	<div class="hui-flex hui-dialog">
		<div class="hui-flex-box hui-dialog-content">
			<el-form :model="userForm" :rules="userRulers" ref="userForm" label-position="top">
				<el-alert title="该账号已存在,请直接保存" show-icon type="success" :closable="false" v-if="alertShow"
					style="margin-bottom: 10px;"></el-alert>
				<el-form-item label="手机号" prop="phone">
					<el-input v-model="userForm.phone" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="姓名" prop="name" v-if="show">
					<el-input v-model="userForm.name" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="性别" v-if="show">
					<el-radio-group v-model="userForm.sex">
						<el-radio label="M">男</el-radio>
						<el-radio label="W">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="邮箱" v-if="show">
					<el-input v-model="userForm.email"></el-input>
				</el-form-item>
			</el-form>
		</div>
		<div class="hui-dialog-submit">
			<el-button size="medium" @click="$emit('callback')">取 消</el-button>
			<el-button size="medium" type="primary" @click="submit">保 存</el-button>
		</div>
	</div>
</template>

<script>
	import {
		insertUser,
		testPhone,
		bindProject
	} from '@/httpApi/organization'
	export default {
		props: ['part'],
		data() {
			return {
				userForm: {
					name: '',
					sex: 'M',
					phone: '',
					email: ''
				},
				userRulers: {
					name: [{
						required: true,
						message: '请输入姓名',
						trigger: 'blur'
					}],
					phone: [{
						required: true,
						message: '请输入手机号',
						trigger: 'blur'
					}, {
						validator: (rule, value, callback) => {
							if (!/^1[123456789]\d{9}$/.test(value)) {
								callback(new Error("请输入正确的手机号"));
							} else {
								testPhone(value).then(data => {
									this.show = !data.data;
									this.alertShow = !this.show;
									callback()
								})
							}
						},
						trigger: 'blur'
					}],
				},
				show: false,
				alertShow: false
			}
		},
		methods: {
			submit() {
				this.$nextTick(() => {
					this.$refs.userForm.validate(valid => {
						if (valid) {
							insertUser(this.$store.getters.organization.id, this.part.id, this.userForm)
								.then(res => {
									if (res.state) {
										bindProject({
											organizationId: this.$store.getters.organization
												.id,
											projectId: this.$store.getters.project.id,
											userId: res.data.id,
											identityId: 3
										}).then(res => {
											if (res.state) {
												this.$emit('callback', 'init');
												this.$message.success('操作成功');
											}
										})

									}
								})
						} else {
							return false;
						}
					});
				});
			}
		}
	}
</script>