<template>
    <div class="content">
        <div class="card" style="flex: 1;">
            <div class="tab_head">
                <el-radio-group v-model="tabActive" @change="callTableQueueAjax">
                    <el-radio-button label="全部" value=""></el-radio-button>
                    <el-radio-button :label="item.name" :value="item.id" v-for="item in tabHeader"
                        :key="item.id"></el-radio-button>
                </el-radio-group>
                <div class="btns">
                    <el-button type="danger" :disabled="!tabHeader.length" @click="GetNumberRef.show(tabHeader)">
                        <template v-if="tabHeader.length">
                            取号
                        </template>
                        <template v-else>
                            请在基本设置添加桌型后取号
                        </template>
                    </el-button>
                    <el-button type="warning" @click="RecordRef.show()">叫号记录</el-button>
                    <el-button type="primary" @click="SettingRef.show()">基本设置</el-button>
                </div>
            </div>
            <div class="queue_list" v-loading="queueList.loading">
                <div class="item" v-for="item in queueList.list" :key="item.id">
                    <div class="head">
                        <div class="row">
                            <div class="row_item">用户</div>
                            <div class="row_item">号码</div>
                            <div class="row_item">桌型</div>
                            <div class="row_item">等待</div>
                        </div>
                        <div class="row">
                            <div class="row_item">{{ item.phone }}</div>
                            <div class="row_item">{{ item.callNum }}</div>
                            <div class="row_item">{{ item.name }}</div>
                            <div class="row_item">{{ item.waitingCount }}分钟</div>
                        </div>
                    </div>
                    <div class="btm">
                        <el-button @click="cancaleHandle(item)">取消</el-button>
                        <el-button type="primary" @click="callHandle(item)">播报</el-button>
                    </div>
                </div>
                <div class="empty">
                    <el-empty description="暂无数据~" v-if="!queueList.list.length" style="width: 100%;" />
                </div>
            </div>
            <div class="pagination" style="display: flex;justify-content: flex-end;">
                <el-pagination v-model:current-page="queueList.page" v-model:page-size="queueList.size"
                    layout="total, prev, pager, next" :total="queueList.total" background
                    @current-change="queueListChange" @size-change="queueListChange">
                </el-pagination>
            </div>
        </div>
    </div>
    <!-- 基本设置 -->
    <Setting ref="SettingRef" @success="callTableAjax" />
    <!-- 叫号记录 -->
    <Record ref="RecordRef" />
    <!-- 取号 -->
    <GetNumber ref="GetNumberRef" @success="callTableQueueAjax" />
    <!-- 播报状态 -->
    <ResultModal ref="ResultModalRef" @success="callTableQueueAjax" />
</template>

<script setup>
import Speech from 'speak-tts'
import { ElMessageBox, ElMessage } from 'element-plus'
import Setting from './components/setting.vue'
import Record from './components/record.vue'
import GetNumber from './components/getNumber.vue'
import ResultModal from './components/resultModal.vue'
import { onMounted, reactive, ref } from 'vue';
import { callTableQueue, getCallTable, callTableCall, callTableCallState } from '@/api/account.js'
import { useUser } from "@/store/user.js"
const store = useUser()

const SettingRef = ref(null)
const RecordRef = ref(null)
const GetNumberRef = ref(null)
const ResultModalRef = ref(null)

// 获取桌型列表
const tabHeader = ref([])
const tabActive = ref('')
async function callTableAjax() {
    try {
        const res = await getCallTable({
            page: 1,
            size: 100,
            callTableId: '',
            state: ''
        })
        tabHeader.value = res.records
    } catch (error) {
        console.log(error);
    }
}

// 取号 排队列表获取 start
const queueList = reactive({
    loading: false,
    list: [],
    page: 1,
    size: 8,
    total: 0
})

function queueListChange() {
    callTableQueueAjax()
}

// 获取数据
async function callTableQueueAjax() {
    try {
        queueList.loading = true
        const res = await callTableQueue({
            page: queueList.page,
            size: queueList.size,
            shopId: store.shopInfo.id,
            callTableId: tabActive.value,
            state: ''
        })
        queueList.list = res.records
        queueList.total = +res.totalRow
    } catch (error) {
        console.log(error);
    }
    queueList.loading = false
}
// 取号 排队列表获取 end

// 取消排队
function cancaleHandle(item) {
    ElMessageBox.confirm('确定要取消排队吗？', '注意').then(async () => {
        try {
            await callTableCallState({
                callQueueId: item.id,
                state: '-1'
            })
            ElMessage.success('已取消')
            callTableQueueAjax()
        } catch (error) {
            console.log(error);
        }
    }).catch(() => { })
}

// 播报
async function callHandle(item) {
    try {
        startSpeech(`请${item.callNum}用餐`)
        const res = await callTableCall({
            callQueueId: item.id,
        })
        ResultModalRef.value.show({
            ...item,
            status: res.state
        })
    } catch (error) {
        console.log(error);
    }
}

// 播放声音
const speech = new Speech()
function speechInit(params) {
    speech.init({
        volume: 1, // 音量
        lang: 'zh-CN', // 语言
        rate: 1, // 语速1正常语速，2倍语速就写2
        pitch: 1, // 音调
        splitSentences: true, // 在句子结束时暂停
        listeners: {
            // 事件
            onvoiceschanged: voices => {
                // console.log('事件声音已更改', voices);
            },
        },
    }).then(data => {
        console.log('语音已准备好，声音可用', data);
    }).catch(err => {
        console.log('初始化发生错误', err);
    })
}

// 开始播报
function startSpeech(text) {
    speech.speak({
        text: text, //这里使用文字或者i18n 都可以 看自己需求
        queue: true,
        listeners: {
            //  开始播放
            onstart: () => {
                console.log('Start utterance')
            },
            //  判断播放是否完毕
            onend: () => {
                console.log('End utterance')
            },
            //  恢复播放
            onresume: () => {
                console.log('Resume utterance')
            },
        }
    }).then(() => {
        console.log('成功!');
    }).catch(e => {
        console.error('发生错误:', e);
    });
}

onMounted(() => {
    callTableAjax()
    callTableQueueAjax()

    if (speech.hasBrowserSupport()) {
        console.log('语音播报加载成功，支持播报');
        speechInit()
    } else {
        console.log('当前浏览器不支持语音播报');
    }
})
</script>

<style lang="scss" scoped>
.card {
    padding: 15px;

    .pagination {
        display: flex;
        justify-content: flex-start;
    }
}

.tab_head {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.queue_list {
    height: 80vh;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(4, 1fr);
    grid-column-gap: 15px;
    grid-row-gap: 15px;
    padding: 15px 0;
    position: relative;

    .empty {
        position: absolute;
        top: 40%;
        left: 50%;
        transform: translate(-50%, -50%);
    }

    .item {
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 10px;

        .head {
            .row {
                display: flex;
                margin-bottom: 10px;

                .row_item {
                    flex: 1;

                    &:last-child {
                        flex: 0.5;
                    }
                }
            }
        }

        .btm {
            display: flex;
            justify-content: flex-end;
        }
    }
}
</style>