import {
	autoBindInviteUser,
	autoGetInviteCode
} from '@/common/api/market/distribution.js'

import {
	shareClaim
} from '@/common/api/market/share.js'
import {
	APIshopUserInfo,
	APIusershopInfodetail
} from '@/common/api/member.js'
import {
	productStore
} from '@/stores/user.js';
const accountStore = productStore();
// #ifdef MP-WEIXIN
const accountInfo = wx.getAccountInfoSync();
export const envVersion = accountInfo.miniProgram.envVersion;
// #endif

// #ifdef H5
const accountInfo = {};
export const envVersion = 'release'
// #endif


let type = 3;
if (envVersion === 'trial') {
	console.log('当前环境是体验版');
	type = 2;
} else if (envVersion === 'release') {
	console.log('当前环境是正式版');
	type = 0;
} else {
	type = 1;
	console.log('当前环境是开发版或其他');
}

export const pageTags = {
	'/userPackage/index/index': 'pp-list', //套餐推广列表页
	'/userPackage/goodsDetail/goodsDetail': 'pp-detail', //套餐推广商品详情页
	'/groupBuying/index/index': 'gb-list', //商品拼团列表页
	'/groupBuying/goodsDetail/goodsDetail': 'gb-detail', //商品拼团详情页
	'/distribution/shop-detail/index': 'dis', //全民股东页面
	'/pages/index/index': 'index', //店铺首页
	'/pages/product/index': 'eat', //点餐页
	'/pages/product/index?pTag=eat-detail': 'eat-detail', //点餐商品详情弹窗页
	'/scoreShop/index/index':'point' ,//积分商品
	'/scoreShop/detail/index':'point-detail' ,//积分商品详情
}

export function returnPageTags(page) {
	for (let key in pageTags) {
		if (page.includes(key)) {
			if (page.includes('/pages/product/index')) {
				if (page.includes('showGoodsId=')||page.includes('goodsId=')) {
					return 'eat-detail'
				} else {
					return 'eat'
				}
			} else {
				return pageTags[key]
			}
		}
	}
	return ''
}
/**
 * 绑定用户邀请关系（核心函数）
 * 功能说明：校验邀请码有效性，有效则调用自动绑定接口完成邀请关系绑定
 * @param {Object} args - 绑定邀请关系的入参对象
 * @param {number} args.fromUserId - 需要绑定邀请人的用户ID（integer <int64>，必填）
 * @param {number} args.shopId - 店铺ID（integer <int64>，必填）
 * @param {string} args.pTag - 来源页面类型
 * @returns {void} 无返回值
 */
export async function bindInvite(args) {
	// 解构入参对象，获取需要的核心参数
	const {
		fromUserId,
		shopId,
		pTag,
	} = args;
	console.log('bindInvite',args);
	if (!fromUserId || !shopId) {
		return;
	}

	const shopUserInfo = uni.cache.get('shopUserInfo')
	// 邀请码有效，调用自动绑定邀请人接口，传递绑定所需参数
	return await shareClaim({
		tagType: pTag || '',
		shopId,
		fromUserId: fromUserId,
		toUserId: shopUserInfo.id
	});
}

export function wxShare(par) {
	const path = par.path
	const pTag = returnPageTags(path)
	if (pTag) {
		par.path += '&pTag=' + pTag
		par.query += '&pTag=' + pTag
	}
	console.log('pTag', pTag);
	console.log('wxShare', {
		...par,
		type
	});
	return {
		...par,
		type
	}
}

export async function returnCommonQuery() {
	const shopId = uni.cache.get('shopId')
	const shopUserInfo = uni.cache.get('shopUserInfo')
	const shopInfo = uni.cache.get('shopInfo')
	// const inviteCode = await autoGetInviteCode({
	// 	shopId: shopId,
	// 	fromUserId: shopUserInfo.id
	// })

	const queryJson = {
		// inviteCode: (inviteCode && inviteCode !== true) ? inviteCode : null,
		shopId,
		fromUserId: shopUserInfo.id,
	}
	return Promise.resolve(queryJson)
}

export function jsonToUrl(json) {
	let result = ''
	for (let key in json) {
		if (json[key]) {
			if (result === '') {
				result += `${key}=${json[key]}`
			} else {
				result += `&${key}=${json[key]}`
			}
		}
	}
	return result
}

/**
 * @param {Object} query 参数对象
 * @param {Array} showkeys  需要显示的key不包括公共参数 
 */
