// vuex使用
import store from '@/store/index.js'
import request from '@/api/request.js'
import amapFile from "@/libs/amap-wx.130.js";
// 跳转tab
function beforeSwitch(e) {
	// 返回一个promisea
	let assitindex = new Promise((resolve, reject) => {
		//验证是否是当前页面重复跳转
		let lastcurrentpro = store.state.lastcurrentpro
		let currentpro = store.state.currentpro
		if (lastcurrentpro === null) {
			resolve('赋值tabbar下标成功')
		} else {
			// 非首次登录,验证是否重复跳转
			if (lastcurrentpro !== e) {
				resolve('赋值tabbar下标成功')
			} else {
				reject('重复跳转')
			}
		}
	})
	//赋值完毕跳转
	assitindex.then(function(data) {
		uni.switchTab({
			url: store.state.vuex_tabbar[store.state.currentpro].pagePath
		})
	}).catch(function(reason) {
		console.log(reason)
	})
}
//跳转登录
function gologin(text) {
	//清除缓存
	uni.clearStorage()
	uni.showToast({
		icon: 'none',
		title: text,
		duration: 600
	})
	setTimeout(() => {
		uni.redirectTo({
			url: '/pages/usercenter/login/login'
		})
	}, 600)
}
//修正路径tabber
function pageaddress(route) {
	store.state.vuex_tabbar.forEach((item, index) => {
		if (item.pagePath === route) {
			store.commit('changecurrentprot', index)
		}
	})
}
//发送指令（向PC）
function postMessage(pdata) {
	// #ifdef H5
	parent.postMessage(JSON.stringify(pdata), "*");
	// #endif
}
// 获取配置
function getsetting(data) {
	return request({
		url: 'api/index/setting',
		method: 'post',
		data
	})
}
//微信授权登录
function h5_wx_auth(appid, redirect_uri) {
	//固定方法  打开授权页面
	uni.showLoading({
		title: '获取授权'
	});
	setTimeout(function() {
		uni.hideLoading();
		window.location.href =
			'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
			appid +
			'&redirect_uri=' +
			redirect_uri +
			'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
	}, 1000);
}
// 扫一扫
function getscan(data) {
	return request({
		url: 'api/vip/getscan',
		method: 'post',
		data
	})
}
//单选更改数据通用处理方法
function radiochangedata(e, operationdata) {
	let params = {
		item: null,
		list: operationdata
	}
	operationdata.forEach((item, index) => {
		if (item.id === e.id) {
			item.selected = 1
			params.item = item
			return params
		} else {
			item.selected = 0
		}
	})
	return params
}
// 多选更改数据通用处理方法
function multisedata(e, operationdata) {
	let seedlengh = operationdata.filter(item => item.selected === 1)
	let selength = seedlengh.filter(item => item.id === e.id).length
	if (selength > 0) {
		operationdata.forEach((item, index) => {
			if (item.id === e.id) {
				if (item.selected === 1) {
					item.selected = 0
				}
			}
		})
		return operationdata
	} else {
		if (seedlengh.length < 5) {
			operationdata.forEach((item, index) => {
				if (item.id === e.id) {
					if (item.selected === 0) {
						item.selected = 1
					}
				}
			})
		} else {
			uni.showToast({
				title: '最多选五项',
				icon: 'none'
			})
		}
	}
	return operationdata
}
// form多选装载数据
function setdata(data) {
	// type等于1则是单选装载数据,否则是多选装载数据
	if (data.length === 0) {
		uni.showToast({
			title: '请选择数据',
			icon: 'none'
		})
		return ''
	} else {
		let arraystring = ''
		let adnum = 0
		data.forEach((item, index) => {
			if (item.selected === 1) {
				if (index !== data.length && adnum !== 0) {
					arraystring = arraystring + ','
				}
				arraystring = arraystring + item.name
				adnum = adnum + 1
			}
		})
		return arraystring
	}
}
// form多选装载数据
function setdata_(data) {
	// type等于1则是单选装载数据,否则是多选装载数据
	if (data.length === 0) {
		uni.showToast({
			title: '请选择数据',
			icon: 'none'
		})
		return ''
	} else {
		let Arr_ = []
		data.forEach((item, index) => {
			let Arr = {
				id: '',
				name: ''
			}
			if (item.selected == 1) {
				Arr.id = item.id
				Arr.name = item.name
				Arr_.push(Arr)
			}
		})
		return Arr_
	}
}

