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;
  }

  /**
   * 获取验证码
   * @param verticalCode
   * @returns {Observable<A>}
   */
  async verificationCode(verticalCode) {
    const url = this.USER_API_URL + '/verificationCode';
    const res = await this.obtainToken();
    this.httpOptions.headers = this.httpOptions.headers.set('X-Authorization', res['data']['token']);
    return this.http
      .post(url, JSON.stringify(verticalCode), this.httpOptions).toPromise().then(response => {
        return response;
      });
  }

  /**
   * 验证验证码
   * @param compareCode
   * @returns {Observable<A>}
   */
  async compare(compareCode) {
    const url = this.USER_API_URL + '/checkVerificationCode';
    const res = await this.obtainToken();
    this.httpOptions.headers = this.httpOptions.headers.set('X-Authorization', res['data']['token']);
    return this.http
      .post(url, JSON.stringify(compareCode), this.httpOptions).toPromise().then(response => {
        return response;
      });
  }

  /**
   * 登录
   * @param login
   * @returns {Observable<A>}
   */
  async login(mobileNo) {
    const url = this.USER_API_URL + '/login';
    const res = await this.obtainToken();
    this.httpOptions.headers = this.httpOptions.headers.set('X-Authorization', res['data']['token']);
    return this.http
      .post(url, JSON.stringify(mobileNo), this.httpOptions).toPromise().then(response => {
        return response;
      });
  }


  /**
   * 删除所有答案
   * @returns {Array<any>}
   */
  remove() {
    this.todos = [];
    sessionStorage.removeItem('todos');
    this.todosSource.next(this.todos);
  }

  /**
   * 返回上一页
   * @returns {Array<any>}
   */
  before() {
    history.go(-1);
  }

  get todosCopy() {
    return this.todos;
  }

}
