import instructions,{Instructions} from './instructions/index';

import config from "./config";

import constName from './const';

import axios from "axios";

import './cache/index';
import './entrust/install';
import {LibRequestStatus} from "$utils/request/const/request";

export { LibRequestStatus,InstructionsMessageType,InstructionsCacheType,InstructionsTypes } from "$utils/request/const/request";

// 创建实例化工具
const requestContent = axios.create(config[constName.mode.default]);

const request = function (data:LibRequestOptions) {
    return new Promise<ResponseData>(function (resolve, reject) {

        // 创建请求上下文

        let requestContext =Instructions.createRequestContext({
            requestData: data,
            reject,
            resolve,
            status:LibRequestStatus.loading
        });

        // 如果前期校验通过触发
        if (instructions.trigger(requestContext)) {
            return requestContent(requestContext.requestData).then(function (data){
                return requestContext.success(data);
            }).catch(function (fail){
                return requestContext.fail(fail);
            });
        } else {
            // 否则释放上下文
            // @ts-ignore
            requestContext = null;
        }

    });

}

request.uploadFile = function (data:LibRequestOptions) {

    // @ts-ignore
    data.file = true;

    data.header ={
        'content-type':'multipart/form-data'
    }

    return request(data);

}

request.getUserInfo = function () {

    return new Promise(function (resolve, reject){
        Promise.all(
            [
                request({
                    url:'user/get_user_info',
                    token:true
                }),
                request({
                    url:'hxuser/getuserinfo',
                    token:true
                }),
                request({
                    url:'user/get_user_money',
                    token:true
                })
            ]
        ).then((data)=>{

            let resultData:Record<string, any> = {};

            for (let i=0,count=data.length;i<count;i++) {
                resultData = Object.assign({},resultData,data[i].data);
            }

            return resolve(resultData);
        }).catch(reject);
    })

}

request.install = function (app:any) {
    app.config.globalProperties.$request = request;
};

export default request;