import { Component, OnInit, Inject, TemplateRef } from '@angular/core';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { ContactService } from '../contact.service';
import { saveAs } from 'file-saver';
import { FlashMessagesService } from 'angular2-flash-messages';
import { FormBuilder, FormGroup } from '@angular/forms';
import { BsModalRef, BsModalService } from 'ngx-bootstrap';
declare var swal: any;

@Component({
  selector: 'app-edit-costumer',
  templateUrl: './edit-costumer.component.html',
  styleUrls: ['./edit-costumer.component.scss'],


})
export class EditCostumerComponent implements OnInit {
  custId: any;
   kycStatus=[{Name:'Approved',value:'Approved'},{Name:'Reject',value:'Reject'},{Name:'Pending',value:'Pending'}]
  dealerInfo:any;
  dealerEditForm:any;
  firstName:any;
  lastName:any;
  email:any;
  is_expand:boolean=false;
  PhoneNum:any;
  password:any;
  cnfrmPass:any;
  image
    emergencyForm:FormGroup;

  userId:any;
  address:any;
  date=new Date();
  expDate = new Date(this.date.getFullYear()+1,this.date.getMonth(), this.date.getDate()).toLocaleString();
  pageId: any;
  testDocuments: any=[];
  doclist: boolean=false;
  imageuploadObject = [];
  documentList = [
    {
      "docId": "Adhar card",
      "docName": "Adhar Card"
    },
    {
      "docId": "voter Id",
      "docName": "Voter Id"
    },
    {
      "docId": "PAN card",
      "docName": "Pan Card"
    },
    {
      "docId": "Driving License",
      "docName": "Driving License"
    },
    {
      "docId": "RC Book",
      "docName": "RC Book"
    },
    {
      "docId": "Device Image",
      "docName": "Device Image"
    },
    {
      "docId": "Other",
      "docName": "Other"
    }
    
  ];
  showUpload: boolean=false;
  Load: boolean;
  uploadStatus: any = 'Upload';
  ifuploadArr: boolean ;
  useridForDocUpload: any;
  disableDelete: boolean;
  errorMsg: string;
  showError: boolean = false;
  dealerStatus: any;
  superAdmin: any;
  superadminAccess: any;
  label: any;
   modalRef: BsModalRef;
  header: any;
  constructor(public dialogRef: MdDialogRef<EditCostumerComponent>,private modalService: BsModalService,public thisDialogRef: MdDialogRef<EditCostumerComponent>,private fb:FormBuilder,
    @Inject(MD_DIALOG_DATA) public data: any,private contactService: ContactService,private _flashMessagesService: FlashMessagesService) {
      var  initialObj = {
        doctype:'',
        image:'',
        phone:''
      }
      this.imageuploadObject.push(initialObj);
     }
     alertLabel:any = 'Delete Dealer';
     alertLabel_1:any = 'you want to delete dealer';


