<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();

/** 从 scene 解析 storeId、tableId（与 App.vue parseSceneToStoreTable 逻辑一致） */
function parseSceneToStoreTable(sceneStr) {
  const trim = (v) => (v == null ? '' : String(v).trim());
  let storeId = '';
  let tableId = '';
  if (!sceneStr) return { storeId, tableId };
  let decoded = String(sceneStr).trim();
  try { decoded = decodeURIComponent(decoded); } catch (_) {}
  const parseKv = (text) => {
    text.split('&').forEach((pair) => {
      const eq = pair.indexOf('=');
      if (eq > 0) {
        const k = pair.substring(0, eq).trim().toLowerCase();
        const v = pair.substring(eq + 1).trim();
        if (['s', 'storeid', 'store_id'].includes(k)) storeId = v;
        if (['t', 'tableid', 'table_id', 'tableno', 'table'].includes(k)) tableId = v;
      }
    });
  };
  try {
    if (decoded.startsWith('{') && decoded.endsWith('}')) {
      const obj = JSON.parse(decoded);
      return { storeId: trim(obj?.storeId ?? obj?.store_id ?? obj?.s ?? ''), tableId: trim(obj?.tableId ?? obj?.table_id ?? obj?.tableid ?? obj?.t ?? obj?.tableNo ?? obj?.table ?? '') };
    }
    if (/^\d+_\d+$/.test(decoded)) {
      const [s, t] = decoded.split('_');
      return { storeId: trim(s), tableId: trim(t) };
    }
    if (/^\d+$/.test(decoded)) return { storeId: '', tableId: decoded };
    parseKv(decoded);
  } catch (_) {}
  return { storeId: trim(storeId), tableId: trim(tableId) };
}

/** 从启动参数/query 中解析 tableid、storeId，兼容微信小程序 scene、query 等 */
function getIdsFromOptions(options) {
  if (!options || typeof options !== 'object') return { tableid: '', storeId: '' };
  const q = options.query || options;
  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() };
  }
  const scene = q.scene ?? q.q ?? '';
  if (scene) {
    const { storeId: s, tableId: t } = parseSceneToStoreTable(scene);
    return { tableid: t, storeId: s };
  }
  return { tableid: '', storeId: '' };
}

async function doRedirect(options = {}) {
  let tableid = uni.getStorageSync('currentTableId') || '';
  if (!tableid) {
    const { tableid: t, storeId: s } = getIdsFromOptions(options);
    tableid = t;
    if (tableid) uni.setStorageSync('currentTableId', tableid);
    if (s) uni.setStorageSync('currentStoreId', s);
  }
  if (!tableid) {
    console.log('[launch] 无 tableid，跳转首页');
    uni.reLaunch({ url: '/pages/index/index' });
    return;
  }
  try {
    console.log('[launch] 调用 GetTableDiningStatus, tableid:', tableid);
    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((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>
