import {
	isFullApp,
	isVpn,
	getAppVersion
} from './utils'
// #ifdef APP-PLUS
import {
	encrypt,
	decrypt
} from './crypto';
// #endif
// #ifndef APP-PLUS
import {
	encrypt,
	decrypt
} from './crypto.dist'
// #endif

const resolveUrl = [
	'https://dns.alidns.com/resolve?name=tj.ht16bb.com&type=TXT',
	'https://doh.pub/dns-query?name=tj.ht16bb.com&type=TXT'
]

const getUrl = (url) => {
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'GET',
			url: url
		}).then((response) => {
			const [error, res] = response
			if (res && res.statusCode === 200) {
				resolve(res.data)
			} else {
				reject(error)
			}
		})
	})
}

export const getApiDomain = async () => {
	let apiDomain = uni.getStorageSync('API_DOMAIN')

	if (apiDomain == '' || apiDomain.length == 0) {
		apiDomain = []
		for (let index = 0; index < resolveUrl.length; index++) {
			const res = await getUrl(resolveUrl[index]).then(res => res).catch(err => {})
			if (res && res.Status == 0 && res.Answer[0].data) {
				let data = res.Answer[0].data.slice(1, -1).split(',')
				data = data.map(item => 'https://' + item.trim())
				for (let key = 0; key < data.length; key++) {
					const ok = await getUrl(data[key] + '/ok.txt').then(res => res).catch(err => {})
					if (ok == '200') {
						break
					}
					data.splice(key, 1)
				}
				if (data.length > 0) {
					apiDomain = data
					uni.setStorageSync('API_DOMAIN', apiDomain)
					uni.setStorageSync('API_DOMAIN_INDEX', 0)
					break
				}
			}
		}
	}
	return apiDomain
}

export const baseURL = () => {
	if (isFullApp()) {
		const apiDomain = uni.getStorageSync('API_DOMAIN')
		const index = uni.getStorageSync('API_DOMAIN_INDEX') || 0
		if (Array.isArray(apiDomain) && apiDomain.length > 0) {
			return apiDomain[index] || ''
		}
		return ''
	} else {
		return ''
	}
}

export const request = (url, params = {}, cache = false, header) => {
	return new Promise(async (resolve, reject) => {
		let apiDomain = uni.getStorageSync('API_DOMAIN')
		let index = uni.getStorageSync('API_DOMAIN_INDEX') || 0
		if (isFullApp()) {
			// #ifdef APP-PLUS
			if (isVpn()) {
				uni.showToast({
					title: '请关闭代理再试试吧~',
					icon: 'none'
				})
				return
			}
			// #endif
			if (apiDomain == '' || apiDomain.length == 0) {
				uni.showToast({
					title: '线路配置失效，即将重启APP',
					icon: 'none',
					complete: () => {
						setTimeout(() => {
							// #ifdef APP-PLUS
							plus.runtime.restart()
							// #endif
							// #ifdef WEB
							uni.reLaunch({
								url: '/pages/splash/splash'
							})
							// #endif
						}, 1500)
					}
				})
				reject('线路配置失效')
				return
			}
		} else {
			apiDomain = ['']
		}
		const token = uni.getStorageSync('user_token')
		const uuid = uni.getStorageSync('user_uuid')

		// #ifdef APP-PLUS
		const app_version = await getAppVersion();
		if (app_version.versionName) {
			params.app_version = app_version.versionName
		}
		if (uni.getSystemInfoSync().platform == 'ios') {
			params.app_name = 'ios' + uni.getSystemInfoSync().appId
		}
		if (uni.getSystemInfoSync().platform == 'android') {
			params.app_name = 'android' + uni.getSystemInfoSync().appId
		}
		// #endif
		// #ifdef H5
		let httpData = uni.getStorageSync('platform') || {};
		params.app_version = httpData.versionCode
		params.app_name = 'h5' + uni.getSystemInfoSync().appId
		// #endif
		if (token) {
			params.user_token = token
		}
		if (uuid) {
			params.user_uuid = uuid
		}

		params.timestamp = parseInt(new Date().getTime() / 1000)
		header = header || {
			'Content-Type': 'application/x-www-form-urlencoded'
		}

		while (index < apiDomain.length) {
			if (cache) {
				const cacheData = uni.getStorageSync(url)
				if (cacheData) {
					console.log('【出发缓存】');
					let resData = JSON.parse(cacheData)
					let nowTimestamp = new Date().getTime();
					if (nowTimestamp - resData.timestamp < 5 * 60 * 1000) {
						resolve(resData.data)
						break
					}
				}
			}
			const response = await uni.request({
				method: 'POST',
				url: apiDomain[index] + url,
				data: {
					data: encrypt(params)
				},
				header: header,
			}).then(response => response)
			const [error, res] = response
			if (error) {
				if (index < apiDomain.length - 1) {
					index++
					uni.setStorageSync('API_DOMAIN_INDEX', index)
				} else {
					uni.removeStorageSync('API_DOMAIN')
					uni.removeStorageSync('API_DOMAIN_INDEX')
					uni.showToast({
						title: '线路配置失效，即将重启APP',
						icon: 'none',
						complete: () => {
							setTimeout(() => {
								// #ifdef APP-PLUS
								plus.runtime.restart()
								// #endif
								// #ifdef WEB
								uni.reLaunch({
									url: '/pages/splash/splash'
								})
								// #endif
							}, 1500)
						}
					})
					reject('线路配置失效')
					break
				}
			} else {
				if (res.statusCode === 200) {
					if (res.data.data) {
						res.data.data = decrypt(res.data.data)
					}
					switch (res.data.code) {
						case 100:
							uni.removeStorage({
								key: 'user_token',
								success: (res) => {
									const pages = getCurrentPages()
									getApp().globalData.share.code = ''
									getApp().globalData.userToken = ''
									if (pages.length === 1) {
										uni.navigateTo({
											url: '/pages/user/login'
										})
									} else {
										uni.redirectTo({
											url: '/pages/user/login'
										})
									}
								}
							})
							break
						default:
							break
					}
					if (cache) {
						let timestamp = new Date().getTime();
						let resData = {
							"data": res.data,
							"timestamp": timestamp,
						}
						uni.setStorage({
							key: url,
							data: JSON.stringify(resData)
						})
					}
					resolve(res.data)
				} else {
					// uni.showToast({
					// 	icon: 'none',
					// 	title: '网络繁忙，请稍候访问~!（' + res.statusCode + '）',
					// 	duration: 3000
					// })
					reject('服务器出错(' + res.statusCode + ')')
				}
				break
			}
		}
	})
}