     ngOnInit() {
    if(this.data.dealer_payload.emergency_contact){

      this.emergencyForm=this.fb.group({
       emg_name1:[this.data.dealer_payload.emergency_contact.contact1.name?this.data.dealer_payload.emergency_contact.contact1.name:''],
       emg_name2:[this.data.dealer_payload.emergency_contact.contact2.name?this.data.dealer_payload.emergency_contact.contact2.name:''],
       emg_cell1:[this.data.dealer_payload.emergency_contact.contact1.cell1?this.data.dealer_payload.emergency_contact.contact1.cell1:''],
       emg_cell2:[this.data.dealer_payload.emergency_contact.contact1.cell2?this.data.dealer_payload.emergency_contact.contact2.cell2:''],
       emg_cell3:[this.data.dealer_payload.emergency_contact.contact2.cell1?this.data.dealer_payload.emergency_contact.contact1.cell1:''],
       emg_cell4:[this.data.dealer_payload.emergency_contact.contact2.cell2?this.data.dealer_payload.emergency_contact.contact2.cell2:''],
       emg_phone1:[this.data.dealer_payload.emergency_contact.contact1.phone1?this.data.dealer_payload.emergency_contact.contact1.phone1:''],
       emg_phone2:[this.data.dealer_payload.emergency_contact.contact1.phone2?this.data.dealer_payload.emergency_contact.contact1.phone2:''],
       emg_phone3:[this.data.dealer_payload.emergency_contact.contact2.phone1?this.data.dealer_payload.emergency_contact.contact2.phone1:''],
       emg_phone4:[this.data.dealer_payload.emergency_contact.contact2.phone2?this.data.dealer_payload.emergency_contact.contact2.phone2:'']
 
     })
    }else{
      this.emergencyForm=this.fb.group({
       emg_name1:[''],
       emg_name2:[''],
       emg_cell1:[''],
       emg_cell2:[''],
       emg_cell3:[''],
       emg_cell4:[''],
       emg_phone1:[''],
       emg_phone2:[''],
       emg_phone3:[''],
       emg_phone4:['']
 
     })
    }
    console.log("Emergency Contacts==>",this.data.dealer_payload.emergency_contact);
    
    this.dealerInfo=this.data;
    console.log(this.dealerInfo);
    this.userId = this.dealerInfo.dealer_payload.user_id?this.dealerInfo.dealer_payload.user_id:'';
     console.log(this.userId);
    this.expDate = this.dealerInfo.dealer_payload.expire_date?this.dealerInfo.dealer_payload.expire_date:'';
    this.firstName = this.dealerInfo.dealer_payload.first_name?this.dealerInfo.dealer_payload.first_name:'';
    this.lastName = this.dealerInfo.dealer_payload.last_name?this.dealerInfo.dealer_payload.last_name:'';
    this.email = this.dealerInfo.dealer_payload.email?this.dealerInfo.dealer_payload.email:'';
    this.PhoneNum = this.dealerInfo.dealer_payload.phone?this.dealerInfo.dealer_payload.phone:'';
    this.address =this.dealerInfo.dealer_payload.address?this.dealerInfo.dealer_payload.address:'';
    this.custId = this.dealerInfo.dealer_payload._id?this.dealerInfo.dealer_payload._id:'';
    this.pageId = this.dealerInfo.dealer_payload.ID;
  
    if(this.dealerInfo.dealer_payload){
      if(this.dealerInfo.dealer_payload.page === 'cust'){
        this.alertLabel = 'Delete Customer';
        this.alertLabel_1 = 'you want to delete Customer'
      }
    }
    // console.log("image Document Object=>",this.data.dealer_payload.imageDoc);

    this.dealerStatus = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;


    // 'superadmin :on'
    // 'isDealer : true'
    this.superadminAccess = localStorage.getItem('superadmin');

    console.log("this.superadminAccess,this.dealerStatus",this.superadminAccess,this.dealerStatus);
    
    console.log("val=",this.pageId);
    this.testDocuments = this.data.dealer_payload.imageDoc;
    for(var i=0;i<this.testDocuments.length;i++){
      if(this.testDocuments[i].image){
        var ext=this.testDocuments[i].image.split('.').pop(); 
        this.testDocuments[i].ext=ext
        this.testDocuments[i].image=(this.testDocuments[i].image).substring(6);

      }
    }
    if(this.testDocuments){
      if(this.testDocuments.length == 0){
        this.doclist = true;
      }
    }
   
    if(this.pageId == 'viewDoc'){
      console.log(this.data);
       this.useridForDocUpload = this.data.dealer_payload.dealer_id?this.data.dealer_payload.dealer_id:this.data.dealer_payload._id
      console.log(this.useridForDocUpload);
    }
  }

