<template>
    <div class="content">
        <div class="cart_wrap card">
            <div class="header">
                <div class="menus">
                    <div class="item" :class="{ active: tabActive == index }" v-for="(item, index) in tabAreas"
                        :key="item.id" @click="tabChange(item, index)">
                        <div class="dot" :style="{ backgroundColor: item.color }" v-if="item.color"></div>
                        <el-text>{{ item.label }}</el-text>
                    </div>
                </div>
                <!-- <div class="all">
                    <el-button type="link" icon="Clock">预定管理</el-button>
                </div> -->
                <div class="order_info">
                    <div class="title">
                        <el-icon>
                            <Tickets />
                        </el-icon>
                        <el-text>未结账：</el-text>
                    </div>
                    <el-text type="primary">
                        {{ orderInfo.num }}笔 | {{ orderInfo.personNum }}人 | ￥{{ formatDecimal(orderInfo.amount) }}
                    </el-text>
                </div>
            </div>
            <div class="tab_container">
                <div class="tab_head" ref="tabHeadRef">
                    <div class="item" :class="{ active: tabItemActive == -1 }" @click="tabItemChange('', -1)">全部</div>
                    <div class="item" :class="{ active: index == tabItemActive }" v-for="(item, index) in areaList"
                        :key="item.id" @click="tabItemChange(item, index)">
                        {{ item.name }}
                    </div>
                </div>
                <div class="overflow_y" v-loading="loading">
                    <div class="tab_list">
                        <div class="item"
                            :style="{ '--color': tableStatusList.find(val => val.type == item.status).color }"
                            v-for="(item, index) in tableList" :key="item.id" @click="slectTableHandle(index, item)">
                            <div class="tab_title" :class="`${item.status}`">
                                <span>{{ item.areaName }} | {{ item.name }}</span>
                                <span>{{ item.personNum || 0 }}/{{ item.maxCapacity }}</span>
                            </div>
                            <div class="tab_cont">
                                <div class="using"
                                    v-if="item.status == 'unsettled' || item.status == 'unsettled' || item.status == 'paying' || item.status == 'settled' || item.status == 'unpaid'">
                                    <div class="t1">￥{{ formatDecimal(+item.orderAmount) }}</div>
                                    <div class="t2">
                                        <el-icon color="#333">
                                            <Timer />
                                        </el-icon>
                                        <span :key="refreshKey">{{ countTime(item.orderCreateTime) }}</span>
                                    </div>
                                </div>
                                <div class="icon_wrap" v-else>
                                    <el-icon class="icon">
                                        <CircleClose />
                                    </el-icon>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="empty" v-if="!tableList.length">
                        <el-empty description="空空如也~" />
                    </div>
                </div>
                <!-- <div class="pagination">
                    <el-pagination background v-model:current-page="query.page" :pager-count="5"
                        layout=" pager, jumper, total" :total="query.total"
                        @current-change="shopTableAjax"></el-pagination>
                </div> -->
            </div>
        </div>
        <el-drawer v-model="drawerVisible"
            :title="`${tableList[tableItemActive].areaName} | ${tableList[tableItemActive].name} （${tableList[tableItemActive].personNum || 0}/${tableList[tableItemActive].maxCapacity}）`"
            size="35%" v-if="tableList.length">
            <tableInfo :tableInfo="tableList[tableItemActive]" @success="paySuccess" />
        </el-drawer>
        <!-- <div class="right_card card">
            <countCard v-if="!slectTable.id" />
            <tableInfo v-else :tableInfo="slectTable" @close="slectTableClose" @success="paySuccess" />
        </div> -->
    </div>
</template>

<script setup>
import { shopArea, shopTable } from "@/api/account.js";
import countCard from '@/views/table/components/countCard.vue'
import tableInfo from '@/views/table/components/tableInfo.vue'
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { dayjs } from 'element-plus'
import tableStatusList from './statusList.js'
import { formatDecimal } from '@/utils/index.js'

const orderInfo = ref({
    num: 0,
    personNum: 0,
    amount: 0
})

const tabActive = ref(0)
const tabAreas = ref([
    {
        label: '全部',
        type: '',
    },
    {
        label: '空闲',
        type: 'idle',
        color: "#187CAA",
    },
    {
        label: '使用中',
        type: 'unsettled',
        color: "#DD3F41",
    },
    {
        label: '待清理',
        type: 'settled',
        color: "#FF9500",
    },
    {
        label: '已预订',
        type: 'subscribe',
        color: "#58B22C",
    }
])

