import {
	defineStore
} from 'pinia';
import {
	ref
} from 'vue';
import {
	APIuserlogin,
	APIuser
} from '@/common/api/api.js'
import {
	APIproductqueryShop,
	APIusershopInfodetail,
	APIshopUserInfo
} from '@/common/api/member.js'
export const Storelogin = defineStore('login', {
	state: () => ({
		token: '',
		miniAppOpenId: '',
		userInfo: '',
		shopInfo: {}
	}),
	actions: {
		async getShopInfo(shopId) {
			const shopRes = await APIusershopInfodetail({
				shopId
			})
			console.log(shopRes);
		},
		actionslogin() {
			return new Promise(async (resolve, reject) => {
				// #ifdef MP-WEIXIN
				uni.login({
					provider: 'weixin',
					success: (data) => {
						// 微信小程序环境
						uni.getUserInfo({
							provider: 'weixin',
							success: async (infoRes) => {
								let res = await APIuserlogin({
									code: data.code, //临时登录凭证
									rawData: infoRes.rawData,
									source: 'wechat'
								})
								if (res) {
									this.token = res.token
									this.miniAppOpenId = res.userInfo
										.miniAppOpenId
									this.userInfo = res.userInfo
									uni.cache.set('token', res.token);
									uni.cache.set('userInfo', res.userInfo);
								}
								resolve(true);
							},
							fail: (err) => {
								reject(false);
							}
						});
					}
				});
				// #endif
				// #ifdef MP-ALIPAY	
				my.getAuthCode({
					scopes: 'auth_base',
					success: async (data) => {
						// 支付宝小程序环境
						// my.getAuthUserInfo({
						// success: async (infoRes) => {
						let res = await APIuserlogin({
							code: data.authCode, //临时登录凭证
							// rawData: JSON.stringify(infoRes),
							source: 'alipay'
						})
						if (res) {
							this.token = res.token
							this.miniAppOpenId = res.userInfo.miniAppOpenId
							this.userInfo = res.userInfo
							uni.cache.set('token', res.token);
							uni.cache.set('openId', res.userInfo
								.alipayOpenId)
							uni.cache.set('userInfo', res.userInfo);
							resolve(true);
						}
					},
					fail: () => {
						reject(false);
					}
				})
				// #endif
			})
		}
	}
});

export const productStore = defineStore('product', {
	actions: {
		getQueryString(url, name) { //解码
			var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
			var r = url.substr(1).match(reg)
			if (r != null) {
				return r[2]
			}
			return null;
		},
		// 扫码请求
		scanCodeactions(q) {
			return new Promise(async (resolve, reject) => {
				if (q) {
					console.log(q)
					let tableCode = ""
					// #ifdef MP-WEIXIN
					tableCode = this.getQueryString(decodeURIComponent(q), 'code')
					// #endif
					// #ifdef MP-ALIPAY
					tableCode = q
					// #endif
					// #ifdef H5
					tableCode = q.tableCode
					// #endif
					console.log(tableCode);
					// 储存卓玛
					uni.cache.set('tableCode', tableCode)
					if (tableCode) {
						console.log(uni.cache.get('tableCode'));
						let data = await this.actionsproductqueryShop(tableCode)
						
						console.log('data', data)
						// -4请求登录
						if (data.code == '500') {
							if (await this.actionslogin()) {
								// 成功 接着在调用
								await this.actionsproductqueryShop()
							}
						}
						// 是否免除桌位费 0否1是
						if (uni.cache.get('shopInfo').isTableFee == 0) {
							uni.reLaunch({
								url: '/pages/product/choosetable'
							});
						} else {
							uni.reLaunch({
								url: '/pages/product/index'
							});
						}

					}
				} else {
					// #ifdef APP || MP-WEIXIN || MP-ALIPAY
					uni.scanCode({
						success: async (res) => {
							let tableCode = this.getQueryString(
								decodeURIComponent(res.result), 'code')
							// 储存卓玛
							uni.cache.set('tableCode', tableCode)
							if (tableCode) {
								let data = await this.actionsproductqueryShop()
								if (!data) {
									uni.showToast({
										title: '店铺已过期或其他问题，请联系商家',
										icon:'none'
									})
									return
								}
								// -4请求登录
								const store = Storelogin()
								if (data.code == '-4') {
									if (await store.actionslogin()) {
										// 成功 接着在调用
										await this.actionsproductqueryShop()
									}
								}
								// 是否免除桌位费 0否1是
								if (uni.cache.get('shopInfo').isTableFee == 0) {
									uni.navigateTo({
										url: '/pages/product/choosetable'
									});
								} else {
									uni.reLaunch({
										url: '/pages/product/index'
									});
								}

							}
						},
						fail: (res) => {
							console.log(res)
						}
					});
					// #endif
				}

			})
		},

		// /通过桌码获取当前店铺信息
		actionsproductqueryShop(tableCode) {
			return new Promise(async (resolve, reject) => {
				// try {
				try {
					let res = await APIproductqueryShop({
						tableCode: tableCode ? tableCode : uni.cache.get('tableCode'),
					})
					if (res) {
						res.shopInfo.isVip = res.vip ? '1' : '0'
						res.shopTable.shopExtendMap = res.shopExtendMap
						// 店铺信息
						uni.cache.set('shopTable', res.shopTable)
						// 台桌信息
						uni.cache.set('shopInfo', res.shopInfo)
						uni.cache.set('shopId', res.shopTable.shopId, 30)
						// 当前用户距离店铺的米数
						uni.cache.set('distance', res.distance)

						resolve(res)
					} else {
						console.log(res)
						reject()
					}

				} catch (error) {
					console.log(error);
					reject()
					//TODO handle the exception
				}

				// } catch (e) {
				// reject(false)
				// }

			})
		},

		// 通过shopId  获取店铺会员信息
		actionsproductqueryProduct() {
			return new Promise(async (resolve, reject) => {
				try {
					let res = await APIshopUserInfo()
					uni.cache.set('shopUserInfo', res);
					uni.cache.set('orderVIP', res)
					uni.cache.set('ordershopUserInfo', res.shopInfo)
					resolve(res)
				} catch (e) {
					reject(false)
				}

			})
		},

		// 用户信息获取
		actionsAPIuser() {
			return new Promise(async (resolve, reject) => {
				try {
					let res = null
					// 获取店铺用户会员信息
					if (uni.cache.get('shopId')) {
						res = await this.actionsproductqueryProduct()
					} else {
						res = await APIuser()
						uni.cache.set('userInfo', res);
					}
					console.log('actionsAPIuser res', res);
					resolve(res)
				} catch (e) {
					reject(false)
				}

			})
		}
	}
});