<!-- 取号 -->
<template>
    <el-dialog title="取号" v-model="visible" @closed="onClose">
        <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
            <el-form-item label="选择桌型">
                <el-radio-group v-model="form.callTableId">
                    <el-radio :value="item.id" border v-for="item in list" :key="item.id">{{ item.name
                    }}</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
                <el-input v-model="form.phone" placeholder="请填写手机号" style="width: 60%;" />
            </el-form-item>
        </el-form>
        <div class="footer" style="display: flex;padding-top: 30px;">
            <el-button style="width: 100%" @click="visible = false">
                取消
            </el-button>
            <el-button type="primary" style="width: 100%" :loading="loading" @click="confirmHandle">
                确认
            </el-button>
        </div>
    </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue';
import { takeNumber } from '@/api/account.js'
import { useUser } from "@/store/user.js"
const store = useUser()

const emits = defineEmits(['success'])

const visible = ref(false)

const list = ref([])

const loading = ref(false)
const formRef = ref(null)
const resetForm = ref({})
const form = ref({
    callTableId: '',
    userId: '',
    phone: '',
    note: '',
    name: ''
})

const rules = ref({
    phone: [
        {
            required: true,
            validator: (rule, value, callback) => {
                let reg = /^(?:(?:\+|00)86)?1\d{10}$/
                if (!reg.test(form.value.phone)) {
                    callback(new Error('手机号码不正确'))
                } else {
                    callback()
                }
            },
            trigger: 'blur',
        }
    ]
})

// 提交
function confirmHandle() {
    formRef.value.validate(async vaild => {
        try {
            if (vaild) {
                loading.value = true
                form.value.note = list.value.find(item => item.id == form.value.callTableId).note
                form.value.name = list.value.find(item => item.id == form.value.callTableId).name

                console.log(form.value);
                

                await takeNumber(form.value)
                loading.value = false
                ElMessage.success('取号成功')
                emits('success')
                visible.value = false
            }
        } catch (error) {
            loading.value = false
            console.log(error);
        }
    })
}

// 初始化
function onClose() {
    form.value = { ...resetForm.value }
    formRef.value.resetFields()
}

function show(arr) {
    visible.value = true
    list.value = [...arr]
    form.value.callTableId = list.value[0].id
}

defineExpose({
    show
})

onMounted(() => {
    resetForm.value = { ...form.value }
})
</script>