import { getToken } from '@/utils/auth';
import errorCode from '@/utils/errorCode';
import { tansParams } from '@/utils/common';
import config from '@/config';
import { getCurrentPage } from '@/utils/public';

interface UploadConfig {
    url: string;
    filePath: string;
    name?: string;
    header?: Record<string, any>;
    headers?: Record<string, any>;
    formData?: Record<string, any>;
    params?: Record<string, any>;
    timeout?: number;
}

interface UploadResult {
    code: number;
    data?: any;
    msg?: string;
}

const timeout = 10000;
const { baseUrl, clientId, appid } = config;

const upload = (uploadConfig: UploadConfig): Promise<UploadResult> => {
    // 是否需要设置 token
    const isToken = (uploadConfig.headers || {}).isToken === false;
    uploadConfig.header = uploadConfig.header || {};
    if (getToken() && !isToken) {
        uploadConfig.header['Authorization'] = 'Bearer ' + getToken();
    }
    uploadConfig.header['Clientid'] = clientId; // 默认值
    uploadConfig.header['xid'] = appid; // 默认值
    
    // get请求映射params参数
    if (uploadConfig.params) {
        let url = uploadConfig.url + '?' + tansParams(uploadConfig.params);
        url = url.slice(0, -1);
        uploadConfig.url = url;
    }
    
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            timeout: uploadConfig.timeout || timeout,
            url: baseUrl + uploadConfig.url,
            filePath: uploadConfig.filePath,
            name: uploadConfig.name || 'file',
            header: uploadConfig.header,
            formData: uploadConfig.formData,
            success: (res) => {
                const result: UploadResult = JSON.parse(res.data);
                const code = result.code || 200;
                const msg = errorCode[code.toString()] || result.msg || errorCode['default'];
                
                if (code === 200) {
                    resolve(result);
                } else if (code === 401) {
                    uni.hideLoading();
                    // 跳转到登录页面
                    uni.$u.route({
                        type: 'reLaunch',
                        url: '/pages/login/login',
                        params: {
                            redirect: getCurrentPage()?.route || ''
                        }
                    });
                    reject('无效的会话，或者会话已过期，请重新登录。');
                } else if (code === 500) {
                    uni.showToast({
                        title: msg,
                        icon: 'none'
                    });
                    reject('500');
                } else if (code !== 200) {
                    uni.showToast({
                        title: msg,
                        icon: 'none'
                    });
                    reject(code);
                }
            },
            fail: (error) => {
                console.log(error);
                let message = '上传失败';
                if (error.errMsg) {
                    if (error.errMsg.includes('timeout')) {
                        message = '系统接口请求超时';
                    } else if (error.errMsg.includes('fail')) {
                        message = '网络连接异常';
                    }
                }
                uni.showToast({
                    title: message,
                    icon: 'none'
                });
                reject(error);
            }
        });
    });
};

// 导出数据函数（简化版本）
export const exportDataFn = (config: any): Promise<void> => {
    return new Promise((resolve, reject) => {
        if (config.url) {
            uni.downloadFile({
                url: config.url,
                success: (result) => {
                    uni.openDocument({
                        filePath: result.tempFilePath,
                        showMenu: true,
                        success: () => {
                            resolve();
                        },
                        fail: (error) => {
                            reject(error);
                        }
                    });
                },
                fail: (error) => {
                    reject(error);
                }
            });
        } else {
            reject(new Error('No URL provided'));
        }
    });
};

export default upload;