export const upload = (url, params = {}) => {
	return new Promise(async (resolve, reject) => {
		let apiDomain = uni.getStorageSync('API_DOMAIN')
		let index = uni.getStorageSync('API_DOMAIN_INDEX') || 0
		if (isFullApp()) {
			if (apiDomain == '' || apiDomain.length == 0) {
				uni.showToast({
					title: '线路配置失效，即将重启APP',
					icon: 'none',
					complete: () => {
						setTimeout(() => {
							// #ifdef APP-PLUS
							plus.runtime.restart()
							// #endif
							// #ifdef WEB
							uni.reLaunch({
								url: '/pages/splash/splash'
							})
							// #endif
						}, 1500)
					}
				})
				reject('线路配置失效')
				return
			}
		} else {
			apiDomain = ['']
		}
		const token = uni.getStorageSync('user_token')
		const uuid = uni.getStorageSync('user_uuid')
		if (token) {
			params.user_token = token
		}
		if (uuid) {
			params.user_uuid = uuid
		}
		params.timestamp = parseInt(new Date().getTime() / 1000)

		while (index < apiDomain.length) {
			const response = await uni.uploadFile({
				url: apiDomain[index] + '/api/upload/save',
				filePath: url,
				name: 'file',
				formData: {
					data: encrypt(params)
				}
			}).then(response => response)
			const [error, res] = response
			if (error) {
				if (index < apiDomain.length - 1) {
					index++
					uni.setStorageSync('API_DOMAIN_INDEX', index)
				} else {
					uni.removeStorageSync('API_DOMAIN')
					uni.removeStorageSync('API_DOMAIN_INDEX')
					uni.showToast({
						title: '线路配置失效，即将重启APP',
						icon: 'none',
						complete: () => {
							setTimeout(() => {
								// #ifdef APP-PLUS
								plus.runtime.restart()
								// #endif
								// #ifdef WEB
								uni.reLaunch({
									url: '/pages/splash/splash'
								})
								// #endif
							}, 1500)
						}
					})
					reject('线路配置失效')
					break
				}
			} else {
				if (res.statusCode === 200) {
					const resData = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
					if (resData.data) {
						resData.data = decrypt(resData.data)
					}
					resolve(resData)
				} else {
					uni.showToast({
						icon: 'none',
						title: '网络繁忙，请稍候访问~!（' + res.statusCode + '）',
						duration: 3000
					})
					reject('服务器出错(' + res.statusCode + ')')
				}
				break
			}
		}
	})
}