import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {InjectorInstance} from '../../app.module';
import {AppComponent} from '../../app.component';
import {FrameVariable} from './frame-variable';
import { Http } from '@angular/http';

@Injectable()
export class FrameRequest {
  /*****************
   * 准备请求头
   */
  private static HEADERS = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8')
    .set('Accept', 'application/json, text/javascript, */*; q=0.01')
    .set('X-Requested-With', 'XMLHttpRequest')
    .set('timeout', '1200000');

  /*************************
   * 通用Ajax请求
   * @param {string} url
   * @param param 参数
   * @param {Function} callback
   * @param {string} type Entity,Map,Array
   */
  public static request(url: string, param?: any, callback?: Function, type?: string, error?: Function) {
    // 获取httpClient
    const httpClient =  InjectorInstance.get<HttpClient>(HttpClient);
    const RequestLoading = param!.RequestLoading;
    if (RequestLoading) {
      setTimeout(() => {
        AppComponent.GobalComponent.setLoading(true);
      }, 600*1000);
    }
    httpClient.post(FrameVariable.BASE_URL + url, new HttpParams({
      fromObject: param
    }), {headers: FrameRequest.HEADERS})
      .subscribe(
        (response: any) => {
          if (response.success) {
            if (callback) {
              let obj = response;
              if (type === 'Entity') {
                obj = response.entity;
              } else if (type === 'Array') {
                obj = response.array;
              } else if (type === 'Page') {
                obj = response.page;
              }  else if (type === 'Map') {
                obj = response.map;
              }
              callback.call(undefined, obj);
            }
          } else {
            if (response.login === false) {
              let token = localStorage.getItem("token");
              let sso_url = localStorage.getItem("sso_url");;
              
              // 登录超时
              alert('登录超时，请重新登录')

              if(token && token != 'null' && token != 'undefined'){
                if(sso_url && sso_url != 'null' && sso_url != 'undefined'){
                  window.location.href = sso_url;
                }else{
                  window.location.href = "https://zhgl.gxeea.cn:20080/login/index";
                }
                
              //  window.location.href = "https://ssotest.gxeea.cn:8084/naga/login/new";

              }else{
                window.location.href = './assets/login/index.html';
              }
              
              return;
            }
            AppComponent.GobalComponent.getToaster().pop('error', '', response.errorMsg);
            // 没有，统一用错误回调
            if (error) {
              error.call(undefined, response);
            }
          }

          if (RequestLoading) {
            setTimeout(() => {
              AppComponent.GobalComponent.setLoading(false);
            }, 600*1000);
          }

        },
        response => {
          if (RequestLoading) {
            setTimeout(() => {
              AppComponent.GobalComponent.setLoading(false);
            }, 600*1000);
          }
          if (error) {
            error.call(undefined, response);
          }
          // 没有，统一用错误回调
          AppComponent.GobalComponent.getToaster().pop('error', '网络/服务器错误', '无法正常连接服务器，请检查网络情况，如网络正常，则服务器无法正常使用，请联系系统管理员！');

        },
        () => {});
  }

  public static requestEntity(url: string, param?: any, callback?: Function, error?: Function) {
    return FrameRequest.request(url, param, callback, 'Entity', error);
  }

  public static requestArray(url: string, param?: any, callback?: Function, error?: Function) {
    return FrameRequest.request(url, param, callback, 'Array', error);
  }

  public static requestMap(url: string, param?: any, callback?: Function, error?: Function) {
    return FrameRequest.request(url, param, callback, 'Map', error);
  }

  public static requestPage(url: string, param?: any, callback?: Function, error?: Function) {
    return FrameRequest.request(url, param, callback, 'Page', error);
  }

  public static getRequestPromise(url, param){
    const httpClient =  InjectorInstance.get<HttpClient>(HttpClient);
    return httpClient.post(FrameVariable.BASE_URL + url, new HttpParams({
      fromObject: param
    }), {headers: FrameRequest.HEADERS}).toPromise();
  }

  
    public static downloadService(url: string, param?: any) {
      const http = InjectorInstance.get<Http>(Http);
      let downloadUrl = FrameVariable.BASE_URL + url;
      return http.get(downloadUrl, { params: param , responseType: 3 }
      ).map(res => {
        return res;
      });
    }

    private static getMimeType(suffix: string, res: any) {
      let blob: any;
      if(suffix === 'xlsx') {
        blob = new Blob([res.json()], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
      } else if(suffix === 'xls') {
        blob = new Blob([res.json()], { type: "application/vnd.ms-excel	application/x-excel" });
      }  else if(suffix === 'pdf') {
        blob = new Blob([res.json()], { type: "application/pdf" });
      } else if(suffix === 'zip') {
        blob = new Blob([res.json()], { type: "application/zip" });
      } else if(suffix === 'txt') {
        blob = new Blob([res.json()], { type: "text/plain" });
      } else if(suffix === 'doc') {
        blob = new Blob([res.json()], { type: "application/msword" });
      } else if(suffix === 'docx') {
        blob = new Blob([res.json()], { type: "application/msword" });
      } else if(suffix === 'rar') {
        blob = new Blob([res.json()], { type: "application/x-rar-compressed" });
      }else if(suffix === 'jpg') {
        blob = new Blob([res.json()], { type: "image/jpeg" });
      } else if(suffix === 'gif') {
        blob = new Blob([res.json()], { type: "image/gif" });
      } else if(suffix === 'png') {
        blob = new Blob([res.json()], { type: "image/png" });
      } else if(suffix === 'dbf') {
        blob = new Blob([res.json()], { type: "application/x-dbf" });
      }
      return blob;
    }
  
    /**
      *  @param url：下载文件的地址
       * @param param ：string类型或者URLSearchParams类型
       */
    public static download(url: string,  param?: any, callback?: Function) {
      // const RequestLoading = param!.RequestLoading;
      // if (RequestLoading) {
      //   setTimeout(() => {
      //     AppComponent.GobalComponent.setLoading(true);
      //   });
      // }
      this.downloadService(url, param).subscribe(res => {
        let content = res.headers.get('content-disposition');
        let name = content.substring(content.indexOf("=")+1,content.length);
        let suffix = name.substring(name.lastIndexOf(".")+1);
        let blob = this.getMimeType(suffix, res);
        let objectUrl = URL.createObjectURL(blob);
        let a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display:none');
        a.setAttribute('href', objectUrl);
        a.setAttribute('download',decodeURI(name));
        a.click();
        document.body.removeChild(a);
        //释放URL地址
        URL.revokeObjectURL(objectUrl);
        // if (RequestLoading) {
        //   setTimeout(() => {
        //     AppComponent.GobalComponent.setLoading(false);
        //   });
        // }
        if(callback) {
          callback.call(undefined);
        }
      });
    }
}
