1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
import config from './config.js'
import md5 from './md5.min.js'
import CryptoJS from 'crypto-js'
let isOffLine = false

// 加法
// eslint-disable-next-line no-extend-native
Number.prototype.add = function (arg) {
	var r1, r2, m
	try {
		r1 = this.toString().split('.')[1].length
	} catch (e) {
		r1 = 0
	}
	try {
		r2 = arg.toString().split('.')[1].length
	} catch (e) {
		r2 = 0
	}
	m = Math.pow(10, Math.max(r1, r2))
	return (this.mul(m) + arg.mul(m)) / m
}

// 减法
// eslint-disable-next-line no-extend-native
Number.prototype.sub = function (arg) {
	return this.add(-arg)
}

// 乘法
// eslint-disable-next-line no-extend-native
Number.prototype.mul = function (arg) {
	var m = 0
	var s1 = this.toString()
	var s2 = arg.toString()
	try {
		m += s1.split('.')[1].length
	} catch (e) {}
	try {
		m += s2.split('.')[1].length
	} catch (e) {}
	return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m)
}

// 除法
// eslint-disable-next-line no-extend-native
Number.prototype.div = function (arg) {
	var t1 = 0
	var t2 = 0
	var r1
	var r2
	try {
		t1 = this.toString().split('.')[1].length
	} catch (e) {}
	try {
		t2 = arg.toString().split('.')[1].length
	} catch (e) {}
	r1 = Number(this.toString().replace('.', ''))
	r2 = Number(arg.toString().replace('.', ''))
	return (r1 / r2) * Math.pow(10, t2 - t1)
}

let timer

const formatTime = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

// 日期格式
const format = (date, fmt) => {
	let myDate
	if (fmt !== undefined) {
		myDate = date.Format(fmt)
	} else {
		myDate = date.Format('yyyy-MM-dd')
	}
	return myDate
}

// eslint-disable-next-line no-extend-native
Date.prototype.Format = function (fmt) {
	// author: meizz
	var o = {
		'M+': this.getMonth() + 1, // 月份
		'd+': this.getDate(), // 日
		'h+': this.getHours(), // 小时
		'm+': this.getMinutes(), // 分
		's+': this.getSeconds(), // 秒
		'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
		S: this.getMilliseconds() // 毫秒
	}
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
	for (var k in o) {
		if (new RegExp('(' + k + ')').test(fmt)) {
			fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
		}
	}
	return fmt
}

const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}

const getErrortxt = () => {
	return new Promise((resolve, reject) => {
		wx.downloadFile({
			url: 'https://hbrand.oss-cn-hangzhou.aliyuncs.com/PLATFORM/DEFAULT/errorMsgCpp.txt',
			success(res) {
				if (res.statusCode === 200) {
					const fs = wx.getFileSystemManager()
					const text = fs.readFileSync(res.tempFilePath, 'utf8', 0)
					resolve(text)
				} else {
					resolve('系统繁忙,请稍后再试')
				}
			},
			fail() {
				resolve('系统繁忙,请稍后再试')
			}
		})
	})
}

