<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="600" destroy-on-close @closed="$emit('closed')" :close-on-click-modal="false">
		<el-form :model="form" :rules="rules" :disabled="mode==='show'" ref="dialogForm" label-width="100px" label-position="right">
			<el-form-item label="机构名称" prop="org_name">
				<el-input v-model="form.org_name" clearable></el-input>
			</el-form-item>
			<el-form-item label="联系人" prop="contact_name">
				<el-input v-model="form.contact_name" clearable></el-input>
			</el-form-item>
			<el-form-item label="手机号" prop="contact_mobile">
				<el-input v-model="form.contact_mobile" clearable></el-input>
			</el-form-item>
			<el-form-item label="登录密码" prop="password">
				<el-input type="password" v-model="form.password" clearable show-password></el-input>
			</el-form-item>
			<el-form-item label="状态" prop="status">
				<el-radio-group v-model="form.status">
					<el-radio :value="1">正常</el-radio>
					<el-radio :value="0">关闭</el-radio>
				</el-radio-group>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false" >取 消</el-button>
			<el-button v-if="mode!=='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>

export default {
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增',
				edit: '编辑',
				show: '查看'
			},
			visible: false,
			isSaveing: false,
			tenant_id: 0,
			//表单数据
			form: {
				org_id: 0,
				org_name: "",
				contact_name: "",
				contact_mobile: "",
				password: "",
				status: 1,
			},
			//验证规则
			rules: {
				org_name: [
					{required: true, message: '请输入租户名称', trigger: 'change'}
				],
				contact_name: [
					{required: true, message: '请输入联系人姓名', trigger: 'change'}
				],
				contact_mobile: [
					{required: true, message: '请输入联系人手机号', trigger: 'change'}
				],
				status: [
					{required: true, message: '请设置租户状态', trigger: 'change'}
				]
			}
		}
	},
	methods: {
		//显示
		open(mode='add'){
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		async submit(){
			// 校验登录
			const validate = await this.$refs.dialogForm.validate().catch(() => {});
			if(!validate){ return false }
			if (this.form.password) this.form.password = this.$TOOLS.crypto.MD5(this.form.password)

			this.isSaveing = true;
			const [res, err] = this.form.org_id ? await this.$TOOLS.go(this.$API.tenant.org.edit(this.form)) : await this.$TOOLS.go(this.$API.tenant.org.add(this.form));
			if (err) {
				this.isSaveing = false;
				return false;
			}
			this.isSaveing = false;
			this.$emit('success')
			this.visible = false;
			this.$message.success(res.msg)
		},
		async setData(data){
			Object.assign(this.form, data)
		},
	}
}
</script>

<style>
</style>
