import HttpClient from './http-client.js'
import { HttpStatus, HttpResponseCode, HttpRequestLog, ShowErrorMessage, HttpRequestHeader, HttpRequestData } from './http-constant.js'
import { useUserStore } from '@/store/useUserStore.js'
import { useAppStore } from '@/store/useAppStore.js'
import toast from '../toast/toast.js'

const httpClient = new HttpClient()

// http通用请求
const httpRequest = (option) => {
	const url = option.url
	const header = HttpRequestHeader(option)
	const data = HttpRequestData(option)
	// console.log("request data:", data);
	
	return new Promise(resolve => {
		httpClient.request({
			url: url,
			method: option.method,
			data: data,
			header: header,
			dataType: 'json',
			name: option.name
		}).then(res => {
			HttpRequestLog(url, data, res.data)
			handleResponse(res, resolve)
		}).catch(err => {
			HttpRequestLog(url, data, err)
			handleError(err, resolve)
		})
	})
}

// 请求结果处理
const handleResponse = (response, resolve) => {
	if (response.statusCode === HttpStatus.SUCCESS) {
		const responseData = response.data
		// 登录无内部code，先这么处理
		if (typeof responseData !== 'object' || !responseData.state) {
			resolve({ code: 200, data: responseData })
			return
		}
		// 有内部code处理
		if (responseData.state === HttpResponseCode.SUCCESS) {
			resolve({ code: 200, data: responseData.resultData, totalData: responseData, message: '', appDownloadUrl: responseData.appDownLoadURL || '' })
		} else {
			if (responseData.state === HttpResponseCode.TOKENERROR || responseData.state === HttpResponseCode.TOKENERROR2 || responseData.msg && (responseData.msg.includes('Please login first') > 0 || responseData.msg.includes('please login') > 0)) {
				console.log('guested', userStore.guested);
				const userStore = useUserStore()
				userStore.logout()
				if (userStore.guested) {
					uni.reLaunch({
						url: '/pages/Login/Login'
					})
				} else {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}
				toast.hideLoading()
				resolve({ code: 999, data: null, message: responseData.msg || 'request failed' })
			} else {
				toast.hideLoading()
				if (responseData.msg && !responseData.msg.includes('system')) {
					ShowErrorMessage(responseData.msg)
				}
			}
		}
	} else if (response.statusCode === HttpStatus.AUTHENTICATE) {
		resolve({ code: response.statusCode, data: null, message: response.errMsg })

		const userStore = useUserStore()
		userStore.logout()
		uni.reLaunch({
			url: '/pages/index/index'
		})
	} else {
		resolve({ code: response.statusCode, data: null, message: response.errMsg })
		if (response.data && response.data.message) {
			// ShowErrorMessage(response.data.message)
		} else {
			// ShowErrorMessage(`System Error! ${response.statusCode} ${response.errMsg}`)
		}
	}
}

const handleError = (error, resolve) => {
	resolve({ code: 999, data: null, message: error.message })
	// ShowErrorMessage(`System Error! ${error.message}`)
}

// get请求方法
const get = (option) => {
	option.method = 'GET'
	return httpRequest(option)
}

// post请求方法
const post = (option) => {
	option.method = 'POST'
	return httpRequest(option)
}

// 取消请求
const cancel = (name) => {
	httpClient.cancelRequest(name)
}

export default {
	get,
	post,
	cancel
}
