<script>
import initConfig from '@/initConfig.js';
// #ifdef MP-WEIXIN
import { SCAN_QR_CACHE } from '@/settings/enums.js';
import * as diningApi from '@/api/dining.js';
import { useUserStore } from '@/store/user.js';
// #endif

/** 从 scene 或 query 中解析：二维码 s=店铺id，t=桌号id */
function parseSceneToStoreTable(sceneStr) {
	const trim = (v) => (v == null ? '' : String(v).trim());
	let storeId = '';
	let tableId = '';
	if (!sceneStr) return { storeId, tableId };
	const str = trim(sceneStr);
	try {
		const parts = str.split('&');
		parts.forEach((pair) => {
			const [k, v] = pair.split('=').map((s) => (s ? decodeURIComponent(String(s).trim()) : ''));
			if (k === 's' || k === 'storeId' || k === 'store_id') storeId = trim(v);
			if (k === 't' || k === 'tableId' || k === 'table_id' || k === 'tableid') tableId = trim(v);
		});
	} catch (err) {
		console.warn('parseSceneToStoreTable', err);
	}
	return { storeId, tableId };
}

/**
 * 查询桌位就餐状态，若 inDining 为 true 则跳转点餐页或选择人数页（未登录时）
 * @param {Object} opts - { fromTabBar: boolean } 来自 TabBar 扫码时，inDining 为 false 需 switchTab 到 numberOfDiners
 */
async function checkTableDiningStatus(opts = {}) {
	const tableid = uni.getStorageSync('currentTableId') || '';

	try {
		const res = await diningApi.GetTableDiningStatus(tableid);
		const raw = (res && typeof res === 'object') ? res : {};
		const inDining =
			raw?.inDining === true ||
			raw?.inDining === 'true' ||
			raw?.data?.inDining === true ||
			raw?.data?.inDining === 'true';
		const dinerCount =
			raw?.dinerCount ?? raw?.diner ?? raw?.data?.dinerCount ?? raw?.data?.diner ?? uni.getStorageSync('currentDiners') ?? 1;
		if (!inDining) {
			if (opts.fromTabBar) uni.switchTab({ url: '/pages/numberOfDiners/index' });
			return;
		}
		uni.setStorageSync('currentDiners', dinerCount);
		const userStore = useUserStore();
		if (!userStore.getToken) {
			uni.reLaunch({
				url: `/pages/numberOfDiners/index?inDining=1&tableid=${encodeURIComponent(tableid)}&diners=${encodeURIComponent(dinerCount)}`
			});
			return;
		}
		uni.reLaunch({
			url: `/pages/orderFood/index?tableid=${encodeURIComponent(tableid)}&diners=${encodeURIComponent(dinerCount)}`
		});
	} catch (err) {
		console.warn('查询桌位就餐状态失败', err);
		if (opts.fromTabBar) uni.switchTab({ url: '/pages/numberOfDiners/index' });
	}
}

export default {
	onLaunch: function (e) {
		// 只有小程序执行
		// #ifdef MP-WEIXIN
		initConfig();
		// 通过二维码编译/扫码进入：将二维码携带的信息缓存（query.scene 为小程序码参数，query.q 为普通链接二维码）
		try {
			const sceneEnc = e?.query?.scene;
			const qEnc = e?.query?.q;
			const scene = sceneEnc != null && sceneEnc !== '' ? decodeURIComponent(String(sceneEnc)) : '';
			const q = qEnc != null && qEnc !== '' ? decodeURIComponent(String(qEnc)) : '';
			const rawFromQR = scene || q || '';
			if (rawFromQR) {
				const { storeId, tableId } = parseSceneToStoreTable(rawFromQR);
				const payload = { raw: rawFromQR, storeId, tableId };
				uni.setStorageSync(SCAN_QR_CACHE, JSON.stringify(payload));
				if (storeId) uni.setStorageSync('currentStoreId', storeId);
				if (tableId) uni.setStorageSync('currentTableId', tableId);
			}
		} catch (err) {
			console.warn('缓存二维码启动参数失败', err);
		}
		// 冷启动时由 pages/launch/index 根据接口结果跳转；TabBar 扫码后由 App 统一调用接口并跳转
		uni.$on('checkTableDiningStatus', () => checkTableDiningStatus({ fromTabBar: true }));
		// #endif
	},
	onShow: function (res) {
		console.log('App Show', res);
		// 是否是从被打开的小程序返回
		const { appId, extraData } = res.referrerInfo;
		if (appId && extraData) {
			uni.$emit('listener:ArBack', res.referrerInfo);
		}
	},
	onHide: function () {
		console.log('App Hide');
	}
};
</script>

<style lang="scss">
view,
image,
label {
  box-sizing: border-box;
  word-break: break-all;
}

image {
  height: auto;
  width: auto;
}

/* #ifndef APP-NVUE */
// 设置整个项目的背景色
page {
  background-color: #f7f9fa;
}

/* #endif */

// 弹性盒子
.flex {
  display: flex;

  &-none {
    flex: none;
  }

  &-1 {
    flex: 1;
  }

  &-y {
    flex-direction: column;
  }

  &-top {
    align-items: flex-start !important;
  }

  // 顶部对齐
  &-bottom {
    align-items: flex-end;
  }

  // 底部对齐
  &-content-end {
    justify-content: flex-end;
  }

  // 水平靠右 || 垂直靠下对齐
  &-center {
    align-items: center;
  }

  // 水平居中对齐
  &-center-center {
    align-items: center;
    justify-content: center;
  }

  // 水平垂直居中
  &-between {
    justify-content: space-between;
  }

  // 两端不留间隙对齐
  &-around {
    justify-content: space-around;
  }

  // 两端留间隙对齐
  &-wrap {
    flex-wrap: wrap;
  }

  // 允许换行
}

.w-0 {
  width: 0;
}

.h-0 {
  height: 0;
}

// 隐藏显示多少行
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  word-break: break-all;

  @for $i from 2 through 10 {
    &.ellipsis-#{$i} {
      -webkit-line-clamp: $i;
    }
  }

  &-no {
    display: block;
  }
}

// 点击时的透明度
.hover-active {
  opacity: 0.8 !important;
}

// 底部安全区
.safe-area {
  padding-bottom: constant(safe-area-inset-bottom);
  /* 兼容 iOS < 11.2 */
  padding-bottom: env(safe-area-inset-bottom);
  /* 兼容 iOS >= 11.2 */
}

.ql-editor.ql-blank:before {
  color: #999999;
  font-size: 28rpx;
  font-style: normal;
}
</style>