function setdata_Cake(data) {
	var cake = data[0].code
	// type等于1则是单选装载数据,否则是多选装载数据
	if (data.length === 0) {
		uni.showToast({
			title: '请选择数据',
			icon: 'none'
		})
		return ''
	} else {
		let Arr_ = {
			facilitator_key: '',
			typecode: '',
			type: []
		}
		Arr_.facilitator_key = cake
		Arr_.typecode = cake
		data.forEach((item, index) => {
			let Arr = {
				typeid: '',
				typename: ''
			}
			if (item.selected == 1) {
				Arr.typeid = item.id
				Arr.typename = item.name
				Arr_.type.push(Arr)
			}
		})
		return Arr_
	}
}

function push_code(data) {
	var cake = data[0].code
	// type等于1则是单选装载数据,否则是多选装载数据
	let Arr_ = {
		push_key: '',
		typecode: '',
		type: []
	}
	Arr_.push_key = cake
	Arr_.typecode = cake
	data.forEach((item, index) => {
		let Arr = {
			typeid: '',
			typename: ''
		}
		if (item.selected == true) {
			Arr.typeid = item.id
			Arr.typename = item.name
			Arr_.type.push(Arr)
		}
	})
	return Arr_
}

function park_code(data) {
	var cake = data[0].code
	// type等于1则是单选装载数据,否则是多选装载数据
	let Arr_ = {
		park_key: '',
		typecode: '',
		type: []
	}
	Arr_.park_key = cake
	Arr_.typecode = cake
	data.forEach((item, index) => {
		let Arr = {
			typeid: '',
			typename: ''
		}
		if (item.selected == true) {
			Arr.typeid = item.id
			Arr.typename = item.name
			Arr_.type.push(Arr)
		}
	})
	return Arr_
}
let jumplist = {
	// 集市
	countryfair: {
		type: 1,
		url: '/pages/mine/market/market',
		typecode: 'countryfair',
		tabcode: 'resourcezhtype'
	},
	// 资源置换
	replacement: {
		type: 1,
		url: '/pages/index/screendetil/screendetil',
		typecode: 'replacement',
		tabcode: 'resourcezhtype'
	},
	// 效果甲方
	aeffectparty: {
		type: 1,
		url: '/pages/index/screendetil/screendetil',
		typecode: 'aeffectparty',
		tabcode: 'cooperationtype'
	},
	// 效果乙方
	beffectparty: {
		type: 1,
		url: '/pages/index/screendetil/screendetil',
		typecode: 'beffectparty',
		tabcode: 'generalization'
	},
	// 产品寻销
	pmarketing: {
		type: 1,
		url: '/pages/index/screendetil/screendetil_cpxx',
		typecode: 'pmarketing',
		tabcode: 'cooperationcxxs'
	},
	// 销货渠道
	saleschannel: {
		type: 1,
		url: '/pages/index/screendetil/screendetil_xhqd',
		typecode: 'saleschannel',
		tabcode: 'providechannels'
	},
	// 免费专区
	industryepe: {
		type: 1,
		url: '/pages/index/freezone/freezone',
		typecode: 'replacement',
		tabcode: 'industryepe'
	},
	// 活动合作
	activityhz: {
		type: 1,
		url: '/pages/index/screendetil/screendetil',
		typecode: 'activityhz',
		tabcode: 'activitytype'
	},
	// 场地资源
	siteresources: {
		type: 1,
		url: '/pages/index/screendetil/screendetil',
		typecode: 'siteresources',
		tabcode: 'sitetype'
	},
	// 线下媒体
	offlinemedia: {
		type: 1,
		url: '/pages/index/screendetil/screendetil',
		typecode: 'offlinemedia',
		tabcode: 'advertisingtypexx'
	},
	// 采购需求
	ptdemand: {
		type: 1,
		url: '/pages/index/screendetil/screendetil',
		typecode: 'ptdemand',
		tabcode: 'resourcezhtype'
	},
	// 企业服务
	cpservices: {
		type: 1,
		url: '/pages/index/screendetil/screendetil',
		typecode: 'cpservices',
		tabcode: 'facilitatortype'
	},
	// 招商加盟
	itpromotion: {
		type: 1,
		url: '/pages/index/screendetil/screendetil_zsjm',
		typecode: 'itpromotion',
		tabcode: 'cooperationtype'
	},
	// 线上媒体
	onlinemedia: {
		type: 1,
		url: '/pages/index/screendetil/screendetil',
		typecode: 'onlinemedia',
		tabcode: 'advertisingtypexs'
	},
	// 项目找代理
	projectagent: {
		type: 1,
		url: '/pages/index/screendetil/screendetil',
		typecode: 'projectagent',
		tabcode: 'joinagentfee'
	},
	// 项目找合伙人
	pproject: {
		type: 1,
		url: '/pages/index/screendetil/screendetil',
		typecode: 'pproject',
		tabcode: 'roletype'
	},
	// 渠道商
	channelbusines: {
		type: 2,
		url: '/pages/index/merchant/merchant_qds'
	},
	// 服务商
	serviceprovider: {
		type: 2,
		url: '/pages/index/merchant/merchant_fws'
	},
	// 品牌主
	brandowner: {
		type: 2,
		url: '/pages/index/merchant/merchant_ppz'
	},
	// 媒体
	media: {
		type: 2,
		url: '/pages/index/merchant/merchant_mt'
	},
	// 金牌会员
	openmember: {
		type: 3,
		url: '/pages/usercenter/openmember/openmember'
	},
	//道具商店
	propsmall: {
		type: 3,
		url: '/pages/usercenter/propsmall/propsmall'
	},
	// 邀请有礼
	sharecenter: {
		type: 3,
		url: '/pages/usercenter/sharecenter/sharecenter'
	},
	// 活动
	activitylist: {
		type: 3,
		url: '/pages/usercenter/activitylist/findactivity/findactivity'
	}
}

