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': ''
      })
    };

  }

  /**
   * 获取问卷所有问题
   * @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);
    this.todosSource.next(this.todos);
    return this;
  }

  // 更新一个答案
  updateTodoById(pageId: number, values: Object = {}) {
    const todo = this.todos.filter(todo => todo.pageId == pageId).pop();
    if (!todo) {
      return null;
    }
    Object.assign(todo, values); // 将更新的values对象的属性值赋给todo对象
    this.todosSource.next(this.todos);
    return todo;
  }

  // 获取所有答案
  getTodos() {
    return this.todos;
  }

}
