// stores/counter.js
import {
	defineStore
} from "pinia";
import * as shopApi from "@/http/api/shop.js";

// 判断是否是主店，并且是否有查看权限
export const isMainShop = (shopId) => {
	const shopInfo = uni.getStorageSync("shopInfo");
	if (shopInfo.isHeadShop) {
		return true
	}
	if (shopInfo.shopType == 'only') {
		return true
	}
	return false
}

/**
 * 判断值是否为 非null + 非空对象（纯对象）
 * @param {any} obj 要检测的值
 * @returns {boolean} true=非空对象，false=否则
 */
function isNonEmptyObject(obj) {
	// 第一步：排除 null/undefined
	if (obj === null || obj === undefined) {
		return false;
	}

	// 第二步：排除非纯对象（数组、函数、日期等）
	if (Object.prototype.toString.call(obj) !== '[object Object]') {
		return false;
	}

	// 第三步：判断是否为空对象（无自有可枚举属性）
	for (const key in obj) {
		// 只检测自有属性（排除原型链属性）
		if (Object.prototype.hasOwnProperty.call(obj, key)) {
			return true;
		}
	}
	return false;
}

/**
 * 主店在配置该功能时未选择分店
 * 判断分店是否显示活动信息
 * @param {Object} activit
 * 活动信息
 */
export function isMarketShow(activit = null, key = 'shopIdList', isEnableKey = 'isEnable') {
	console.log('isMarketShow.activit===', activit);
	if (!isNonEmptyObject(activit)) return false

	let flag = false
	const shopInfo = uni.getStorageSync("shopInfo");

	if (!shopInfo.isHeadShop && (!activit[key].some(item => item == shopInfo.id) || !activit[isEnableKey])) {
		flag = true
	} else {
		flag = false
	}
	console.log('isMarketShow.flag===', flag);
	return flag
}

// 分销
export const useAccountInfoStore = defineStore("accountInfo", {
	state: () => {
		return {
			shopInfo: {},
		};
	},
	actions: {
		getShopInfo() {
			return shopApi.getShopInfo().then((res) => {
				this.shopInfo = res;
				return this.shopInfo;
			});
		},
		editShopInfo(data, autoRefresh = true) {
			return shopApi.editShopInfo(data).then((res) => {
				if (autoRefresh) {
					this.getShopInfo()
				}
				return res
			});
		},
	},
	unistorage: true, // 开启后对 state 的数据读写都将持久化
});