import { Injectable } from '@angular/core';

import { Observable, of, throwError } from 'rxjs';
import { environment } from '../../environments/environment';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/internal/operators';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  constructor(private http: HttpClient) {
  }

  private API = environment.BACKEND_URL_CONFIG_VALUE;
  private ydapi = environment.ORIGINNAME;
  isLoggedIn = false;
  // store the URL so we can redirect after logging in
  redirectUrl: string;
  // 经纪人登陆
  login(loginInfo): Observable<any> {
    const api = this.ydapi + '/practitioner/login';
    return this.http.post(api, JSON.stringify(loginInfo));
  }

  //  发送验证码
  verificationCode(verticalCode) {
    const url = this.API + '/verificationCode';
    return this.http
      .post(url, JSON.stringify(verticalCode));
  }

  //  校验验证码
  compare(compareCode) {
    const url = this.API + '/checkVerificationCode';
    return this.http
      .post(url, JSON.stringify(compareCode))
      .pipe(
        catchError(this.handleError)
      );
  }

  /**
   * 获取TOKEN
   */
  obtainToken(loginId) {
    const url = this.API + '/authorize/obtainToken';
    return this.http.post(url, JSON.stringify({ ticket: "life",loginId:loginId}));
  }

  //获取微信配置ydLife公众号
  ydWxConfig(Currenturl) {
    const url = this.ydapi + '/wxConfig';
    const postUrl = {
      url: Currenturl
    };
    return this.http.post(url, JSON.stringify(postUrl));
  }



  //  获取错误详情
  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${JSON.stringify(error.error)}`);
    }
    return throwError(
      'Something bad happened; please try again later.');
  }

  currentVersionQuery() {
    const url = this.API + '/metadata/currentVersionQuery';
    return this.http.get(url);
  }

  getOppId(urlParam) {
    return this.http.get(urlParam)
  }
}
