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

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { isScanEntryAllowed } from '@/utils/qrScene.js';
import { SCAN_QR_CACHE } from '@/settings/enums.js';
import { syncM2GenericPricingStorage } from '@/utils/m2GenericApiPath.js';
import {
  getScanEntryIdsFromOptions,
  runTableDiningStatusAndRedirect,
  trim
} from '@/utils/tableDiningLaunch.js';

async function doRedirect(options = {}) {
  let { tableid, storeId: optStore, m } = getScanEntryIdsFromOptions(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;
  }

  /** 本次启动参数里的桌号（新扫太阳码）优先于本地缓存，避免仍用上一桌 */
  const fromScan = trim(tableid);
  const stored = trim(uni.getStorageSync('currentTableId') || '');
  const tableidResolved = fromScan || stored;
  if (!tableidResolved) {
    console.log('[launch] 无 tableid，跳转首页');
    uni.reLaunch({ url: '/pages/index/index' });
    return;
  }
  if (fromScan) {
    uni.setStorageSync('currentTableId', tableidResolved);
    if (optStore) uni.setStorageSync('currentStoreId', optStore);
  } else if (!stored) {
    uni.setStorageSync('currentTableId', tableidResolved);
    if (optStore) uni.setStorageSync('currentStoreId', optStore);
  }

  console.log('[launch] 调用 GetTableDiningStatus, tableid:', tableidResolved);
  await runTableDiningStatusAndRedirect(tableidResolved);
}

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>