const query = ref({
    page: 1,
    size: 12,
    total: 0
})
const loading = ref(false)
// 区域列表
const areaList = ref([])
// 台桌列表
const tableList = ref([])
// 所选区域
const area = ref('')
// 选择台桌索引
const tableItemActive = ref(0)
// 选择台桌信息
const slectTable = ref('')

// 切换类型
function tabChange(item, index) {
    tabActive.value = index
    shopTableAjax()
}

const tabItemActive = ref(-1)
function tabItemChange(item, index) {
    tabItemActive.value = index
    if (index == -1) {
        area.value = ''
    } else {
        area.value = item.id
    }
    shopTableAjax()

    nextTick(() => {
        scrollTabToCenter()
    })
}

// 自动居中滚动
const tabHeadRef = ref(null)
function scrollTabToCenter() {
    const container = tabHeadRef.value
    if (!container) return

    // 获取当前激活的 item
    const activeItem = container.querySelector('.item.active')
    if (!activeItem) return

    // 计算居中位置
    const containerWidth = container.offsetWidth
    const itemWidth = activeItem.offsetWidth
    const itemLeft = activeItem.offsetLeft

    // 滚动到中间（核心公式）
    container.scrollTo({
        left: itemLeft - containerWidth / 2 + itemWidth / 2,
        behavior: 'smooth' // 丝滑滚动
    })
}

// 计算当前的时间差
function countTime(t) {
    if (!t) return '0小时1分'

    const now = dayjs().valueOf()
    const createTime = dayjs(t).valueOf()

    let diff = now - createTime

    // 负数 或 小于1分钟，都强制显示 0小时1分
    if (diff < 0 || diff < 60 * 1000) {
        return '0小时1分'
    }

    const h = Math.floor(diff / 3600000)
    const m = Math.floor((diff % 3600000) / 60000)

    return `${h}小时${m}分`
}

// 支付成功，刷新状态
async function paySuccess() {
    drawerVisible.value = false
    await shopTableAjax()
    // slectTableHandle(tableItemActive.value, tableList.value[tableItemActive.value])
}

// 选择台桌
const drawerVisible = ref(false)
function slectTableHandle(index, item) {
    tableItemActive.value = index
    drawerVisible.value = true
    // if (tableItemActive.value == index) {
    //     tableItemActive.value = -1
    //     slectTable.value = ''
    // } else {
    //     tableItemActive.value = index
    //     slectTable.value = item
    // }
}

// 关闭台桌
function slectTableClose() {
    tableItemActive.value = -1
    slectTable.value = ''
    drawerVisible.value = false
}

// 获取台桌区域
async function shopAreaAjax() {
    try {
        const res = await shopArea({
            page: 1,
            size: 500
        })
        areaList.value = res.records
    } catch (error) {
        console.log(error)
    }
}

// 获取台桌列表
async function shopTableAjax(isLoading = true) {
    try {
        orderInfo.value = {
            num: 0,
            personNum: 0,
            amount: 0
        }
        if (isLoading) {
            loading.value = true
        }
        const res = await shopTable({
            // page: query.value.page,
            // size: query.value.size,
            page: 1,
            size: 999,
            areaId: area.value,
            tableCode: '',
            name: '',
            status: tabAreas.value[tabActive.value].type,
        })
        tableList.value = res.records
        query.value.total = +res.totalRow

        tableList.value.forEach(item => {
            if (item.status == 'unsettled') {
                orderInfo.value.num += 1
                orderInfo.value.personNum += item.personNum || 0
                orderInfo.value.amount += item.orderAmount || 0
            }
        })
        if (isLoading) {
            setTimeout(() => {
                loading.value = false
            }, 500)
        }
    } catch (error) {
        if (isLoading) {
            loading.value = false
        }
        console.log(error)
    }
}

const refreshKey = ref(0)

// 精准【每分钟 00 秒】自动刷新时间（和时钟完全同步）
let timeTimer = null

function syncMinuteRefresh() {
    // 1. 计算当前时间距离下一个 00 秒还剩多少毫秒
    const now = new Date()
    const seconds = now.getSeconds()
    const delay = (60 - seconds) * 1000 // 等到下一个整分钟

    // 2. 等到整分钟时，执行一次刷新
    setTimeout(() => {
        refreshKey.value++ // 刷新时间

        // 3. 之后每 60 秒执行一次（永远在 00 秒刷新）
        timeTimer = setInterval(() => {
            refreshKey.value++
        }, 60000)
    }, delay)
}

