import { Apis } from '@/gen/Apis'

// #region pre_upload
export interface IPreUploadResult {
  success: boolean
  data: {
    cosHost: string
    cosKey: string
    authorization: string
  }
}

export interface IPreUploadData {
  /**
   * -
   */
  file_ext?: string
}

const handlePreUpload = async (val: { filename: string; alc: string }) => {
  const res = await Apis.Login.Auth.PreUpload(val)
  return res
}

export const avatarUpload = (path: string) => {
  return new Promise<{ url: string; status: string; type: string | undefined }[]>(
    (resolve, reject) => {
      if (path.startsWith('wxfile://')) {
        const match: any = path.match(/[^\/\\]+(?=\.[^\.]+$|$)/)
        const filePathName = match[0] // 获取文件名（不包括扩展名）
        const filePath = path
        handlePreUpload({
          filename: filePathName,
          alc: 'public-read'
        }).then((res: any) => {
          if (res?.success) {
            const wxfs = uni.getFileSystemManager()
            wxfs.readFile({
              filePath: filePath,
              complete(e) {
                console.log('complete', e)
              },
              success: function (fileRes) {
                console.log(fileRes, 'fileRes1')
                uni.request({
                  url: res?.data?.url,
                  method: 'PUT',
                  header: {
                    ...res?.data?.headers,
                    'x-amz-acl': 'public-read' // 明确指定 ACL
                  },
                  data: fileRes?.data,
                  success: function success(json) {
                    console.log(json, 'resUpadte')
                    if (json.statusCode !== 200) {
                      uni.showToast({
                        title: '上传失败',
                        icon: 'none'
                      })
                      reject()
                    } else {
                      let data = {
                        url: res?.data?.url?.split('?')[0],
                        status: 'done',
                        type: 'image/png',
                        uid: Date.now()
                      }
                      resolve([data])
                    }
                  },
                  fail: function fail() {
                    uni.showToast({
                      title: '上传失败',
                      icon: 'none'
                    })
                    reject()
                  }
                })
                console.log(fileRes, 'fileRes')
              }
            })
          }
        })
        return
      }
      uni.downloadFile({
        url: path,
        success: async res => {
          if (res.statusCode === 200) {
            const match: any = res.tempFilePath.match(/[^\/\\]+(?=\.[^\.]+$|$)/)
            const filePath = res.tempFilePath
            const filePathName = match[0] // 获取文件名（不包括扩展名）
            console.log(match[0])
            handlePreUpload({
              filename: filePathName,
              alc: 'public-read'
            }).then((res: any) => {
              if (res?.success) {
                const wxfs = uni.getFileSystemManager()
                wxfs.readFile({
                  filePath: filePath,
                  complete(e) {
                    console.log('complete', e)
                  },
                  success: function (fileRes) {
                    console.log(fileRes, 'fileRes1')
                    uni.request({
                      url: res?.data?.url,
                      method: 'PUT',
                      header: {
                        ...res?.data?.headers,
                        'x-amz-acl': 'public-read' // 明确指定 ACL
                      },
                      data: fileRes?.data,
                      success: function success(json) {
                        console.log(json, 'resUpadte')
                        if (json.statusCode !== 200) {
                          uni.showToast({
                            title: '上传失败',
                            icon: 'none'
                          })
                          reject()
                        } else {
                          let data = {
                            url: res?.data?.url?.split('?')[0],
                            status: 'done',
                            type: 'image/png',
                            uid: Date.now()
                          }
                          resolve([data])
                        }
                      },
                      fail: function fail() {
                        uni.showToast({
                          title: '上传失败',
                          icon: 'none'
                        })
                        reject()
                      }
                    })
                    console.log(fileRes, 'fileRes')
                  }
                })
              }
            })
          } else {
            console.log(`文件下载失败，状态码: ${res.statusCode}`)
          }
        },
        fail: err => {}
      })
    }
  )
}

