import request from '@/utils/request'
import http from '@/websoft/api/index.js'
import {
	fileUrl
} from '@/config.js';
import storage from '@/utils/storage'
import dayjs from "dayjs"
import appConfig from '@/config.js'
// api地址
const api = {
  image: 'upload/image'
}

// 图片上传
export const image = files => {
  // 文件上传大小, 2M
  const maxSize = 1024 * 1024 * 2
  // 执行上传
  return new Promise((resolve, reject) => {
    request.urlFileUpload({ files, maxSize })
      .then(result => resolve(result.map(item => item.data.fileInfo.file_id), result))
      .catch(reject)
  })
}


export const uploadFile = async ({filePath}) => {

	// 获取临时凭证
	let sts = storage.get('sts');
	if(!sts){
		const stsRes = await http.get('/oss/getPostForm')
		console.log('stsRes: ',stsRes);
		sts = stsRes.data
		storage.set('sts', sts, 60)
	}
	const {polocyBase64,signature} = sts;
	var suffix = filePath.substring(filePath.lastIndexOf(".")); //.txt
	const fileName = dayjs().format('YYYYMMDD')  + '/'+ uni.$u.guid() + suffix;
	return new Promise((reso, rej) => {
		uni.uploadFile({
			url: appConfig.fileUrl, // 开发者服务器的URL。
			filePath: filePath,
			name: 'file', // 必须填file。
			formData: {
				key: fileName,
				'policy': polocyBase64,
				'OSSAccessKeyId': 'LTAI5tSZ62sPCvUsLRDDf7fH',
				'success_action_status': '200', //让服务端返回200,不然，默认会返回204
				'signature': signature,
				// 'x-oss-security-token': this.stsToken,
			},
			success: (res) => {
				const webUrl = appConfig.fileUrl + '/' + fileName;
				reso({data: {url: webUrl,thumb: webUrl}})
			},
			fail: err => {
				rej(err)
			}
		});
	})


}

export const getTempOssToken = () => http.get('/oss/getTempToken')
export default {
	uploadFile,
	getTempOssToken
}