function charinit(bytedesk) {
	var appsetting = uni.getStorageSync('appsetting')
	if (!appsetting) {
		// 获取系统配置
		getsetting().then(res => {
			if (res.code === 1) {
				uni.setStorageSync('appsetting', res.data)
				var kf = res.data.set.kf
				if (kf.status == 1) {
					// 登录后台->渠道管理-》uniapp中创建应用获取
					bytedesk.init(kf.subdomain, kf.appKey)
				}
			}
		})
	} else {
		if (appsetting.set && appsetting.set.kf) {
			var kf = appsetting.set.kf
			if (kf.status == 1) {
				// 登录后台->渠道管理-》uniapp中创建应用获取
				bytedesk.init(kf.subdomain, kf.appKey)
			}
		}
	}
}

function toChar() {
	var appsetting = uni.getStorageSync('appsetting')
	if (!appsetting) {
		// 获取系统配置
		getsetting().then(res => {
			if (res.code === 1) {
				uni.setStorageSync('appsetting', res.data)
				var kf = res.data.set.kf
				console.log(JSON.stringify(kf))
				if (kf.status == 1) {
					uni.navigateTo({
						url: '/components/bytedesk_kefu/chat-kf?wid=' + kf.wid +
							'&type=workGroup&aid=&title=在线客服'
					})
				} else {
					uni.showToast({
						icon: 'none',
						title: '客服暂未开通'
					})
				}
			}
		})
	} else {
		var kf = appsetting.set.kf

		if (kf.status == 1) {
			uni.navigateTo({
				url: '/components/bytedesk_kefu/chat-kf?wid=' + kf.wid + '&type=workGroup&aid=&title=在线客服'
			})
			console.log(JSON.stringify(kf))
		} else {
			uni.showToast({
				icon: 'none',
				title: '客服暂未开通'
			})
		}
	}
}

