/* eslint-disable no-prototype-builtins */
/* eslint-disable no-undef */
import config from "../../config";
import CryptoJS from "crypto-js";
// crypto 加密
const encryptByAES = (string, key) => {
    let ckey = CryptoJS.enc.Utf8.parse(key);
    let cStr = string + " " + config.siteId;
    let encrypted = CryptoJS.AES.encrypt(cStr, ckey, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
    });
    //return encrypted.toString(); //此方式返回base64格式密文
    return encrypted.ciphertext.toString(); // 返回hex格式的密文
};
export function upload(params) {
    const header = {};
    if (params.token != null) {
        header["Token"] = params.token;
    }
    header["lianshoutoken"] = encryptByAES(
        Date.now().toString(),
        config.cryptoKey
    );
    header["siteid"] = config.siteId;
    return new Promise(function (resolve, reject) {
        // token判断
        // if (token == null) {
        //   return getApp()
        //     .login()
        //     .then((token) => {
        //       return resolve(get.apply(this, [...options, token]));
        //     });
        // }
        params.holder.uploadTask = wx.uploadFile({
            url: config.server.api.baseUrl + params.path,
            formData: params.formData,
            filePath: params.filePath,
            name: params.name,
            header,
            success: ({ data, statusCode }) => {
                data = JSON.parse(data);
                if (statusCode >= 200 && statusCode < 300) {
                    return resolve(data);
                }
                // 未登录
                if (statusCode === 401) {
                    return getApp()
                        .login()
                        .then((token) => {
                            return resolve(
                                post.apply(this, [...options, token])
                            );
                        });
                }
                return reject(
                    data.message
                        ? data
                        : {
                            message: "抱歉，发生网络错误",
                        }
                );
            },
            fail: ({ errMsg }) => {
                if (errMsg === "request:fail abort") {
                    return;
                }
                return reject(
                    Object.assign({
                        message: "网络连接失败",
                    })
                );
            },
        });
    });
}

export function uploadWithToken(params) {
    return upload({
        ...params,
        token: getApp().globalData.token,
    });
}

export function get(path, data, holder = {}, token) {
    const options = [path, data, holder];
    const header = {
        "content-type": "application/x-www-form-urlencoded",
    };
    header["lianshoutoken"] = encryptByAES(
        Date.now().toString(),
        config.cryptoKey
    );
    header["siteid"] = config.siteId;
    if (token != null) {
        header["Token"] = token;
    }
    return new Promise(function (resolve, reject) {
        // token判断
        // if (token == null) {
        //   return getApp()
        //     .login()
        //     .then((token) => {
        //       return resolve(get.apply(this, [...options, token]));
        //     });
        // }
        holder.requestTask = wx.request({
            url: config.server.api.baseUrl + path,
            data: data,
            method: "GET",
            timeout: 10000,
            header,
            success: ({ data, statusCode }) => {
                if (statusCode >= 200 && statusCode < 300) {
                    return resolve(data);
                }
                // 未登录
                if (statusCode === 401) {
                    return getApp()
                        .login()
                        .then((token) => {
                            return resolve(
                                get.apply(this, [...options, token])
                            );
                        });
                }
                return reject(
                    data.message
                        ? data
                        : {
                            message: "抱歉，发生网络错误",
                        }
                );
            },
            fail: ({ errMsg }) => {
                if (errMsg === "request:fail abort") {
                    return;
                }
                return reject({
                    message: "网络连接失败",
                });
            },
        });
    });
}

export function getWithToken(path, data, holder) {
    return get(path, data, holder, getApp().globalData.token);
}

export function post(path, data, token, contentType = "application/json") {
    const options = [path, data];
    const header = { "content-type": contentType };
    if (token != null) {
        header["Token"] = token;
    }
    header["lianshoutoken"] = encryptByAES(
        Date.now().toString(),
        config.cryptoKey
    );
    header["siteid"] = config.siteId;

    return new Promise(function (resolve, reject) {
        // token判断
        // if (token == null) {
        //   return getApp()
        //     .login()
        //     .then((token) => {
        //       return resolve(get.apply(this, [...options, token]));
        //     });
        // }
        wx.request({
            url: config.server.api.baseUrl + path,
            data: data,
            method: "POST",
            header,
            timeout: 10000,
            success: ({ data, statusCode }) => {
                if (statusCode >= 200 && statusCode < 300) {
                    return resolve(data);
                }
                // 未登录
                if (statusCode === 401) {
                    return getApp()
                        .login()
                        .then((token) => {
                            return resolve(
                                post.apply(this, [...options, token])
                            );
                        });
                }
                return reject(
                    data.message
                        ? data
                        : {
                            message: "抱歉，发生网络错误",
                        }
                );
            },
            fail: ({ errMsg }) => {
                if (errMsg === "request:fail abort") {
                    return;
                }
                return reject(
                    Object.assign({
                        message: "网络连接错误",
                    })
                );
            },
        });
    });
}

export function postWithToken(path, data, json = false) {
    return post(
        path,
        data,
        getApp().globalData.token,
        json ? "application/json" : "application/x-www-form-urlencoded"
    );
}
/**
 * 网络方法加载状态
 * @param {*} fn Promise方法
 * @param {*} title 加载文案 默认 加载中
 * @param {*} delay 延时时间 默认 200毫秒
 * @return {*} Promise方法回调
 */
export function showLoading(fn, title = "加载中", delay = 200) {
    return new Promise((resolve, reject) => {
        let timer = setTimeout(() => {
            wx.showLoading({
                title,
            });
        }, delay);
        fn.then((v) => {
            clearTimeout(timer);
            wx.hideLoading();
            resolve(v);
        }).catch((err) => {
            reject(err);
        });
    });
}
export function serializePathQuery(params) {
    const str = [];
    for (let key in params)
        if (params.hasOwnProperty(key)) {
            str.push(key + "=" + params[key]);
        }
    return str.join("&");
}
