// const { request } = require('../utils/util.js')
import strings from '../utils/strings.js';

module.exports = {

    // 上传图片到服务器
    uploadImage: (filePath, formData = {}) => {
        var Authorization = "";
        try {
            var value = wx.getStorageSync('token') || "";
            if (!strings.isEmpty(value)) {
                const resData = JSON.parse(value);
                Authorization = resData.token;
            }
        } catch (e) {
            Authorization = "";
        }
        console.log("Authorization:", Authorization)

        return new Promise((resolve, reject) => {
            // 拼接地址
            var baseUrl = getApp().globalData.baseUrl;
            let url = '/mini/wx/image/getUrl';
            let fullurl = `${baseUrl}${url}`;
            console.log("上传图片参数：", fullurl, filePath)
            wx.uploadFile({
                url: fullurl, // 替换为你的服务器地址
                filePath: filePath,
                name: 'file', // 文件对应的 key，后端需要根据这个 key 获取文件
                formData: formData, // 其他需要上传的表单数据,
                header: Object.assign({
                    "content-type": "multipart/form-data",
                    "appid": "wx08f94a3e90881910",
                    "Authorization": Authorization
                },),
                responseType: 'arraybuffer',
                success: (res) => {
                    console.log("上传图片返回：", res);
                    try {
                        // 检查响应头中的 Content-Type
                        const contentType = res.header['Content-Type'] || res.header['content-type'];
                        console.log("上传图片返回2：", contentType);
                        if (contentType && contentType.includes('image/jpeg')) {
                            // 服务器返回的是图片数据
                            console.log("上传图片返回3：", res.data);
                            resolve(dataUrl);
                        } else {
                            // 服务器返回的不是图片数据
                            const data = JSON.parse(res.data ?? "{}");
                            resolve(data);
                        }
                    } catch (e) {
                        reject(new Error('解析服务器响应失败', e));
                    }
                },
                fail: (err) => {
                    console.log("上传图片返回2：", err);

                    reject(new Error('上传失败: ' + err.errMsg));
                }
            });
        });
    }

}