import {
	user
} from '@/utils/api'

export const parseTime = (time, cFormat) => {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if (typeof time === 'string') {
			if (/^[0-9]+$/.test(time)) {
				time = parseInt(time)
			} else {
				time = time.replace(new RegExp(/-/gm), '/')
			}
		}
		if (typeof time === 'number' && time.toString().length === 10) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
		const value = formatObj[key]
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		return value.toString().padStart(2, '0')
	})
	return time_str
}

module.exports = {
	loadImage(url) {
		return new Promise((resolve, reject) => {
			uni.request({
				method: 'get',
				url: url,
				responseType: 'arraybuffer'
			}).then((response) => {
				const [error, res] = response
				if (res && res.statusCode == 200) {
					try {
						var bytes = new Uint8Array(res.data);
						var binary = '';
						var len = bytes.byteLength;

						// 对数据进行异或处理
						for (var i = 0; i < len; i++) {
							bytes[i] = bytes[i] ^ 136; // 注意：136 是数字，不要加引号
						}

						// #ifdef APP-PLUS
						for (var i = 0; i < len; i++) {
							binary += String.fromCharCode(bytes[i]);
						}
						var base64Data = btoa(binary);
						resolve('data:image/jpeg;base64,' + base64Data);
						// #endif

						// #ifdef H5
						var blob = new Blob([bytes], {
							type: 'image/jpeg'
						});
						var reader = new FileReader();
						reader.onloadend = function() {
							resolve(reader.result); // 读取结果为 Base64 格式的 Data URL
						};
						reader.readAsDataURL(blob); // 将 Blob 读取为 Base64 Data URL
						// #endif
					} catch (e) {
						resolve(url);
					}
				} else {
					resolve(url);
				}
			}).catch(error => {
				resolve(url);
			});
		});
	},
	getAppVersion() {
		return new Promise(resolve => {
			plus.runtime.getProperty(plus.runtime.appid, function(inf) {
				resolve({
					versionCode: inf.versionCode,
					versionName: inf.version
				});
			});
		});
	},
	isVpn: () => {
		return plus.networkinfo.isSetProxy();
	},
	openVideo(id) {
		// #ifdef H5
		this.openUrl('/pages/video/video?id=' + id);
		// #endif
		// #ifdef APP-PLUS
		this.openUrl('/pages/video/video-app?id=' + id);
		// #endif
	},
	getuuid: () => {
		// #ifdef APP-PLUS
		return new Promise((resolve, reject) => {
			plus.device.getInfo({
				success: function(e) {
					resolve(e.uuid)
				},
				fail: function(e) {
					resolve('')
				}
			});
		})
		// #endif
	},

	isFullApp: () => {
		if (process.env.NODE_ENV === 'development') {
			return true
		}
		// #ifndef APP-PLUS
		return window.navigator.standalone
		// #endif
		return true
	},
	openApp: (url) => {
		// #ifdef H5
		window.location.href = url
		// #endif

		// #ifdef APP-PLUS
		plus.runtime.openURL(url);
		// #endif
	},
	error(url) {
		return new Promise((resolve, reject) => {
			uni.request({
				method: 'get',
				url: url,
				responseType: 'arraybuffer'
			}).then((response) => {
				const [error, res] = response
				try {
					var bytes = new Uint8Array(res.data);
					var binary = ''
					var len = bytes.byteLength
					for (var i = 0; i < len; i++) {
						bytes[i] = bytes[i] ^ '136'
					}
					if (this.isFullApp()) {
						for (var i = 0; i < len; i++) {
							binary += String.fromCharCode(bytes[i]);
						}
						var base64Data = btoa(binary);
						resolve('data:image/jpeg;base64,' + base64Data);
					} else {
						var blob = new Blob([bytes], {
							type: 'image/jpeg'
						})
						resolve(URL.createObjectURL(blob));
					}
				} catch (e) {}
			}).catch(error => {})
		});

	},
	openAD: (url) => {
		const token = uni.getStorageSync('user_token')
		if (token) {
			user.task(3).then()
		}
		// #ifdef H5
		window.open(url)
		// #endif

		// #ifdef APP-PLUS
		plus.runtime.openURL(url);
		// #endif
	},
	openUrl: (url) => {
		uni.navigateTo({
			url: url
		})
	},
	back: () => {
		const pages = getCurrentPages()
		if (pages.length === 1) {
			uni.switchTab({
				url: '/pages/home/index'
			})
		} else {
			uni.navigateBack()
		}
	},
	formatTime: (time) => {
		if (('' + time).length === 10) {
			time = parseInt(time) * 1000
		} else {
			time = +time
		}
		const date = new Date(time)
		const localTime = Date.now()
		const localDate = new Date(localTime)
		const utcTime = localTime + (localDate.getTimezoneOffset() * 60000)
		const currentTime = utcTime + (3600000 * (8))
		const currentDate = new Date(currentTime)
		const diff = (currentTime - time) / 1000
		if (diff < 60) {
			return '刚刚'
		} else if (diff < 3600) {
			return parseInt(diff / 60) + '分钟前'
		} else if (diff < 3600 * 24) {
			return parseInt(diff / 3600) + '小时前'
		} else if (currentDate.getFullYear() == date.getFullYear()) {
			return parseTime(time, '{m}-{d} {h}:{i}')
		} else {
			return parseTime(time, '{y}-{m}-{d} {h}:{i}')
		}
	}
}