<template>
    <el-dialog v-model="visible" title="添加用户" width="600px" @closed="handleClosed"
        destroy-on-close>
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" v-loading="loading"
            style="padding: 20px">
            <el-form-item label="用户名" prop="account">
                <el-input v-model="formData.account" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
            <el-form-item label="确认密码" prop="password2">
                <el-input v-model="formData.password2" type="password" placeholder="请再次输入密码" show-password />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
                <el-input v-model="formData.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="formData.phone" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="formData.status">
                    <el-radio :label="1">启用</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" :loading="submitting" @click="submitForm">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
/**
 * 租户详情内「添加用户」：提交到 /platform/tenantUser/create，
 * 后端写入 yz_tenant_user（租户-用户绑定，含冗余账号/密码等字段）。
 */
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { addUser } from '@/api/user';

const emit = defineEmits(['success']);
const visible = ref(false);
const loading = ref(false);
const submitting = ref(false);
const formRef = ref();
const currentTenantId = ref<number | null>(null);

const formData = reactive({
    account: '',
    password: '',
    password2: '',
    name: '',
    phone: '',
    email: '',
    status: 1
});

const rules = {
    account: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur', min: 5 }],
    password2: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
            validator: (_rule: any, value: string, callback: any) => {
                if (!value) {
                    callback(new Error('请再次输入密码'));
                    return;
                }
                if (value !== formData.password) {
                    callback(new Error('两次输入的密码不一致'));
                    return;
                }
                callback();
            },
            trigger: 'blur'
        }
    ],
    phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    email: [
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ]
};

const open = (tenantId: number) => {
    visible.value = true;
    currentTenantId.value = tenantId;
    Object.assign(formData, {
        account: '',
        password: '',
        password2: '',
        name: '',
        phone: '',
        email: '',
        status: 1
    });
};

const submitForm = async () => {
    if (!formRef.value) return;

    try {
        await formRef.value.validate();
    } catch {
        // 校验失败时 validate 会 reject，避免 Uncaught (in promise)
        return;
    }

    submitting.value = true;

    try {
        const submitData = {
            ...formData,
            tid: currentTenantId.value,
        };
        // 提交时不需要把确认密码发给后端
        delete (submitData as any).password2;
        const res = await addUser(submitData);
        if (res.code === 200) {
            ElMessage.success('添加成功');
            visible.value = false;
            emit('success');
        }
    } catch (error) {
        console.error('提交失败', error);
    } finally {
        submitting.value = false;
    }
};

const handleClosed = () => {
    formRef.value?.resetFields();
};

defineExpose({ open });
</script>
