import { FormGroup, FormControl, Validators} from '@angular/forms';
import {ResponseOptions, Response} from '@angular/http';
import {Contact} from '../contact';
import {ContactService} from '../contact.service';
import {Otp} from '../otp';
// import {Md5} from 'ts-md5/dist/md5';
import * as moment from 'moment-timezone';
declare var google :any;

import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn } from '@angular/forms';
const EMAIL_REGEX =/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
import { Component, OnInit,Inject } from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
declare var swal: any;
declare var ol : any;
declare var $:any;
declare var $: any, _: any;
@Component({
  selector: 'app-add-dealer',
  templateUrl: './add-dealer.component.html',
  styleUrls: ['./add-dealer.component.scss'],
  providers:[ContactService]
})
export class AddDealerComponent implements OnInit {
  superAdmin: any;
  inventoryManagement
  show1:boolean = false;
  show2:boolean = true;
  passwordtype : any = 'password';
  passwordtype_1 :any = 'password';
  show3:boolean = false;
  first_name:any=null;
  imageuploadObject = [];
  timezone:any = 'Asia/Kolkata';
  last_name:any=null;
  passwordd:any=null;
  org_name:any=null;
  emaill:any=null;
  phone:any=null;
  executed:any;
  $event2:any;
  dealer:any;
  contacts: Contact[]=[];
  contact: Contact;
  login1:any;
  mess2:any;
  mess:any;
  otp:any;
  str:boolean = false;
  password2:any=null;
  before:any;
  emmnerr:any;
  Load:any
  $event:any;
  fs:any;
  ls:any;
  emailid:any;
  or:any;
  useridd:any;
  custtype:any;
  cust:boolean=false;
  mb:any;
  logo:any;
  text:any;
  userID:any;
  address:any;
  sup_admin: any;
  documentDetail:any;
  imageURL:any;

  documentList = [
    {
      "docId": "Adhar",
      "docName": "Adhar Card"
    },
    {
      "docId": "voterCard",
      "docName": "Voter Id"
    },
    {
      "docId": "PAN",
      "docName": "Pan Card"
    },
    {
      "docId": "DL",
      "docName": "Driving License"
    },
    {
      "docId": "Nepali Citizenship",
      "docName": "Nepali Citizenship"
    }
    
  ];
  countrySelected: { countryCode: any; dialcode: any; };
  timezoneArray: any[];
  telCountryCode: any;

  constructor(private contactService: ContactService,private router: Router,private _flashMessagesService: FlashMessagesService,public dialogRef: MdDialogRef<AddDealerComponent>,
    @Inject(MD_DIALOG_DATA) public data: any) { 

      var script = document.createElement("script");
      script.setAttribute("type", "text/javascript");
      script.setAttribute("src", "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.0/js/intlTelInput-jquery.min.js");
      document.getElementsByTagName("head")[0].appendChild(script);
      
      var  initialObj = {
        doctype:'',
        image:'',
        phone:''
      }
      this.imageuploadObject.push(initialObj);
    }
bussinessType:boolean=false;
db_token: any = { isDealer: false, isSuperAdmin: false };;
db_state_city_list:boolean=false;
_org = JSON.parse(localStorage.ORG);
  ngOnInit() {
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.fs = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).fn;
    this.ls = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).ln;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    // this.bussinessType=this.data.userInfo.bussinessType?this.data.userInfo.bussinessType=="1"?true:false:false
    this.sup_admin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;
    this.db_token = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    );
    var that = this;
    setTimeout(() => {
     that.telCountryCode =  $("#telephone").intlTelInput({
        allowDropdown:true,
        autoPlaceholder:"Enter Mobile Number",
        initialCountry:"in",
        preferredCountries: ["in","us" ],
        separateDialCode:true,
        }); 
    }, 300);
 
      this.getAllState()
    var Phoneinput = document.getElementById('telephone');
    var that = this;
    Phoneinput.addEventListener("countrychange",function(p) {
      console.log("Inside Function");
      var countryData = $('#telephone').intlTelInput("getSelectedCountryData");
      console.log(countryData); 
      that.countrySelected = {
        countryCode : countryData.iso2,
        dialcode: countryData.dialCode
      }
      });
 
   
    if(this.superAdmin){
      this.sup_admin = this.useridd;
    }

    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
  //  this.getdev();
  if(this.mb.charAt(0)=="n"){
    this.mb = ' '
  }
  if(this.custtype == true){
    this.cust = true;
  }

  this.logo=window.localStorage['logo'];
  this.text=window.localStorage['text']; 

  var timeZn = moment.tz.guess(); 
  if(timeZn != 'Asia/Calcutta'){
    this.timezone = timeZn;
  }
  console.log(this.timezone);


