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-device-setting",
  templateUrl: "./device-setting.component.html",
  styleUrls: ["./device-setting.component.scss"],
})
export class DeviceSettingComponent implements OnInit {
  emailId: any;
  Load: Boolean = false;
  searchForm: FormGroup;
  deleteShow: boolean = false;
  submitted = false;
  userId: any;
  deviceForm: FormGroup;
  data: any;
  deleted: boolean = false;
  ditributers;
  dealers;
  users: any;
  selectedSupAdmin;
  selectedDealer;
  selectedUser;
  // @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],
    });
    this.deviceForm = this.fb.group({
      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');
    });
    $("#dealer").change(function () {
      // var that = this
      // alert($(this).val());
      console.log($(this).val());
      var value = $(this).val();
      that.selectedUser = value[0];
      // that.getUser(that.selectedUser)

      console.log(that.selectedUser);

      // 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);

    setTimeout(() => {
      $("#user").multipleSelect({
        width: 470,
        placeholder: "Select User",
        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;
      }
    );
  }

  getUsers(id) {
    this.Load = true;
    this.users = [];
    this.contactService
      .getContactsbyDealer(
        id,
        "&projection=_id,user_id,phone,email,first_name,last_name"
      )
      .subscribe(
        (res) => {
          this.users = res;
          this.users = this.users.concat(this.ditributers);
          this.users = this.users.concat(this.dealers);
          this.users = this.users.filter((el, i, a) => i === a.indexOf(el));

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

  selectSupAdmin(event) {
    // console.log(event.target.value);
    this.getDealers(event);
  }

  selectDealer(event) {
    console.log(event.target.value);
    this.getUsers(event.target.value);
  }

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

    this.submitted = true;

    // stop here if form is invalid
    if (this.searchForm.invalid) {
      return;
    }
    this.contactService.searchByImei(this.searchForm.value).subscribe(
      (res: any) => {
        console.log(res);
        this.data = res[0];
        this.Load = false;
        if (res.length != 0) {
          this.deleteShow = true;
          if (res[0].deletedDevice) {
            this.deleteShow = false;
            this.deleted = true;
          } else {
            this.deleted = false;
          }
          this.selectedSupAdmin = this.data.supAdmin
            ? this.data.supAdmin._id
            : "";
          this.selectedUser = this.data.user ? this.data.user._id : "";
          (this.selectedDealer = this.data.Dealer ? this.data.Dealer._id : ""),
            console.log(this.selectedSupAdmin);

          this.deviceForm.patchValue({
            imei: this.data.Device_ID,
            registrationNumber: this.data.Device_Name,
            sim1: this.data.sim_number ? this.data.sim_number : "",
            sim2: this.data.sim_number2 ? this.data.sim_number2 : "",
            dealaer: this.data.Dealer ? this.data.Dealer._id : "",
            user: this.data.user ? this.data.user._id : "",
            deviceModel: this.data.device_model
              ? this.data.device_model.device_type
              : "",
            vehicleType: this.data.vehicleType
              ? (this.data.vehicleType.brand
                  ? this.data.vehicleType.brand
                  : "") +
                " " +
                (this.data.vehicleType.model ? this.data.vehicleType.model : "")
              : "",
            expirationDate: this.data.expiration_date
              ? this.data.expiration_date
              : "",
            superAdmin: this.data.supAdmin ? this.data.supAdmin._id : "",
            lastRenewal: this.data.renew_at ? this.data.renew_at : "",
            creationDate: this.data.created_on ? this.data.created_on : "",
            status: this.data.status,
            deleted: this.data.deletedDevice ? "Yes" : "No",
            deletedBy: this.data.device_deleted_by
              ? this.data.device_deleted_by.first_name +
                " " +
                this.data.device_deleted_by.last_name
              : " ",
            deletedAt: this.data.device_delete_on,
            deletedFrom: this.data.login_type,
          });
          if (this.data.supAdmin) this.getDealers(this.data.supAdmin._id);
          if (this.data.Dealer) this.getUsers(this.data.Dealer._id);
        } else {
          this.deleteShow = false;
          this.deviceForm.reset();
          this.snackBar.open("No Data Found", "", {
            duration: 4000,
          });
        }
      },
      (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 req = {
          _id: this.data._id,
          Dealer: this.selectedDealer
            ? this.selectedDealer
            : this.data.Dealer
            ? this.data.Dealer._id
            : undefined,
          user: this.selectedUser
            ? this.selectedUser
            : this.data.user
            ? this.data.user._id
            : undefined,
          supAdmin: this.selectedSupAdmin
            ? this.selectedSupAdmin
            : this.data.supAdmin
            ? this.data.supAdmin._id
            : undefined,
        };
        this.contactService
          .post("/devices/updateDeviceByAdmin", req)
          .subscribe((res) => {
            swal({
              title: "Saved!",
              html: "Your file has been saved.",
              icon: "success",
            });
          });
        this.deviceForm.reset();
        this.deleteShow = false;
      }
    });
  }

  deleteDevicePermenatly() {
    swal({
      title: "<strong>Are you sure?</strong>",
      icon: "warning",
      html: "Device 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) {
        var req = {
          device: this.data.Device_ID,
          userId: this.userId,
          permenant: true,
        };
        this.contactService.deldev(req).subscribe((res) => {
          swal({
            title: "Deleted!",
            html: "Your file has been deleted.",
            icon: "success",
          });
        });
        this.deviceForm.reset();
      }
    });
  }
}
