import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { StorageService } from 'src/app/core/services/storage.service';
import { environment } from '../../environments/environment';
@Injectable({
  providedIn: 'root',
})
export class ReportingService {
  private endpointFind = 'accountNameSearch';
  constructor(
    private http: HttpClient,
    public storage: StorageService
  ) {}

  public listTemplate(): Observable<[]> {
    return this.http
      .post<any>(
        `${environment.API_URL}v1/Reporting/generateReporting/getReportingTemplates`,
        {}
      )
      .pipe(
        map((reportingListTemplate) => {
          return reportingListTemplate;
        })
      );
  }

  public getAutocompletion(typeSearch: string, keyword: string) {
    return typeSearch === 'accountGroup'
      ? this.getByGroupName(keyword)
      : this.getByAccountName(keyword);
  }

  public getAutocompletionGroup(typeSearch: string, keyword: string) {
    return this.getByGroupName(keyword);
  }

  public getByAccountName(keyword: string) {
    return this.http
      .post<any>(
        `${environment.API_URL}v1/Reporting/generateReporting/accountNameSearch`,
        {
          keyWord: keyword,
        }
      )
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? resultAutocompletion.accounts
            : [];
        })
      );
  }

  public getByContrepartieName(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Contrepartie',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getBySimulationName(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Simulation',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByCotationName(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Nom cotation',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByContrat(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Contrat',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByPrestationName(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Prestations',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByBeneficiaireName(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Beneficiaire',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByMandataire(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Mandataire',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getBySignatureName(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Nom du signataire',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByApportAffaire(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Apport Affaire',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByNameAccount(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Nom du Compte',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByContactName(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Nom du contact',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getBySimulations(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Simulation',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByDemandeur(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Demandeur',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByInstallateur(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Installateur',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByProjectName(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Nom du projet',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByOpportunity(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Nom opportunite',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByFiliale(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Filiale de',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByFiche(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Fiche',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionFiche(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByEquipement(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Equipement',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByBook(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Book',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByModule(module:string,keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        modulename: module,
        // fieldName: 'Name',
        keyWord: keyword,
        setup:environment.SETUP
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }
  public getByDepot(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        // fieldName: 'Name',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getBySousjacent(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Sous jacent',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByOdt(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'ODT',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByOperations(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Operation',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByComptes(keyword: string) {
    return this.http
      .post<any>(`${environment.API_URL}v1/admin/searchRecord`, {
        fieldName: 'Comptes',
        keyWord: keyword,
      })
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formaAutoCompletionProject(resultAutocompletion.result)
            : [];
        })
      );
  }

  public getByGroupName(keyword: string) {
    return this.http
      .post<any>(
        `${environment.API_URL}v1/Reporting/generateReporting/accountGroupSearch`,
        {
          keyWord: keyword,
        }
      )
      .pipe(
        map((resultAutocompletion) => {
          return resultAutocompletion.success
            ? this.formatResultatsGroupAutocompletion(
                resultAutocompletion.groups
              )
            : [];
        })
      );
  }

  private formatResultatsGroupAutocompletion(data: any) {
    const response = data.map((res: [], i: number) => {
      return {
        id: i,
        name: res,
      };
    });

    return response;
  }

  public genetateReporting(payload: any, filename: string): any {
    return this.http
      .post<any>(
        `${environment.API_URL}v1/Reporting/generateReporting`,
        {
          accountName: payload.accountName,
          templateId: payload.templateId,
        },
        { observe: 'body', responseType: 'blob' as 'json' }
      )
      .pipe(
        map((resultAutocompletion: any) => {
          if (resultAutocompletion) {
            let dataType = resultAutocompletion.type;
            let binaryData = [];
            binaryData.push(resultAutocompletion);
            let downloadLink = document.createElement('a');
            downloadLink.href = window.URL.createObjectURL(
              new Blob(binaryData, { type: dataType })
            );
            downloadLink.setAttribute('download', `reporting_${filename}.xlsx`);
            document.body.appendChild(downloadLink);
            downloadLink.click();
          }
          return true;
        })
      );
  }

  public formaAutoCompletionProject(data: any) {
    let response = data.map((res: any) => {
      return { id: res.id, name: res.value };
    });

    return response ? response : [];
  }

  public formaAutoCompletionFiche(data: any) {
    let response = data.map((res: any) => {
      return { id: res.id, name: res.value, active: res.active };
    });

    return response ? response : [];
  }

  public genetateReportingGroup(payload: any) {
    return this.http
      .post<any>(
        `${environment.API_URL}v1/Reporting/generateReporting`,
        {
          accountGroup: payload.accountGroup,
          templateId: payload.templateId,
        },
        { observe: 'body', responseType: 'blob' as 'json' }
      )
      .pipe(
        map((resultAutocompletion: any) => {
          if (resultAutocompletion) {
            let dataType = resultAutocompletion.type;
            let binaryData = [];
            binaryData.push(resultAutocompletion);
            let downloadLink = document.createElement('a');
            downloadLink.href = window.URL.createObjectURL(
              new Blob(binaryData, { type: dataType })
            );
            downloadLink.setAttribute(
              'download',
              `reporting_${payload.accountGroup}.xlsx`
            );
            document.body.appendChild(downloadLink);
            downloadLink.click();
          }
          return true;
        })
      );
  }
}