export async function returnQuery(query, showkeys) {


	const shopId = uni.cache.get('shopId')
	const shopUserInfo = uni.cache.get('shopUserInfo')
	const shopInfo = uni.cache.get('shopInfo')
	// const inviteCode = await autoGetInviteCode({
	// 	shopId: shopId,
	// 	fromUserId: shopUserInfo.id
	// })

	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	const currentPath = currentPage.route;
	const currentOptions = currentPage.options;


	let sharePath = `/${currentPath}`;
	const queryJson = {
		// inviteCode: (inviteCode && inviteCode !== true) ? inviteCode : null,
		shopId,
		fromUserId: shopUserInfo.id,
		...query
	}
	for (const key in currentOptions) {
		if (currentOptions.hasOwnProperty(key)) {
			if (showkeys && Array.isArray(showkeys) && showkeys.includes(key)) {
				queryJson[key] = encodeURIComponent(currentOptions[key])
			} else {
				queryJson[key] = encodeURIComponent(currentOptions[key])
			}
		}
	}
	queryJson.shopId = shopId
	// queryJson.inviteCode = (inviteCode && inviteCode !== true) ? inviteCode : null
	queryJson.fromUserId = shopUserInfo.id

	let result = ''
	for (let key in queryJson) {
		if (queryJson[key]) {
			if (result === '') {
				result += `${key}=${queryJson[key]}`
			} else {
				result += `&${key}=${queryJson[key]}`
			}
		}
	}
	return Promise.resolve(result)
}

function parseQueryString(queryString) {
	const queryParams = queryString.split("&").map((param) => param.split("="));
	const params = {};
	for (const [key, value] of queryParams) {
		params[key] = value;
	}
	return params;
}
/**
 * 混入的 onLoad 核心逻辑（抽成独立函数）
 * @param {Object} opt - 页面 onLoad 接收的参数
 * @param {Object} vm - 组件实例（this）
 */
export async function handleMixinOnLoad(opt, vm) {
	console.log('onLoad');
	const options = {}
	if (opt.q) {
		const q = decodeURIComponent(opt.q);
		const params = parseQueryString(q.split("?")[1]);
		Object.assign(options, params);
	} else {
		Object.assign(options, opt);
	}
	console.log('options', options);
	if (options.shopId) {
		uni.cache.set('shopId', options.shopId)
		accountStore.shopId = options.shopId
		await accountStore.pageOnload()
	}
	uni.setStorageSync('loadFinsh', true)

	if (options.shopId) {
		return await bindInvite(options)
	}
}

import {
	isJsonArrayString
} from '@/utils/util.js';


/**
 * 返回店铺首页图片
 */
export function returnIndexBg() {
	try {
		const orderVIP = uni.cache.get('orderVIP')
		if (!orderVIP || !orderVIP.shopExtendList) {
			return ''
		}
		if (!isJsonArrayString(orderVIP.shopExtendList[0].value)) {
			return ''
		}
		return JSON.parse(orderVIP.shopExtendList[0].value)[0]
	} catch (error) {
		console.error('orderVIP.shopExtendList[0].value 格式不正确')
		return ''
		//TODO handle the exception
	}


}

// utils/share.js
export const shareMixin = {


	async onShareAppMessage(res) {

		const shopInfo = uni.cache.get('shopInfo')
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const currentPath = currentPage.route;
		const currentOptions = currentPage.options;

		let sharePath = `/${currentPath}`;


		let query = await returnQuery()
		const indexBg = returnIndexBg()
		console.log('indexBg', indexBg);
		const imageUrl = indexBg || shopInfo.logo

		// 全局默认配置（可被页面覆盖）
		const defaultShareConfig = {
			title: shopInfo.shopName,
			path: sharePath + '?' + query,
			imageUrl: imageUrl,
			query,
			// desc: '描述',
			success: (res) => {
				console.log('分享好友成功', res);
				// 可加埋点等统一逻辑
			},
			fail: (err) => {
				console.error('分享好友失败', err);
			}
		};


		// 页面自定义配置覆盖全局
		const pageShareConfig = this.$options.shareConfig || {};
		console.log('mixIn onShareAppMessage', {
			...defaultShareConfig,
			...pageShareConfig
		})
		return wxShare({
			...defaultShareConfig,
			...pageShareConfig
		});
	},



	async onShareTimeline() {



		const shopInfo = uni.cache.get('shopInfo')

		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const currentPath = currentPage.route;
		const currentOptions = currentPage.options;


		let sharePath = `/${currentPath}`;


		let query = await returnQuery()
		const indexBg = returnIndexBg()
		const imageUrl = indexBg || shopInfo.logo


		const defaultTimelineConfig = {
			title: shopInfo.shopName,
			path: sharePath + '?' + query,
			imageUrl: imageUrl,
			query,
		};

		const pageTimelineConfig = this.$options.shareTimelineConfig || {};
		return wxShare({
			...defaultTimelineConfig,
			...pageTimelineConfig
		});
	}
};