function onNetworkStatusChange() {
	// uni.getNetworkType({
	// 	success: (res) => {
	// 		if (res.networkType == 'none'||res.networkType == 'unknown') {
	// 			uni.navigateTo({
	// 				url: '/pages/index/nonetwork'
	// 			})
	// 		}
	// 	}
	// })
}
// 综合跳转方法
function jumphref(jumpitem) {
	console.log(JSON.stringify(jumpitem))
	if (jumpitem.url != '#' && jumpitem.url != '') {
		//跳入内部制定好的页面
		if (jumpitem.opentype === 'inside') {
			let jumpurl = jumpitem.url
			var regPhone = (/pages/)
			if (!regPhone.test(jumpurl)) {
				let pageitem = jumplist[jumpitem.url]
				//tab筛选页面
				let params = {
					title: jumpitem.modularname,
					typecode: pageitem.typecode,
					tabcode: pageitem.tabcode
				}
				jumpurl = pageitem.url + '?params=' + JSON.stringify(params)
			}
			uni.navigateTo({
				url: jumpurl
			})
		}
		//跳入外部链接
		else if (jumpitem.opentype === 'web') {
			console.log(jumpitem.url)
			uni.navigateTo({
				url: '/pages/index/webpage?title=' + (jumpitem.modularname || jumpitem.title) + '&url=' +
					jumpitem.url
			})
		}
		//跳入文章
		else if (jumpitem.opentype === 'article') {
			uni.navigateTo({
				url: '/pages/release/agreement/agreement?type=3&title=' + jumpitem.modularname + '&id=' +
					jumpitem.url
			})
		}
	}
}

function toarticle(title, id = 0, type = 1) {
	uni.navigateTo({
		url: '/pagesC/pages/index/message/message?id=' + id + '&title=' + title + '&type=' + type
	})
}

function EACh(data, res) {
	var cake = data[0].code
	// type等于1则是单选装载数据,否则是多选装载数据
	let Arr_ = {
		type: [],
		title: ''
	}
	let name = ''
	data.forEach((item, index) => {
		res.forEach(d => {
			if (item.name == d.name) {
				name = d.name + ',' + name
				item.selected = 1
			}
		})
	})
	Arr_.type = data
	Arr_.title = name
	return Arr_
}

function u_gopage(key, item) {
	// console.log('key', key)
	// console.log('u_gopage', JSON.stringify(item))
	switch (key) {
		case 'U_cube':
		case 'U_slideshow':
		case 'U_button':
		case 'U_monitor':
			if (item.is_minApp == 1) {
				toUrl(item.h5_link);
			} else if (item.is_minApp == 2) {
				//跳转小程序
				skip(item.appid, item.minApp_link)
			}
			break;
		case 'U_goods':
		case 'U_goods2':
			toUrl('/pagesD/pages/product/product?id=' + item.id);
			break;
		case 'U_simplegraph':
			if (item.choose_style == 2) {
				if (item.value.is_minApp == 1) {
					toUrl(item.value.h5_link);
				} else if (item.value.is_minApp == 2) {
					//跳转小程序
					skip(item.value.appid, item.value.minApp_link)
				}
			} else if (item.choose_style == 3) {
				if (item.value.hotArea) {
					item = item.value.hotArea[0]
					if (item.is_minApp == 1) {
						toUrl(item.h5_link);
					} else if (item.is_minApp == 2) {
						//跳转小程序
						skip(item.appid, item.minApp_link)
					}
				}
			}
			break;
	}
}

