/**
 * uni-app formdata 请求封装
 * 使用 uni.request 模拟 formdata 提交
 */

import { useGlobSetting } from '/@/hooks/setting'
import { useUserStoreWithOut } from '@/store/modules/user'

interface FormDataRequestOptions {
    url: string
    data?: Record<string, any>
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
    header?: Record<string, any>
    timeout?: number
}

interface FormDataResponse<T = any> {
    data: T
    statusCode: number
    header: Record<string, any>
    errMsg: string
}

/**
 * formdata 格式请求
 * @param options 请求配置
 * @returns Promise
 */
export function formDataRequest<T = any>(options: FormDataRequestOptions): Promise<FormDataResponse<T>> {
    return new Promise((resolve, reject) => {
        const { url, data = {}, method = 'POST', header = {}, timeout = 60000 } = options

        // 获取全局配置
        const globSetting = useGlobSetting()
        const urlPrefix = globSetting.urlPrefix
        const apiUrl = globSetting.apiUrl

        // 获取 token
        const userStore = useUserStoreWithOut()
        const token = userStore.getToken

        // 拼接完整 URL
        const fullUrl = `${apiUrl}${urlPrefix}${url}`

        // 将数据转换为 formdata 格式字符串
        const formDataStr = Object.keys(data)
            .map((key) => {
                const value = data[key]
                if (value === null || value === undefined) {
                    return ''
                }
                if (Array.isArray(value)) {
                    // 处理数组
                    return value.map((item) => `${encodeURIComponent(key)}=${encodeURIComponent(item)}`).join('&')
                }
                return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
            })
            .filter((item) => item !== '')
            .join('&')

        uni.request({
            url: fullUrl,
            method,
            data: formDataStr,
            header: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Access-Token': token,
                ...header,
            },
            timeout,
            success: (res: any) => {
                resolve({
                    data: res.data,
                    statusCode: res.statusCode,
                    header: res.header,
                    errMsg: res.errMsg,
                })
            },
            fail: (err: any) => {
                reject({
                    data: null,
                    statusCode: err.statusCode || 0,
                    header: err.header || {},
                    errMsg: err.errMsg || '请求失败',
                })
            },
        })
    })
}

/**
 * POST formdata 请求
 * @param url 请求地址
 * @param data 请求数据
 * @param header 请求头
 * @returns Promise
 */
export function postFormData<T = any>(
    url: string,
    data?: Record<string, any>,
    header?: Record<string, any>,
): Promise<FormDataResponse<T>> {
    return formDataRequest<T>({
        url,
        data,
        method: 'POST',
        header,
    })
}

/**
 * PUT formdata 请求
 * @param url 请求地址
 * @param data 请求数据
 * @param header 请求头
 * @returns Promise
 */
export function putFormData<T = any>(
    url: string,
    data?: Record<string, any>,
    header?: Record<string, any>,
): Promise<FormDataResponse<T>> {
    return formDataRequest<T>({
        url,
        data,
        method: 'PUT',
        header,
    })
}