export const upload = (count = 1, size = 2, mediaType = ['image']) => {
  return new Promise<{ url: string; status: string; type: string | undefined }>(
    (resolve, reject) => {
      let currentCount = 0
      let ArrImgList: any = []

      uni.chooseMedia({
        count: count > 9 ? 9 : count, //默认9
        mediaType: mediaType as ['image'],
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        success: async function (i) {
          console.log('filePath_i', i)
          i.tempFiles?.map((k: any) => {
            console.log(k, '??kj')
            let match = k.tempFilePath.match(/[^\/\\]+(?=\.[^\.]+$|$)/)
            const filePath = k.tempFilePath
            const extIndex = filePath.lastIndexOf('.')
            const filePathName = match[0] // 获取文件名（不包括扩展名）
            const fileExt = extIndex >= -1 ? filePath.substr(extIndex + 1) : ''
            const img_size = i.tempFiles[0].size
            const max_size = 1024 * 1024 * (size || 2) // 默认2M
            if (img_size > max_size) {
              uni.showToast({
                title: `${filePathName}文件大小不能超过${size}M`,
                icon: 'none'
              })
              return false
            }
            handlePreUpload({
              filename: filePathName,
              alc: 'public-read'
            }).then((res: any) => {
              if (res?.success) {
                const wxfs = uni.getFileSystemManager()
                wxfs.readFile({
                  filePath: filePath,
                  complete(e) {
                    console.log('complete', e)
                  },
                  success: function (fileRes) {
                    console.log(fileRes, 'fileRes1')
                    uni.request({
                      url: res?.data?.url,
                      method: 'PUT',
                      header: {
                        ...res?.data?.headers,
                        'x-amz-acl': 'public-read' // 明确指定 ACL
                      },
                      data: fileRes?.data,
                      success: function success(json) {
                        console.log(json, 'resUpadte')
                        if (json.statusCode !== 200) {
                          uni.showToast({
                            title: '上传失败',
                            icon: 'none'
                          })
                          reject()
                        } else {
                          const timestamp = Date.now()
                          let data = {
                            url: res?.data?.url?.split('?')[0],
                            status: 'done',
                            type: `${k?.fileType}/${filePath.split('.')[1]}`,
                            uid: timestamp,
                            size: k?.size
                          }
                          ArrImgList?.push(data)
                          resolve(ArrImgList)
                        }
                      },
                      fail: function fail() {
                        uni.showToast({
                          title: '上传失败',
                          icon: 'none'
                        })
                        reject()
                      }
                    })
                    console.log(fileRes, 'fileRes')
                  }
                })
              }
            })
          })
        }
      })
    }
  )
}


export const uploadImgWatermark = (data: any) => {
  return new Promise<{ url: string; status: string; type: string | undefined }>(
    (fileResolve, fileReject) => {
      const timestamp = Date.now()
      const extIndex = data?.path.lastIndexOf('.')
      const fileExt = extIndex >= -1 ? data?.path.substr(extIndex + 1) : ''
      console.log(extIndex, fileExt, 'fileExt')
      handlePreUpload({
        filename: `${data?.name || ''}_${timestamp}.${fileExt}`,
        alc: 'public-read'
      })
        .then((res: any) => {
          if (res?.success) {
            const wxfs = uni.getFileSystemManager()
            wxfs.readFile({
              filePath: data?.path || '',
              success: function (fileRes) {
                uni.request({
                  url: res?.data?.url,
                  method: 'PUT',
                  header: {
                    ...res?.data?.headers,
                    'x-amz-acl': 'public-read'
                  },
                  data: fileRes?.data,
                  success: function success(json) {
                    if (json.statusCode !== 200) {
                      fileReject(new Error(`上传失败: ${json.statusCode}`))
                    } else {
                      uni.getImageInfo({
                        src: data?.path,
                        success: imgInfo => {
                          console.log(imgInfo, 'imgInfo')
                          let imgJson = {
                            url: res?.data?.url?.split('?')[0],
                            status: 'done',
                            type: imgInfo?.type,
                            uid: timestamp,
                            size: '',
                            name: `${data?.name}-${timestamp}`
                          }
                          fileResolve(imgJson)
                        }
                      })
                    }
                  },
                  fail: function fail() {
                    fileReject(new Error('网络请求失败'))
                  }
                })
              },
              fail: function () {
                fileReject(new Error('读取文件失败'))
              }
            })
          } else {
            fileReject(new Error('获取上传链接失败'))
          }
        })
        .catch(err => {
          fileReject(err)
        })
    }
  )
}
