import { AfterViewInit, Component, OnInit, TemplateRef } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { Router } from "@angular/router";
import { FlashMessagesService } from "angular2-flash-messages";
import { BsDatepickerConfig, BsModalRef, BsModalService } from "ngx-bootstrap";
import { ContactService } from "../contact.service";
import { Location } from "@angular/common";

declare var $: any, _: any, swal: any;

@Component({
  selector: "app-db-edit-device",
  templateUrl: "./db-edit-device.component.html",
  styleUrls: ["./db-edit-device.component.scss"],
})
export class DbEditDeviceComponent implements OnInit {
  DeviceModelValue: any;
  deviceImg = ["", "", ""];
  modalRef: BsModalRef;
  submitted = false;
  date = new Date();
  mfdyear_arr: any = [];
  expDate: any = new Date(
    this.date.getFullYear() + 1,
    this.date.getMonth(),
    this.date.getDate()
  ).toLocaleString();
  pg_sh: any = {
    tab1: true,
    tab2: true,
    tab3: true,
    tab4: true,
    tab5: true,
    tab6: true,
    tab101: true,
    tab102: true,
    tab103: true,
    tab104: true,
  };
  contactMessage: any = "";
  Indianstate = [
    "Andhra Pradesh",
    "Arunachal Pradesh",
    "Assam",
    "Bihar",
    "Chhattisgarh",
    "Goa",
    "Gujarat",
    "Haryana",
    "Himachal Pradesh",
    "Jammu and Kashmir",
    "Jharkhand",
    "Karnataka",
    "Kerala",
    "Madhya Pradesh",
    "Maharashtra",
    "Manipur",
    "Meghalaya",
    "Mizoram",
    "Nagaland",
    "Odisha",
    "Punjab",
    "Rajasthan",
    "Sikkim",
    "Tamil Nadu",
    "Telangana",
    "Tripura",
    "Uttarakhand",
    "Uttar Pradesh",
    "West Bengal",
    "Andaman and Nicobar Islands",
    "Chandigarh",
    "Dadra and Nagar Haveli",
    "Daman and Diu",
    "Delhi",
    "Lakshadweep",
    "Puducherry",
  ];
  vehicleCat = [
    "Luxury Cab",
    "Three wheeled vehicles for transport of passengers/goods",
    "Goods carrier trucks or tankers or mail carriers",
    "Power tiller and Tractors using public roads",
    "Mobile clinic or X-Ray van or library vans",
    "Mobile Workshops",
    "Mobile canteens",
    "Private Service Vehicle",
    "maxi cab",
    "motor cab",
    "stage cariage",
    "contract carriage",
    "Tourist",
    "Educational Institution buses",
    "Ambulances",
    "Animal Ambulances",
    "Camper vans or trailers",
    "Cash vans",
    "Fire tenders, snorked ladders,auxiliary trailers and fire fighting vehicles",
    "Articulated vehicles",
    "Hearses",
    "Motor car",
    "Crane mounted vehicle",
    "Agricultural Tractor and Power Tiller",
    "Tow Trucks, Breakdown Van and Recovery Vehicles",
    "Construction Equipment Vehicles",
  ];
  DB_TOKEN = JSON.parse(
    window.atob(window.localStorage.token.split(".")[1])
  );
  custtype: any;
  DealerId: any;
  db_state_city_list: any = [];
  constructor(
    private modalService: BsModalService,
    private location: Location,
    private fb: FormBuilder,
    private contactService: ContactService,
    private router: Router,
    private _flashMessagesService: FlashMessagesService
  ) {}
  deviceForm: FormGroup;
  userId;
  deviceData;
  deviceModel;
  Load: boolean = false;
  bsConfig: Partial<BsDatepickerConfig>;
  dataDevModel: any[];
  vehicle_Type: any[];
  imageuploadObject = [
    {
      doctype: "ID proof",
      req: true,
      image: "",
      phone: "",
      docdate: new Date(),
      fill: false,
      isText: true,
    },
    {
      doctype: "Address Proof",
      req: true,
      image: "",
      phone: "",
      docdate: new Date(),
      fill: false,
      isText: true,
    },
    {
      doctype: "Warrenty Card",
      req: true,
      image: "",
      phone: "",
      docdate: new Date(),
      fill: false,
      isText: false,
    },
    {
      doctype: "vehicle Photo",
      req: false,
      image: "",
      phone: "",
      docdate: new Date(),
      fill: true,
      isText: false,
    },
    {
      doctype: "Vehicle Ownership Proof",
      req: true,
      image: "",
      phone: "",
      docdate: new Date(),
      fill: false,
      isText: true,
    },
    {
      doctype: "vehicle RC",
      req: false,
      image: "",
      phone: "",
      docdate: new Date(),
      fill: true,
      isText: true,
    },
  ];
  // imageuploadObject = [
  //   {
  //     doctype: "ID proof",
  //     req: true,
  //     image: "",
  //     phone: "",
  //     docdate: new Date(),
  //     fill: false,
  //   },
  //   {
  //     doctype: "Address Proof",
  //     req: true,
  //     image: "",
  //     phone: "",
  //     docdate: new Date(),
  //     fill: false,
  //   },
  //   {
  //     doctype: "Warrenty Card",
  //     req: true,
  //     image: "",
  //     phone: "",
  //     docdate: new Date(),
  //     fill: false,
  //   },
  //   {
  //     doctype: "vehicle Photo",
  //     req: false,
  //     image: "",
  //     phone: "",
  //     docdate: new Date(),
  //     fill: true,
  //   },
  //   {
  //     doctype: "Vehicle Ownership Proof",
  //     req: true,
  //     image: "",
  //     phone: "",
  //     docdate: new Date(),
  //     fill: false,
  //   },
  //   {
  //     doctype: "vehicle RC",
  //     req: false,
  //     image: "",
  //     phone: "",
  //     docdate: new Date(),
  //     fill: true,
  //   },
  // ];

