import { Component, OnInit,ViewChild,ElementRef, OnDestroy, AfterViewInit  } from '@angular/core';
import { MyService } from '../../my.service';
import { ActivatedRoute,Router } from "@angular/router";
import { LifeCommonService } from "../../../common/life-common.service";
import {SignaturePad} from 'angular2-signaturepad';
declare var rrweb:any;
@Component({
  selector: 'ydlife-signature',
  templateUrl: './signature.component.html',
  styleUrls: ['./signature.component.scss']
})
export class SignatureComponent implements OnInit,OnDestroy,AfterViewInit {
  hiringBasicInfoId:any;
  signatureImage:string;
  signaturePadOptions:any;
  imgStr:any;
  isNeedAlert: boolean;
  dialogInfo: any;
  isSignatureShow:boolean=false;
  viewApprovalInfo:any;
  approveStatus:any;
  // 获取页面适用类型
  type:string;
  todayDate:Date = new Date();
  @ViewChild(SignaturePad) signaturePad : SignaturePad;
  timerId:any;
  events:Array<any> = [];
  pageInfo = {
    type:7,
    name:'签字页面'
  }
  constructor(private activatedRoute: ActivatedRoute,
    private router: Router,public lifeCommonService:LifeCommonService,
    public myService:MyService) {



    }
    ngAfterViewInit(): void {
      setTimeout(()=>{this.creatRecord()},500);
      this.timerId = setInterval(()=>{
        if(this.events.length > 100){
          this.saveRecord()
        }
      },10 * 1000);
    }
    ngOnDestroy(): void {
      clearInterval(this.timerId)
    }

    creatRecord(){
      let _this = this;
      _this.events = [];
      rrweb.record({
        emit(event){
          // 将evene存入events数组中
          _this.events.push(event);
        },
        recordCanvas: true
      });
    }
    saveRecord(){
      this.myService.rrwebInfo(this.events,this.pageInfo).subscribe(res=>{
        this.creatRecord()
      })
    }
  ngOnInit() {
    this.type = this.activatedRoute.snapshot.queryParams.type ? this.activatedRoute.snapshot.queryParams.type :null;
    this.signaturePadOptions = {
      minWidth: 0.5,
      maxWidth: 3,
      dotSize: 1.5,
      penColor: "#333",
      /* INVERSE BECAUSE IT IS SHOW ONLY IN LANDSCAPE */
      canvasWidth: document.body.clientWidth-26,
      canvasHeight: 280,
      // backgroundColor:"rgb(248 248 248)"
    }
    const title = this.activatedRoute.snapshot.data[0]['title'];
    this.lifeCommonService.setTitle(title);
    if(this.type!='eNotice' && this.type !='continuationRate' && this.type != 'unionSaleSignature'){
      this.hiringBasicInfoId = this.activatedRoute.snapshot.queryParams.hiringBasicInfoId?this.activatedRoute.snapshot.queryParams.hiringBasicInfoId:null;
      this.queryWholeInfo(this.hiringBasicInfoId)
      this.viewApprovalInfo = sessionStorage.getItem('viewApprovalInfo');
    }
  }

  next(){
	this.isNeedAlert = true;
	this.dialogInfo = {
	  title: null,
	  content: { value: '本人承诺，报聘银盾保险经纪有限公司经纪人过程中填写的信息真实有效，报聘链接的附件文件已认真查看，并电子签字确认执行', align: 'center' },
	  footer: [{ value: '确认', routerLink: '', className: 'weui-dialog__btn_primary' },{ value: '关闭', routerLink: ''}],
	};
   
  }

  drawComplete() {
    this.imgStr = this.signaturePad.toDataURL();
  }

  drawStart() {
    // console.log('begin drawing');
  }