function toUrl(_url) {
	//处理老版本更新 分包 url 变更
	let allurl = {
		'/pages/broadcast/broadcast': '/pagesE/pages/broadcast/broadcast',
		'/pages/mall/list': '/pagesE/pages/mall/list',
		'/pages/mall/group': '/pagesE/pages/mall/group',
		'/pages/mall/integral': '/pagesE/pages/mall/integral',
		'/pages/user/coupon/coupon': '/pagesE/pages/user/coupon/coupon',
		'/pages/index/signin/signin': '/pagesE/pages/index/signin/signin',
		'/pages/mynews/mynews': '/pagesE/pages/mynews/mynews',
		'/pages/user/problem/problem': '/pagesE/pages/user/problem/problem',
		'/pages/cart/cart': '/pagesE/pages/cart/cart',
	};
	let okeys = Object.keys(allurl)
	let tlist = uni.getStorageSync("tabbar")
	let flag = false
	if (tlist) {
		tlist.forEach((item, index) => {
			if (flag == false && _url.indexOf(item.url) > -1) {
				flag = true
			}
		})
	}
	okeys.forEach(function(item) {
		if (item == _url) {
			_url = allurl[item];
			return;
		}
	})
	// console.log('_url2', _url)
	// console.log('flag', flag)
	if (flag) {
		uni.switchTab({
			url: _url,
			fail: function(e) {
				uni.navigateTo({
					url: _url
				})
			}
		})
	} else {
		uni.navigateTo({
			url: _url,
			fail: function(e) {
				uni.switchTab({
					url: _url
				})
			}
		})
	}
}

//小程序跳转小程序
function skip(appId, path) {
	// #ifdef MP-WEIXIN
	uni.navigateToMiniProgram({
		// appid  写你要跳转的小程序的 appid
		appId: appId,
		// 路径写  src下的路径,假如你跳转的是pages下的页面,就可以写pages/index
		path: path,
		extraData: {
			// 'type': 'out'
		},
		// 这个不写的话会显示开发环境,不能正常跳转,写上就能正常跳转了
		envVersion: 'develop',
		success(res) {
			// 打开成功
			uni.showToast({
				title: '跳转成功'
			})
		},
		fail(err) {
			// 打开失败/取消
			uni.showToast({
				title: '跳转不成功'
			})
		}
	})
	// #endif	
}

function getselectlist(list1, list2) {
	for (var i = 0; i < list1.length; i++) {
		var item = list1[i]
		if (list2 && list2.length > 0) {
			for (var ii = 0; ii < list2.length; ii++) {
				var item2 = list2[ii]
				if (item.id == item2) {
					list1[i].selected = 1
				}
			}
		}
	}
	return list1
}

function myCache(k, v, t = 3600 * 24) {
	let dtime = '_deadtime';
	if (v) {
		uni.setStorageSync(k, v)
		var seconds = parseInt(t);
		if (seconds > 0) {
			var timestamp = Date.parse(new Date()); // 获取时间戳的毫秒数
			timestamp = timestamp / 1000 + seconds; // 时间戳 + 过期时间
			uni.setStorageSync(k + dtime, timestamp + "")
		} else {
			uni.removeStorageSync(k + dtime)
		}
	} else {
		var deadtime = parseInt(uni.getStorageSync(k + dtime)) // 获取缓存的时间
		if (deadtime) {
			if (parseInt(deadtime) < Date.parse(new Date()) / 1000) { // 如果缓存时间小于 当前时间戳
				return null;
			}
		}
		var res = uni.getStorageSync(k); // 否则直接读取真正的缓存名, 并且返回出去
		if (res) {
			return res;
		} else {
			return null;
		}
	}
}

// 位置授权（小程序）
function getAuthorizeInfo() {
	uni.authorize({
		scope: 'scope.userLocation',
		success() { // 允许授权
			uni.getLocation({
				success: function(res) {
					console.log("经纬度", res);
				},
			})
		},
		fail() { // 拒绝授权
			console.log("你拒绝了授权，无法获得周边信息")
		}
	})
}
// 获取地理位置
function getLocationInfo(mapkey, fun) {
	let amapObject = new amapFile.AMapWX({
		key: mapkey
	})
	amapObject.getRegeo({
		iconPath: "../../static/marker.png",
		success: (res) => {
			console.log(res, res[0].regeocodeData.formatted_address)
			// 移动到当前位置
			if (fun) {
				fun(res)
			}
		},
		fail: (err) => {
			console.log(err)
		}
	})
}
//改变地图中心位置
function toLocation(mapCtx, obj) {
	// 改变地图中心位置
	console.log('改变地图中心位置', obj)
	mapCtx.moveToLocation(obj)
	// 移动标记点并添加动画效果
	mapCtx.translateMarker({
		markerId: 1,
		autoRotate: false,
		duration: 100,
		destination: {
			latitude: obj.latitude,
			longitude: obj.longitude,
		},
		animationEnd() {
			console.log('animation end')
		}
	})
}

