import {Injectable} from '@angular/core';
import {environment} from './../environments/environment';
import {HttpClient, HttpHeaders} from '@angular/common/http';
declare const wx: any;
@Injectable()
export class EventBusService {
  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': ''
      })
    };
  }

  /**
   * 获取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;
      });
  }

  /**
   * 没有分享码的分享
   */
  noShareCode() {
    setTimeout(() => {
      // 默认的分享信息
      const shareData = {
        title: '银盾保险经纪人',
        link: window.location.href,
        desc: '银盾保经，优选和定制最适合的保险方案，为您提供专业、中立的保险经纪服务。',
        imgUrl: 'https://ajb-images.oss-cn-shanghai-finance-1-pub.aliyuncs.com/images/yd_shield.jpg'
      };
      wx.ready(function () {
        wx.onMenuShareAppMessage(shareData);  // 分享微信
        wx.onMenuShareTimeline(shareData);    // 分享到朋友圈
        wx.onMenuShareQQ(shareData);          // 分享到QQ
      });
    }, 1000);    // 说明：根组件初始化完成，子组件的异步请求数据可能还未返回，因此在2秒后注册分享。
  }


}