// 请求request
const request = (postData = {}) => {
	const { url = '', params = '', showLoading = true, noLogin = false, needErrorLog = false, method = 'POST', isShowCofirm = true,noPath = false } = postData

	wx.showNavigationBarLoading()

	if (showLoading) {
		wx.showLoading({
			title: '请求中...',
			mask: true
		})
	}

	return new Promise(async (resolve, reject) => {
			// 请求头相关
			const header = {
				'Content-Type': 'application/json'
			}
	
			if (!getApp().globalData.t && url !== '/system/doQueryApiSignValue.json' && url !== 'wpp/commonrequest/getRequestId.json') {
				const res = await getSelfCode()
				getApp().globalData.t = res.data
				currPost = null
			}
			if (url !== '/system/doQueryApiSignValue.json' && url !== 'wpp/commonrequest/getRequestId.json') {
				const r = await getRequestCode()
				const salt = config.clientType + getApp().globalData.t + r.slice(0, 3) + r.slice(-3)
				const key = CryptoJS.enc.Utf8.parse(r)
				const encrypted = CryptoJS.AES.encrypt(salt, key, {
					mode: CryptoJS.mode.ECB,
					padding: CryptoJS.pad.Pkcs7
				})
				header['X-RequestId'] = md5(CryptoJS.enc.Hex.stringify(CryptoJS.enc.Base64.parse(encrypted.toString())).toUpperCase())
			}
			/**
			 * 请求域名
			 */
			let apiBase = ''
			apiBase = config.dataServer
			if (noPath) {
				apiBase = config.noPathServer
			}

		console.log(apiBase + url,"apiBase + url");
		wx.request({
			url: apiBase + url,
			header,
			method,
			data: getPramsData(params),
			timeout: 30 * 1000,
			async success(res) {
				if (res.statusCode === 200) {
					resolve(res.data)
					if (!res.data.status && res.data.status !== 0) {
						if (res.data.errorCode === 'PROJECT_SERVER_OFFLINE_1001000') {
							if (!isOffLine) {
								isOffLine = true
								wx.showModal({
									title: '提示',
									content: res.data.errorMsg,
									showCancel: false,
									confirmText: '知道了',
									confirmColor: '#fe8600',
									success: (res) => {
										if (res.confirm) {
											wx.exitMiniProgram()
										}
									}
								})
							}
						} else {
							let { errorMsg } = res.data
							if (!errorMsg) {
								errorMsg = '提示|系统繁忙,请稍后再试'
							}
							const msg = errorMsg.split('|')
							const [title, content] = msg.length > 1 ? msg : ['提示', ...msg]
							wx.showModal({
								title,
								content,
								showCancel: false,
								confirmText: '知道了',
								confirmColor: '#fe8600'
							})
						}
						reject(res)
					} else if (res.data.status === 0) {
						if (res.data.errorMsg === 'MEMBER_NOT_LOGIN' || res.data.errorMsg === 'NOT_AUTH') {
							wx.removeStorageSync('nick')
							timer && clearTimeout(timer)
							timer = setTimeout(() => {
								needLogin()
							}, 500)
						} else if (res.data.errorMsg === 'SYSTEM_PUBLISHING') {
							wx.reLaunch({
								url: '/pages/defend/defend'
							})
						} else {
							if (needErrorLog) {
								reject(res.data)
								return
							}
							let { errorMsg } = res.data
							if (!errorMsg) {
								errorMsg = '提示|系统繁忙,请稍后再试'
							}
							const msg = errorMsg.split('|')
							const [title, content] = msg.length > 1 ? msg : ['提示', ...msg]
							if (isShowCofirm) {
								wx.showModal({
									title,
									content,
									showCancel: false,
									confirmText: '知道了',
									confirmColor: '#fe8600'
								})
							}
						}
					}
				} else {
					// errorMsgReport(
					//   `requestPath=${url}|params=${JSON.stringify(
					//     params
					//   )}|errorMsg=${res.statusCode}`
					// )
					const msg = await getErrortxt()
					wx.showModal({
						title: '提示',
						content: msg,
						showCancel: false,
						confirmText: '知道了',
						confirmColor: '#fe8600'
					})
					reject(res)
				}
			},
			async fail(res) {
				// rejecj(res)
				console.log(res)
				// errorMsgReport(
				//   `requestPath=${url}|params=${JSON.stringify(
				//     params
				//   )}|errorMsg=${res.statusCode}`
				// )
				const msg = await getErrortxt()
				wx.showModal({
					title: '提示',
					content: msg,
					showCancel: false,
					confirmText: '知道了',
					confirmColor: '#fe8600'
				})
			},
			complete() {
				wx.hideNavigationBarLoading()
				if (showLoading) {
					wx.hideLoading()
				}
			}
		})
	})
}

const getRequestCode = () => {
	return new Promise((resolve, reject) => {
		doPost({
			url: 'wpp/commonrequest/getRequestId.json',
			data: '',
			noPath: true,
			noLogin: true,
			isShowLoading: false,
			needErrorLog: true
		}).then(res => {
			getApp().globalData.r = res.data
			resolve(res.data)
		})
	})
}

let currPost

const getSelfCode = () => {
	if (getApp().globalData.t) {
		return Promise.resolve(getApp().globalData.t)
	} else {
		if (currPost) {
			return currPost
		}
		currPost = doPost({
			url: '/system/doQueryApiSignValue.json',
			noLogin: true,
			isShowLoading: false,
			params: ''
		},true)
		return currPost
	}
}

