var QQMapWX = require("./qqmap.js");

const loadPrevMerchant = req => {
	return new Promise((resolve, reject) => {
		req.g('/api/merchant/default', res => {
			resolve(res);
		});
	});
};

/**
 * 初始化距离
 * @param {*} form 
 */


const initRange = (data, form, success, req) => {
	console.log('initRange==' + data, form);
	var timestamp = Date.parse(new Date());
	data.time = timestamp + 1 * 60 * 1000
	if (!form.latitude || !form.longitude) {
		if (data && data.type == 5) {
			data.merchantDTO.time = timestamp + 1 * 60 * 1000
			req.setStorage('smallShop', data);
			req.setStorage('MERCHANT', data.merchantDTO);
		} else {
			req.setStorage('MERCHANT', data);
			req.removeStorage('smallShop');
		}
		success.call(this, data); // req.setStorage('MERCHANT', data);
		return false;
	}

	// console.log(data, "/**");
	QQMapWX.initMap(); // const form = { latitude: point.lat, longitude: point.lng };

	if (!data.lat || !data.lng) {
		if (data && data.type == 5) {
			data.merchantDTO.time = timestamp + 1 * 60 * 1000
			req.setStorage('smallShop', data);
			req.setStorage('MERCHANT', data.merchantDTO);
		} else {
			req.setStorage('MERCHANT', data);
			req.removeStorage('smallShop');
		}
	} else {
		const to = {
			latitude: data.lat,
			longitude: data.lng
		};

		QQMapWX.reverseGeocoder(to, resp => {
			console.log('地理位置数据22222>>>>>>>==',resp);
			req.setStorage('loctionAddressMap', resp.ad_info);
		});

		QQMapWX.calculateDistance(form, [to], response => {
			// console.log('地理位置数据>>>>>>>==',response);
			if (response) {
				data.range = Math.round(response.elements[0].distance / 1000);
				data.mDistance = response.elements[0].distance;
			}

			if (data && data.type == 5) {
				data.merchantDTO.time = timestamp + 1 * 60 * 1000
				req.setStorage('smallShop', data);
				req.setStorage('MERCHANT', data.merchantDTO);
			} else {
				req.setStorage('MERCHANT', data);
				req.removeStorage('smallShop');
			}

			success.call(this, data);
		});



	}
};

const initMerchant = (req, point, success) => {
	//初始化门店信息
	//获取本地缓存门店信息
	// let merchant = req.getStorage("MERCHANT");
	// if (merchant) success.call(this, merchant);
	// else {
	//获取上次选择的门店
	loadPrevMerchant(req).then(data => {
		if (!data || !data.id) {
			let userPid
			if (!JSON.parse(req.getStorage('configRes')).User_Limit_Store || JSON.parse(req.getStorage(
					'configRes'))
				.User_Limit_Store != 1) {

			} else {
				if (!req.getStorage('userInfo').pid) {
					userPid = 1
				} else {
					delete point.lat
					delete point.lng
					point.pid = req.getStorage('userInfo').pid
				}
			}

			//获取最近的门店
			req.getRequest('/api/merchant/getMerchantList', point, res => {

				// if (point.type == "shopindex") {AA
				// 	res = res.filter(it => it.isDefault != 1);
				// }
				if (userPid == 1) {
					res = res.filter(it => it.isDefault == 1);
				}
				console.log('最近的门店==')
				initRange(res[0], {
					latitude: point.lat,
					longitude: point.lng
				}, success, req);
			});
		} else {
			console.log('上次有门店==')
			initRange(data, {
				latitude: point.lat,
				longitude: point.lng
			}, success, req);
		}
	})
	// }
};

// 获取默认门店
const defaultMerchant = (req, point, success) => {
	// let merchant = req.getStorage('defaultMerchant');
	// if(merchant){
	// 	req.setStorage('defaultMerchant', merchant);
	// 	if(JSON.parse(req.getStorage('configRes')).Many_Store == 0){
	// 		success.call(this,merchant);	
	// 	}
	// }else{
	req.getRequest('/api/merchant/getIsdefault', {}, res => {
		// 默认门店
		// console.log(res);
		// if (point && point.type == "index") {
		// 	initRange(data[0], {
		// 		latitude: point.lat,
		// 		longitude: point.lng
		// 	}, success, req);
		// }
		req.setStorage('defaultMerchant', res);
		if (JSON.parse(req.getStorage('configRes')).Many_Store == 0) {
			success.call(this, res);
		}
		if(req.getStorage('isVideoScene')) {
			success.call(this, res);
		}
	});
	// }
};