function chooseLocation(fun) {
	uni.chooseLocation({
		success: (res) => {
			if (fun) {
				fun(res);
			}
		},
		fail: () => {
			// 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息
			uni.getSetting({
				success: (res) => {
					console.log('getSetting', JSON.stringify(res));
					var status = res.authSetting;
					if (!status['scope.userLocation']) {
						// 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
						uni.showModal({
							title: "是否授权当前位置",
							content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
							success: (tip) => {
								if (tip.confirm) {
									// 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
									uni.openSetting({
										success: (data) => {
											// 如果用户授权了地理信息在，则提示授权成功
											if (data
												.authSetting[
													'scope.userLocation'
												] === true
											) {
												uni.showToast({
													title: "授权成功",
													icon: "success",
													duration: 1000
												})
												// 授权成功后，然后再次chooseLocation获取信息
												uni.chooseLocation({
													success: (
														res
													) => {
														if (
															fun
														) {
															fun(
																res
															);
														}
													}
												})
											} else {
												uni.showToast({
													title: "授权失败",
													icon: "none",
													duration: 1000
												})
											}
										}
									})
								}
							}
						})
					}
				},
				fail: (res) => {
					console.log('chooseLocationfail', JSON.stringify(res));
					uni.showToast({
						title: "调用授权窗口失败",
						icon: "none",
						duration: 1000
					})
				}
			})
		}
	});
}

function getnewurl() {
	let url = document.location.href;
	let reg = /[^\w](state|code)=?([^&|^#]*)/g;
	url = url.replace(reg, "");
	reg = /&&/g;
	url = url.replace(reg, "");
	reg = /&#/g;
	url = url.replace(reg, "#");
	reg = /\?#/g;
	url = url.replace(reg, "#");
	reg = /\?#/g;
	url = url.replace(reg, "#");
	return url;
}

function requestSubscribeMessage(tids, tmplId, callback) {
	// #ifdef MP-WEIXIN
	uni.getSetting({
	 
		withSubscriptions: true,
		success(res) {
			
			
			var itemSettings = res.subscriptionsSetting.itemSettings ? res.subscriptionsSetting
				.itemSettings : "";
			var flag = false;
			 
			//校验是否
			if (tids && tids.length > 0) {
				if (itemSettings) {
					tids.forEach((item, index) => {
						if (itemSettings[item] != 'accept') {
							flag = true;
						}
					});
				} else {
					flag = true;
				}
			}
			if (flag) {
				//未授权唤起授权
				uni.requestSubscribeMessage({
					tmplIds: tids,
					success(res) {},
					fail(err) {},
					complete() {
						callback ? callback() : null;
					}
				})
			} else {
				callback ? callback() : null;
			}
		}
	})
	// #endif
	// #ifndef MP-WEIXIN
	callback ? callback() : null;
	// #endif
}

export default {
	requestSubscribeMessage,
	getnewurl,
	chooseLocation,
	getAuthorizeInfo,
	getLocationInfo,
	toLocation,
	park_code,
	myCache,
	getselectlist,
	EACh,
	beforeSwitch,
	getsetting,
	radiochangedata,
	multisedata,
	setdata,
	setdata_,
	setdata_Cake,
	push_code,
	jumphref,
	toChar,
	charinit,
	pageaddress,
	getscan,
	toarticle,
	h5_wx_auth,
	onNetworkStatusChange,
	gologin,
	postMessage,
	toUrl,
	u_gopage
}