const doPost = (postData = {},old) => {
	const { url = '', params = '', showLoading = true, noLogin = false, needErrorLog = false, method = 'POST', isShowCofirm = true, isIntercept = false,noPath = false  } = postData

	wx.showNavigationBarLoading()

	if (showLoading) {
		wx.showLoading({
			title: '请求中...',
			mask: true
		})
	}

	return new Promise(async (resolve, reject) => {
		console.log(config.dataServer)
		// 请求头相关
		const header = {
			'Content-Type': 'application/json'
		}
		if (!getApp().globalData.t && url !== '/system/doQueryApiSignValue.json' && url !== 'wpp/commonrequest/getRequestId.json') {
			const res = await getSelfCode()
			getApp().globalData.t = res.data
			currPost = null
		}
		if (url !== '/system/doQueryApiSignValue.json' && url !== 'wpp/commonrequest/getRequestId.json') {
			const r = await getRequestCode()
			const salt = config.clientType + getApp().globalData.t + r.slice(0, 3) + r.slice(-3)
			const key = CryptoJS.enc.Utf8.parse(r)
			const encrypted = CryptoJS.AES.encrypt(salt, key, {
				mode: CryptoJS.mode.ECB,
				padding: CryptoJS.pad.Pkcs7
			})
			header['X-RequestId'] = md5(CryptoJS.enc.Hex.stringify(CryptoJS.enc.Base64.parse(encrypted.toString())).toUpperCase())
		}
		/**
		 * 请求域名
		 */
		let apiBase = ''
			apiBase = config.dataServer
		if (noPath) {
			apiBase = config.noPathServer
		}
		if(old){
			apiBase = config.dataServerOld
		}
		wx.request({
			url: apiBase + url,
			header,
			method,
			data: getPramsData(params),
			timeout: 30 * 1000,
			async success(res) {
				if (res.statusCode === 200) {
					if (isIntercept) {
						resolve(res.data)
						return
					}
					if (res.data.status === 1) {
						resolve(res.data)
					}
					if (res.data.status === 0) {
						if (res.data.errorMsg === 'MEMBER_NOT_LOGIN' || res.data.errorMsg === 'NOT_AUTH') {
							wx.removeStorageSync('nick')
							timer && clearTimeout(timer)
							timer = setTimeout(() => {
								needLogin('scan')
							}, 500)
						} else if (res.data.errorMsg === 'SYSTEM_PUBLISHING') {
							wx.reLaunch({
								url: '/pages/defend/defend'
							})
						} else {
							if (needErrorLog) {
								reject(res.data)
								return
							}
							let { errorMsg } = res.data
							if (!errorMsg) {
								errorMsg = '提示|系统繁忙,请稍后再试'
							}
							const msg = errorMsg.split('|')
							const [title, content] = msg.length > 1 ? msg : ['提示', ...msg]
							if (isShowCofirm) {
								wx.showModal({
									title,
									content,
									showCancel: false,
									confirmText: '知道了',
									confirmColor: '#fe8600'
								})
							}
							reject(res.data)
						}
					}
					if (!res.data.status && res.data.status !== 0) {
						if (res.data.errorCode === 'PROJECT_SERVER_OFFLINE_1001000') {
							if (!isOffLine) {
								isOffLine = true
								wx.showModal({
									title: '提示',
									content: res.data.errorMsg,
									showCancel: false,
									confirmText: '知道了',
									confirmColor: '#fe8600',
									success: (res) => {
										if (res.confirm) {
											wx.exitMiniProgram()
										}
									}
								})
							}
						} else {
							let { errorMsg } = res.data
							if (!errorMsg) {
								errorMsg = '提示|系统繁忙,请稍后再试'
							}
							const msg = errorMsg.split('|')
							const [title, content] = msg.length > 1 ? msg : ['提示', ...msg]
							wx.showModal({
								title,
								content,
								showCancel: false,
								confirmText: '知道了',
								confirmColor: '#fe8600'
							})
						}
						reject(res)
					}
				} else {
					const msg = await getErrortxt()
					wx.showModal({
						title: '提示',
						content: msg,
						showCancel: false,
						confirmText: '知道了',
						confirmColor: '#fe8600'
					})
					reject(res)
				}
			},
			async fail(res) {
				console.log(res)
				const msg = await getErrortxt()
				wx.showModal({
					title: '提示',
					content: msg,
					showCancel: false,
					confirmText: '知道了',
					confirmColor: '#fe8600'
				})
				reject(res)
			},
			complete() {
				wx.hideNavigationBarLoading()
				if (showLoading) {
					wx.hideLoading()
				}
			}
		})
	})
}

