import request from '@repo/api-client'

type UploadResponse = {
	id: string
	name: string
	extensionName: string
	size: number
	path: string
}

/**
 * 上传文件
 * @param file
 * @returns
 */
export const UploadFile = (
	data: FormData,
	callback?: (p: number) => void
): Promise<UploadResponse> | undefined => {
	// return request<{
	// 	code: number
	// 	result: {
	// 		id: string
	// 	}[]
	// }>('/fileApi/File/UploadFiles', {
	// 	method: 'POST',
	// 	headers: {
	// 		'Content-Type': 'multipart/form-data'
	// 	},
	// 	data
	// })
	const partSize = 2 * 1024 * 1024

	// 进行文件分块传输
	// @ts-ignore
	if (window?.BpmTools) {
		return new Promise((resolve, reject) => {
			// @ts-ignore
			window?.BpmTools?.$$doFilePartUpload({
				file: data.get('files'),
				partSize: partSize,
				success: function (res: UploadResponse) {
					console.log('success', res)
					callback?.(100)
					resolve(res)
				},
				progress: function (progress: number) {
					console.log('progress', progress)
					callback?.(progress)
				},
				error: function (err: Error) {
					console.error(err)
					reject(err)
				}
			})
		})
	}
}

/**
 * 获取图片
 * @param fileId 文件id
 * @returns
 */
export const GetImage = (data: { fileId: string }) => {
	return request('/File/GetImage', {
		method: 'GET',
		params: data,
		responseType: 'blob'
	})
}

/**
 * 下载文件
 * @param fileId 文件id
 * @returns
 */
export const Download = (data: { fileId: string }) => {
	return request('/File/Download', {
		method: 'GET',
		params: data,
		responseType: 'blob'
	})
}
