// @ts-ignore
import {clearToken, fetchToken} from "@/utils/auth"

// 根据微信小程序的运行环境自动切换: 开发版/体验版→测试地址，正式版→生产地址
// #ifdef MP-WEIXIN
let env: string = 'dev'
try {
  const accountInfo = uni.getAccountInfoSync()
  // envVersion: 'develop' 开发版 | 'trial' 体验版 | 'release' 正式版
  env = accountInfo.miniProgram.envVersion === 'release' ? 'prd' : 'dev'
} catch (e) {
  // getAccountInfoSync 不可用时兜底
}
// #endif
// #ifndef MP-WEIXIN
let env: string = import.meta.env.PROD ? 'prd' : 'dev'
// #endif
const apis: any = {
    dev: {
        serverUrl: "https://dev-wash.kuaiyuman.cn/api",
        // serverUrl: "http://localhost:9099/api",
        fileUrl: "https://zyp-1258963180.cos.ap-guangzhou.myqcloud.com/"
    },
    prd: {
        serverUrl: "https://api.yeswash.cn/api",
        fileUrl: "https://api.yeswash.cn",
    },
};
// @ts-ignore
// @ts-ignore
const cfg = {
    key: {
        token: 'wash.token'
    },
    env: env,
    api: {
        serverUrl: apis[env]?.serverUrl,
        fileUrl: apis[env].fileUrl,
        uploadUrl: apis[env].serverUrl + "file/upload"
    }
};

const serverUrl = apis[env]?.serverUrl;
const fileUrl = apis[env].fileUrl;

const isEmptyOrNull = function (exp: any) {
    return !exp || typeof (exp) == "undefined" || exp.length === 0 || exp === '' || Object.keys(exp).length === 0;
};


/**
 * get请求封装
 * @param url
 * @param param
 */
const get = (url: string, param = {}) => {
    let token = fetchToken() || ""
    if (!isEmptyOrNull(param)) {
        let params = [];
        for (let key in param) {
            // @ts-ignore
            params.push(encodeURIComponent(key) + "=" + encodeURIComponent(param[key]));
        }
        param = params.join("&")
    }
    let options = {
        url: fillUrl(url) + (isEmptyOrNull(param) ? "" : "?" + param),
        data: param,
        method: 'GET',
        header: {
            "Accept": "application/json",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "satoken": token,
        },
    };
    return request(options)
};


const post = (url: string, param = {}) => {
    let token = fetchToken() || ""
    let options = {
        url: fillUrl(url),
        data: param,
        method: 'POST',
        header: {
            'X-Requested-With': 'XMLHttpRequest',
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8;",
            "satoken": token,
        },
        dataType: 'json'
    };
    return request(options);
};


const body = (url: string, param = {}) => {
    let token = fetchToken() || ""
    let options = {
        url: fillUrl(url),
        data: param,
        method: 'POST',
        header: {
            'X-Requested-With': 'XMLHttpRequest',
            "Accept": "application/json",
            "Content-Type": "application/json; charset=UTF-8",
            "satoken": token,
        },
        dataType: 'json'
    };
    return request(options);
};


const request = (options: any) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: options.url,
            data: options.data,
            method: options.method,
            header: options.header,
            dataType: options.dataType
        }).then((res: any) => {
            // @ts-ignore
            let response = res.data;
            if (response.code !== 200) {
                let errMsg = response.message || '服务异常，请稍后重试';
                console.error("error=>", errMsg);
                if (response.code !== 301) {
                    uni.showToast({
                        title: errMsg,
                        icon: 'error',
                        duration: 5000
                    });
                }
                if (response.code == 1001) {
                    //清除登录状态
                    clearToken();
                }
                reject(errMsg);
            } else {
                resolve(response.data);
            }
        }).catch(error => {
            uni.hideLoading();
            uni.showToast({
                title: '网络异常，请稍后重试',
                icon: 'none'
            });
            console.error("error=>", error);
            reject(error);
        })
    });
};

const del = (url: string) => {
    let token = fetchToken() || ""
    let options = {
        url: fillUrl(url),
        method: 'DELETE',
        header: {
            'Accept': 'application/json',
            'Content-Type': 'application/json; charset=UTF-8',
            'satoken': token,
        },
        dataType: 'json'
    };
    return request(options);
};

const upload = (url: string, param: any = {}) => {
    let token = fetchToken() || ""
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: fillUrl(url),
            filePath: param.filePath || param.url,
            name: 'file',
            header: {
                "satoken": token
            },
            success: function (res) {
                let response = JSON.parse(res.data);
                if (response.code === 200) {
                    resolve(response);
                } else if (response.code === 500) {
                    uni.showToast({
                        title: '系统繁忙，请稍后重试',
                        icon: 'none'
                    });
                    reject();
                } else {
                    uni.showToast({
                        title: response.message
                    });
                    reject();
                }

            },
            fail: function (e) {
                console.error(e)
                uni.showToast({
                    title: '请稍后重试'
                });
                reject();
            }
        });
    })
}

const uploadV2 = (opt: any) => {
    opt = opt || {};
    opt.url = opt.url || '';
    opt.filePath = opt.filePath || null;//要上传文件资源的路径。
    opt.name = opt.name || null;//文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容

    opt.filePath = opt.filePath || null;
    opt.success = opt.success || function () {
    };


    uni.uploadFile({
        url: fillUrl(opt.url),
        filePath: opt.filePath,
        name: opt.name,
        success: function (res) {
            opt.success(res);
        },
        fail: function () {
            uni.showToast({
                title: '请稍后重试'
            });
        }
    })
};


const fillUrl = function (url: string) {
    if (url.indexOf("http") === 0) {
        return url;
    } else {
        return serverUrl + url;
    }
};

const formatUrl = (v: string) => {
    if (v == null || v == "") {
        return "/static/missing-face.png";
    }
    if (v.indexOf("http") === 0) {
        return v;
    }
    return fileUrl + v.replace(/\\/g, "/");
};

export {
    get, post, body, del, upload, uploadV2, cfg, serverUrl, fileUrl, formatUrl
}