  editCustmer(){
    // console.log("Custmer method");
     var emergencyContact={
          contact1:{
            name:this.emergencyForm.value.emg_name1,
            cell1:this.emergencyForm.value.emg_cell1,
            cell2:this.emergencyForm.value.emg_cell2,
            phone1:this.emergencyForm.value.emg_phone1,
            phone2:this.emergencyForm.value.emg_phone2

          },
           contact2:{
            name:this.emergencyForm.value.emg_name2,
            cell1:this.emergencyForm.value.emg_cell3,
            cell2:this.emergencyForm.value.emg_cell4,
            phone1:this.emergencyForm.value.emg_phone3,
            phone2:this.emergencyForm.value.emg_phone4

          }
        }
    var editDealerPayload = {
      first_name : this.firstName,
      last_name:this.lastName,
      user_id:this.userId,
      // email:this.email,
      // phone:this.PhoneNum,
      address:this.address,
      contactid:this.custId,
      expire_date:new Date(this.expDate),
       emergencyContact:emergencyContact
    
    }
    // status: true
    // this.dealerInfo.dealer_payload.status
    if(this.PhoneNum !== this.dealerInfo.dealer_payload.phone){
      editDealerPayload['phone'] = this.PhoneNum
    }
    if(this.email!== this.dealerInfo.dealer_payload.email){
      editDealerPayload['email'] = this.email
    }
    this.contactService.editDealer(editDealerPayload)
      .subscribe(res=>{
        // console.log(res);
        if(res){
          // console.log(res);
          this.thisDialogRef.close("success");
      }  
      },err=>{
        var that = this;
        console.log(JSON.parse(err._body).message);
        var errorM = (JSON.parse(err._body).message).split(":");
        console.log(errorM);
        var mainErr =errorM[2];
        if(mainErr == " phone_1 dup key"){
          this.errorMsg = "Phone number already exists";
        }else if(mainErr == " email_1 dup key"){
          this.errorMsg = "Email id already exists";
        }else{
          this.errorMsg = "Internal server error";
        }

        this.showError  = true;
      
        var error =  setTimeout(function(){
          clearInterval(error);
          that.showError = false; 
        },5000)
      })
  }

  deleteResponse(action){
    if(action =='yes'){
      this.thisDialogRef.close("yes");
    }else{
      this.thisDialogRef.close("no");
    }
  
  }



  downloadDoc(doc:any){
    console.log(doc.image);
    var imageLink = doc.image; 
    var filetext  = imageLink.split('.');
    console.log(filetext[1]);
    
    this.contactService.DownloadDocument(doc.image).subscribe(res=>{
      console.log(res);
      this.saveToFileSystem(res,doc,filetext[1]);
    },err=>{
      console.log(err);
    })
  }

  private saveToFileSystem(response,doc,fileex) { 
    console.log(response._body);
    if(fileex == 'pdf'){
      console.log("Inside pdf");
      var blob = new Blob([response._body], { type: "application/pdf" });
    }else{
      var blob = new Blob([response._body], { type: "image/png" });
    }
   
    var filename = doc.doctype+'_'+doc.phone;
    // console.log(filename);
    saveAs(blob,filename);
  }

  deleteDoc(doc,index){
    console.log(index);
    console.log(doc);

  }

  Adddocuments(doc){
    console.log(doc);
    this.disableDelete = true;
    this.showUpload = true;
    if(this.imageuploadObject.length == 0){
      this.ifuploadArr = false;
    }
  }

  docRow:boolean=false;
  AddDocumentsField(addedRow:any){
    console.log("Inside function !!!");
      if(addedRow){    
        this.docRow = true;
      }
       var obj={doctype:'',image:'',phone:''};
       this.imageuploadObject.push(obj);
       console.log(this.imageuploadObject);
  }

  DeleteDocumentsField(index){
    console.log(this.imageuploadObject.length);
    if(this.imageuploadObject.length == 1){
      this.docRow = false;
      this.showUpload = false;
    }
    this.imageuploadObject.splice(index, 1);

  }
  
