import applist from '@/api/modules/applist.js'
import sha256 from 'crypto-js/sha256'
import request from '@/api/request'
import QRCode from 'qrcode'
import dayjs from 'dayjs'
import wxUtils from './modules/wx.js'
import route from './modules/route.js'
dayjs.locale('zh-cn')

let goMiniAppFlag = false
let imagePrefix = ''
setTimeout(()=>{
	imagePrefix="https://ct.zzxcx.net/ctjk/mp-wx/"
},500)
const utils = {
	dynaImagePrefix(src){
		return imagePrefix+src


	},
	mapToUrlQuery(map) {
		let str = ""
		if (typeof map !== 'object') {
			return false
		}
		for (const key in map) {
			if (Object.hasOwnProperty.call(map, key)) {
				str += (key + "=" + map[key])+"&"

			}
		}
		// console.log(str)
		return str

	},
	//生成二维码图片
	async qrcodeGenerate(data) {
		let qrcodeRes = await QRCode.toString(data, {
			margin: 0,
			errorCorrectionLevel: 'H'
		});
		return 'data:image/svg+xml;base64,' + Buffer(qrcodeRes).toString('base64');
	},
	//引入路由相关函数
	route,
	//引入微信相关utils
	wxUtils,
	//引入moment模块
	dayjs,
	//临时测试接口请求
	testReq(data) {
		return request(data)
	},

	//vant通知组件调用函数
	Toast(title) {
		wx.showToast({
			title,
			icon: 'none'
		})
	},
	//防抖函数
	debounce(func, fnThis, wait) {
		var timer;
		return () => {
			timer && clearTimeout(timer);
			timer = setTimeout(() => {
				func.call(fnThis)
				timer = null
			}, wait);
		};
	},
	//节流函数
	throttling(func, fnThis, wait) {
		var timer;
		return () => {
			clearTimeout(timer);
			timer = setTimeout(func.bind(fnThis), wait);
		};
	},
	//跳转小程序
	goMiniApp(data, item) {

		if (goMiniAppFlag) return
		goMiniAppFlag = true

		let myData = JSON.parse(data)
		wx.navigateToMiniProgram({
			...myData,
			success: (res) => {
				// 打开成功
				goMiniAppFlag = false
				item && applist.BrowseRecordAdd(item.id)
			},
			fail: () => {
				goMiniAppFlag = false
			}
		})

	},
	//跳转页面
	goPage(url, type, data) {
		if (type == 'reLaunch') {
			uni.reLaunch({
				url
			});
			return
		}
		if (type == 'redirectTo') {
			uni.redirectTo({
				url
			});
			return
		}
		uni.navigateTo({
			url,
			success: function (res) {
				// 通过eventChannel向被打开页面传送数据
				res.eventChannel.emit('passParameters', data)
			}
		});
	},
	//页面接受参数
	goPageGetData() {
		return new Promise((res) => {
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.on('passParameters', function (data) {
				res(data)
			})
		})
	},
	//返回今天明天后天周几
	getDay(date) {
		let UTCDay = new Date(date).getUTCDay()
		let jetLag = new Date(date).getTime() - new Date().getTime()
		let dayDif = jetLag / (1000 * 60 * 60 * 24)
		if (dayDif < 2) {
			if (dayDif < 0) {
				return '今天'
			}
			if (dayDif < 1) {
				return '明天'
			}
			if (dayDif < 2) {
				return '后天'
			}
		}
		switch (UTCDay) {
			case 0:
				return '周天';
			case 1:
				return '周一';
			case 2:
				return '周二';
			case 3:
				return '周三';
			case 4:
				return '周四';
			case 5:
				return '周五';
			case 6:
				return '周六';
		}
	}
}


export default utils
