import { Injectable } from '@angular/core';
import { environment } from './../environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Subject } from "rxjs/index";
declare const wx: any;
@Injectable()
export class EventBusService {
  private USER_API_URL = '';
  private httpOptions;
  private shareStatusSource = new Subject<string>();
  shareStatus$ = this.shareStatusSource.asObservable();
  constructor(private http: HttpClient) {
    this.USER_API_URL = environment.apiUrl;
    this.httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'X-Authorization': ''
      })
    };
  }

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



  /**
   * 经纪人查询
   */
  async userPractitionerQuery(userPractitioner) {
    const url = this.USER_API_URL + '/user/userPractitionerQuery';
    const res = await this.obtainToken();
    this.httpOptions.headers = this.httpOptions.headers.set('X-Authorization', res['data']['token']);
    return this.http.post(url, JSON.stringify(userPractitioner), this.httpOptions)
      .toPromise().then(response => {
        return response;
      });
  }

  /**
   * 经纪人详细查询
   */
  async userPractitionerDetailQuery(userPractitionerDetail) {
    const url = this.USER_API_URL + '/user/userPractitionerDetailQuery';
    const res = await this.obtainToken();
    this.httpOptions.headers = this.httpOptions.headers.set('X-Authorization', res['data']['token'])
    return this.http.post(url, JSON.stringify(userPractitionerDetail), this.httpOptions)
      .toPromise().then(response => {
        return response;
      });
  }

  /**
   * 微信分享配置接口
   * @param Currenturl
   * @returns {Promise<any|TResult2|TResult1>}
   */

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

  // 向订阅者发布分享结果
  // 0.关闭分享引导页
  // 1.用户点击分享
  // 2.已经分享过了
  shareStatusPublish(type) {
    this.shareStatusSource.next(type);
  }

  wxShare(title: string, desc: string, link: string, imgUrl: string) {
    const shareData = {
      title: title, // 分享标题
      desc: desc, // 分享描述
      link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: imgUrl, // 分享图标
      success: () => {
        this.shareStatusPublish(0);
      }

    };
    wx.ready(() => {   // 需在用户可能点击分享按钮前就先调用
      wx.updateAppMessageShareData(shareData);
      wx.updateTimelineShareData(shareData);
    });
  }


}
