import {Component, OnInit, ElementRef, ViewChild} from '@angular/core';
import {MyService} from '../../my/my.service';
import {LifeCommonService} from '../../common/life-common.service';
import {Subscription} from "rxjs/index";
import {OnDestroy} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router";
import * as uuid from 'uuid';
declare const wx: any;

@Component({
  selector: 'ydlife-article-detail',
  templateUrl: './article-detail.component.html',
  styleUrls: ['./article-detail.component.scss']
})
export class ArticleDetailComponent implements OnInit, OnDestroy {
  @ViewChild('payForm') payForm: ElementRef;
  articleInfo: any;
  lifeCustomerInfo: any;
  paymentForm: any;
  customerId: number;
  agentInfo: any;
  shareAbled: boolean = false;
  subscription: Subscription;
  articleId: number;
  shareCode: string;
  articleShareCodeSaveInfo: any;
  sharePractitionerInfo: any;

  constructor(private myService: MyService, public lifeCommonService: LifeCommonService, public router: Router, public activatedRoute: ActivatedRoute) {
    // this.subscription = lifeCommonService.shareStatus$.subscribe(status => {
    //   this.shareAbled = !(status == '0');
    // });
  }

  ngOnInit() {
    this.articleId = this.activatedRoute.snapshot.params['id'];
    this.shareCode = this.activatedRoute.snapshot.queryParams['shareCode'];
    if (this.activatedRoute.snapshot.queryParams['shareCode']) {
      this.practitionerFileSharingList(null, this.shareCode);
      this.articleTrackSave();
    } else {
      this.practitionerFileSharingList(this.articleId, null);
    }
    this.lifeCustomerInfo = JSON.parse(localStorage.getItem('lifeCustomerInfo')) ? JSON.parse(localStorage.getItem('lifeCustomerInfo')) : null;
    if (this.lifeCustomerInfo) {
      this.customerId = JSON.parse(localStorage.getItem('lifeCustomerInfo'))['customerId'];
      this.agentInfo = {
        headImagePath: this.lifeCustomerInfo.practitionerBasicInfo.headImagePath,
        agentName: this.lifeCustomerInfo.practitionerBasicInfo.name,
        insurerBranchName: this.lifeCustomerInfo.practitionerBasicInfo.insurerBranchName,
        qrCodePath: this.lifeCustomerInfo.practitionerBasicInfo.qrCodePath,
        mobileNo: this.lifeCustomerInfo.mobileNo
      };
    } else {
      this.customerId = null;
    }
    // if (this.lifeCommonService.checkDeviceType() == '3' && !this.customerId) {
    //   this.getWxUserInfo();
    // }
  }

  ngOnDestroy() {
    this.articleTrackSave();
    sessionStorage.removeItem('articleTrackId');
  }

  // 从后台获取到获取微信code的URL
  getWxUserInfo(trackId) {
    this.myService.getWxUserInfo(trackId).subscribe(res => {
      if (res['success']) {
        this.paymentForm = res['data'].paymentForm;
        this.getOrPost(this.paymentForm.action, this.paymentForm.param, this.paymentForm.charset, this.paymentForm.actionType);
      }
    })
  }


  // 点击分享
  share() {
    this.shareAbled = true;
    this.articleShareCodeSave();
    setTimeout(() => {
      this.shareAbled = false;
    }, 6000);
  }

  // 通过文章ID或者分享码查询文章详情
  practitionerFileSharingList(id, shareCode) {
    this.myService.practitionerFileSharingList({
      shareCode: shareCode,
      id: id,
      practitionerFileShares: {pageNum: 1, pageSize: 5}
    }).subscribe(res => {
      this.articleInfo = res['data'].practitionerFileShares.list['0'];
      this.sharePractitionerInfo = res['data'].sharePractitionerInfo;
      if (this.sharePractitionerInfo) {
        this.agentInfo = {
          headImagePath: this.sharePractitionerInfo.headImagePath,
          agentName: this.sharePractitionerInfo.name,
          insurerBranchName: this.sharePractitionerInfo.insurerBranchName,
          qrCodePath: this.sharePractitionerInfo.qrCodePath,
          mobileNo: this.sharePractitionerInfo.mobileNo
        };
      }


    });
  }

  // 保存文章code
  articleShareCodeSave() {
    this.articleShareCodeSaveInfo = {
      itemId: this.articleId,
      shareCode: uuid.v4(),
      practitionerId: this.lifeCustomerInfo ? this.lifeCustomerInfo.practitionerId : this.sharePractitionerInfo.practitionerId,
      customerId: this.lifeCustomerInfo ? this.lifeCustomerInfo.customerId : this.sharePractitionerInfo.customerId,
      os: this.lifeCommonService.checkOs(),
      channel: 1,
      url: window.location.href
    };
    this.lifeCommonService.wxShare(this.articleInfo.title, `来自银盾经纪人${this.lifeCustomerInfo ? this.lifeCustomerInfo.practitionerBasicInfo.name : this.sharePractitionerInfo.name}的分享`, `${window.location.origin}${window.location.pathname}?shareCode=${this.articleShareCodeSaveInfo.shareCode}`, this.articleInfo.coverUrl);
    this.myService.articleShareCodeSave(this.articleShareCodeSaveInfo).subscribe(res => {
      // console.log(res);
    });
  }

  // 保存客户痕迹:
  // 有id就是出  没id就是进
  articleTrackSave() {
    const param = {
      id: sessionStorage.getItem('articleTrackId') ? sessionStorage.getItem('articleTrackId') : null,
      shareCode: this.shareCode,
      nickname: null,
      gender: null,
      imagePath: null,
      deviceType: this.lifeCommonService.checkDeviceType()
    };
    this.myService.articleTrackSave(param).subscribe(res => {
      sessionStorage.setItem('articleTrackId', res['data']['id']);
      if (this.lifeCommonService.getQueryString('state') != '1') {
        this.getWxUserInfo(res['data']['id']);
      }
    })
  }

  // 判断是get请求还是post请求进行支付请求
  getOrPost(action, params, charset, actionType) {
    let url = '';
    let paramHTML = '';
    let hiddenContent = '';
    if (actionType.toLowerCase() === 'get') {
      url = action;
      if (params) {
        for (let i = 0; i < params.length; i++) {
          url += '&' + params[i].name + '=' + params[i].value;
        }
      }
      window.location.href = url;
    } else if (actionType.toLowerCase() === 'post') {
      if (params) {
        for (let i = 0; i < params.length; i++) {
          paramHTML += '<input type="text" value="' + params[i].value + '" name="' + params[i].name + '" hidden>'
        }
      }
      hiddenContent +=
        '<form action="' + action + '"method="post" accept-charset="' + charset + '" onsubmit="document.charset=\'' + charset + '\';">'
        + paramHTML
        + '<button type="submit" id="submit" hidden></button>'
        + '</form>';
      this.payForm.nativeElement.innerHTML = hiddenContent;
      document.getElementById('submit').click();
    }
  }
}