onMounted(() => {
    shopAreaAjax()
    shopTableAjax()
    syncMinuteRefresh()
})

// 销毁清理
onUnmounted(() => {
    clearInterval(timeTimer)
})

</script>

<style scoped lang="scss">
.pagination {
    display: flex;
    justify-content: flex-end;
    padding-top: var(--el-font-size-base);
}

.cart_wrap {
    flex: 2;
}

.right_card {
    flex: 1;
    height: 100%;
    margin-left: var(--el-font-size-base);
}

.header {
    display: flex;
    height: var(--el-component-size-large);
    justify-content: space-between;
    border-bottom: 1px solid #ececec;

    .menus {
        display: flex;
        padding: 0 10px;

        .item {
            padding: 0 20px;
            display: flex;
            align-items: center;
            position: relative;

            span {
                font-size: var(--el-font-size-base);
            }

            .dot {
                width: 8px;
                height: 8px;
                border-radius: 50%;
                margin-right: 6px;
            }

            &.active {

                &::after {
                    content: "";
                    width: 70%;
                    height: 4px;
                    border-radius: 4px;
                    position: absolute;
                    bottom: 0;
                    left: 15%;
                    background-color: var(--primary-color);
                }

                span {
                    color: var(--primary-color);
                }
            }
        }
    }

    .all {
        display: flex;
        align-items: center;
    }

    .order_info {
        display: flex;
        padding-right: 14px;

        .title {
            display: flex;
            align-items: center;
            gap: 4px;
        }
    }
}

.tab_container {
    padding: var(--el-font-size-base);

    .tab_head {
        width: calc(100vw - 125px);
        padding-bottom: var(--el-font-size-base);
        overflow-x: auto;
        white-space: nowrap;

        /* 隐藏滚动条（通用） */
        scrollbar-width: none;
        -ms-overflow-style: none;


        .item {
            height: 42px;
            display: inline-flex;
            align-items: center;
            padding: 4px 12px;
            border-radius: 4px;
            background-color: #f5f5f5;
            margin-right: 10px;

            &.active {
                background-color: var(--primary-color);
                color: #fff;
            }

            &:hover {
                cursor: pointer;
                background-color: var(--primary-color);
                color: #fff;
            }
        }
    }

    /* 隐藏滚动条（Chrome / Electron / Edge） */
    .tab_head::-webkit-scrollbar {
        display: none !important;
    }

    .overflow_y {
        // height: calc(100vh - 220px);
        height: calc(100vh - 162px);
        overflow-y: auto;
    }

    .tab_list {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
        grid-template-rows: auto;
        gap: 10px;

        .item {
            border-radius: 6px;
            overflow: hidden;
            padding: 4px;
            background-color: var(--color);

            &.active {
                .tab_cont {
                    position: relative;

                    &::before {
                        content: "";
                        width: 100%;
                        height: 100%;
                        position: absolute;
                        top: 0;
                        left: 0;
                        background-color: var(--color);
                        opacity: .2;
                        z-index: 1;
                    }
                }
            }

            &:hover {
                cursor: pointer;
            }

            .tab_title {
                height: var(--el-component-size-large);
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 0 10px;
                color: #fff;
                gap: 4px;

                span:nth-child(1) {
                    /* 核心：最多两行，超出... */
                    display: -webkit-box;
                    -webkit-line-clamp: 2;
                    /* 最多2行 */
                    -webkit-box-orient: vertical;
                    overflow: hidden;
                    text-overflow: ellipsis;

                    /* 保证换行正常 */
                    white-space: normal;
                    word-break: break-all;
                }
            }

            .tab_cont {
                height: 108px;
                display: flex;
                background-color: #fff;
                border-radius: 4px;
                position: relative;

                .icon_wrap {
                    width: 100%;
                    height: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: center;

                    .icon {
                        color: var(--color);
                        font-size: 30px;
                        transform: rotate(45deg);
                        position: relative;
                        z-index: 2
                    }
                }

                .using {
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    gap: 20px;
                    padding-left: 14px;

                    .t1 {
                        color: #333;
                    }

                    .t2 {
                        display: flex;
                        align-items: center;
                        gap: 4px;

                        span {
                            color: #555;
                        }
                    }
                }
            }
        }
    }
}
</style>