const getSign = context => {
	// 返回加密时间戳
	const { timestamp, token } = context
	const content = token + timestamp + 'key=MKnEu6zaS04N23XoMUL8GOwOKIQwXMvT'
	return md5(content).toUpperCase()
}

const getPramsData = prams => {
	// 所有必要传送数据的结合;
	const result = {}
	const context = getContext()
	result['data'] = prams
	result['context'] = context
	result['sign'] = getSign(context)
	return JSON.stringify(result)
}

const getContext = () => {
	// 返回context对象
	const result = {}
	result['clientType'] = config.clientType
	result['token'] = getToken()
	result['clientMac'] = getMac()
	result['versionNo'] = config.VERSION
	result['timestamp'] = Date.now().toString()
	result['requestPath'] = pageRouter().route
	return result
}

const getToken = () => {
	// 返回TOKEN值
	// return "member:2003631851592cfd235536f45"
	// return "member:2003774119a7079a5c4a71f7a"
	return wx.getStorageSync('nick') ? wx.getStorageSync('nick').token : ''
}

const getMac = () => {
	// 获取设备信息
	const res = wx.getSystemInfoSync()
	return `${res.model};${res.SDKVersion};${res.system};${res.version}`
}

const pageRouter = (index = 1) => {
	// eslint-disable-next-line no-undef
	const pages = getCurrentPages() // 获取加载的页面
	const currentPage = pages[pages.length - index] // 获取页面的对象
	return currentPage
}

const errorMsgReport = param => {
	wx.request({
		url: config.dataServer + '/operateLog/monitorLog.json',
		header: {
			'Content-Type': 'application/json'
		},
		method: 'POST',
		data: getPramsData(param)
	})
}

const needLogin = (type = '') => {
	setTimeout(() => {
		wx.showToast({
			title: '需要登录,查看更多',
			icon: 'none',
			duration: 1500
		})
	}, 0)
	setTimeout(() => {
		if (type === 'scan') {
			wx.reLaunch({
				url: `/pages/login/login?router=${encodeURIComponent(handleRouter())}&type=${type}`
			})
		} else {
			wx.reLaunch({
				url: `/pages/login/login?router=${encodeURIComponent(handleRouter())}`
			})
		}
	}, 1500)
}

const authPhone = () => {
	wx.reLaunch({
		url: `/pages/authPhone/authPhone?router=${encodeURIComponent(handleRouter())}`
	})
}

const handleRouter = () => {
	const { options, route } = pageRouter()
	return `/${route}${qs(options)}`
}

const qs = (options = {}) => {
	let qs = ''
	if (Object.keys(options)) {
		for (const i in options) {
			if (qs) {
				qs += `&${i}=${options[i]}`
			} else {
				qs += `?${i}=${options[i]}`
			}
		}
	}
	return qs
}

// 文件上传
const uploadFile = (context, callBack, hideLoading = true) => {
	let filePath = context
	if (typeof context === 'object') {
		wx.showLoading({
			title: context.msg
		})
		filePath = context.filePath
	}

	wx.uploadFile({
		url: config.uploadUrl + '/doUploadToCOS.json',
		filePath,
		name: 'file',
		header: {
			'content-type': 'multipart/form-data'
		},
		success(res) {
			if (res.statusCode === 200 && JSON.parse(res.data).data) {
				typeof callBack === 'function' && callBack(JSON.parse(res.data).data)
			} else {
				setTimeout(() => {
					wx.showToast({
						title: '上传失败',
						icon: 'none'
					})
				}, 1000)
			}
		},
		fail(e) {
			setTimeout(() => {
				wx.showToast({
					title: '上传出错',
					icon: 'none'
				})
			}, 1000)
		},
		complete() {
			if (hideLoading) {
				wx.hideLoading()
			}
		}
	})
}

