import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MdSnackBar } from '@angular/material';

import { ContactService } from '../contact.service';
declare var $: any;

declare var google: any, swal: any;
@Component({
  selector: 'app-user-setting',
  templateUrl: './user-setting.component.html',
  styleUrls: ['./user-setting.component.scss']
})
export class UserSettingComponent implements OnInit {
  emailId: any;
  Load:Boolean=false;
  searchForm: FormGroup;
  deleteShow: boolean = false;
  submitted = false;
  userId: any;
  deviceForm: FormGroup
  data: any;
  deleted: boolean = false;
  dealers: any[];
  ditributers: any;
  selectedSupAdmin: any;
  selectedDealer: any;
  // @ViewChild(BaseChartDirective) public chart: BaseChartDirective;
  constructor(private contactService: ContactService, private fb: FormBuilder, public snackBar: MdSnackBar) {

  }
  ngOnInit(): void {
    this.searchForm = this.fb.group({
      imei: ['', Validators.required]
    })

    //  Name
    //  emial
    //  dealer
    //  superadmin
    //  isdeleted
    //  issuspended
    //  user id
    //  createdon
    //  expiredon

    this.deviceForm = this.fb.group({
      Name: [''],
      email: [''],
      Dealer: [''],
      supAdmin: [''],
      accountSuspended: [''],
      user_id: [''],
      created_on: [''],
      expire_date: [''],
      DeletedUser: ['']
      // imei:[''],
      // registrationNumber:[''],
      // sim1:[''],
      // sim2:[''],
      // dealaer:[''],
      // user:[''],
      // deviceModel:[''],
      // vehicleType:[''],
      // expirationDate:[''],
      // creationDate:[''],
      // superAdmin:[''],
      // lastRenewal:[''],
      // status:[''],
      // deleted:[''],
      // deletedBy:[''],
      // deletedAt:[''],
      // deletedFrom:['']

      // 352887076587769
    })
    this.emailId = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.userId = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.loadDropdown()
    this.getDistributers();

    var that = this
    $("#distributer").change(function () {
      // alert($(this).val());
      console.log($(this).val());
      var value = $(this).val();
      that.selectedSupAdmin = value[0];
      that.getDealers(that.selectedSupAdmin)

      console.log(that.selectedSupAdmin);

      // var prevSelect = $("#MultiSelect_Preview").select2();
      // prevSelect.val($(this).val()).trigger('change');
    });

    $("#dealer").change(function () {
      // var that = this
      // alert($(this).val());
      console.log($(this).val());
      var value = $(this).val();
      that.selectedDealer = value[0];
      // that.getUsers(that.selectedDealer)
      // that.getUser(that.selectedDealer)

      console.log(that.selectedDealer);

      // var prevSelect = $("#MultiSelect_Preview").select2();
      // prevSelect.val($(this).val()).trigger('change');
    });
    

  }

  loadDropdown() {
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
    document.getElementsByTagName("head")[0].appendChild(script);

    setTimeout(() => {
      $('#distributer').multipleSelect({
        width: 470,
        placeholder: "Select Distributer",
        filter: true,
        single: true,
        selectAll: false

      })
    }, 100);

    setTimeout(() => {
      $('#dealer').multipleSelect({
        width: 470,
        placeholder: "Select Dealer",
        filter: true,
        single: true,
        selectAll: false

      })
    }, 100);

   

  }

  get f() { return this.searchForm.controls; }

  getDistributers() {
    this.Load=true;
    this.contactService.getSuperAdminList().subscribe(res => {
      this.ditributers = res;
      this.loadDropdown()
      this.Load = false;
    },err=>{
      this.Load = false;
    })
  }
  getDealers(id) {
    this.Load = true;
    this.dealers = []
    this.contactService.getDealersDetails(id).subscribe(res => {
      this.dealers = res;
      this.dealers = this.dealers.concat(this.ditributers);
      this.loadDropdown()
      this.Load = false;
    }, err => {
      this.Load = false;
    })
  }
 
  selectSupAdmin(event) {
    console.log(event.target.value);
    this.getDealers(event.target.value)
  }