var timeZones = moment.tz.names();
console.log(timeZones);
this.timezoneArray=[];
for (var i in timeZones) {
  this.timezoneArray.push({ viewValue: "(GMT" + moment.tz(timeZones[i]).format('Z') + ")" + timeZones[i], value: timeZones[i] });
}


setTimeout(() => {
  $('#dbselect').multipleSelect({
    width: 300,
    placeholder: 'Select Timezone',
    filter: true,
    single: true,
    selectAll: false
  })   
}, 100);
this.latLongDetail()
  }

  stre(){
    this.str =true;
  }
  stren(){
    this.str =false;
  }
  addcus(){
    this.router.navigateByUrl("add");
  }
  clear(){
    this.first_name=' '
    this.last_name=' '
    this.emaill = null
    this.phone = null
  }
  customer_role='normal';
  state='all'

  onUsertypeChange(event){

  }
  onStateChange(event) {
    let stList: any = _.find(this.db_state_city_list, {
      state: event.target.value,
    });
  }

  states = [];
  getAllState() {
    this.contactService.get("/RTO_master/getAllState").subscribe((res: any) => {
      for (var i = 0; i < res.length; i++) {
        this.states.push(res[i]._id.state);
      }
      // this.states=res;
    });
  }
  addContact2(){
    debugger
    var tzone = $('#dbselect').multipleSelect('getSelects','value'); 
    console.log(tzone);
   var expDate = new Date()
   expDate.setFullYear(expDate.getFullYear()+1); 
   var countryData = $('#telephone').intlTelInput("getSelectedCountryData");
   console.log(countryData); 
   this.countrySelected = {
     countryCode : countryData.iso2,
     dialcode: countryData.dialCode
   }
  
   console.log('expDate=>',expDate);
    if(this.first_name==null || this.last_name==null || this.passwordd==null)
      {
     return  this._flashMessagesService.show('Please fill all Requied fields', { cssClass: 'alert-danger', timeout: 3000 });
       
      }  
      else if((this.userID == undefined)||(this.userID.trim() == '')){
      return  this._flashMessagesService.show('User ID is mandatory', { cssClass: 'alert-danger', timeout: 3000 });
      }   
      // else if((this.emaill == undefined)||(this.emaill.trim() == '')){
      //  return this._flashMessagesService.show('Email is mandatory', { cssClass: 'alert-danger', timeout: 3000 });

      // }
      else if(this.password2 != this.passwordd){
       // this._flashMessagesService.show('Password and Confirm Password do not match', { cssClass: 'alert-danger', timeout: 3000 });
        this.tost1("psdnmtch")
       }
      else if (this.emaill && this.phone){
        this.Load=true
   //  if (!this.executed) {
       
    //   this.executed = true;
       const newContact2 ={
       first_name: this.first_name,
       last_name: this.last_name,
       email: this.emaill,
       password: this.passwordd,
       phone: this.phone,
       isDealer: true,
       custumer:false,
       sysadmin:this.superAdmin,
       expdate : new Date(expDate),
       supAdmin:this.sup_admin,
       user_id:this.userID,
       address:this.address

   }
   
   if(this.customer_role !== 'normal'){
    newContact2['customer_role']=this.customer_role;
    newContact2['state']=this.state;
    newContact2['organisation']=this._org._id
    // newContact2['transportOfficeState']=this.state
    // transportOfficeState
   }   
   if(this.inventoryManagement!=undefined){
     newContact2['inventoryManagement']=this.inventoryManagement;
   }
   if(this.bussinessType!=undefined){
      newContact2['bussinessType']=this.bussinessType?"1":"0";
   }
   if(this.countrySelected != undefined){
    newContact2['std_code']=this.countrySelected;
   }
   
      if (tzone != undefined) {
        newContact2['timezone'] = tzone[0];
      }

  

   if(this.imageuploadObject.length > 0){  
     
    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("Final DOC ARRAY",this.imageuploadObject);
    newContact2['imageDoc'] = this.imageuploadObject;
    console.log(newContact2);
   this.contactService.addContact(newContact2)
   .subscribe(contact => {
    console.log(contact);
    //  USER_ID already exists   
    if(contact.message == "USER_ID already exists"){
      return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }if(contact.message == "USER_ID already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else if(contact.message == "User Duplicate"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else if(contact.message == "Email ID already exists"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else if(contact.message == "Mobile Number already exists"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else{
      this.clear();
      this.Load=false
      this.onNoClick("succ");
      this.contacts.push(contact);
    }
  
   }, (err: any) => { 
    //  console.log(err.status); 
    // console.log(err);
  if(err.status ==  500)
  {
  //  console.log(err._body);
    this.Load=false
    this.emmnerr=JSON.parse(err._body);
    this.data_descip = this.emmnerr.split(':')[1];
    console.log(this.data_descip);
    swal(
      'Error',
      this.data_descip,
      'error'
    )

    this.tost1("EmM")
  }
  else{
    this.Load=false
    swal(
      'Error',
      'Internal Server error , Please try after sometime !!!',
      'error'
    )

  }
  });
/*    this._flashMessagesService.show('OTP Sent Sucessfully', { cssClass: 'alert-success', timeout: 3000 }); */

 }
      else if((this.phone)||(this.userID)){
        this.Load=true

    //   if (!this.executed) {
    //     this.executed = true;
         const newContact2 ={
         first_name: this.first_name,
         last_name: this.last_name,
         password: this.passwordd,
        //  phone: this.phone,
         isDealer: true,
         custumer:false,
         sysadmin:this.superAdmin,
         expdate : new Date(expDate).toISOString(),
         supAdmin:this.sup_admin,
        //  user_id:this.userID,
         address:this.address
     }
     if(this.customer_role !== 'normal'){
      newContact2['customer_role']=this.customer_role;
      newContact2['state']=this.state;
      newContact2['organisation']=this._org._id
      // newContact2['transportOfficeState']=this.state
      // transportOfficeState
     }
     if(this.phone){
      newContact2['phone'] = this.phone  ;
    }

    if(this.countrySelected != undefined){
      newContact2['std_code']=this.countrySelected;
     }
    
     
   if(tzone != undefined){
    newContact2['timezone'] = tzone[0];
}
  if(this.inventoryManagement!=undefined){
     newContact2['inventoryManagement']=this.inventoryManagement;
   }
    if(this.bussinessType!=undefined){
      newContact2['bussinessType']=this.bussinessType?"1":"0";
   }
    if(this.userID){
      newContact2['user_id'] = this.userID  ;

    }

     if(this.imageuploadObject.length > 0){  

      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);        
        }
      }
    }
    newContact2['imageDoc'] = this.imageuploadObject;
     this.contactService.addContact(newContact2)
     .subscribe(contact => {
   
      if(contact.message == "USER_ID already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }if(contact.message == "USER_ID already exists"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
          }else if(contact.message == "User Duplicate"){
            return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
          }else if(contact.message == "Email ID already exists"){
            return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
          }else if(contact.message == "Mobile Number already exists"){
            return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
          }else{
        
      this.clear();
      this.Load=false;
      this.onNoClick("succ");
       this.contacts.push(contact);

      }
  
     }, (err: any) => {
    if(err.status ==  500)
    {
    //  console.log(err._body);
      this.Load=false
      this.emmnerr=JSON.parse(err._body);
      this.data_descip = this.emmnerr.split(':')[1];
      console.log(this.data_descip);
      swal(
        'Error',
        this.data_descip,
        'error'
      )
  

      this.tost1("EmM")
    }
    else{
      this.Load=false
      // console.log("dadsa");
      swal(
        'Error',
        'Internal Server error , Please try after sometime !!!',
        'error'
      )
    }})}
 else if(this.emaill){
 // if (!this.executed) {
  //  this.executed = true;
    const newContact2 ={
    first_name: this.first_name,
    last_name: this.last_name,
    password: this.passwordd,
    org_name: this.org_name,
    email: this.emaill,
    isDealer: true,
    custumer:false,  
    sysadmin:this.superAdmin,
    expdate : new Date(expDate).toISOString(),
    supAdmin:this.sup_admin,
    user_id:this.userID,
    address:this.address

}

if(this.countrySelected != undefined){
  newContact2['std_code']=this.countrySelected;
 }

 
 if(tzone != undefined){
  newContact2['timezone'] = tzone[0];
}
if(this.inventoryManagement!=undefined){
     newContact2['inventoryManagement']=this.inventoryManagement;
   }
 if(this.bussinessType!=undefined){
      newContact2['bussinessType']=this.bussinessType?"1":"0";
   }

if(this.imageuploadObject.length > 0){  

  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);   
    }
  }
}
newContact2['imageDoc'] = this.imageuploadObject;

