import { BASE_URL } from '../config'
import { get, del } from './request'

function parseUploadResponse(res: UniApp.UploadFileSuccessCallbackResult): { code?: number; msg?: string; data?: any } {
  try {
    return JSON.parse(typeof res.data === 'string' ? res.data : '{}')
  } catch {
    return {}
  }
}

/**
 * 通用文件上传
 * @param filePath 本地临时文件路径
 * @returns 上传后的访问 URL
 */
export function uploadFile(filePath: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    uni.uploadFile({
      url: `${BASE_URL}/file/upload`,
      filePath,
      name: 'file',
      header: token ? { Authorization: `Bearer ${token}` } : {},
      success: (res) => {
        const result = parseUploadResponse(res)
        if (res.statusCode === 200 && result.code === 200 && result.data?.url) {
          resolve(result.data.url)
        } else {
          reject(new Error(result.msg || '上传失败'))
        }
      },
      fail: (err) => {
        reject(new Error(err.errMsg || '上传失败'))
      },
    })
  })
}

/**
 * 任务照片上传
 * @param filePath 本地临时文件路径
 * @param taskId 任务ID
 * @param step SOP步骤编码（英文 code）
 * @param phase admin 前端照片分组 phase
 * @returns 上传后的访问 URL
 */
export function uploadTaskPhoto(
  filePath: string,
  taskId: number,
  step: string,
  phase?: string
): Promise<string> {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    uni.uploadFile({
      url: `${BASE_URL}/task-photo/upload`,
      filePath,
      name: 'file',
      formData: {
        taskId: String(taskId),
        step,
        phase: phase || step,
      },
      header: token ? { Authorization: `Bearer ${token}` } : {},
      success: (res) => {
        const result = parseUploadResponse(res)
        if (res.statusCode === 200 && result.code === 200 && result.data) {
          resolve(result.data)
        } else {
          reject(new Error(result.msg || '上传失败'))
        }
      },
      fail: (err) => {
        reject(new Error(err.errMsg || '上传失败'))
      },
    })
  })
}

/** 查询任务照片列表 */
export function getTaskPhotos(taskId: number): Promise<any[]> {
  return get(`/task-photo/list/${taskId}`)
}

/** 删除任务照片 */
export function deleteTaskPhoto(photoId: number): Promise<any> {
  return del(`/task-photo/${photoId}`)
}

/** 单张任务照片结构 */
export interface TaskPhoto {
  photoId?: number
  taskId?: number
  phase?: string
  stepCode?: string
  photoType?: string
  photoUrl?: string
  photoTime?: string
  remark?: string
  uploadUserId?: number
  createTime?: string
}