  submit() {
    console.log(this.searchForm.value);
    this.Load = true;
    this.submitted = true;

    // stop here if form is invalid
    if (this.searchForm.invalid) {
      return;
    }
    this.contactService.get('/users/searchUser?search=' + this.searchForm.value.imei).subscribe((res: any) => {
      console.log(res);
      this.Load = false;
      this.data = res[0];
      if (res.length != 0) {
        this.deleteShow = true
        if (res[0].DeletedUser) {
          this.deleteShow = false;
          this.deleted = true;
        } else {

          this.deleted = false;
        }

        this.selectedSupAdmin = res[0].supAdmin ? res[0].supAdmin._id : ''

        this.selectedDealer = res[0].Dealer ? res[0].Dealer._id : ''

        console.log(res[0].Dealer ? res[0].Dealer.last_name ? res[0].Dealer.last_name : "" : '');
        var dealerFirst = res[0].Dealer ? res[0].Dealer.first_name ? res[0].Dealer.first_name : '' : '';
        var dealerLast = res[0].Dealer ? res[0].Dealer.last_name ? res[0].Dealer.last_name : "" : ''
        var supFirst = res[0].supAdmin ? res[0].supAdmin.first_name ? res[0].supAdmin.first_name : '' : ''
        var supLast = res[0].supAdmin ? res[0].supAdmin.last_name ? res[0].supAdmin.last_name : '' : ''
        // var dealer=res[0].Dealer?res[0].Dealer.first_name?res[0].Dealer.first_name:'':''+' '+res[0].Dealer?res[0].Dealer.last_name?res[0].Dealer.last_name:"":''
        // var supAdm=res[0].supAdmin?res[0].supAdmin.first_name?res[0].supAdmin.first_name:'':''+' '+res[0].supAdmin?res[0].supAdmin.last_name?res[0].supAdmin.last_name:'':''
        this.deviceForm.patchValue({
          Name: [res[0].first_name ? res[0].first_name : '' + ' ' + res[0].last_name ? res[0].last_name : ''],
          email: [res[0].email],
          Dealer: [res[0].Dealer ? res[0].Dealer._id:''],
          supAdmin: [res[0].supAdmin ? res[0].supAdmin._id : ''],
          accountSuspended: [res[0].accountSuspended == true ? 'Yes' : 'No'],
          user_id: [res[0].user_id],
          created_on: [new Date(res[0].created_on)],
          expire_date: [new Date(res[0].expire_date)],
          DeletedUser: res[0].DeletedUser == true ? 'Yes' : 'No'
        })
        if (this.data.supAdmin)
          this.getDealers(this.data.supAdmin._id);
      } else {
        this.deleteShow = false;
        this.deviceForm.reset();
        this.snackBar.open("No Data Found", '', {
          duration: 4000,
        });
      }

      this.Load = false;
    }, err => {
      this.Load = false;
    })

  }

  deleteDevice() {
    swal({
      title: '<strong>Are you sure?</strong>',
      icon: 'warning',
      html: "You won't be able to revert this!",
      showCloseButton: true,
      focusConfirm: false,
      // confirmButtonText: 'Reset today ODO',
      confirmButtonText: 'Yes, save it!',
      // cancelButtonText: 'Reset total ODO',
      // cancelButtonAriaLabel: 'Thumbs down'
      cancelButtonText: 'No, cancel!',
    }).then((result: { value: boolean; }) => {
      if (result) {
        var deletePayload = {
          _id: this.data._id,
          Dealer: this.selectedDealer ? this.selectedDealer : this.data.Dealer ? this.data.Dealer._id:undefined,
          supAdmin: this.selectedSupAdmin ? this.selectedSupAdmin : this.data.supAdmin ? this.data.supAdmin._id : undefined
        }
        console.log(deletePayload);
        this.contactService.post('/users/updateUserFrom',deletePayload).subscribe(res => {
          swal({
            title: 'Transfered!',
            html: 'Your file has been saved.',
            icon: 'success'
          })
          this.deviceForm.reset();
        }, err => {
          console.log(err);
          var message = JSON.parse(err._body)
          swal({
            title: 'Status: ' + err.status,
            html: message.message,
            icon: 'warning'
          })
        })

      }
    }
    )
  }

  deleteDevicePermenatly() {
    swal({
      title: '<strong>Are you sure?</strong>',
      icon: 'warning',
      html: "User will be deleted permanantly",
      showCloseButton: true,
      focusConfirm: false,
      // confirmButtonText: 'Reset today ODO',
      confirmButtonText: 'Yes, delete it!',
      // cancelButtonText: 'Reset total ODO',
      // cancelButtonAriaLabel: 'Thumbs down'
      cancelButtonText: 'No, cancel!',
    }).then((result: { value: boolean; }) => {
      if (result) {

        this.contactService.permanentDeluser(this.data._id).subscribe(res => {
          swal(
            'Deleted',
            'User Deleted',
            'success'
          )
          this.deviceForm.reset();
        })
      }
    }
    )
  }


}