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'] ? this.activatedRoute.snapshot.queryParams['shareCode'] : uuid.v4();
    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']
    } else {
      this.customerId = null;
    }
    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
    };
    if (this.lifeCommonService.checkDeviceType() == '3' && !this.customerId) {
      this.getWxUserInfo();
    }
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  // 从后台获取到获取微信code的URL
  getWxUserInfo() {
    this.myService.getWxUserInfo().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 = !this.shareAbled;
    this.lifeCommonService.wxShare(this.articleInfo.title, `来自银盾经纪人${this.agentInfo.agentName}的分享`, `${window.location.href}?shareCode=${this.shareCode}`, this.articleInfo.coverUrl);
    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;
      this.agentInfo = {
        headImagePath: this.sharePractitionerInfo.headImagePath,
        agentName: this.sharePractitionerInfo.name,
        insurerBranchName: this.sharePractitionerInfo.insurerBranchName,
        qrCodePath: this.sharePractitionerInfo.qrCodePath,
        mobileNo: this.sharePractitionerInfo.mobileNo
      };
      this.lifeCommonService.wxShare(this.articleInfo.title, `来自银盾经纪人${this.agentInfo.agentName}的分享`, `${window.location.href}`, this.articleInfo.coverUrl);
    });
  }

  // 保存文章code
  articleShareCodeSave() {
    this.articleShareCodeSaveInfo = {
      itemId: this.articleId,
      shareCode: this.shareCode,
      practitionerId: this.lifeCustomerInfo.practitionerId ? this.lifeCustomerInfo.practitionerId : this.sharePractitionerInfo.practitionerId,
      customerId: this.lifeCustomerInfo.customerId ? this.lifeCustomerInfo.customerId : this.sharePractitionerInfo.customerId,
      os: this.lifeCommonService.checkOs(),
      channel: 1,
      url: window.location.href
    };
    this.myService.articleShareCodeSave(this.articleShareCodeSaveInfo).subscribe(res => {
      // console.log(res);
    });
  }

  // 保存客户痕迹:
  // 有id就是出  没id就是进
  articleTrackSave() {
    const param = {
      id: null,
      shareCode: this.shareCode,
      nickname: null,
      gender: null,
      imagePath: null,
      deviceType: this.lifeCommonService.checkDeviceType()
    };
    this.myService.articleTrackSave(param).subscribe(res => {
      console.log(res);
    })
  }

  // 判断是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();
    }
  }
}
