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;
  isLoggedIn = false;
// store the URL so we can redirect after logging in
  redirectUrl: string;
// 经纪人登陆
  login(loginInfo): Observable<any> {
    const api = this.API + '/practitionerLogin';
    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() {
    const url = this.API + '/authorize/obtainToken';
    const ticketObj = {
      ticket: 'life'
    };
    return this.http.post(url, JSON.stringify(ticketObj));
  }
  //   获取微信配置
  wxConfig(Currenturl) {
    const url = this.API + '/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.');
  }
}
