import $store from "@/store/index";
import Vue from "vue"
let prototype = Vue.prototype;

function findRule(name) {
    let pos = name.indexOf('.');
    if (pos > 0) {
        let temp, arr = name.split('.');
        for (let i = 0; i < arr.length; i++) {
            if (i == 0) {
                temp = prototype.$apis[arr[i]] || {};
            } else {
                temp = temp[arr[i]] || {};
            }
        }
        return temp;
    }

    return name;
}

const request = async (args) => {
    let rule = findRule(args.api || '');
    if (JSON.stringify(rule) === "{}") {
        throw "找不到API：" + args.api;
    }

    let query = (args.query) ? '?' + args.query : '';

    if (typeof rule.auth !== "undefined" && rule.auth === true && !$store.state.user.token) {
        $store.commit("user/showLoginModal", true);
        return;
    }

    (rule.showLoading) && uni.showLoading({
        title: "加载中"
    });

    const headers = {
        "XX-Wxapp-AppId": prototype.$config.appId,
        'XX-Token': $store.state.user.token,
        'XX-Device-Type': 'wxapp',
    };

    const [error, response] = await uni.request({
        url: prototype.$config.root + rule.url + query,
        method: rule.method || 'post',
        data: args.data,
        header: {
            'X-Requested-With': 'XMLHttpRequest',
            'content-type': 'application/x-www-form-urlencoded',
            ...headers
        }
    });

    (rule.showLoading) && uni.hideLoading();

    if (response.data.code == 10001) {
        $store.dispatch("user/logout");
        $store.commit("user/showLoginModal", true);
        return;
    }

    return Promise.resolve(response.data);
};

export default request