import {Injectable} from '@angular/core';
import {environment} from './../environments/environment';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Subject} from "rxjs/index";
@Injectable({
  providedIn: 'root'
})
export class CommonService {
  // Observable string sources
  private todosSource = new Subject<any>();
  // Observable string streams
  todos$ = this.todosSource.asObservable();
  todos: Array<any> = []; // 任务列表
  private USER_API_URL = '';
  private httpOptions;

  constructor(private http: HttpClient) {
    this.USER_API_URL = environment.apiUrl;
    this.httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'X-Authorization': ''
      })
    };
    if (sessionStorage.getItem('todos')) {
      this.todos = JSON.parse(sessionStorage.getItem('todos'));
    }
  }

  /**
   * 获取问卷所有问题
   * @returns {Promise<TResult2|TResult1>}
   */
  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;
      });
  }

  /**
   * 保存答案
   * @param objParam
   * @returns {Promise<TResult2|TResult1>}
   */
  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();
  }

  /**
   * 获取省份
   * @param objParam
   * @returns {Promise<TResult2|TResult1>}
   */
  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;
    })
  }

  /**
   * 获取城市
   * @param objParam
   * @returns {Promise<TResult2|TResult1>}
   */
  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;
      })
  }

  /**
   * 获取URL参数
   * @param name
   * @returns {any}
   */
  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;
      }
    }
  }

  /**
   * 添加一个答案
   */
  addAnswer(todo) {
    for (let i = 0; i < this.todos.length; i++) {
      if (this.todos[i].pageId == todo.pageId) {
        const index = this.todos.indexOf(this.todos[i]);
        this.todos.splice(index, 1);
        break;
      }
    }
    this.todos.push(todo);
    sessionStorage.setItem('todos', JSON.stringify(this.todos));
    this.todosSource.next(this.todos);
    return this;
  }

  get todosCopy() {
    return this.todos;
  }

}
