import { Injectable } from '@angular/core';
import {environment} from './../environments/environment';
import {HttpClient, HttpHeaders} from '@angular/common/http';
// import {LocalStorage} from './local.storage';
@Injectable({
  providedIn: 'root'
})
export class CommonService {
  private USER_API_URL = '';
  private httpOptions;
  constructor(private http: HttpClient,
    // private ls: LocalStorage
    ) { 
  this.USER_API_URL = environment.apiUrl;
  this.httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'X-Authorization': ''
    })
  };
  
 }
  async surveyInfo() {
  const url = this.USER_API_URL + '/survey/surveyInfo';
  const res = await this.obtainToken();
  this.httpOptions.headers = this.httpOptions.headers.set('X-Authorization', res['data']['token']);
  return this.http
    .post(url, JSON.stringify({}),this.httpOptions).toPromise().then(response => {
      return response;
    });
  }

  async saveCustomerAnwers(objParam){
    const url = this.USER_API_URL + '/survey/saveCustomerAnwers';
    const res = await this.obtainToken();
    this.httpOptions.headers = this.httpOptions.headers.set('X-Authorization', res['data']['token']);
    return this.http
      .post(url, JSON.stringify(objParam),this.httpOptions).toPromise().then(response => {
        return response;
      });
  }

  /**
   * 获取TOKEN
   */
  obtainToken() {
    const url = this.USER_API_URL + '/authorize/obtainToken';
    const ticketObj = {
      ticket: 'questionnair'
    };
    return this.http.post(url, JSON.stringify(ticketObj), this.httpOptions).toPromise();
  }

  async provinceqry(objParam){
    const url = this.USER_API_URL + '/partner/provinceqry';
    const res = await this.obtainToken();
    this.httpOptions.headers = this.httpOptions.headers.set('X-Authorization', res['data']['token']);
    return this.http.post(url,JSON.stringify(objParam),this.httpOptions).toPromise().then(res => {
     return res;
   })
  }

  async getCityqry(objParam){
    const url = this.USER_API_URL + '/partner/cityqry';
    const res = await this.obtainToken();
    this.httpOptions.headers = this.httpOptions.headers.set('X-Authorization', res['data']['token']);
    return this.http
    .post(url,JSON.stringify(objParam),this.httpOptions)
    .toPromise().then(res => {
      return res;
    })
  }

  getQueryString(name) {
    const after = window.location.hash.split('?')[1];
    if (after) {
      const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
      const r = after.match(reg);
      if (r != null) {
        return decodeURIComponent(r[2]);
      } else {
        return null;
      }
    }
  }
}