const uploadFileToOss = (context, callBack) => {
	let filePath = context
	if (typeof context === 'object') {
		wx.showLoading({
			title: context.msg
		})
		filePath = context.filePath
	}

	wx.uploadFile({
		url: config.uploadUrl + '/doUploadFile.json',
		filePath,
		name: 'file',
		header: {
			'content-type': 'multipart/form-data'
		},
		success(res) {
			if (res.statusCode === 200 && JSON.parse(res.data).data) {
				typeof callBack === 'function' && callBack(JSON.parse(res.data).data)
			} else {
				setTimeout(() => {
					wx.showToast({
						title: '上传失败',
						icon: 'none'
					})
				}, 1000)
			}
		},
		fail(e) {
			setTimeout(() => {
				wx.showToast({
					title: '上传出错',
					icon: 'none'
				})
			}, 1000)
		},
		complete() {
			wx.hideLoading()
		}
	})
}

// 判断是否开启定位
const authorizeLocation = cb => {
	wx.getSetting({
		success(res) {
			if (!res.authSetting['scope.userLocation']) {
				wx.authorize({
					scope: 'scope.userLocation',
					success() {
						if (typeof cb === 'function') {
							cb()
						}
					},
					fail() {
						wx.navigateTo({
							url: '/pages/defaultError/defaultError?errorId=0&errorMsg=授权失败|我们需要您的位置信息来判断您能否参与活动, 请允许授权'
						})
					}
				})
			}
		}
	})
}
const authorizeFuzzyLocation = cb => {
	wx.getSetting({
		success(res) {
			if (!res.authSetting['scope.userFuzzyLocation']) {
				wx.authorize({
					scope: 'scope.userLocation',
					success() {
						if (typeof cb === 'function') {
							cb()
						}
					},
					fail() {
						wx.navigateTo({
							url: '/pages/defaultError/defaultError?errorId=0&errorMsg=授权失败|我们需要您的位置信息来判断您能否参与活动, 请允许授权'
						})
					}
				})
			}
		}
	})
}



// set小程序埋点参数
const setMatReportData = cb => {
	const userid = wx.getStorageSync('nick') ? wx.getStorageSync('nick').userId : ''
	const { model, system, version } = wx.getSystemInfoSync()
	const area = ''
	wx.getFuzzyLocation({
		type: 'gcj02',
		success(res) {
			request({
				url: '/doQueryLocate.json',
				params: res.latitude + ',' + res.longitude
			}).then(res => {
				if (res.data) {
					const area = res.data.province + res.data.city
					cb({
						wechatversion: version,
						userid: userid,
						mobile: model,
						os: system,
						area: area
					})
				}
			})
		}
	})
}

// 获取URL参数
const getQueryString = (str, queryName) => {
	var query = str.split('?')[1]
	var vars = query.split('&')
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split('=')
		if (pair[0] == queryName) {
			return pair[1]
		}
	}
	return null
}

const judgeEnv = () => {
	const ENV = {
		develop: {
			ywymCode: 'https://cos.hzhuihe.cn/y?r=', // 一物一码核销
			ksfGroupId: 2840 // 康师傅单品券活动ID
		},
		trial: {
			ywymCode: 'https://cos.hzhuihe.cn/y?r=',
			ksfGroupId: 2840
		},
		release: {
			ywymCode: 'https://cos.hzhuihe.cn/y?r=',
			ksfGroupId: 1491
		}
	}
	let urls = {}
	if (wx.getAccountInfoSync) {
		const accountInfo = wx.getAccountInfoSync()
		if (accountInfo.miniProgram && accountInfo.miniProgram.envVersion) {
			urls = ENV[accountInfo.miniProgram.envVersion] // DEV 开发环境  TEST 测试环境   PRO 生产环境
		} else {
			urls = ENV['release']
		}
	} else {
		urls = ENV['release']
	}
	return urls
}

// 校验
const regCheck = {
	Default(reg, str) {
		return reg.test(str)
	},
	IdCard(id) {
		var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
		return reg.test(id)
	},
	Phone(str) {
		var reg = /^1[3456789]\d{9}$/
		return reg.test(str)
	}
}