  pdfUrl: string =
    "https://www.oneqlik.in/images/oneqlikProfilePic/VEH%20INVOICE1705150211737.pdf";
  dealerId;
  sup_admin;
  hrdwr;
  hrdwr2;
  custId;
  documentList = [
    {
      docId: "Adhar card1",
      docName: "Adhar Card Front",
    },
    {
      docId: "Adhar card2",
      docName: "Adhar Card Back",
    },
    {
      docId: "vehicle sales invoice",
      docName: "vehicle sales invoice",
    },
    {
      docId: "voter Id",
      docName: "Voter Id",
    },
    {
      docId: "vehicle RC",
      docName: "vehicle RC",
    },
    {
      docId: "vehicle Photo",
      docName: "vehicle Photo",
    },
    {
      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: "Co.registered Card",
      docName: "Co.registered Card",
    },
    {
      docId: "Nepal Citizenship",
      docName: "Nepal Citizenship",
    },
    {
      docId: "Blue Book",
      docName: "Blue Book",
    },
    {
      docId: "Warrenty Card",
      docName: "Warrenty Card",
    },
    {
      docId: "Other",
      docName: "Other",
    },
  ];
  invalidEmeiSelected = false;
  checkDeviceEMI(id) {
    console.log("checkDeviceEMI");
    this.contactService.checkDeviceId(id).subscribe((res) => {
      try {
        this.invalidEmeiSelected = res["_body"] != "No device Found";
      } catch (error) {}
    });
  }
  removeSpecialChar(_deviceData) {
    //deviceData.Device_ID == deviceForm.value.device_id
    console.log("_deviceData=>", _deviceData, this.deviceForm.value.device_id);
  }
  db_show(data: any) {
    console.log("show=>", data);
  }
  ngOnInit() {
    this.deviceData = JSON.parse(localStorage.getItem("deviceData"));
    debugger;
    fetch("./assets/js/db_list.json")
      .then((j: any) => j.json())
      .then((resp) => {
        this.db_state_city_list = resp;
        this.newonStateChange({
          target: { value: this.deviceData.user.state },
        });
        console.log("this.db_state_city_list=>", resp);
      });
    let curr_year = new Date().getFullYear();
    for (let i = curr_year - 20; i <= curr_year; i++) {
      this.mfdyear_arr.push(i);
    }

    if (localStorage.getItem("deviceData")) {
      console.log(this.deviceData);
      var data = {
        target: {
          value: this.deviceData.transportOfficeState
            ? this.deviceData.transportOfficeState
            : "",
        },
      };
      var data1 = {
        target: {
          value: this.deviceData.transportOfficeCity
            ? this.deviceData.transportOfficeCity
            : "",
        },
      };
      var data3 = {
        target: {
          value: this.deviceData.manufacturingCompany
            ? this.deviceData.manufacturingCompany
            : "",
        },
      };
      this.selectModel(data3);
      this.onCityChange(data1);
      this.onStateChange(data);

      this.imageuploadObject = this.deviceData.imageDoc;
      this.deviceImg = this.deviceData.deviceImage
        ? this.deviceData.deviceImage
        : ["", "", ""];
      this.bsConfig = Object.assign(
        { dateInputFormat: "DD-MM-YYYY" },
        { containerClass: "theme-dark-blue" }
      );
   
      this.userId = JSON.parse(
        window.atob(window.localStorage.token.split(".")[1])
      )._id;
      this.dealerId = JSON.parse(
        window.atob(window.localStorage.token.split(".")[1])
      ).Dealer_ID;
      this.sup_admin = JSON.parse(
        window.atob(window.localStorage.token.split(".")[1])
      ).supAdmin;
      this.custtype = JSON.parse(
        window.atob(window.localStorage.token.split(".")[1])
      ).isDealer;
      this.custId = localStorage.getItem("custId");
      if (this.custtype == false && window.localStorage["Custumer"] == "ON") {
        this.DealerId = JSON.parse(
          window.atob(window.localStorage.Dealer_token.split(".")[1])
        )._id;
      }
      console.log("this.custtype", this.custtype);
      var fname = this.deviceData.user
        ? this.deviceData.user.first_name
          ? this.deviceData.user.first_name
          : ""
        : "";
      var lname = this.deviceData.user
        ? this.deviceData.user.last_name
          ? this.deviceData.user.last_name
          : ""
        : "";
      this.deviceForm = this.fb.group({
        customerType: [this.deviceData.customerType || ""],
        customer_state: [this.deviceData.user.state || ""],
        customer_city: [this.deviceData.user.city || ""],
        customer_pin: [
          this.deviceData.user
            ? this.deviceData.user.pin
              ? this.deviceData.user.pin
              : ""
            : "",
          [Validators.required, Validators.pattern("[0-9 ]{6}")],
        ],
        state: [this.deviceData.transportOfficeState || ""],
        city: [this.deviceData.transportOfficeCity || ""],
        rtoOffice: [this.deviceData.rto ? this.deviceData.rto : ""],
        mfdyear: [
          this.deviceData.manufacturingYear || "",
          [Validators.required],
        ],
        fuelType: [this.deviceData.fuelType || "", [Validators.required]],
        m2mprovider: [this.deviceData.m2mprovider || ""],
        sim_provider: [this.deviceData.sim_provider || ""],
        sim_provider2: [this.deviceData.sim_provider2 || ""],
        vahanID: [this.deviceData.vahanID || ""],
        first_name: [this.deviceData.user.first_name, [Validators.required]],
        last_name: [this.deviceData.user.last_name, [Validators.required]],
        ownerName: [
          fname + " " + lname,
          [Validators.required, Validators.pattern("[a-zA-Z][a-zA-Z ]+")],
        ],
        contactNo: [
          this.deviceData.user
            ? this.deviceData.user.phone
              ? this.deviceData.user.phone
              : ""
            : "",
          [Validators.required, Validators.pattern("[0-9 ]{10}")],
        ],
        device_id: [this.deviceData.Device_ID ? this.deviceData.Device_ID : ""],
        address: [
          this.deviceData.user
            ? this.deviceData.user.address
              ? this.deviceData.user.address
              : ""
            : "",
          Validators.required,
        ],

        vehicleManufacture: [
          this.deviceData.manufacturingCompany
            ? this.deviceData.manufacturingCompany
            : "",
        ],
        vehicleModel: [this.deviceData.Model ? this.deviceData.Model : ""],
        vehicleCategory: [
          this.deviceData.vehicleCategory
            ? this.deviceData.vehicleCategory
            : "",
          [Validators.required],
        ],
        vehicleType: [
          this.deviceData.vehicleType ? this.deviceData.vehicleType._id : "",
        ],
        vehicleNo: [
          this.deviceData.Device_Name ? this.deviceData.Device_Name : "",
          [Validators.required, Validators.maxLength(10)],
        ],
        chasisNo: [
          this.deviceData.ChassisNo ? this.deviceData.ChassisNo : "",
          Validators.required,
        ],
        engineNo: [
          this.deviceData.engineNo ? this.deviceData.engineNo : "",
          Validators.required,
        ],
        panic: [this.deviceData.numberOfSOS ? this.deviceData.numberOfSOS : ""],
        bsnlPlan: [""],
        hostingPlan: [""],
        SMSPlan: [""],

        deviceModel: [
          this.deviceData.device_model ? this.deviceData.device_model._id : "",
        ],
        trackingExp: [
          this.deviceData.expiration_date
            ? new Date(this.deviceData.expiration_date)
            : "",
        ],
        eSimExpiry: [
          this.deviceData.esim_validity
            ? new Date(this.deviceData.esim_validity)
            : "",
        ],
        model: [
          this.deviceData.Model ? this.deviceData.Model : "",
          [Validators.required],
        ],
        email: [
          this.deviceData.user
            ? this.deviceData.user.email
              ? this.deviceData.user.email
              : ""
            : "",
        ],
        dealerFollowup: [
          this.deviceData.CID_No ? this.deviceData.CID_No : "",
          Validators.required,
        ],
        sim1: [
          this.deviceData.sim_number ? this.deviceData.sim_number : "",
          Validators.required,
        ],
        sim2: [this.deviceData.sim_number2 ? this.deviceData.sim_number2 : ""],
        iccid: [this.deviceData.IccidNo ? this.deviceData.IccidNo : ""],
        // pin: [this.deviceData.transportOfficePin],
      });
      // let dev = this.deviceData.Device_ID ? this.deviceData.Device_ID : "";
      // $("#inventory").multipleSelect("setSelects", [dev]);
      // let cc: any = that.deviceForm.controls;
      // cc.iccid.disable();
      // cc.sim1.disable();
      // cc.sim2.disable();
      // cc.eSimExpiry.disable();
      // cc.device_id.disable();
      // cc.m2mprovider.disable();
      // cc.sim_provider.disable();
      // cc.sim_provider2.disable();
      // cc.vahanID.disable();
      // console.log("DEVICEFORM=>", this.deviceForm);
    } else {
      this.location.back();
    }

    this.loadropdown();
    this.getDeviceModel();
    this.getvehDetail();
    this.getUserSetting(this.userId);
    this.getModelData();
    this.getAllState();

    var that = this;
    $(document).on("change", "#inventory", function () {
      var value = $("#inventory").val();
      that.checkDeviceEMI(value);
      for (var i = 0; i < that.inventory.length; i++) {
        if (value == that.inventory[i].IMEI) {
          // console.log("new imei =>", that.inventory[i]);
          var date = new Date();
          var exp;
          if (that.inventory[i].eSIMValidaity == "One Year") {
            exp = new Date(
              date.getFullYear() + 1,
              date.getMonth(),
              date.getDate()
            ).toLocaleString();
          } else if (that.inventory[i].eSIMValidaity == "Two Year") {
            exp = new Date(
              date.getFullYear() + 2,
              date.getMonth(),
              date.getDate()
            ).toLocaleString();
          } else {
            exp = new Date(
              date.getFullYear() + 1,
              date.getMonth(),
              date.getDate()
            ).toLocaleString();
          }
          that.deviceForm.patchValue({
            iccid: that.inventory[i].IccidNo,
            sim1: that.inventory[i].Mob1,
            sim2: that.inventory[i].Mob2,
            eSimExpiry: new Date(exp),
            device_id: value,
          });
          console.log("set new Value that.deviceForm=>", that.deviceForm.value);
          let cc: any = that.deviceForm.controls;
          cc.iccid.disable();
          cc.sim1.disable();
          cc.sim2.disable();
          cc.eSimExpiry.disable();
          cc.device_id.disable();
          cc.m2mprovider.disable();
          cc.sim_provider.disable();
          cc.sim_provider2.disable();
          cc.vahanID.disable();
          that.hrdwr = that.inventory[i].Mob1;
          that.hrdwr2 = that.inventory[i].Mob2;
        }
      }
      // var value = this.deviceData.Device_ID;
      // for (var i = 0; i < that.inventory.length; i++) {
      //   if (value == that.inventory[i].IMEI) {
      //     var date = new Date();
      //     var exp;
      //     if (that.inventory[i].eSIMValidaity == "One Year") {
      //       exp = new Date(
      //         date.getFullYear() + 1,
      //         date.getMonth(),
      //         date.getDate()
      //       ).toLocaleString();
      //     } else if (that.inventory[i].eSIMValidaity == "Two Year") {
      //       exp = new Date(
      //         date.getFullYear() + 2,
      //         date.getMonth(),
      //         date.getDate()
      //       ).toLocaleString();
      //     } else {
      //       exp = new Date(
      //         date.getFullYear() + 1,
      //         date.getMonth(),
      //         date.getDate()
      //       ).toLocaleString();
      //     }
      //     that.deviceForm.patchValue({
      //       iccid: that.inventory[i].IccidNo,
      //       sim1: that.inventory[i].Mob1,
      //       sim2: that.inventory[i].Mob2,
      //       eSimExpiry: new Date(exp),
      //       device_id: value,
      //     });

      //     that.hrdwr = that.inventory[i].Mob1;
      //     that.hrdwr2 = that.inventory[i].Mob2;
      //   }
      // }
    });
  }
  get f() {
    return this.deviceForm.controls;
  }
  dbmodelSET(ev, flag) {
    console.log(ev, flag);
  }
  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;
    });
  }
  showNAME(name) {
    let n = name;
    return n.split("/").at(-1).slice(-15);
  }
  launch_toast() {
    console.log("ihjgdfds");
    var x = document.getElementById("toast");
    //console.log(x);
    if (x != null) {
      x.className = "show";
      setTimeout(function () {
        x.className = x.className.replace("show", "");
      }, 1500);
    }
  }
  db_val: any = [
    {
      v: "Follow-up",
      k: "dealerFollowup",
    },
    {
      v: "Customer Type",
      k: "customerType",
    },
    {
      v: "Customer Name",
      k: "first_name",
    },

    {
      v: "Mobile No",
      k: "contactNo",
    },
    {
      v: "Address",
      k: "address",
    },
    {
      v: "State",
      k: "customer_state",
    },
    {
      v: "City",
      k: "customer_city",
    },
    {
      v: "Pin Code",
      k: "customer_pin",
    },
    {
      v: "IMEI",
      k: "device_id",
    },
    {
      v: "Panic Count",
      k: "panic",
    },
    {
      v: "Manufacturer",
      k: "vehicleManufacture",
    },
    {
      v: "Model",
      k: "model",
    },
    {
      v: "Chassis No.",
      k: "chasisNo",
    },
    {
      v: "Engine No.",
      k: "engineNo",
    },
    {
      v: "Vehicle NO.",
      k: "vehicleNo",
    },
    {
      v: "Mfd Year",
      k: "mfdyear",
    },
    {
      v: "Vehicle Category",
      k: "vehicleCategory",
    },
    {
      v: "Fuel Type",
      k: "fuelType",
    },
    {
      v: "RTO State",
      k: "state",
    },
    {
      v: "RTO City",
      k: "city",
    },
    {
      v: "RTO Name",
      k: "rtoOffice",
    },
    {
      v: "RTO Name",
      k: "rtoOffice",
    },
  ];
  submit() {
    this.submitted = true;
    this.contactService
      .db_ajaxURL("/Device_inventory/edit", {
        IMEI: JSON.parse(localStorage.deviceData).Device_ID,
        Status: "Sold",
      })
      .subscribe();

    let temp_db_val: any = JSON.parse(JSON.stringify(this.db_val));
    //new code
    if (this.deviceForm.invalid) {
      const controls = this.deviceForm.controls;

      if (controls.customerType.value == "Firm") {
        temp_db_val.push({
          v: "Custodian Name",
          k: "last_name",
        });
      }
      if (
        controls.customerType.value == "Firm" &&
        controls.last_name.value == ""
      ) {
        this.data_descip = "please enter Custodian Name";
        this.launch_toast();
        return;
      }
      for (let i = 0; i < temp_db_val.length; i++) {
        if (controls[temp_db_val[i].k].invalid) {
          // invalid.push(name);

          this.data_descip = "please enter valid " + temp_db_val[i].v;
          this.launch_toast();
          return;
        }
      }
      // for (const name in controls) {
      //   if (controls[name].invalid) {
      //     // invalid.push(name);
      //     this.data_descip = "please enter valid " + name;
      //     this.launch_toast();
      //     return;
      //   }
      // }
    }

    for (var i = 0; i < this.imageuploadObject.length; i++) {
      if (!this.imageuploadObject[i].fill) {
        swal("Upload Error", "Please upload required documnets !!!", "error");
        return;
      }
      if (
        this.imageuploadObject[i].phone == "" &&
        this.imageuploadObject[i].isText == true &&
        this.imageuploadObject[i].req == true
      ) {
        swal(
          "Upload Error",
          "Please Enter " + this.imageuploadObject[i].doctype + " number",
          "error"
        );
        return;
      }
    }
    for (var i = 0, x = $(".db_select"); i < $(".db_select").length; i++) {
      if ($(x[i]).val() == null || $(x[i]).val() == "") {
        this.data_descip =
          "Please Select " + $($(".db_select")[i]).attr("data-type") ||
          "" + "Dropdown";
        this.launch_toast();
        return;
      }
    }

    if (!this.deviceImg[0]) {
      swal("Upload Error", "Please Upload device image !!!", "error");
      return;
    }
    //new code end

    // for (var i = 0; i < this.imageuploadObject.length; i++) {
    //   if (!this.imageuploadObject[i].fill) {
    //     swal("Upload Error", "Please upload required documnets !!!", "error");
    //     return;
    //   }
    // }

    if (this.userFound) {
      this.addDevice(this.user);
    } else {
      var expDate = new Date();
      expDate.setFullYear(expDate.getFullYear() + 1);
      // GLOBALENGINEERING PRABR MALAKAR
      var name = this.deviceForm.value.ownerName.split(" ");

      var data = {
        customer_state: this.deviceForm.value.customer_state,
        customer_city: this.deviceForm.value.customer_city,
        customer_pin: this.deviceForm.value.customer_pin,
        transportOfficeState: this.deviceForm.value.state,
        transportOfficeCity: this.deviceForm.value.customer_city,
        // Dealer:this.reactiveForm.value.manager,
        contactid: this.deviceData.user._id,
        custumer: true,
        expdate: new Date(expDate).toISOString(),
        // first_name:name[0]?name[0]:'',
        // last_name:name[1]?name[1]:'',
        first_name: this.deviceForm.value.first_name,
        last_name: this.deviceForm.value.last_name,
        isDealer: false,
        phone: this.deviceForm.value.contactNo,
        user_id: "",
        org_name: null,
        password: this.generatePassword(6),
        supAdmin: this.sup_admin,
        Dealer:
          this.deviceData.Dealer && this.deviceData.Dealer._id
            ? this.deviceData.Dealer._id
            : this.userId,
        timezone: "Asia/Kolkata",
        std_code: { countryCode: "in", dialcode: "91" },
      };
      if (this.deviceForm.value.pin) {
        data["pin"] = this.deviceForm.value.customer_pin;
      }

      if (this.deviceForm.value.email) {
        data["email"] = this.deviceForm.value.email;
      }
      if (this.deviceForm.value.address) {
        data["address"] = this.deviceForm.value.address;
      }
      if (this.deviceForm.value.eSimExpiry) {
        data["esim_validity"] = this.deviceForm.value.eSimExpiry;
      }
      if (this.deviceForm.value.trackingExp) {
        data["expdate"] = this.deviceForm.value.trackingExp;
      }
      console.log(data);

      this.contactService
        .post("/users/editUserDetails", data)
        .subscribe((res: any) => {
          console.log(res);

          if (res.message == "Saved") {
            this.addDevice(res._id);
            // this.router.navigateByUrl('/dashboard');
          }
        });
    }
  }
  docupclick(id) {
    $("#" + id).click();
  }
  setKey(ob: any, key: any, value: any) {
    ob[key] = value;
  }
  addDevice(data) {
    var model = $("#dbselect").multipleSelect("getSelects", "value");
    var type = $("#vehicleType").multipleSelect("getSelects", "value");
    var deviceid;
    if (this.inventoryManagement) {
      deviceid = $("#inventory").val();
    } else {
      deviceid = $("#inventory").val();
    }
    var newDevice = {
      _id: this.deviceData._id,
      devicename: this.deviceForm.value.vehicleNo,
      deviceid: deviceid,
      // des: this.des,
      model: this.deviceForm.value.model,

      typdev: "Tracker",
      Mileage: "10",

      customerType: this.deviceForm.value.customerType,
      phn: this.deviceForm.value.contactNo,
      sim_number: this.deviceForm.value.sim1,
      sim_number1: this.deviceForm.value.sim2,
      sim_provider: this.deviceForm.value.sim_provider,
      sim_provider2: this.deviceForm.value.sim_provider2,
      m2mprovider: this.deviceForm.value.m2mprovider,

      fuelType: this.deviceForm.value.fuelType,
      created_by:
        this.deviceData.created_by && this.deviceData.created_by._id
          ? this.deviceData.created_by
          : this.userId,
      supAdmin: this.sup_admin,
      // driver_name: this.driver,
      // contact_number: this.dcontact,
      device_model: model,
      expdate: new Date(this.expDate),
      user: this.deviceData.user._id,
      kycStatus: "Pending",
      bussinessType: 1,
    };
    if (this.custtype) {
      newDevice["Dealer"] =
        this.deviceData.Dealer && this.deviceData.Dealer._id
          ? this.deviceData.Dealer._id
          : newDevice["Dealer"];
    } else if (
      this.custtype == false &&
      window.localStorage["Custumer"] == "ON"
    ) {
      newDevice["Dealer"] = this.DealerId;
    }

    //  hrdwr: this.deviceForm.value.sim1,
    //         hrdwr1: this.deviceForm.value.sim1,
    /* 
    manufacturingYear"",
m2mprovider"",
sim_number2"",
sim:"",
model:"",
 */
    if (this.deviceForm.value.sim1) {
      newDevice["hrdwr"] = this.deviceForm.value.sim1;
    }
    if (this.deviceForm.value.sim2) {
      newDevice["hrdwr1"] = this.deviceForm.value.sim2;
    }

    if (this.deviceForm.value.sim1) {
      newDevice["manufacturingCompany"] = this.deviceForm.value.sim1;
    }

    if (this.deviceForm.value.mfdyear) {
      newDevice["manufacturingYear"] = this.deviceForm.value.mfdyear;
    }
    if (this.deviceForm.value.m2mprovider) {
      newDevice["m2mprovider"] = this.deviceForm.value.m2mprovider;
    }
    if (this.deviceForm.value.sim2) {
      newDevice["sim_number2"] = this.deviceForm.value.sim2;
    }
    if (this.deviceForm.value.sim1) {
      newDevice["sim"] = this.deviceForm.value.sim1;
    }

    if (this.deviceForm.value.model) {
      newDevice["model"] = this.deviceForm.value.model;
    }

    if (this.deviceForm.value.dealerFollowup) {
      newDevice["CID_No"] = this.deviceForm.value.dealerFollowup;
    }
    if (this.hrdwr) {
      newDevice["hrdwr"] = this.hrdwr;
    }
    if (this.deviceForm.value.engineNo) {
      newDevice["engineNo"] = this.deviceForm.value.engineNo;
    }

    if (this.deviceForm.value.city) {
      newDevice["transportOfficeCity"] = this.deviceForm.value.city;
    }
    if (this.deviceForm.value.state) {
      newDevice["transportOfficeState"] = this.deviceForm.value.state;
    }

    if (this.deviceForm.value.chasisNo) {
      newDevice["ChassisNo"] = this.deviceForm.value.chasisNo;
    }
    if (this.deviceForm.value.vehicleManufacture) {
      newDevice["manufacturingCompany"] =
        this.deviceForm.value.vehicleManufacture;
    }

    if (this.deviceForm.value.eSimExpiry) {
      newDevice["esim_validity"] = this.deviceForm.value.eSimExpiry;
    }
    if (this.deviceForm.value.trackingExp) {
      newDevice["expdate"] = this.deviceForm.value.trackingExp;
    }
    if (this.deviceForm.value.vehicleCategory) {
      newDevice["vehicleCategory"] = this.deviceForm.value.vehicleCategory;
    }
    if (this.deviceForm.value.rtoOffice) {
      newDevice["rto"] = this.deviceForm.value.rtoOffice;
    }

    if (type) {
      newDevice["typeOfVehicle"] = type[0];
    }
    if (this.deviceForm.value.vehicleType) {
      newDevice["vehicleType"] = this.deviceForm.value.vehicleType;
    }

    if (this.deviceForm.value.state) {
      newDevice["transportOfficeState"] = this.deviceForm.value.state;
    }

    if (this.deviceForm.value.panic) {
      newDevice["numberOfSOS"] = this.deviceForm.value.panic;
    }

    if (this.deviceImg != undefined) {
      newDevice["deviceImage"] = this.deviceImg;
    }
    console.log("imageuploadDocument", this.imageuploadObject);
    if (this.imageuploadObject.length != 0) {
      newDevice["imageDoc"] = this.imageuploadObject;
    }
    console.log("=======>", newDevice);
    //  this.Load = false;
    this.contactService.editdevice(newDevice).subscribe(
      (device) => {
        window.localStorage["DataUpdate"] = "True";
        localStorage.getItem("KycApprovalRedirect");
        if (localStorage.getItem("KycApprovalRedirect")) {
          localStorage.removeItem("KycApprovalRedirect");
          this.router.navigateByUrl("KycApproval");
        } else {
          this.router.navigateByUrl("dashboard");
        }
      }
      // this.Load = false
    ),
      (err: any) => {
        // console.log(err.status);
        // console.log(err);
        var that = this;
        if (err.status == 400) {
          console.log(JSON.parse(err._body).deviceObj);
          var dupObj = JSON.parse(err._body).deviceObj;
          // this.Load = false;
          var devicesupAdmin = dupObj.supAdmin;
          var deviceDealer = dupObj.Dealer;
          var devOwner = dupObj.user;
        } else {
          var message;
          if (err.status == 401) {
            message = "Access Denied !!!";
          } else {
            message = "Network Error !!!";
          }
          console.log(err);

          this._flashMessagesService.show(message, {
            cssClass: "alert-danger",
            timeout: 2000,
          });
          // this.Load = false
        }
      };
  }

  generatePassword(passwordLength) {
    var numberChars = "0123456789";
    var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var lowerChars = "abcdefghijklmnopqrstuvwxyz";
    var allChars = numberChars + upperChars + lowerChars;
    var randPasswordArray = Array(passwordLength);
    randPasswordArray[0] = numberChars;
    randPasswordArray[1] = upperChars;
    randPasswordArray[2] = lowerChars;
    randPasswordArray = randPasswordArray.fill(allChars, 3);
    return this.shuffleArray(
      randPasswordArray.map(function (x) {
        return x[Math.floor(Math.random() * x.length)];
      })
    ).join("");
  }

  shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
      var j = Math.floor(Math.random() * (i + 1));
      var temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array;
  }
  message;
  user;
  userFound: boolean = false;
  onSearchChange(value) {
    this.userFound = false;
    this.message = undefined;
    console.log(value);
    var phone = this.deviceForm.value.contactNo;
    if (phone.length == 10) {
      console.log("KLDJNDKjk");
      this.contactService
        .get("/users/searchUserByPhone?user=" + this.userId + "&phone=" + phone)
        .subscribe(
          (res: any) => {
            console.log(res);
            if (res.message == "User already Present") {
              this.deviceForm.patchValue({
                ownerName: res.data[0].first_name
                  ? res.data[0].first_name
                  : "" + " " + res.data[0].last_name
                  ? res.data[0].first_name
                  : "",
                email: res.data[0].email ? res.data[0].email : "",
              });
              this.user = res.data[0];
              this.userFound = true;
              this.deviceForm.controls.ownerName.disable();
              this.deviceForm.controls.email.disable();
            } else {
              this.userFound = false;
              this.message = res.message;
            }
          },
          (err) => {
            console.log(err);
            this.message = err.error.message;
          }
        );
    }
  }
  device_Model: any;
  getDeviceModel() {
    this.contactService.getDevModel().subscribe((res) => {
      this.device_Model = res;

      var devname = [];
      console.log("Device_Model", this.device_Model);
      for (var i = 0; i < this.device_Model.length; i++) {
        var a = {
          model: this.device_Model[i].device_type,
          id: this.device_Model[i]._id,
        };
        var modelName;

        if (this.device_Model[i].deviceport != undefined) {
          modelName =
            this.device_Model[i].device_type +
            " " +
            "(Port : " +
            this.device_Model[i].deviceport +
            ")";
        } else {
          modelName = this.device_Model[i].device_type;
        }
        this.device_Model[i].modelName = modelName;
        devname.push(a);
      }
      setTimeout(() => {
        console.log("dbselect setSelects");
        $("#dbselect").multipleSelect("setSelects", [
          this.deviceData.device_model._id,
        ]);
      }, 1000);

      this.loadropdown();
    });
  }

  loadropdown() {
    let that = this;

    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);
    // ||(this.componentIdentifier === 'notification_master')

    setTimeout(() => {
      $("#dbselect").multipleSelect({
        width: 470,
        placeholder: "Select model",
        filter: true,
        single: true,
        selectAll: false,
      });
      $("#vehicleType").multipleSelect({
        width: 470,
        placeholder: "Select Type",
        filter: true,
        single: true,
        selectAll: false,
      });
      $("#inventory").multipleSelect({
        width: 470,
        placeholder: "Select IMEI",
        filter: true,
        single: true,
        selectAll: false,
      });
    }, 100);
  }

  vehData: any;
  getvehDetail() {
    this.contactService.getvehType(this.userId).subscribe((res) => {
      // console.log(res);
      this.vehData = res;
      var vdata = res;
      for (var a = 0; a < this.vehData.length; a++) {
        var vehtypename = vdata[a].brand + " " + vdata[a].model;
        this.vehData[a].vehicle_name = vehtypename;
      }
      console.log("allveh", this.vehData);
      this.loadropdown();
    });
  }
  docRow: boolean = false;
  // AddDocumentsField(addedRow:any){
  //   console.log("Inside function !!!");
  //     if(addedRow){
  //       this.docRow = true;
  //     }

  //      var obj={doctype:'',image:'',phone:'',docdate:''};
  //      this.imageuploadObject.push(obj);
  //      console.log(this.imageuploadObject);
  //     // console.log("ImageuploadObject=>",this.imageuploadObject);
  // }
  showUpload: boolean = true;
  DeleteDocumentsField(index) {
    console.log(this.imageuploadObject.length);
    if (this.imageuploadObject.length == 1) {
      this.docRow = false;
      this.showUpload = false;
    }
    this.imageuploadObject.splice(index, 1);
  }

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

    this.Load = true;
    const validTypes = ['image/jpeg', 'image/jpg', 'image/png'];
    if (this.selectedFile && !validTypes.includes(this.selectedFile.type)) {
      swal("Upload Error", "Please upload a valid file type (.jpeg, .jpg, .png)", "error");
      event.target.value = ''; // Clear the input if invalid file is selected
      return;
    }
    console.log(imgIndex);
    this.imageuploadObject[imgIndex].fill = true;
    console.log(this.imageuploadObject);
    const fd = new FormData();
    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;
        //   this.uploadStatus = 'Uploaded';
        console.log(res);
        var resImage = "";
        resImage = res["_body"];
        console.log(res["_body"]);
        this.imageuploadObject[imgIndex].image = resImage;
        console.log(this.imageuploadObject);
        this.selectedFile = undefined;
        // console.log(res);
      },
      (err) => {
        this.Load = false;
        this._flashMessagesService.show("Internal server error , try again", {
          cssClass: "alert-success",
          timeout: 2000,
        });
        this.selectedFile = undefined;
      }
    );
  }
  ifuploadArr: boolean;
  uploadStatus: any = "Upload";
  onUpload(imgIndex) {
    this.Load = true;
    console.log(imgIndex);
    this.imageuploadObject[imgIndex].fill = true;
    console.log(this.imageuploadObject);
    const fd = new FormData();
    // console.log("selected file name =>",this.selectedFile.name);
    if (!this.selectedFile) {
      swal(
        "Upload Error",
        "Please select document type before upload !!!",
        "error"
      );
      this.Load = false;
    } 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;
          //   this.uploadStatus = 'Uploaded';
          console.log(res);
          var resImage = "";
          resImage = res["_body"];
          console.log(res["_body"]);
          this.imageuploadObject[imgIndex].image = resImage;
          console.log(this.imageuploadObject);
          this.selectedFile = undefined;
          // console.log(res);
        },
        (err) => {
          this.Load = false;
          this._flashMessagesService.show("Internal server error , try again", {
            cssClass: "alert-success",
            timeout: 2000,
          });
          this.selectedFile = undefined;
        }
      );
    }
  }
  documentType(docType) {
    console.log("doctypeObject=>", docType);
  }

  inventoryManagement: Boolean = false;
  inventory = [];
  getUserSetting(userId) {
    let that = this;
    that.contactService
      .post("/users/get_user_setting", { uid: userId })
      .subscribe((res: any) => {
        that.inventoryManagement = res.inventoryManagement;
        if (that.inventoryManagement) {
          console.log(
            that.userId,
            (that.dealerId = JSON.parse(
              window.atob(window.localStorage.token.split(".")[1])
            ).isDealer)
          );
          var isDealer = JSON.parse(
            window.atob(window.localStorage.token.split(".")[1])
          ).isDealer;
          var isSuperAdmin = JSON.parse(
            window.atob(window.localStorage.token.split(".")[1])
          ).isSuperAdmin;
          // var user
          // if(isSuperAdmin){
          //   var user
          // }else if(isDealer){

          // }
          var user = isSuperAdmin
            ? that.userId
            : that.sup_admin
            ? that.sup_admin
            : that.userId;
          console.log(user);

          that.contactService
            .get("/Device_inventory/getInventory?user=" + that.userId)
            .subscribe((res: any) => {
              that.inventory = res;
              setTimeout(() => {
                let dev = that.deviceData.Device_ID
                  ? that.deviceData.Device_ID
                  : "";
                $("#inventory").multipleSelect("setSelects", [dev]);
              }, 1000);

              that.loadropdown();
            });
        }
      });
  }

  manufacturingData;
  getModelData() {
    this.contactService.get("/model_master/GetNames").subscribe((res: any) => {
      this.manufacturingData = res;
    });
  }
  modelData;
  selectModel(event) {
    console.log(event.target.value);

    this.contactService
      .get("/model_master/getModel?name=" + event.target.value)
      .subscribe((res: any) => {
        this.modelData = res;
      });
  }
  newcityList: any = [];
  newonStateChange(event) {
    debugger;
    if (this.db_state_city_list.length > 0) {
      let stList: any = _.find(this.db_state_city_list, {
        state: event.target.value,
      });
      this.newcityList = stList.city;
    }

    // this.contactService
    //   .get("/RTO_master/getCity?state=" + event.target.value)
    //   .subscribe((res: any) => {
    //     this.newcityList = res;
    //   });
  }
  cityList;
  onStateChange(event) {
    this.contactService
      .get("/RTO_master/getCity?state=" + event.target.value)
      .subscribe((res: any) => {
        this.cityList = res;
      });
  }
  RTO;
  onCityChange(event) {
    this.contactService
      .get("/RTO_master/getRTO?city=" + event.target.value)
      .subscribe((res: any) => {
        this.RTO = res;
      });
  }
  back() {
    this.location.back();
  }
  image;
  docName;
  openModal(template: TemplateRef<any>, doc) {
    debugger;
    console.log(doc);
    this.modalRef = this.modalService.show(template, {
      backdrop: "static",
      class: "modal-lg modal-dialog-centered",
    });
    this.docName = doc.doctype;
    this.image = "https://www.oneqlik.in" + doc.image.substring(6);
  }
  openModal1(template: TemplateRef<any>, doc) {
    this.modalRef = this.modalService.show(template, {
      backdrop: "static",
      class: "modal-lg modal-dialog-centered",
    });
    this.image = "https://www.oneqlik.in" + doc.substring(6);
  }

  imageURL: any;
  selectedDeviceFile: File;
  data_descip: any;
  onDeviceImageChanged(event, index) {
    debugger
    this.selectedDeviceFile = <File>event.target.files[0];
    console.log(this.selectedDeviceFile);
    this.Load = true;
    const fdDevice = new FormData();
    fdDevice.append(
      "photo",
      this.selectedDeviceFile,
      this.selectedDeviceFile.name
    );
    const validTypes = ['image/jpeg', 'image/jpg', 'image/png'];
    if (this.selectedDeviceFile && !validTypes.includes(this.selectedDeviceFile.type)) {
      swal("Upload Error", "Please upload a valid file type (.jpeg, .jpg, .png)", "error");
      event.target.value = ''; // Clear the input if invalid file is selected
      return;
    }
    console.log("Binaryimage = > ", fdDevice);
    this.contactService.deviceImageupload(fdDevice).subscribe(
      (res) => {
        console.log(res);
        if (res) {
          //  if(this.deviceImg.length==3){
          //  if(this.deviceImg[index]){
          this.deviceImg[index] = res["_body"];
          //  }else{
          //    this.deviceImg.push(res['_body'])
          //  }
          //  }else{
          //    this.deviceImg.push(res['_body'])

          //  }
        }
        this.Load = false;
        this.selectedDeviceFile = undefined;
        console.log("this.deviceImg", this.deviceImg);
        this.data_descip = "Image Uploaded";
        launch_toast();
      },
      (err) => {
        this.data_descip = "Internal Server Error";
        launch_toast();
        this.selectedDeviceFile = undefined;
        console.log(err);
        this.Load = false;
      }
    );

    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", "");
      }, 1500);
    }
  }
 


  onDeviceImageUploadUpload(index) {
    if (!this.selectedDeviceFile) {
      swal("Upload Error", "Please choose file before upload !!!", "error");
    } else {
      this.Load = true;
      const fdDevice = new FormData();
      fdDevice.append(
        "photo",
        this.selectedDeviceFile,
        this.selectedDeviceFile.name
      );
      console.log("Binaryimage = > ", fdDevice);
      this.contactService.deviceImageupload(fdDevice).subscribe(
        (res) => {
          console.log(res);
          if (res) {
            if (this.deviceImg.length == 3) {
              if (this.deviceImg[index]) {
                this.deviceImg[index] = res["_body"];
              } else {
                this.deviceImg.push(res["_body"]);
              }
            } else {
              this.deviceImg.push(res["_body"]);
            }
          }
          this.selectedDeviceFile = undefined;
          console.log("this.deviceImg", this.deviceImg);
          this.data_descip = "Image Uploaded";
          launch_toast();
        },
        (err) => {
          this.data_descip = "Internal Server Error";
          launch_toast();
          this.selectedDeviceFile = undefined;
          console.log(err);
        }
      );
    }
    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", "");
      }, 1500);
    }
  }
}

// WEBPACK FOOTER //
// D:/oneqlik_2024/src/app/db-edit-device/db-edit-device.component.ts