this.contactService.addContact(newContact2)
.subscribe(contact => {
  console.log(contact);
  //  USER_ID already exists

  //this.tost1("succ")
  if(contact.message == "USER_ID already exists"){
    return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
    }if(contact.message == "USER_ID already exists"){
      return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else if(contact.message == "User Duplicate"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else if(contact.message == "Email ID already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else if(contact.message == "Mobile Number already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else{
    this.clear();
    this.Load=false
    this.onNoClick("succ");
    this.contacts.push(contact);
  }

}, (err: any) => {
  if(err.status ==  500)
  {
  //  console.log(err._body);
    this.Load=false
    this.emmnerr=JSON.parse(err._body);
    this.data_descip = this.emmnerr.split(':')[1];
    console.log(this.data_descip);
    swal(
      'Error',
      this.data_descip,
      'error'
    )
    // console.log(this.emmnerr)
    this.tost1("EmM")
  }
  else{
    this.Load=false
    swal(
      'Error',
      'Internal Server error , Please try after sometime !!!',
      'error'
    )
 
  }});


 }
 
 }

 data_descip:any;
 onNoClick(a): void {
  this.dialogRef.close(a);
 }
 tost1(divid){
  if(divid == "EmM"){
     this.data_descip =  this.emmnerr.split(":")[1]
     this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-danger', timeout: 3000 });
   }
   else if(divid == "succ"){
     this.data_descip =  "Dealer Successfully Added"
     this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-success', timeout: 3000 });
   }
   else if(divid == "psdnmtch"){
    this.data_descip =  "Error: Password and confirm password do not match"
    this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-danger', timeout: 3000 });
   }
  //    function launch_toast() {
  //     // console.log(divid);
  //      var x = document.getElementById("toast")
  //      //console.log(x);
  //      x.className = "show";
  //      setTimeout(function(){ x.className = x.className.replace("show", ""); }, 4500);
  //  }
    }

  valclear(){
    this._flashMessagesService.show("Cleared", { cssClass: 'alert-warning', timeout: 2000 });        
    
  }

  devicess:any;
  final:any;
  click1(event){
    this.show2=false;
    this.show3=true;
    if((event.keyCode >= 48 && event.keyCode <= 57) || event.keyCode == 9 || event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39){
    }
    /* if(event.keyCode===13){
    this.otp_window();
    } */
    
    else
    event.preventDefault();
    }
    click2(event2){
      this.show2=true;
      this.show3=false;
      
      }
      call(e) {
        {
               if (e.keyCode == 32) {
                   e.preventDefault();
               }
           }
   }


   getdev(){
    let foods = []
    this.contactService.getDevice(this.emailid,this.useridd).subscribe(
        
      data => {
        this.devicess = data 
  
        let swap;
        for(let g = 0;g<this.devicess.devices.length-1;g++ ){
          for(let c = 0;c<this.devicess.devices.length-g-1;c++ ){
            if(this.devicess.devices[c].Device_Name>this.devicess.devices[c+1].Device_Name){
                swap = this.devicess.devices[c];
                this.devicess.devices[c] = this.devicess.devices[c+1];
                this.devicess.devices[c+1] = swap;
            }
          }
        }
  
        this.final = this.devicess.devices
        
       for(let i=0;i<this.devicess.devices.length;i++){
       
        //  if(this.devicess.devices[i].type_of_device =="Tracker"){
           let a ={
            value : this.devicess.devices[i].Device_Name,
            viewValue:this.devicess.devices[i].Device_Name
           }
           foods.push(a);
        //  }
      
       }
  
      });
  }

  cond:Boolean = false;
  point : any = 0;
  aa(){
    console.log(this.point);
     if(this.point == 0){
      this.cond = true;
      this.point ++;
     }
   else if(this.point % 2 == 0){
    this.cond = true;
    this.point ++;
   }
   else{
     this.cond = false
     this.point ++;
   }
  
    
  }
  documentType(docType){
    console.log("doctypeObject=>",docType);

  }

  docRow:boolean=false;
  AddDocumentsField(addedRow){
    if(addedRow){
      this.docRow = true;
    }
     var obj={doctype:'',image:''};
     this.imageuploadObject.push(obj);
     console.log(this.imageuploadObject);
    // console.log("ImageuploadObject=>",this.imageuploadObject);
}

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

}

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

