<template>
    <el-dialog :model-value="visible" :title="isEdit ? '修改用户账号' : '添加用户账号'" width="640px"
        append-to-body @update:model-value="$emit('update:visible', $event)" @closed="onClosed">
        <el-form ref="formRef" :model="form" :rules="formRules" label-width="120px">
            <el-form-item label="账号" prop="account">
                <el-input v-model="form.account" placeholder="请输入账号" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" :placeholder="isEdit ? '留空不修改' : '请输入密码'" type="password"
                    show-password />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirm_password">
                <el-input v-model="form.confirm_password" placeholder="请确认密码" type="password" show-password />
            </el-form-item>
            <el-form-item label="门店" prop="store_id">
                <el-select v-model="form.store_id" placeholder="请选择门店" style="width: 100%">
                    <el-option v-for="item in storeList" :key="item.id" :label="item.store_name"
                        :value="Number(item.id)" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="$emit('update:visible', false)">取消</el-button>
            <el-button type="primary" :loading="loading" @click="submit">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch } from 'vue';
import { addStoreAccount, editStoreAccount } from '@/api/store/index';
import { ElMessage } from 'element-plus';

interface StoreItem {
    id: number;
    store_name: string;
}

interface Props {
    visible: boolean;
    storeList: StoreItem[];
    editId?: number;
    editData?: {
        id: number;
        account: string;
        store_id: number;
    };
}

const props = defineProps<Props>();
const emit = defineEmits<{
    'update:visible': [val: boolean];
    success: [];
}>();

const loading = ref(false);
const formRef = ref();
const form = reactive({
    id: undefined as number | undefined,
    account: '',
    password: '',
    confirm_password: '',
    store_id: undefined as number | undefined,
});

const isEdit = computed(() => !!props.editId);

const formRules = computed(() => {
    if (isEdit.value) {
        return {
            account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
            password: [{ required: false }],
            confirm_password: [
                {
                    validator: (_rule: any, value: string, cb: any) => {
                        if (value && value !== form.password) cb(new Error('两次密码不一致'));
                        else cb();
                    },
                },
            ],
            store_id: [{ required: true, message: '请选择门店', trigger: 'change' }],
        };
    }
    return {
        account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        confirm_password: [
            { required: true, message: '请确认密码', trigger: 'blur' },
            {
                validator: (_rule: any, value: string, cb: any) => {
                    value !== form.password ? cb(new Error('两次密码不一致')) : cb();
                },
            },
        ],
        store_id: [{ required: true, message: '请选择门店', trigger: 'change' }],
    };
});

watch(
    () => props.visible,
    (val) => {
        if (val) {
            if (isEdit.value && props.editData) {
                form.id = props.editData.id;
                form.account = props.editData.account;
                form.store_id = Number(props.editData.store_id);
            } else {
                formRef.value?.resetFields();
                form.id = undefined;
                form.store_id = undefined;
            }
            form.password = '';
            form.confirm_password = '';
        }
    }
);

function onClosed() {
    formRef.value?.resetFields();
}

const submit = async () => {
    const valid = await formRef.value?.validate().catch(() => false);
    if (!valid) return;

    const payload: any = { ...form };
    if (!payload.password) delete payload.password;
    if (!payload.confirm_password) delete payload.confirm_password;

    loading.value = true;
    try {
        if (isEdit.value) {
            await editStoreAccount(payload);
            ElMessage.success('修改成功');
        } else {
            await addStoreAccount(payload);
            ElMessage.success('添加成功');
        }
        emit('update:visible', false);
        emit('success');
    } catch {
        ElMessage.error(isEdit.value ? '修改失败' : '添加失败');
    } finally {
        loading.value = false;
    }
};
</script>
