import request from '@repo/api-client'

interface UploadResponse {
	id: string
	name: string
	extensionName: string
	size: number
	path: string
}

interface BpmToolsWindow extends Window {
	BpmTools?: {
		$$doFilePartUpload: (options: {
			file: FormDataEntryValue | null
			partSize: number
			success: (res: UploadResponse) => void
			progress: (progress: number) => void
			error: (err: Error) => void
		}) => void
	}
}

/**
 * 上传文件
 */
export const uploadFile = (
	data: FormData,
	callback?: (p: number) => void
): Promise<UploadResponse> | undefined => {
	const partSize = 2 * 1024 * 1024
	const win = window as BpmToolsWindow

	if (win.BpmTools) {
		return new Promise((resolve, reject) => {
			win.BpmTools!.$$doFilePartUpload({
				file: data.get('files'),
				partSize,
				success: (res: UploadResponse) => {
					callback?.(100)
					resolve(res)
				},
				progress: (progress: number) => {
					callback?.(progress)
				},
				error: (err: Error) => {
					console.error(err)
					reject(err)
				}
			})
		})
	}
}

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

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