// 计算年龄
const getAge = strBirthday => {
	let returnAge
	const strBirthdayArr = strBirthday.split('-')
	const birthYear = Number(strBirthdayArr[0])
	const birthMonth = Number(strBirthdayArr[1])
	const birthDay = Number(strBirthdayArr[2])

	const d = new Date()
	const nowYear = d.getFullYear()
	const nowMonth = d.getMonth() + 1
	const nowDay = d.getDate()

	if (nowYear === birthYear) {
		returnAge = 0 // 同年 则为0岁
	} else {
		const ageDiff = nowYear - birthYear // 年之差
		if (ageDiff > 0) {
			if (nowMonth === birthMonth) {
				const dayDiff = nowDay - birthDay // 日之差
				if (dayDiff < 0) {
					returnAge = ageDiff - 1
				} else {
					returnAge = ageDiff
				}
			} else {
				const monthDiff = nowMonth - birthMonth // 月之差
				if (monthDiff < 0) {
					returnAge = ageDiff - 1
				} else {
					returnAge = ageDiff
				}
			}
		} else {
			returnAge = -1 // 返回-1 表示出生日期输入错误 晚于今天
		}
	}
	return returnAge // 返回周岁年龄
}

/**
 * @desc 倒计时功能
 * @params *num 倒计时时间(秒)*pending 每隔一秒执行的函数 *ending 倒计时结束
 */
const timeDown = (num, pending, ending) => {
	const date = new Date()
	const StartTime = date.getTime()
	time()
	const t = setInterval(time, 1000)

	function time() {
		const date = new Date()
		const ThisTime = date.getTime()
		const desc = ThisTime - StartTime
		const showTime = num - parseInt(desc / 1000)
		typeof pending === 'function' && pending(showTime)
		if (showTime <= 0) {
			clearInterval(t)
			typeof ending === 'function' && ending()
		}
	}
	return t
}

// 修复浮点计算的问题
const flootFix = val => {
	return Math.round(val * 100) / 100
}
// 获取链接?后面的参数
const GetUrlPara = (para, key) => {
	if (para) {
		var urlLength = para.split('?')
		if (urlLength.length <= 1) {
			return ''
		}
		var arr = urlLength[1].split('&')
		var len = arr.length
		var obj = {}
		for (var i = 0; i < len; i++) {
			var v = arr[i].split('=')
			var k = v[0]
			var value = v[1] ? v[1] : ''
			obj[k] = value
		}
		if (!key) {
			// 无key值,取全部
			return obj
		} else {
			// 有key值,取key值对应值
			return obj[key]
		}
	} else {
		return ''
	}
}
// 获取链接子路由
const GetUrlPath = path => {
	if (!path) {
		return ''
	}
	return path.split('n/')[1].split('?')[0]
}


//获取二维码的code与uri
const getCodeAndUri = url => {
	const code = url.split('/').pop(); // 获取最后一个部分
	const parts = url.split('/'); // 以 '/' 为分隔符拆分字符串
	const uri = parts.slice(2, 4).join('/'); // 提取第3和第4部分,并用 '/' 连接
	return {
		code,
		uri
	}
}


class Public {
	constructor() {
		this.handlers = {}
	}

	on(name, fun) {
		if (!(name in this.handlers)) {
			this.handlers[name] = []
		}
		this.handlers[name].push(fun)
		return this
	}

	off(name, fun) {
		const currentEvent = this.handlers[name]
		let len = 0
		if (currentEvent) {
			len = currentEvent.length
			for (let i = 0; i < len; i++) {
				if (currentEvent[i] === fun) {
					currentEvent.splice(i, 1)
				}
			}
			if (currentEvent.length === 0) {
				delete this.handlers[name]
			}
		}
		return this
	}

	emit() {
		const key = Array.prototype.shift.call(arguments)
		const callBack = this.handlers[key]
		if (!callBack || !callBack.length) return
		callBack.forEach(item => {
			item.apply(this, Array.prototype.slice.call(arguments, 1))
		})
	}
}

export default {
	format,
	request,
	authorizeLocation,
	authorizeFuzzyLocation,
	uploadFile,
	setMatReportData,
	getQueryString,
	regCheck,
	handleRouter,
	getAge,
	timeDown,
	judgeEnv,
	flootFix,
	Public,
	doPost,
	needLogin,
	GetUrlPara,
	GetUrlPath,
	authPhone,
	getToken,
	uploadFileToOss,
	getCodeAndUri
}