import { fileUpload } from '@/service/modules/uploadFile'
import { useLoginStore } from '@/store/login'

interface uploadImgType {
  count?: number
  sourceType?: string[]
}

export function uploadImg(params?: uploadImgType) {
  return new Promise((resove, reject) => {
    const loginStore = useLoginStore()
    uni.chooseImage({
      count: params?.count || 9,
      sizeType: ['original', 'compressed'],
      sourceType: params?.sourceType || ['album'],
      success(res: any) {
        uni.uploadFile({
          url: fileUpload(),
          filePath: res.tempFilePaths[0],
          name: 'file',
          header: {
            Authorization: `Bearer ${loginStore.accessToken}`
          },
          success: (uploadFileRes: any) => {
            const data = JSON.parse(uploadFileRes.data)
            resove(data)
          },
          fail(e) {
            console.log('uploadImg', e)
            reject(e)
          }
        })
      }
    })
  })
}

export function uploadFile(params: string) {
  return new Promise((resove, reject) => {
    const loginStore = useLoginStore()
    uni.uploadFile({
      url: fileUpload(),
      filePath: params,
      name: 'file',
      header: {
        Authorization: `Bearer ${loginStore.accessToken}`
      },
      success: (uploadFileRes: any) => {
        if (uploadFileRes.statusCode === 200) {
          const data = JSON.parse(uploadFileRes.data)
          resove(data)
        } else {
          reject(uploadFileRes)
        }
      },
      fail(e) {
        console.log('uploadImg', e)
        reject(e)
      }
    })
  })
}
