import { getCache } from '@/utils/cache';
import { HOST, TENANT_ID } from '@/utils/request';

/**
 * 上传图片到后端，返回 { url, ... }
 */
export const uploadFile = (filePath: string): Promise<{ url: string; [key: string]: any }> => {
    const token = getCache('token');

    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: `${HOST}/api/main/sysFileInfo/tenUploadAll`,
            filePath,
            name: 'file',
            header: {
                Authorization: token ? `Bearer ${token}` : '',
                'x-tenant-id': TENANT_ID,
            },
            success: (res) => {
                try {
                    const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
                    if (data.code === 200) {
                        resolve(data.data);
                    } else {
                        reject(new Error(data.message || '上传失败'));
                    }
                } catch (e) {
                    reject(new Error('上传返回格式异常'));
                }
            },
            fail: (err) => reject(err),
        });
    });
};
