import {mgop} from "@aligov/jssdk-mgop";
import zlbConfig from "@/common/js/zlbConfig";
import {httpApi} from "@/common/js/baseUrl";
import {handleHttpError, handleNormalResponse} from "@/utils/fetch/responseHandler";
import handleReqLoading from "@/utils/fetch/handleReqLoading";
import {handleRequest} from "@/utils/fetch/requestHandler";

function download(url, type = "get", data = {}) {
    return new Promise((resolve, reject) => {
        uni.request({
            url: url,
            method: type,
            responseType: "arraybuffer",
            header: {
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                src: "wechat",
            },
            data: data,
            timeout: 10000,
            success: function (res) {
                console.log("返回结果:", res);
                if (res.statusCode === 200) {
                    resolve(res);
                } else {
                    reject(); // 接口不正常 reject
                    uni.showToast({title: "服务异常", icon: "none"});
                }
            },
            fail: function (err) {
                uni.showToast({title: "服务异常", icon: "none"});
                reject(err);
            },
        });
    });
}

// 通用版upload
function commonUpload(url, data, config = {}) {
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: httpApi + url,
            ...data,
            ...config,
            header: {
                "content-type": "multipart/form-data",
                Token: '1'
            },
            // 设置请求的 header
            success: function (res) {
            },
            fail: function (res) {
                uni.showToast({
                    title: "服务异常",
                    icon: "none",
                    duration: 2000,
                });
                reject();
            },
        });
    });
}

function index(url, type = "get", data = {}, dataType) {
    return new Promise((resolve, reject) => {
        (url && url.startsWith("mgop.alibaba")) ? handleMgop(url, type, data, dataType, resolve, reject) : handleFetch(url, type, data, dataType, resolve, reject);
    });
}

function handleMgop(url, type, data, dataType, resolve, reject) {
    let extraHeader = {};
    /*  当请求头 isTestUrl 为 "1" 时，使用联调环境 */
    extraHeader.isTestUrl = "1";
    mgop({
        api: url, // 必填
        // host: 'https://mapi.zjzwfw.gov.cn/',
        dataType: "JSON",
        type: type,
        data: data,
        appKey: zlbConfig.appKey, // 必填
        appId:zlbConfig.appId,
        header: {
            "Content-Type":
                dataType === "form"
                    ? "application/x-www-form-urlencoded"
                    : "application/json",
            src: "wechat", // 小程序免登陆
            ...extraHeader,
        },
        onSuccess: (res) => {
            const code = res.ret[0].split("::")[0];
            if (code === "1000") {
                if (
                    res.data.code === 0 ||
                    res.data.code === "0" ||
                    res.data.status === 0 ||
                    res.data.status === "1" //高德地图
                ) {
                    resolve(res.data);
                } else {
                    //特殊处理下，获取门牌数据的接口code是1 ,是业务错误
                    if (res.api === "mgop.alibaba.digitalDoorplate.getHomePageOneDoorplateFullInfo") {
                        resolve(res.data);
                    } else {
                        reject(res);
                        if (res.data.message || res.data.msg) {
                            uni.showToast({
                                title: res.data.message || res.data.msg,
                                icon: "none",
                                duration: 2000,
                            });
                        }
                    }

                }
            } else {
                reject(res); // 接口不正常 reject
                uni.showToast({
                    title: "服务异常",
                    icon: "none",
                    duration: 2000,
                });
            }
        },
        onFail: (err) => {
            reject(err);
        },
    });
}


function handleFetch(url, type, data, dataType, resolve, reject) {
    let header = {
        "Content-Type":
            dataType === "form"
                ? "application/x-www-form-urlencoded"
                : "application/json",
        Token: '1'
    };
    uni.request({
        url: httpApi + url,
        method: type,
        header,
        data: data,
        timeout: 60000,
        success: function (res) {
            if (res.statusCode === 200) {
                if (
                    res.data.code === 0 ||
                    res.data.code === "0" ||
                    res.data.status === 0 ||
                    res.data.status === "1" //高德地图
                ) {
                    resolve(res.data);
                } else {
                    reject();
                    if (res.data.message || res.data.msg) {
                        uni.showToast({
                            title: res.data.message || res.data.msg,
                            icon: "none",
                            duration: 2000,
                        });
                    }
                }
            } else {
                reject(); // 接口不正常 reject

                uni.showToast({
                    title: "服务异常",
                    icon: "none",
                    duration: 2000,
                });
            }
        },
        fail: function (err) {
            uni.showToast({
                title: "服务异常",
                icon: "none",
                duration: 2000,
            });
            reject(err);
        },
        complete: function () {
        },
    });
}

//export {index, download, commonUpload};

/**
 * 封装请求
 * @param url 请求地址
 * @param type 请求方式
 * @param data 请求参数
 * @param dataType 请求数据类型
 */
export const myFetch = async (url, type = "get", data = {}, dataType) => {
    const reqConfig = {
        url: httpApi + url,
        method: type,
        data: data,
        dataType: dataType,
        timeout: 60000,
        header: {
            'content-type': 'application/json',
            Token: '1',
            appId:'2002407848',
        },
    }

    try {
        handleReqLoading(true);
        const response = await handleRequest(reqConfig);
        const responseData = handleNormalResponse(response);
        handleReqLoading(false);
        //返回一个promise对象
        return responseData;
    }catch (err) {
        handleReqLoading(false);
        return handleHttpError(err);
    }
}
