<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';
import { parseSceneToStoreTable, isScanEntryAllowed } from '@/utils/qrScene.js';
import { SCAN_QR_CACHE } from '@/settings/enums.js';
import { syncM2GenericPricingStorage } from '@/utils/m2GenericApiPath.js';

const userStore = useUserStore();

function trim(v) {
  return v == null ? '' : String(v).trim();
}

/** 从启动参数/query 中解析 tableid、storeId、m（m=1 美食，走 dining） */
function getIdsFromOptions(options) {
  if (!options || typeof options !== 'object') return { tableid: '', storeId: '', m: '' };
  const q = options.query || options;
  let m = trim(q.m ?? q.mode ?? '');
  const directTable = q.tableId ?? q.tableid ?? q.table_id ?? q.t ?? '';
  if (directTable) {
    const directStore = q.storeId ?? q.storeid ?? q.s ?? '';
    return { tableid: String(directTable).trim(), storeId: String(directStore || '').trim(), m };
  }
  const scene = q.scene ?? q.q ?? '';
  if (scene) {
    const { storeId: s, tableId: t, m: sm } = parseSceneToStoreTable(scene);
    return { tableid: t, storeId: s, m: m || sm || '' };
  }
  return { tableid: '', storeId: '', m };
}

async function doRedirect(options = {}) {
  let { tableid, storeId: optStore, m } = getIdsFromOptions(options);
  if (trim(m) === '') {
    try {
      const c = uni.getStorageSync(SCAN_QR_CACHE);
      if (c) m = trim(JSON.parse(c).m ?? '');
    } catch (_) {}
  }
  syncM2GenericPricingStorage(m);
  if (!isScanEntryAllowed(m)) {
    uni.showToast({ title: '请扫描正确的点餐二维码', icon: 'none' });
    uni.reLaunch({ url: '/pages/index/index' });
    return;
  }

  let tableidFinal = uni.getStorageSync('currentTableId') || '';
  if (!tableidFinal) {
    tableidFinal = tableid;
    if (tableidFinal) uni.setStorageSync('currentTableId', tableidFinal);
    if (optStore) uni.setStorageSync('currentStoreId', optStore);
  }
  const tableidResolved = tableidFinal;
  if (!tableidResolved) {
    console.log('[launch] 无 tableid，跳转首页');
    uni.reLaunch({ url: '/pages/index/index' });
    return;
  }
  try {
    console.log('[launch] 调用 GetTableDiningStatus, tableid:', tableidResolved);
    const res = await diningApi.GetTableDiningStatus(tableidResolved);
    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(tableidResolved)}&diners=${encodeURIComponent(dinerCount)}`
      });
      
    }
    else{
      uni.reLaunch({
          url: `/pages/numberOfDiners/index?inDining=1&tableid=${encodeURIComponent(tableidResolved)}&diners=${encodeURIComponent(dinerCount)}`
        });
    }

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

onLoad((options) => {
  doRedirect(options);
});
</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>
