import {BASEURL, TokenPrefix, APIPrefix} from '../publicConfig/config'
import compress from '../utils/compress'

let uploadFile = async (api, filePath, fileType, header = {}) => {
	header = {
		'Cookie': 'XSRF-TOKEN=' + uni.getStorageSync(`${TokenPrefix}_XSRFToken`) || '',
		"X-XSRF-TOKEN": uni.getStorageSync(`${TokenPrefix}_XSRFToken`) || '',
		"Authorization": uni.getStorageSync(`${TokenPrefix}_token`) || '',
	}
	uni.showLoading({
		title: '上传中',
	})

	if(fileType === 'image'){
		filePath = await compress(filePath) //图片压缩
	}
	
	return new Promise((reslove, reject) => {
		api = APIPrefix + api
		uni.uploadFile({
			//#ifdef MP
			url: BASEURL.url + `${api}`, //开发者服务器地址
			//#endif

			//#ifdef H5
			url: api, //H5使用代理
			//#endif		
			filePath,
			name: 'file',
			header,
			success: (res) => {
				uni.hideLoading()
				if (res.data.reCode == 401 || res.data.reCode == -1) {
					let app = getApp()
					uni.showToast({
						title: '登录已过期',
						icon: 'error',
						duration: 3000
					})
					uni.removeStorageSync(`${TokenPrefix}_token`)
					uni.removeStorageSync(`${TokenPrefix}_XSRFToken`)
					uni.removeStorageSync('cookies')
					app.judgePlatform();
				}
				reslove(res.data)
			},
			fail: (err) => {
				uni.hideLoading()
				uni.showToast({
					title: '上传失败！',
					icon: 'error'
				})
				console.log(err);
				reject(err)
			}
		})
	})
}

export default uploadFile
