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

// 上传方法
const uploadFile = (option) => {
	const header = HttpRequestHeader(option)
	return new Promise(resolve => {
		uni.uploadFile({
			url: option.url,
			filePath: option.filePath,
			header: header,
			timeout: 10000,
			name: option.name || 'file',
			formData: option.formData || {},
			success: (response) => {
				if (response.data) {
					response.data = JSON.parse(response.data)
				}
				// HttpRequestLog(option.url, params, res.data)
				handleResponse(response, resolve)
			},
			fail: (err) => {
				// HttpRequestLog(option.url, params, err)
				handleError(err, resolve)
			}
		})
	})
}

// 批量上传文件，同一个bizCode
const uploadFiles = (option) => {
	const queue = async (filePaths) => {
		let res = []
		for (let filePath of filePaths) {
			const params = {
				url: option.url,
				filePath: filePath,
				formData: option.formData
			}
			const { code, data } = await uploadFile(params)
			if (code === 200) {
				res.push(data)
			} else {
				return Promise.resolve({ code: 999 })
			}
		}
		const callbackData = {
			files: res
			// filePaths: res.map(el => el.filePath)
		}
		return Promise.resolve({ code: 200, data: callbackData })
	}
	return queue(option.filePaths)
}

// 请求结果处理
const handleResponse = (response, resolve) => {
	if (response.statusCode === HttpStatus.SUCCESS) {
		const responseData = response.data
		// 登录无内部code，先这么处理
		if (!responseData.Code) {
			resolve({ code: 200, data: responseData })
			return
		}
		// 有内部code处理
		if (responseData.Code === HttpResponseCode.SUCCESS) {
			resolve({ code: 200, data: responseData.Data, totalData: responseData, message: '' })
		} else {
			resolve({ code: 999, data: null, message: responseData.Msg || '' })
			if (responseData.Msg) {
				ShowErrorMessage(responseData.Msg)
			}
			if (responseData.Code === HttpResponseCode.TOKENERROR || responseData.Code === HttpResponseCode.TOKENERROR2) {
				const userStore = useUserStore()
				userStore.logout()
				uni.reLaunch({
					url: '/pages/index/index'
				})
			}
		}
	} 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('Sorry，服务器开小差了！')
		}
	}
}

const handleError = (error, resolve) => {
	resolve({ code: 999, data: null, message: error.message })
	ShowErrorMessage('Sorry，服务器开小差了！')
}

export default {
	uploadFile,
	uploadFiles
}
