<template>
    <el-dialog v-model="data.dialogVisible" :title="data.title" :before-close="handleClose" style="width: 550px; padding-bottom: 20px">
        <el-form ref="formDataRef" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="用户姓名" prop="username">
                <el-input v-model="ruleForm.username" placeholder="请输入用户姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="用户手机号" prop="mobile">
                <el-input v-model="ruleForm.mobile" placeholder="请输入用户手机号" clearable></el-input>
            </el-form-item>
            <el-form-item label="用户类型" prop="type">
                <el-select v-model="ruleForm.type" clearable placeholder="请选择用户类型" style="width: 100%">
                    <el-option v-for="item in data.typeOptions" :key="item.id" :label="item.label" :value="item.value"> </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="CBK账号" prop="cbkAccount">
                <el-input 
                    v-model="ruleForm.cbkAccount" 
                    :type="data.showCbkAccount ? 'text' : 'password'"
                    placeholder="请输入CBK账号" 
                    clearable
                    @click="data.showCbkAccount = true"
                    @blur="data.showCbkAccount = false"
                >
                    <template #suffix>
                        <el-icon @click="data.showCbkAccount = !data.showCbkAccount" style="cursor: pointer;">
                            <View v-if="!data.showCbkAccount" />
                            <Hide v-else />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="账号状态" prop="status">
                <el-radio-group v-model="ruleForm.status">
                    <el-radio :value="0">启用</el-radio>
                    <el-radio :value="1">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="ruleForm.remark" placeholder="请输入备注" clearable></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button :loading="data.saveLoading" type="primary" @click="onClickSave">保存</el-button>
                <el-button @click="handleClose">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { userAdd, userEdit } from '@/api/userManage.js';
import { checkMobile } from '~/utils/validateFuns.js';
import { View, Hide } from '@element-plus/icons-vue';

const emits = defineEmits();
const formDataRef = ref();
const data = reactive({
    dialogVisible: false,
    title: '',
    typeOptions: [
    {
            value: 1,
            label: '司机',
        },
        {
            value: 2,
            label: '供应商',
        },
        {
            value: 3,
            label: '资金方',
        },
        {
            value: 4,
            label: '采购商',
        },
    ],
    saveLoading: false,
    showCbkAccount: false, // 控制CBK账号显示/隐藏
});
const ruleForm = reactive({
    username: '', // 用户姓名
    mobile: '', // 用户手机号
    type: '', // 用户类型    2供应商 3资金方 4采购商
    cbkAccount: '', // CBK账号
    status: '', // 账号状态  1是0否
    remark: '', // 备注
});
const rules = reactive({
    username: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
    mobile: [
        {
            validator(rule, value, callback) {
                // 如果为空，直接通过验证
                if (!value || value.trim() === '') {
                    callback();
                    return;
                }
                // 如果有值，则验证格式
                if (!checkMobile(value)) {
                    callback(new Error('请输入正确的手机号'));
                    return;
                }
                callback();
            },
            trigger: 'blur',
        },
    ],
    type: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
    cbkAccount: [],
    status: [{ required: true, message: '请选择账户状态', trigger: 'change' }],
});
const handleClose = () => {
    if (formDataRef.value) {
        formDataRef.value.resetFields();
    }
    data.dialogVisible = false;
};

// 保存按钮
const onClickSave = () => {
    if (formDataRef.value) {
        formDataRef.value.validate((valid) => {
            if (valid) {
                data.saveLoading = true;
                if (data.title === '新增用户') {
                    const params = { ...ruleForm };
                    userAdd(params)
                        .then((res) => {
                            data.saveLoading = false;
                            if (res.code === 200) {
                                ElMessage({
                                    message: res.msg,
                                    type: 'success',
                                });
                                emits('success');
                                if (formDataRef.value) {
                                    formDataRef.value.resetFields();
                                    data.dialogVisible = false;
                                } else {
                                    data.saveLoading = false;
                                    ElMessage.error(res.msg);
                                }
                            }
                        })
                        .catch((err) => {
                            data.saveLoading = false;
                        });
                } else {
                    const params = { ...ruleForm };
                    userEdit(params)
                        .then((res) => {
                            data.saveLoading = false;
                            if (res.code === 200) {
                                ElMessage({
                                    message: res.msg,
                                    type: 'success',
                                });
                                emits('success');
                                if (formDataRef.value) {
                                    formDataRef.value.resetFields();
                                    data.dialogVisible = false;
                                } else {
                                    data.saveLoading = false;
                                    ElMessage.error(res.msg);
                                }
                            }
                        })
                        .catch((err) => {
                            data.saveLoading = false;
                            console.error('编辑用户失败:', err);
                            ElMessage.error('编辑用户失败，请检查网络连接或权限设置');
                        });
                }
            } else {

            }
        });
    }
};
const onShowDialog = (row) => {
    data.title = row ? '编辑用户' : '新增用户';
    data.dialogVisible = true;
    data.showCbkAccount = false; // 重置CBK账号显示状态
    
    if (formDataRef.value) {
        formDataRef.value.resetFields();
    }
    if (row) {
        nextTick(() => {
            ruleForm.id = row.id;
            // 字段绑定说明：
            // 用户姓名 -> member_user.username
            // 用户手机号 -> member.mobile (通过member_id关联)
            // 用户类型 -> member.type (通过member_id关联)
            // 账号状态 -> member.status (通过member_id关联，0=启用，1=禁用)
            ruleForm.username = row.name || row.username; // 用户姓名 - 绑定到member_user.username
            ruleForm.mobile = row.mobile; // 用户手机号 - 绑定到member.mobile
            ruleForm.type = row.type || row.roleId; // 用户类型 - 绑定到member.type
            ruleForm.cbkAccount = row.cbkAccount || ''; // CBK账号 - 绑定到member_user.cbk_account
            ruleForm.status = row.status; // 账号状态 - 绑定到member.status (0=启用，1=禁用)
            ruleForm.remark = row.remark || ''; // 备注 - 绑定到member_user.remark
        });
    }
};
defineExpose({
    onShowDialog,
});
</script>

<style lang="less" scoped></style>