// 获取门店
const getMerchant = (query, req, success) => {
	console.log('api+query' + JSON.stringify(query))
	if(req.getStorage('isVideoScene')){
		console.log('视频号')
		defaultMerchant(req, query, success);
	} else{
		defaultMerchant(req, query, success);
		if (JSON.parse(req.getStorage('configRes')).Many_Store == 0) {
			// defaultMerchant(req, query, res=>{success.call(this, res)})
		} else {
			let merchant
			if (query.merchantId && query.merchantId != 'undefined') {
				console.log('query有门店id');
				let from = {};
				if (query.shopId != null && query.shopId != undefined && query.shopId != "") {
					from.id = query.shopId;
				} else {
					from.id = query.merchantId;
				}
				req.getRequest('/api/merchant/detail', from, data => {
					if (!data.id) {
						req.msg('该门店不存在' + (JSON.parse(req.getStorage('configRes')).User_Limit_Store != 1 ?
							'，请切换门店' : ''))
					} else {
						if (!data.isBusiness) {
							req.msg('该门店暂未营业' + (JSON.parse(req.getStorage('configRes')).User_Limit_Store !=
								1 ? '，请切换门店' : ''))
							setTimeout(() => {
								success.call(this, data);
							}, 800)
						} else {
							var timestamp = Date.parse(new Date());
							data.time = timestamp + 1 * 60 * 1000
							if (data.type == 5) {
								data.merchantDTO.time = timestamp + 1 * 60 * 1000
								req.setStorage("smallShop", data), req.setStorage("MERCHANT", data
									.merchantDTO);
							} else {
								req.setStorage("MERCHANT", data);
							}
							success.call(this, data);
						}
					}

					// console.log(data, "执行+++++++++++++++++++++");
				});
			} else {
				console.log('query--没有门店id');
				var timestamp = Date.parse(new Date());
				if (req.getStorage('configRes') && JSON.parse(req.getStorage('configRes')).User_Limit_Store && JSON
					.parse(
						req.getStorage('configRes'))
					.User_Limit_Store == 1) {
					if (req.getStorage('smallShop')) {
						merchant = req.getStorage('smallShop');
					} else if (req.getStorage('MERCHANT')) {
						merchant = req.getStorage('MERCHANT');
					}
				} else {
					// console.log(req.getStorage('smallShop').time, "=================================", req.getStorage(
					// 	'MERCHANT').time, req.getStorage('smallShop').time > timestamp,req.getStorage('MERCHANT').time > timestamp)
					if (req.getStorage('smallShop') && req.getStorage('smallShop').time > timestamp) {
						merchant = req.getStorage('smallShop');
					} else if (req.getStorage('MERCHANT') && req.getStorage('MERCHANT').time > timestamp) {
						merchant = req.getStorage('MERCHANT');
					}
				}
				if (merchant) {
					merchant.mDistance = parseInt(merchant.mDistance);
					merchant.range = parseInt(merchant.range);
					success.call(this, merchant);
				} else {
					if (JSON.parse(req.getStorage('configRes')).User_Limit_Store && JSON.parse(req.getStorage(
							'configRes'))
						.User_Limit_Store == 1) {
						initMerchant(req, {}, data => {
							if (data) {
								data.mDistance = parseInt(data.mDistance);
								data.range = parseInt(data.range); // if(data.isDefault!=1){
								success.call(this, data);
							}
						});
					} else {
						req.getLocation(res => {
							if (res == 1 || res == 2) {
								success.call(this, req.getStorage("defaultMerchant"));
							} else {
								let form = {
									lat: res.latitude,
									lng: res.longitude
								}
								if (query.type) {
									form.type = query.type
								}
								initMerchant(req, form, data => {
									if (data) {
										data.mDistance = parseInt(data.mDistance);
										data.range = parseInt(data.range); // if(data.isDefault!=1){
										success.call(this, data);
									}
								});
							}
						});
					}
				}

			}
		}
	}
};

const locationShow = () => {
	uni.showModal({
		title: '温馨提示',
		content: '获取定位失败，请前往设置打开定位权限',
		showCancel: false,
		success(res) {
			if (res.confirm) {
				// console.log('用户点击确定');
				uni.openSetting({
					success(res) {
						// console.log(res.authSetting); // res.authSetting = {
					}

				});
			}
		}

	});
}


module.exports = {
	initMerchant: initMerchant,
	defaultMerchant: defaultMerchant,
	getMerchant: getMerchant,
	
	
	// poi位置
	get_nearby_dialogue: '/api/v3/moments/getNearbyDialogue',//获取附近话题
	
	// 团队管理
	create_user_team: '/api/v3/cloud/user/team',//创建团队get,修改团队put
	user_team_page: '/api/v3/cloud/user/team/page',//团队列表
	user_team_list: '/api/v3/cloud/user/team/list',//我的团队列表
	user_team_info: '/api/v3/cloud/user/team/',//团队详情{id}
	user_team_users: '/api/v3/cloud/user/team/users',//团队成员
	user_team_follow: '/api/v3/cloud/user/team/follow',//加入团队
	user_team_remove: '/api/v3/cloud/user/team/remove',//移除团队成员
	
	// 优惠券
	coupon_exchange: '/api/v3/coupon/exchange',//兑换码兑换优惠券
	
	//关注用户
	follow_user_list: '/api/v3/behavior/getFollowUserList',//关注用户列表
};
