import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { CommonService } from "../common.service";
import { ActivatedRoute, Router } from "@angular/router";
import { environment } from "../../environments/environment";
import { Location } from '@angular/common';

declare const wx: any;
@Component({
  selector: 'app-transit',
  templateUrl: './transit.component.html',
  styleUrls: ['./transit.component.css']
})
export class TransitComponent implements OnInit {
  picFlag: boolean;
  wxShareFlag: boolean;
  alertFlag: boolean;
  customerId: string;
  deviceType: number;
  dialogTips: string;
  constructor(private location: Location, private router: Router, private commonService: CommonService, private activatedRoute: ActivatedRoute, private changeDetectorRef: ChangeDetectorRef) {
  }

  ngOnInit() {
    this.customerId = this.activatedRoute.snapshot.queryParams['customerId'];
    if (this.customerId) {
      this.router.navigateByUrl(`/index?campaign=AIRobot&task=AItask1`)
    }
    this.commonService.surveyInfo().then();
    const activityCode = this.commonService.getQueryString('activityCode');
    if (activityCode == 'mmh') {
      this.picFlag = true;
      sessionStorage.setItem('activityCode', activityCode);
    } else {
      this.picFlag = false;
    }
    this.deviceType = this.checkDeviceType();
    if (this.deviceType === 3) {
      this.configWX();
    }
  }
  //  分享给朋友
  wxShare() {
    this.wxShareFlag = true;
    if (this.customerId) {
      const shareCode = {
        shareCode: Math.random().toString(36).substr(2, 15),
        destinationType: null,
        destinationId: null,
        destinationName: null,
        adultCount: null,
        childCount: null,
        eldCount: null,
        effectiveStartDate: null,
        effectiveEndDate: null,
        dayCount: null,
        shareType: 4,
        customerId: this.customerId,
        planId: 464,
        productId: 767,
        os: this.checkOs(),
        channel: 0,
        url: window.location.href,
        isOrder: 0,
        jsonParams: null
      };
      this.commonService.defineWxContent(shareCode).then(res => {
        let _this = this;
        // 默认的分享信息
        const shareData = {
          title: 'AI智能保险顾问',
          link: `${environment.hostName}/questionnaire/#/index?campaign=AIRobot&task=AItask1&shareCode=${shareCode.shareCode}`,
          desc: 'AI智能家庭风险评测 、实时保障方案推荐。一分钟、搞定家庭保险。',
          imgUrl: 'https://ajb-images.oss-cn-shanghai-finance-1-pub.aliyuncs.com/9/ydshare.jpg',
          success: function () {
            _this.wxShareFlag = false;
            _this.alertFlag = true;
            if (res['success'] === true) {
              _this.dialogTips = '分享成功';
            } else {
              _this.dialogTips = '分享失败';
            }
            setTimeout(() => {
              _this.alertFlag = false;
              _this.changeDetectorRef.markForCheck();
              _this.changeDetectorRef.detectChanges();
            }, 500)
            _this.changeDetectorRef.markForCheck();
            _this.changeDetectorRef.detectChanges();
          }
        };
        wx.ready(function () {
          wx.onMenuShareAppMessage(shareData);  // 分享微信
          wx.onMenuShareTimeline(shareData);    // 分享到朋友圈
          wx.onMenuShareQQ(shareData);    // 分享到QQ
          wx.onMenuShareQZone(shareData);    // 分享到QQ空间
        });
      });
    } else {
      this.defaultWxShare();
    }
  }

  // 配置分享
  private configWX() {
    const url = encodeURIComponent(location.href.split('#')[0]);
    this.commonService.getWXJsInitConfig(url).then(res => {
      const data = res['data'];
      wx.config({
        debug: false,
        appId: data.appId,
        timestamp: data.timestamp,
        nonceStr: data.nonceStr,
        signature: data.signature,
        jsApiList: data.jsApiList,
        beta: true
      });
    });
  }

  // 分享
  defaultWxShare() {
    const _this = this;
    // 默认的分享信息
    const shareData = {
      title: 'AI智能保险顾问',
      link: `${environment.hostName}/questionnaire/#/index?campaign=AIRobot&task=AItask1`,
      desc: 'AI智能家庭风险评测 、实时保障方案推荐。一分钟、搞定家庭保险。',
      imgUrl: 'https://ajb-images.oss-cn-shanghai-finance-1-pub.aliyuncs.com/9/ydshare.jpg',
      success: function () {
        _this.wxShareFlag = false;
        _this.alertFlag = true;
        _this.dialogTips = '分享成功';
        setTimeout(() => {
          _this.alertFlag = false;
          _this.changeDetectorRef.markForCheck();
          _this.changeDetectorRef.detectChanges();
        }, 500)
        _this.changeDetectorRef.markForCheck();
        _this.changeDetectorRef.detectChanges();
      }
    };
    wx.ready(function () {
      wx.onMenuShareAppMessage(shareData);  // 分享微信
      wx.onMenuShareTimeline(shareData);    // 分享到朋友圈
      wx.onMenuShareQQ(shareData);    // 分享到QQ
      wx.onMenuShareQZone(shareData);    // 分享到QQ空间
    });
  }

  /**
   * 检测操作系统
   */
  checkOs() {
    let os;
    const isWin = (navigator.platform === 'Win32') || (navigator.platform === 'Windows');
    const isMac = (navigator.platform === 'Mac68K') ||
      (navigator.platform === 'MacPPC') ||
      (navigator.platform === 'Macintosh') ||
      (navigator.platform === 'MacIntel');
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
      os = 1;
      return os; // 这是iOS平台下浏览器
    } else if (/android/i.test(navigator.userAgent)) {
      os = 2;
      return os; // 这是Android平台下浏览器
    } else if (isWin) {
      os = 3;
      return os; // 这是Android平台下浏览器
    } else if (isMac) {
      os = 4;
      return os; // 这是mac系统
    } else if (/Linux/i.test(navigator.userAgent)) {
      os = 5;
      return os; // 这是Linux平台下浏览器
    } else {
      os = 6;
      return os;
    }
  }

  /**
   * 检测设备信息
   * deviceType:PC为1,移动端为2,微信为3
   */
  checkDeviceType() {
    let deviceType = null;
    if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
      if (navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1) {
        deviceType = 3;
      } else {
        deviceType = 2;
      }
    } else {
      deviceType = 1;
    }
    return deviceType;
  }
}
