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

let downloadFile = (api, filePath, header = {}, showLoading = true) => {
	filePath = filePath.split('=')[1] ? filePath.split('=')[1] : filePath
	header = {
		'Cookie': 'XSRF-TOKEN=' + uni.getStorageSync(`${TokenPrefix}_XSRFToken`) || '',
		"X-XSRF-TOKEN": uni.getStorageSync(`${TokenPrefix}_XSRFToken`) || '',
		"Authorization": uni.getStorageSync(`${TokenPrefix}_token`) || '',
	}
	if(showLoading){
		uni.showLoading({
			title: '下载中',
		})
	}	
	return new Promise((reslove, reject) => {
		api = APIPrefix + api
		uni.downloadFile({
			//#ifdef MP
			url: BASEURL.url + `${api}/` + filePath, //下载资源的 url 
			//#endif

			//#ifdef H5
			url: `${api}/` + filePath, //H5使用代理
			//#endif		
			header,
			success: (res) => {
				if(showLoading){
					uni.hideLoading()
				}
				if (res.statusCode == 401 || res.statusCode == -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.tempFilePath)
			},
			fail: (err) => {
				if(showLoading){
					uni.hideLoading()
				}
				uni.showToast({
					title: '下载失败！',
					icon: 'error'
				})
				reject(err)
			}
		})
	})
}

export default downloadFile
