/**
 * workcase_wechat API 封装
 * 使用 uni.request 替代 axios
 */

/* eslint-disable @typescript-eslint/no-explicit-any */
declare const uni: {
    getStorageSync: (key: string) => any
    request: (options: any) => void
    uploadFile: (options: any) => void
}

import type { ResultDomain } from '../types'
import { BASE_URL as CONFIG_BASE_URL } from '../config'
// API 基础配置
const BASE_URL = CONFIG_BASE_URL

// 通用请求方法
export function request<T>(options: {
    url: string
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
    data?: any
    header?: Record<string, string>
}): Promise<ResultDomain<T>> {
    return new Promise((resolve, reject) => {
        const token = uni.getStorageSync('token') as string
        uni.request({
            url: BASE_URL + options.url,
            method: options.method || 'GET',
            data: options.data,
            header: {
                'Content-Type': 'application/json',
                ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
                ...options.header
            },
            success: (res: any) => {
                if (res.statusCode === 200) {
                    resolve(res.data as ResultDomain<T>)
                } else {
                    reject(new Error(`请求失败: ${res.statusCode}`))
                }
            },
            fail: (err: any) => {
                reject(err)
            }
        })
    })
}

// 文件上传方法
export function uploadFile<T>(options: {
    url: string
    filePath: string
    name?: string
    formData?: Record<string, any>
    header?: Record<string, string>
}): Promise<ResultDomain<T>> {
    return new Promise((resolve, reject) => {
        const token = uni.getStorageSync('token') as string
        uni.uploadFile({
            url: BASE_URL + options.url,
            filePath: options.filePath,
            name: options.name || 'file',
            formData: options.formData,
            header: {
                ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
                ...options.header
            },
            success: (res: any) => {
                try {
                    if (res.statusCode === 200) {
                        const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
                        resolve(result as ResultDomain<T>)
                    } else {
                        reject(new Error(`上传失败: ${res.statusCode}`))
                    }
                } catch (error) {
                    reject(new Error('解析响应失败'))
                }
            },
            fail: (err: any) => {
                reject(err)
            }
        })
    })
}
