<template>
  <!-- 启动页：根据 table-dining-status 接口结果跳转，避免先展示错误页面 -->
  <view class="launch-wrap">
    <view class="launch-loading">正在加载...</view>
  </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import * as diningApi from '@/api/dining.js';
import { useUserStore } from '@/store/user.js';
import { TOKEN } from '@/settings/enums.js';

const userStore = useUserStore();

async function doRedirect() {
  const tableid = uni.getStorageSync('currentTableId') || '';
  if (!tableid) {
    uni.reLaunch({ url: '/pages/index/index' });
    return;
  }
  try {
    const res = await diningApi.GetTableDiningStatus(tableid);
    const raw = (res && typeof res === 'object') ? res : {};
    // 兼容多种返回：{ inDining: true }、{ data: { inDining: true } }、直接返回 true
    const inDining =
      res === true ||
      res === 'true' ||
      raw?.inDining === true ||
      raw?.inDining === 'true' ||
      raw?.data?.inDining === true ||
      raw?.data?.inDining === 'true';
    const token = userStore.getToken || uni.getStorageSync(TOKEN) || '';
    const dinerCount =
      raw?.dinerCount ?? raw?.diner ?? raw?.data?.dinerCount ?? raw?.data?.diner ?? uni.getStorageSync('currentDiners') ?? 1;
    if (inDining) {
      uni.setStorageSync('currentDiners', dinerCount);    
      uni.reLaunch({
        url: `/pages/orderFood/index?tableid=${encodeURIComponent(tableid)}&diners=${encodeURIComponent(dinerCount)}`
      });
      
    }
    else{
      uni.reLaunch({
          url: `/pages/numberOfDiners/index?inDining=1&tableid=${encodeURIComponent(tableid)}&diners=${encodeURIComponent(dinerCount)}`
        });
    }

  } catch (err) {
    console.warn('查询桌位就餐状态失败，进入选择人数页', err);
    uni.reLaunch({ url: '/pages/numberOfDiners/index' });
  }
}

onLoad(() => {
  doRedirect();
});
</script>

<style scoped lang="scss">
.launch-wrap {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f7f9fa;
}
.launch-loading {
  font-size: 28rpx;
  color: #999;
}
</style>
