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";
import {
	getDistance
} from "@/utils/address.js";
import {
	APIgeocodelocation
} from "@/common/api/api.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",
								});
								console.log('APIuserlogin', res);
								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);
									uni.cache.set("followIndex", res
										.followIndex || "");
								}
								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
				// #ifdef H5
				resolve(true)
				// #endif
			});
		},
	},
});

export const productStore = defineStore("product", {
	state: () => ({
		location: {
			latitude: "",
			longitude: "",
		},
		token: "",
		miniAppOpenId: "",
		userInfo: "",
		shopId: uni.cache.get('shopId') || '',
		shopInfo: {
			shopId: "",
			isOrderFence: 0,
			id: '',
		},
		shopUserInfo:{
			
		},
		isHasLogin:false
	}),
	actions: {
		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",
								});
								console.log('APIuserlogin', res);
								if (res) {
									this.token = res.token;
									this.isHasLogin=true
									this.miniAppOpenId = res.userInfo
										.miniAppOpenId;
									this.userInfo = res.userInfo;
									uni.cache.set("token", res.token);
									uni.cache.set("userInfo", res.userInfo);
									uni.cache.set("followIndex", res
										.followIndex || "");
								}
								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.isHasLogin=true
							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
				// #ifdef H5
				resolve(true)
				// #endif
			});
		},
		getLocation() {
			return new Promise((resolve, reject) => {
				console.log("获取经纬度");
				// #ifdef H5
				resolve({
					accuracy: 65,
					altitude: 0,
					errMsg: "getLocation:ok",
					horizontalAccuracy: 65,
					latitude: 23.129163,
					longitude: 113.264435,
					speed: -1,
					verticalAccuracy: 65,
				});
				// #endif
				uni.getLocation({
					type: "wgs84",
					altitude: true,
					isHighAccuracy: true,
					success: (res) => {
						console.log("获取经纬度成功", res);

						this.location = res;
						this.APIgeocodelocation();
						resolve(res);
					},
					fail: (err) => {
						console.error("获取经纬度失败", err);
						reject(err);
					},
				});
			});
		},
		async APIgeocodelocation() {
			let successres = await APIgeocodelocation({
				lng: this.location.longitude,
				lat: this.location.latitude,
			});
			if (successres) {
				let datastorage = {
					country: successres.addressComponent.country, // "中国"
					province: successres.addressComponent.province, //province: "陕西省"
					address: successres.addressComponent.city, //district: "西安市"
					district: successres.addressComponent.district, //district: "未央区"
					lng: this.location.longitude,
					lat: this.location.latitude,
				};
				uni.cache.set("getLocationstorage", datastorage);
			}
		},
		getQueryString(url, name) {
			//解码
			var reg = new RegExp("(^|&|/?)" + name + "=([^&|/?]*)(&|/?|$)", "i");
			var r = url.substr(1).match(reg);
			if (r != null) {
				return r[2];
			}
			return null;
		},

		/**
		 * 扫码请求
		 * @param {*} q
		 * @returns
		 */
		async scanCodeactions(q) {
			console.log("扫码内容", q);
			// #ifdef H5
			uni.navigateTo({
				url: '/pages/product/index'
			})
			return
			// #endif

			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();
							}
						}

						if (this.shopInfo.isOrderFence == 0) {
							this.jumpToOrderPage();
							return;
						}
						const canGetLocation = await this.openLocationAuth();
						if (canGetLocation) {
							const canOrder = await this.computedDistance();
						}
					}
				} 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();
									}
								}
								if (this.shopInfo.isOrderFence == 0) {
									this.jumpToOrderPage();
									return;
								}
								const canGetLocation = await this
									.openLocationAuth();
								if (canGetLocation) {
									const canOrder = await this.computedDistance();
								}
							}
						},
						fail: (res) => {
							console.log(res);
						},
					});
					// #endif
				}
			});
		},
		async openLocationAuth() {
			try {
				// 1. 检查当前位置授权状态
				return new Promise((resolve, reject) => {
					uni.getSetting({
						success: (settingRes) => {
							if (settingRes.authSetting["scope.userLocation"]) {
								// 2. 已授权：直接获取位置
								resolve(true);
							} else if (
								settingRes.authSetting["scope.userLocation"] ===
								undefined
							) {
								// 3. 未请求过授权：发起授权请求
								uni
									.authorize({
										scope: "scope.userLocation"
									})
									.then((authRes) => {
										if (authRes.errMsg === "authorize:ok") {
											// 授权成功后获取位置
											resolve(true);
										} else {
											reject(false);
										}
									});
							} else {
								// 4. 已拒绝授权：提示用户去设置页开启
								uni.showModal({
									title: "开启定位",
									content: "请允许“零点八零”使用您的位置，方便您进入店铺点餐",
									confirmText: "开启定位",
									cancelText: "取消",
									success: (modalRes) => {
										if (modalRes.confirm) {
											// 跳转微信小程序授权设置页
											uni.openSetting({
												success: async (
													openRes
												) => {
													// 用户在设置页开启授权后，再次获取位置
													if (openRes
														.authSetting[
															"scope.userLocation"
														]) {
														resolve(
															true
														);
													} else {
														reject(
															false
														);
													}
												},
											});
										}
									},
								});
							}
						},
						fail: (err) => {
							reject(err);
						},
					});
				});
			} catch (err) {
				console.error("位置授权失败：", err);
				uni.showToast({
					title: "授权失败，请稍后重试",
					icon: "none"
				});
			}
		},
		//计算距离判断是否可以点餐
		async computedDistance() {
			return new Promise((resolve, reject) => {
				console.log("店铺经纬度", this.shopInfo.lat, this.shopInfo.lng);
				console.log(
					"用户经纬度",
					this.location.latitude,
					this.location.longitude
				);

				const juli = getDistance(
					this.location.latitude,
					this.location.longitude,
					this.shopInfo.lat,
					this.shopInfo.lng
				);
				const orderFenceDistance = (
					(this.shopInfo.orderFenceDistance || 2000) / 2000
				).toFixed(2);

				console.log("距离", juli);

				if (this.shopInfo.isOrderFence && juli > orderFenceDistance) {
					uni.showModal({
						title: "提示",
						confirmText: "重新定位",
						content: "抱歉，您当前距离店铺过远，为保障您的用餐体验，请您到店后或在门店附近再下单。若您已在店铺附近，可尝试重新定位",
						success: async (res) => {
							if (res.confirm) {
								console.log("用户点击了确认");
								await this.getLocation();
								this.computedDistance();
							} else if (res.cancel) {
								console.log("用户点击了取消");
							}
						},
					});
					reject();
					return;
				}
				this.jumpToOrderPage();
				resolve(juli);
			});
		},
		// 跳转点餐页面
		jumpToOrderPage() {
			// 是否免除桌位费 0否1是
			if (this.shopInfo.isTableFee == 0) {
				uni.reLaunch({
					url: "/pages/product/choosetable",
				});
			} else {
				uni.reLaunch({
					url: "/pages/product/index",
				});
			}
		},

		// /通过桌码获取当前店铺信息
		actionsproductqueryShop(tableCode) {
			console.log("台桌码", 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;
						this.shopInfo = res.shopInfo;
						// 店铺信息
						uni.cache.set("shopTable", res.shopTable);
						// 台桌信息
						uni.cache.set("shopInfo", res.shopInfo);
						// uni.cache.set("shopId", res.shopTable.shopId, 30);
						uni.cache.set("shopId", res.shopTable.shopId);

						resolve(res);
					} else {
						uni.showToast({
							title: "通过桌码获取当前店铺信息失败",
							icon: "none",
						});
						console.error("通过桌码获取当前店铺信息失败", res);
						reject();
					}
				} catch (error) {
					console.log(error);
					reject();
					//TODO handle the exception
				}

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

		// 通过shopId  获取店铺会员信息
		actionsproductqueryProduct() {
			console.log('actionsproductqueryProduct:token',uni.cache.get('token'));
			return new Promise(async (resolve, reject) => {
				try {
					let res = await APIshopUserInfo();
					if(res&& typeof res === 'object'){
						this.shopUserInfo=res;
						uni.cache.set("shopUserInfo", res);
						uni.cache.set("orderVIP", res);
						uni.cache.set("ordershopUserInfo", res.shopInfo);
						resolve(res);
					}else{
						reject(false);
					}
					
				} catch (e) {
					reject(false);
				}
			});
		},

		async pageOnload() {
			console.log('开始加载必须数据')
			//登录
			await this.actionslogin()
			//获取会员信息
			await this.actionsproductqueryProduct()
			//获取店铺信息
			await this.getShopInfo()
			console.log('必须数据加载完毕')
		},
		async getShopInfo(shopId) {
			const shopRes = await APIusershopInfodetail({
				shopId: this.shopId || shopId,
			});
			this.shopInfo = shopRes.shopInfo;
			uni.cache.set("shopInfo", shopRes.shopInfo);
		},
		// 用户信息获取
		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);
				}
			});
		},
	},
});