  saveDigitalSignatures(){
    if (this.signaturePad.isEmpty()) {
      this.openPopInfo('您还没有签名！');
      return;
    }
    if(this.type=='eNotice'){
      this.saveRecord();
      this.myService.signInformedSheet({'id':sessionStorage.getItem('eNoticeId'),imgStr:this.imgStr}).subscribe(res=>{
        if(res['success']){
          // 确认提交
          this.router.navigate(['/eNotice_submit']);
        }else{
         this.openPopInfo(res['message']);
        }
      })
    }else if(this.type == 'continuationRate'){
      this.saveRecord();
      // console.log('继续率承诺书');
      const param = {
        practitionerId: localStorage.getItem('lifeCustomerInfo')?JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId']:null,
        practitionerName: localStorage.getItem('lifeCustomerInfo')?JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerBasicInfo']['name']:null,
        imgStr:this.imgStr
      }
      console.log(param)
      this.myService.signCommitment(param).subscribe((res)=>{
        if(res['success']){
          // 确认提交
          this.router.navigate(['/eNotice_submit']);
        }else{
         this.openPopInfo(res['message']);
        }
      })
    }else if(this.type == 'unionSaleSignature'){
      const param = {
        practitionerId:localStorage.getItem('lifeCustomerInfo')?JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId']:null,
        imgStr:this.imgStr,
        unionSalesPractitionerId:this.activatedRoute.snapshot.queryParams['unionSalesPractitionerId'],
        unionSalesId:this.activatedRoute.snapshot.queryParams['unionSalesId']
      }
      this.myService.signUnionSales(param).subscribe(res=>{
        if(res['success']){
          // 确认提交
          this.router.navigate(['/eNotice_submit']);
        }else{
         this.openPopInfo(res['message']);
        }
      })
    }else{
      const param = {
        hiringBasicInfoId:this.hiringBasicInfoId,
        imgStr:this.imgStr
      }
      this.myService.saveDigitalSignatures(param).subscribe((res)=>{
        if(res['success']){
          this.queryWholeInfo(this.hiringBasicInfoId);
          this.saveRecord();
          this.router.navigate(['/employee_submit'],{queryParams:{ hiringBasicInfoId:this.hiringBasicInfoId,status:this.approveStatus}});
        }else{
          this.openPopInfo(res['message']);
        }
      })
    }

  }

  queryWholeInfo(hiringBasicInfoId){
    this.myService.queryWholeInfo({hiringBasicInfoId:hiringBasicInfoId}).subscribe((res)=>{
      if(res['success']){
        this.approveStatus = res['data']['hiringBasicInfo']['approveStatus'];
        if(res['data']['hiringBasicInfo']['personalSignOssPath']){
          this.imgStr = res['data']['hiringBasicInfo']['personalSignOssPath'];
          //控制查询的图片显示
          this.isSignatureShow = true;
        }else{
          this.isSignatureShow = false;
        }
      }else{
        this.isSignatureShow = false;
      }
    })
  }

  revokeSignature(){
    var data = this.signaturePad.toData();
    if (data) {
      data.pop(); // remove the last dot or line
      this.signaturePad.fromData(data);
    }
    this.drawComplete();
  }

  // 打开弹窗
  openPopInfo(message) {
    this.isNeedAlert = true;
    this.dialogInfo = {
      title: null,
      content: { value: message, align: 'center' },
      footer: [{ value: '我知道了', routerLink: '', className: 'weui-dialog__btn_primary' }],
    };
  }

  // 关闭弹窗
  getPopInfo(e) {
    this.isNeedAlert = false;
	if(e=='确认'){
		if (this.isSignatureShow == false) {
			this.saveDigitalSignatures();
		} else {
			this.saveRecord();
			this.router.navigate(['/employee_submit'], { queryParams: { hiringBasicInfoId: this.hiringBasicInfoId, status: this.approveStatus } });
		}
	}
  }

  clearSignature(){
    if(this.isSignatureShow == true){
      this.isSignatureShow = false;
      this.signaturePad.clear();
    }else{
      this.signaturePad.clear();
    }
  }

  viewNext(){
    if(this.viewApprovalInfo==0){
      this.saveRecord();
      this.router.navigate(['/approval_comments'],{ queryParams: { hiringBasicInfoId:this.hiringBasicInfoId} });
    }else{
      this.saveRecord();
      this.router.navigate(['/employee_submit'],{queryParams:{ hiringBasicInfoId:this.hiringBasicInfoId,status:this.approveStatus}});
    }
  }

  goBack(){
    history.go(-1);
  }

  returnResult(){
    this.saveRecord();
    this.router.navigate([`/approval_result_list`],{queryParams:{hiringBasicInfoId:this.hiringBasicInfoId}})

  }
}
