import env from '../config/env.js'

/**
 * 文件上传工具
 * 对应PC端的 upload.js
 */
const upload = {
  buildUploadPath(kind = 'img') {
    const typeMap = {
      img: 'img',
      aud: 'aud',
      vid: 'vid',
      file: ''
    }
    const normalizedKind = String(kind || 'img').toLowerCase()
    const mappedType = typeMap[normalizedKind]
    if (mappedType === undefined) return '/service?ssServ=ulByHttp&type=img'
    if (!mappedType) return '/service?ssServ=ulByHttp'
    return `/service?ssServ=ulByHttp&type=${mappedType}`
  },

  /**
   * 上传文件到服务器
   * @param {String} filePath - 文件临时路径
   * @param {Object} options - 配置选项
   * @param {String} options.name - 文件字段名，默认 'fileEdit'
   * @param {Object} options.formData - 额外的表单数据，默认 { application: '' }
   * @param {Boolean|String} options.loading - 是否显示loading，或loading文字
   * @returns {Promise} 返回服务器响应数据
   */
  uploadFile(filePath, options = {}) {
    const {
      name = 'fileEdit',
      formData = { application: '' },
      loading = true,
      kind = 'img'
    } = options

    // 显示 loading
    if (loading) {
      const loadingTitle = typeof loading === 'string' ? loading : '上传中...'
      uni.showLoading({
        title: loadingTitle,
        mask: true
      })
    }

    // 获取设备信息
    const deviceInfo = uni.getStorageSync("deviceInfo") || {}
    const devId = deviceInfo.deviceId || ''
    const sbmc = deviceInfo.model || ''

    // 构建上传URL，支持 img/aud/vid/file(无type)
    const url = this.buildUploadPath(kind)
    const separator = url.includes('?') ? '&' : '?'
    const finalUrl = `${env.baseUrl}${url}${separator}devId=${devId}&sbmc=${sbmc}`

    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: finalUrl,
        filePath,
        name,
        formData,
        header: (() => {
          const headers = {}
          const jsessionId = uni.getStorageSync('JSESSIONID')
          if (jsessionId) {
            headers['Cookie'] = `JSESSIONID=${jsessionId}`
          }
          return headers
        })(),
        success: (res) => {
          if (res.statusCode === 200) {
            try {
              // 解析返回数据，对应PC端的格式：
              // { fileList: [{ path: "xxx.png", fileName: "xxx.png" }] }
              const data = JSON.parse(res.data)
              resolve(data)
            } catch (e) {
              // 如果解析失败，返回原始数据
              resolve(res.data)
            }
          } else {
            reject(res)
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
          reject(err)
        },
        complete: () => {
          if (loading) {
            uni.hideLoading()
          }
        }
      })
    })
  },

  /**
   * 上传图片（快捷方法）
   * @param {String} filePath - 图片临时路径
   * @param {Object} options - 配置选项
   * @returns {Promise<String>} 返回服务器上的图片路径
   */
  async uploadImage(filePath, options = {}) {
    try {
      const result = await this.uploadFile(filePath, {
        ...options,
        loading: options.loading !== false ? '上传图片中...' : false,
        kind: 'img'
      })

      // 提取文件路径（对应PC端的 result.fileList[0].path）
      return result?.fileList?.[0]?.path || ''
    } catch (error) {
      console.error('上传图片失败:', error)
      throw error
    }
  },

  async uploadAudio(filePath, options = {}) {
    try {
      const result = await this.uploadFile(filePath, {
        ...options,
        loading: options.loading !== false ? '上传语音中...' : false,
        kind: 'aud'
      })
      return result?.fileList?.[0]?.path || ''
    } catch (error) {
      console.error('上传语音失败:', error)
      throw error
    }
  },

  async uploadVideo(filePath, options = {}) {
    try {
      const result = await this.uploadFile(filePath, {
        ...options,
        loading: options.loading !== false ? '上传视频中...' : false,
        kind: 'vid'
      })
      return result?.fileList?.[0]?.path || ''
    } catch (error) {
      console.error('上传视频失败:', error)
      throw error
    }
  },

  async uploadCommonFile(filePath, options = {}) {
    try {
      const result = await this.uploadFile(filePath, {
        ...options,
        loading: options.loading !== false ? '上传文件中...' : false,
        kind: 'file'
      })
      return result?.fileList?.[0]?.path || ''
    } catch (error) {
      console.error('上传文件失败:', error)
      throw error
    }
  },

  /**
   * 上传头像（专用方法）
   * @param {String} filePath - 头像临时路径
   * @returns {Promise<String>} 返回服务器上的头像路径
   */
  async uploadAvatar(filePath) {
    return this.uploadImage(filePath, {
      loading: '上传头像中...'
    })
  }
}

export default upload
