import Taro, { UploadTask } from '@tarojs/taro';

import http from '@/http';
import { API } from '@/http/api';
import { GetVideoInfoRequest, UploadVideoResult } from '@/types/material';
import qiniuUpload from '@/utils/qiniu-upload';

export const commonUploadProgress: UploadTask.OnProgressUpdateCallback = res => {
  if (res.progress >= 100) {
    Taro.hideLoading();
    return;
  }
  Taro.showLoading({ title: `上传${res.progress}%` });
};

export const uploadVideo = async (
  filePath: string,
  type: string,
  onProgress?: UploadTask.OnProgressUpdateCallback,
  prefixName?: string
) => {
  const qiniuKey = await qiniuUpload.upload(filePath, onProgress, prefixName);
  const data: GetVideoInfoRequest = { sourcePath: qiniuKey, type: type === 'video' ? 'VIDEO' : 'IMAGE' };
  return http.post<UploadVideoResult>(API.GET_VIDEO_INFO, { data, contentType: 'application/x-www-form-urlencoded' });
};
