"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fly_1 = __importDefault(require("flyio/dist/npm/fly"));
const history_1 = require("history");
const linked_env_1 = __importDefault(require("./linked-env"));
const login_user_1 = require("./login-user");
let isInit = false;
let fly = {};
let history;
const FoxPageApi = {
    initClient() {
        if (isInit) {
            return;
        }
        fly = new fly_1.default();
        // default baseurl
        // @ts-ignore
        fly.config.baseURL = APP_CONFIG.foxpageApi;
        // default time out
        fly.config.timeout = 1000 * 60;
        // with cookies
        fly.config.withCredentials = true; // auto with cookies
        // set request interceptors
        fly.interceptors.request.use((request) => {
            const { location: { hash, search }, } = history;
            const userInfo = (0, login_user_1.getLoginUser)();
            const token = userInfo.token;
            request.headers['token'] = token;
            request.headers['url'] = `/${hash}${search}`;
            return request;
        });
        // set response interceptors
        fly.interceptors.response.use((response) => response.data);
        // catch error
        // (err) => {
        //   message.error(`${err.status} - ${err.message}`);
        // },
        // );
        history = (0, history_1.createBrowserHistory)();
        isInit = true;
    },
    // get request
    get(path, obj, cb, opt) {
        const o = { method: 'get' };
        if (opt)
            Object.assign(o, opt);
        this.execute(path, obj, cb, o);
    },
    // create request
    post(path, obj, cb, opt) {
        const o = { method: 'post' };
        if (opt)
            Object.assign(o, opt);
        this.execute(path, obj, cb, o);
    },
    // put request
    put(path, obj, cb, opt) {
        const o = { method: 'put' };
        if (opt)
            Object.assign(o, opt);
        this.execute(path, obj, cb, o);
    },
    // delete request
    delete(path, obj, cb, opt) {
        const o = { method: 'delete' };
        if (opt)
            Object.assign(o, opt);
        this.execute(path, obj, cb, o);
    },
    execute(path, obj, cb, opt) {
        fly
            .request(path, obj, opt)
            .then((rs) => {
            if (rs.code && rs.code === 401) {
                history.push({
                    pathname: (0, linked_env_1.default)('/#/login'),
                    state: { from: history.location },
                });
                location.reload();
            }
            if (cb)
                cb(rs);
        })
            .catch(() => {
            if (cb)
                cb({});
        });
    },
};
FoxPageApi.initClient();
exports.default = FoxPageApi;