  documentType(docType){
    console.log("doctypeObject=>",docType);

  }
  selectedFile: File;
  onFileChanged(event) { 
    console.log(event.target.files[0]);
    this.selectedFile = <File>event.target.files[0];
    console.log(this.selectedFile); 
  }

  onUpload(imgIndex) {
    console.log(imgIndex);
    console.log(this.imageuploadObject);
    const fd = new FormData();
    console.log("selected file name =>",this.selectedFile.name);
    if(this.selectedFile.name == " "){
      swal(
        'Upload Error',
        'Please select document type before upload !!!',
        'error'
      )
    }else{
      fd.append('photo',this.selectedFile,this.selectedFile.name)
      console.log("imgURL=>",fd) ;
      this.Load = true;
      this.contactService.imageupload(fd)
      .subscribe(res=>{
        this.Load = false;
        this.ifuploadArr = true;
   
        console.log(res);
        var resImage ='';
        resImage = res['_body'];
        console.log(res['_body']);
        this.imageuploadObject[imgIndex].image = resImage;
         console.log(this.imageuploadObject);
    
      },err=>{
        this.Load= false;
        this._flashMessagesService.show('Internal server error , try again', { cssClass: 'alert-success', timeout: 2000 }); 
      })
    }
   }


   SaveDocuments(actionString,objIndex){
    console.log(this.imageuploadObject);
    console.log("Save");
    var imageuploadArr = {
      _id : this.useridForDocUpload
    }
    if(actionString == 'deldoc'){
      this.testDocuments.splice(objIndex,1);
      console.log("testArray after deleting doc =>",this.testDocuments); 
    }
     for(var d = 0 ;d <this.imageuploadObject.length;d++){
      if((this.imageuploadObject[d].doctype == "")&&(this.imageuploadObject[d].image == "")&&(this.imageuploadObject[d].phone == "")){   
            this.imageuploadObject.splice(d,1);         
      }
    }
   console.log(this.imageuploadObject);
   for(var j = 0;j< this.testDocuments.length;j++){
        console.log(this.testDocuments[j]);
        this.imageuploadObject.push(this.testDocuments[j]);
   }
   
   imageuploadArr['imageDoc'] = this.imageuploadObject;
   console.log(this.imageuploadObject.length);
   this.contactService.updateImage(imageuploadArr).subscribe(res=>{
     console.log(res);
     if(actionString != 'deldoc'){
      this.thisDialogRef.close("imageupdated"); 
     }   
     if(actionString == 'deldoc'){
      this.imageuploadObject = [];
     }
   },err=>{
    this._flashMessagesService.show('Internal server error , try again', { cssClass: 'alert-success', timeout: 2000 }); 
   })
   }

   expand(value){
     console.log(value);
     if(value){
       document.getElementById('container').style.width='80vh'
     }else{
       
     }
     

   }

   
changeKYC(event){
  console.log(event);
  var req={
    user:this.data.dealer_payload._id,
    status:event
  }
  this.contactService.changeKycStatus(req).subscribe(res=>{
    console.log(res);
    //  this.tost1('kyc');
    this.dialogRef.close('yes')
  })
  
}

openModal(template: TemplateRef<any>,data) {
    this.modalRef = this.modalService.show(template,{'backdrop':'static',class:'modal-lg modal-dialog-centered'});
    this.header=data.doctype
    this.image='https://www.oneqlik.in/'+data.image
  }
}


// swal({
//   title: 'Are you sure?',
//   text: "You won't be able to revert this!",
//   type: 'warning',
//   showCancelButton: true,
//   confirmButtonColor: '#3085d6',
//   cancelButtonColor: '#d33',
//   confirmButtonText: 'Yes, delete it!'
// }).then((result: { value: boolean; }) => {
//   if (result) {
//               swal(
//                   'Deleted!',
//                   'Your file has been deleted.',
//                   'success'
//                 )
    
//               swal(
//                   'Server Error',
//                   'Error occured while deleting POI , Please try after sometime !!!',
//                   'error'
//                 )
         
//   }
// })