closebox(){
  this.dialogRef.close(null);
 }
 
onUpload(imgIndex) {
  console.log(imgIndex);
  console.log(this.imageuploadObject);
  const fd = new FormData();

  fd.append('photo',this.selectedFile,this.selectedFile.name)
   console.log("imgURL=>",fd) ;
   this.contactService.imageupload(fd)
   .subscribe(res=>{
     var resImage ='';
     resImage = res['_body'];
     console.log(res['_body']);
     this.imageuploadObject[imgIndex].image = resImage;
      console.log(this.imageuploadObject);
     // console.log(res);
   },err=>{
     console.log(err);
   })

 }
 passwordIcon:any='visibility_off';
 passwordIcon_1:any='visibility_off';


 showpassword(p:any){
  
   if((p == 'p1')&&(this.passwordtype == "password")){
     this.passwordtype = 'text';
     this.passwordIcon = 'visibility';
     return;

   }

   if((p == 'p1')&&(this.passwordtype == "text")){
     this.passwordtype = 'password'
     this.passwordIcon = 'visibility_off';
     return;
   }

   if((p == 'p2')&&(this.passwordtype_1 == "password")){
    this.passwordtype_1 = 'text';
    this.passwordIcon_1 = 'visibility';
    return;


  }

  if((p == 'p2')&&(this.passwordtype_1 == "text")){
    this.passwordtype_1 = 'password';
    this.passwordIcon_1 = 'visibility_off';
    return;
  }

 }

 latLongDetail(){
  var that =this;
  console.log("Inside Latlong Function");
  if (navigator.geolocation) {  
 
    if(location.protocol != 'https:'){
      this.contactService.getlatLong().subscribe(res=>{
        console.log(res); 
          let t_latlng = new google.maps.LatLng(res.lat, res.lon);
          let request = {
            latLng: t_latlng
          };

        this.getAddress(request);
      })
    }else{
      navigator.geolocation.getCurrentPosition(function(position) {
        var d_lat= position.coords.latitude;
        var d_lng=position.coords.longitude;
        let t_latlng = new google.maps.LatLng(d_lat, d_lng);
        let request = {
          latLng: t_latlng
        };

        that.getAddress(request);
      })
      
    }}            
}

getAddress(request){ 
  let geocoder = new google.maps.Geocoder();  
  geocoder.geocode(request, function (data, status) {
    console.log("Inside geocoder function");  
    var userCountry;
    if (status == google.maps.GeocoderStatus.OK) {
      if (data[0] != null) {
        var address_show = data[0];
        console.log('var=>' ,address_show);
        for (var ac = 0; ac < data[0].address_components.length; ac++) {
          var component = data[0].address_components[ac];
          switch(component.types[0]) {     
              case 'country':
                  userCountry  = component.short_name;
                  console.log(userCountry);
                  break;      
          }
      };
       
          var aaa = $('#telephone').intlTelInput("setCountry",userCountry);
      } else {
        userCountry = 'in';  
      }
    }
    else {
      console.log("Inside Error function");  
      userCountry = 'in';
    }
  })  
}


}
