
class RequestUtil {
     getHeader(){
        let header=config.defaultHeader;
        header.platform=getPlatformType();
        header.version="1.0.0_1.0.0";
        header.deviceId="";
        header.token="";
        header.loginPlatform=(window.WebViewJavascriptBridge || window.__android)?"APP":"H5";
        header={
            ...header,
            ...getHeaderDate()
        }
        return header;
    };
     async doRequest(url: string, options?: any):Promise<any>{
         const defaultOptions = {
             credentials: 'include'
         };
         let new_url = "/h5/" + uuid();
         const newOptions = {...defaultOptions, ...options};
         newOptions.headers = {
             ...newOptions.headers,
             x_x_path: encryptUrl(url),
             ...this.getHeader()
         };
         if (
             newOptions.method === 'POST' ||
             newOptions.method === 'PUT' ||
             newOptions.method === 'DELETE'
         ){
             if (newOptions.contentType === 'application/json') {
                 newOptions.headers = {
                     Accept: 'application/json',
                     'Content-Type': 'application/json',
                     ...newOptions.headers,
                 };
                 newOptions.body = encrypt(newOptions.body);

             } else if (newOptions.body) {
                 newOptions.body = setUrlEncoded(newOptions.body);
             }
         }
          else if  (newOptions.method === 'GET') {
             new_url = new_url + '?' + setUrlEncoded(newOptions.body);
             newOptions.headers = {};
             delete newOptions.body
         }
        return fetch(new_url, {
            ...newOptions
        }).then(async (response)=>{
            let result: any = {};
            let actual: any = {};
            let text=await response.text();
            if (response.status != 200) {
                const errorText = "Error response http-code of " + response.status + " responsed!";

                result = {code: response.status == 401 ? response.status: 500, toast: errorText, success: false}
            } else {
                actual = decrypt(text);

                result = {...actual};
            }
            if (config.isDebug) {
                console.log("call:" + url + "\nresult==>>" + JSON.stringify(result))
            }
            return  result;
        });
    }
     async requestPost(url: string, data: any, options?: any){
        options = options || {};
        if (!options.contentType) {
            options.contentType = "application/json";
        }
        options.body = data || {};
        options.method = 'POST';
        return this.doRequest(url, options);
    }
     async requestGet(url: string, data: any, options?: any){
        options = options || {};
        options.body = data || {};
        options.method = 'GET';
        return this.doRequest(url, options);
    }
}
const requestUtil=new RequestUtil();
