import { 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";
import { of } from "rxjs/observable/of";
declare var $: any, _: any;
declare var swal: any;
@Component({
  selector: "app-add-new-device",
  templateUrl: "./add-new-device.component.html",
  styleUrls: ["./add-new-device.component.scss"],
})
export class AddNewDevices2Component implements OnInit {
  DeviceModelValue: any;
  modalRef: BsModalRef;
  contactMessage = "";
  submitted = false;
  date = new Date();

  DB_TOKEN = JSON.parse( window.atob(window.localStorage.token.split(".")[1]) );
  //customerType: any = "";
  mfdyear_arr: any = [];
  checkChasisNoFlag  :any = false;
  pg_sh: any = {
    tab1: true,
    tab2: true,
    tab3: true,
    tab4: true,
    tab5: true,
    tab6: true,
    tab101: true,
    tab102: true,
    tab103: true,
    tab104: true,
  };
  expDate: any = new Date(
    this.date.getFullYear() + 1,
    this.date.getMonth(),
    this.date.getDate()
  ).toLocaleString();
  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",
  ];
  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;
  deviceModel;
  // iconType == "car"
  // iconType == "bike"
  // iconType == "bus"
  // iconType == "truck"
  // iconType == "tractor"
  // iconType == "ambulance"
  // iconType == "tractor"
  // iconType == "user"
  // iconType == "jcb"
  vehicleCat2 = [
    { value: "Luxury Cab", key: "car" },
    {
      value: "Three wheeled vehicles for transport of passengers/goods",
      key: "car",
    },
    { value: "Goods carrier trucks or tankers or mail carriers", key: "truck" },
    { value: "Power tiller and Tractors using public roads", key: "tractor" },
    { value: "Mobile clinic or X-Ray van or library vans", key: "bus" },
    { value: "Mobile Workshops", key: "car" },
    { value: "Mobile canteens", key: "car" },
    { value: "Private Service Vehicle", key: "car" },
    { value: "maxi cab", key: "car" },
    { value: "motor cab", key: "car" },
    { value: "stage cariage", key: "bus" },
    { value: "contract carriage", key: "tractor" },
    { value: "Tourist", key: "bus" },
    { value: "Educational Institution buses", key: "bus" },
    { value: "Ambulances", key: "ambulance" },
    { value: "Animal Ambulances", key: "ambulance" },
    { value: "Camper vans or trailers", key: "bus" },
    { value: "Cash vans", key: "bus" },
    {
      value:
        "Fire tenders, snorked ladders,auxiliary trailers and fire fighting vehicles",
      key: "bus",
    },
    { value: "Articulated vehicles", key: "tractor" },
    { value: "Hearses", key: "bus" },
    { value: "Motor car", key: "car" },
    { value: "Crane mounted vehicle", key: "tractor" },
    { value: "Agricultural Tractor and Power Tiller", key: "tractor" },
    {
      value: "Tow Trucks, Breakdown Van and Recovery Vehicles",
      key: "tractor",
    },
    { value: "Construction Equipment Vehicles", key: "jcb" },
  ];
  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",
  ];

  // vehicleCat=['Truck','Bus','Car','School Van'];
  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: true,
      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,
    },
  ];
  dealerId;
  sup_admin;
  hrdwr;
  hrdwr2;
  custId;
  vahanID;
  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",
    },
  ];
  docupclick(id) {
    $("#" + id).click();
  }
  
  
  checkChasisNo(value:any){
    debugger;
let that = this;
    if(value.chasisNo.length >= 17 ){
      this.contactService.db_db_get("/devices/deviceExistsByChassisNo?ChassisNo="+value.chasisNo)
      .subscribe((res:any)=>{
        if(res.exists == true ){
          that.checkChasisNoFlag = true;
        //  that.deviceForm.patchValue({chasisNo:""})
          // that.data_descip = "Chassis No already exists";
          swal('Oops...', 'Chassis No already exists!', 'error');
          // that.launch_toast();  
        }else{
          that.checkChasisNoFlag = false;
        }
      })
    } 
    

  }
  ngOnInit() {
    fetch("./assets/js/db_list.json")
      .then((j: any) => j.json())
      .then((resp) => {
        this.db_state_city_list = resp;
        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);
    }
    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;
    if (
      JSON.parse(window.atob(window.localStorage.token.split(".")[1]))
        .isSuperAdmin
    ) {
      this.sup_admin = JSON.parse(
        window.atob(window.localStorage.token.split(".")[1])
      )._id;
    } else {
      this.sup_admin = JSON.parse(
        window.atob(window.localStorage.token.split(".")[1])
      ).supAdmin;
    }
    console.log("SUPPPERADMIN-----,", this.sup_admin);

    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;
    }
    this.deviceForm = this.fb.group({
      //ownerName:['',[Validators.required,Validators.pattern("[a-zA-Z][a-zA-Z ]+")]],
      first_name: ["", Validators.required],
      customerType: ["", Validators.required],
      last_name: [""],
      contactNo: ["", [Validators.required, Validators.pattern("[0-9 ]{10}")]],
      device_id: ["", Validators.required],
      address: ["", Validators.required],
      state: ["", Validators.required],
      rtoOffice: ["", Validators.required],
      vehicleManufacture: ["", Validators.required],
      vehicleModel: [""],
      vehicleCategory: ["", Validators.required],
      vehicleType: [""],
      vehicleNo: ["", [Validators.required, Validators.maxLength(10)]],
      chasisNo:[
        "", 
        [
          Validators.required, 
          Validators.pattern("^[a-zA-Z0-9]*$"), 
          Validators.minLength(17)
        ]
      ],
      engineNo: ["", Validators.required],
      panic: ["", Validators.required],
      bsnlPlan: [""],
      hostingPlan: [""],
      SMSPlan: [""],
      city: ["", Validators.required],
      deviceModel: [""],
      trackingExp: new Date(
        new Date().setFullYear(new Date().getFullYear() + 2)
      ),
      eSimExpiry: [""],
      model: ["", Validators.required],
      email: [""],
      dealerFollowup: [
        "",
        [Validators.required, Validators.pattern("[0-9 ]{10}")],
      ],
      sim1: ["", Validators.required],

      sim2: [""],
      iccid: [""],
      // pin: ["", [Validators.required, Validators.pattern("[0-9 ]{6}")]],

      customer_state: ["", [Validators.required]],
      customer_city: ["", [Validators.required]],
      customer_pin: [
        "",
        [Validators.required, Validators.pattern("[0-9 ]{6}")],
      ],
      mfdyear: ["", [Validators.required]],
      fuelType: ["", [Validators.required]],
      m2mprovider: [""],
      sim_provider: [""],
      sim_provider2: [""],
      vahanID: ["", [Validators.required]],
    });
    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) {
          var exp: any = new Date();
          if (that.inventory[i].eSIMValidaity == "One Year") {
            exp.setFullYear(exp.getFullYear() + 1);
          } else if (that.inventory[i].eSIMValidaity == "Two Year") {
            exp.setFullYear(exp.getFullYear() + 2);
          } else {
            exp.setFullYear(exp.getFullYear() + 1);
          }

          that.deviceForm.patchValue({
            iccid: that.inventory[i].IccidNo,
            sim1: that.inventory[i].Mob1,
            sim2: that.inventory[i].Mob2,
            eSimExpiry: new Date(exp),
            vahanID: that.inventory[i].SerialNo,
            trackingExp: new Date(exp),

            device_id: value,
          });
          $("#dbselect").multipleSelect("setSelects", [
            that.inventory[i].device_model,
          ]);
          that.vahanID = that.inventory[i]["SerialNo"];
          that.hrdwr = that.inventory[i].Mob1;
          that.hrdwr2 = that.inventory[i].Mob2;
        }
      }
    });
  }
  get f() {
    return this.deviceForm.controls;
  }
  states = [];
  db_show(data: any) {
    console.log("show=>", data);
  }
  getAllState() {
    let that = this;
    that.contactService.get("/RTO_master/getAllState").subscribe((res: any) => {
      res = _.sortBy(res, "_id.state");
      for (var i = 0; i < res.length; i++) {
        that.states.push(res[i]._id.state);
      }
      // this.states=res;
    });
  }

  db_val: any = [
    {
      v: "Follow-up",
      k: "dealerFollowup",
    },
    {
      v: "Customer Type",
      k: "customerType",
    },
    {
      v: "Customer Name",
      k: "first_name",
    },
    {
      v: "Custodian Name",
      k: "last_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() {
    debugger;
    this.submitted = true;
    console.log(this.deviceForm);
    // stop here if form is invalid
    if (this.deviceForm.invalid) {
      const controls = this.deviceForm.controls;

      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 < this.db_val.length; i++) {
        if (controls[this.db_val[i].k].invalid) {
          // invalid.push(name);
          this.data_descip = "please enter valid " + this.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
      ) {
        // var err;
        // if (i == 0 || i == 1) {
        //   err = "Please Enter Adhar card number";
        // }
        // // else
        // // if (i == 2) {
        // //   err = "Please Enter Warrenty card number";
        // // }
        // else {
        //   err = "Please Enter vehicle sales invoice number";
        // }
        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;
    }
    if (this.userFound) {
      var data1 = {
        contactid: this.user._id,
      };
      // if (this.deviceForm.value.pin) {
      //   data1["pin"] = this.deviceForm.value.pin;
      // }
      this.contactService.post("/users/editUserDetails", data1).subscribe(
        (res: any) => {
          console.log(res);

          if (res.message == "Saved") {
            this.addDevice(this.user);
          }
        },
        (err) => {
          swal("Something Went Wrong");
        }
      );
    } else {
      var expDate = new Date();
      expDate.setFullYear(expDate.getFullYear() + 1);

      //var name=this.deviceForm.value.ownerName.split(' ')

      var data = {
        // Dealer:this.reactiveForm.value.manager,
        custumer: true,
        expdate: new Date(expDate).toISOString(),
        first_name: this.deviceForm.value.first_name
          ? this.deviceForm.value.first_name
          : "",
        last_name: this.deviceForm.value.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.userId,
        timezone: "Asia/Kolkata",
        std_code: { countryCode: "in", dialcode: "91" },
      };

      if (this.deviceForm.value.customer_pin) {
        data["customer_pin"] = this.deviceForm.value.customer_pin;
      }
      if (this.deviceForm.value.customer_city) {
        data["customer_city"] = this.deviceForm.value.customer_city;
      }
      if (this.deviceForm.value.customer_state) {
        data["customer_state"] = this.deviceForm.value.customer_state;
      }

      if (this.deviceForm.value.email) {
        data["email"] = this.deviceForm.value.email;
      }
      if (this.deviceForm.value.address) {
        data["address"] = this.deviceForm.value.address;
      }

      console.log(data);

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

          if (
            res.message == "Registered Sucessfully" ||
            res.message == "Registered and Message Sent Successfuly" ||
            res.message == "Registered"
          ) {
            this.addDevice(res._id);
            // this.router.navigateByUrl('/dashboard');
          } else {
            swal(res.message);
          }
        },
        (err) => {
          console.log("err=>", err);
          swal("Something Went Wrong");
        }
      );
    }
  }
  /* 
stop 

*/
  addDevice(data) {
    let that = this;
    var model = $("#dbselect").multipleSelect("getSelects", "value");
    var type = $("#vehicleType").multipleSelect("getSelects", "value");
    var deviceid;
    if (this.inventoryManagement) {
      var id = $("#inventory").multipleSelect("getSelects", "value");
      deviceid = id[0];
    } else {
      deviceid = this.deviceForm.value.device_id;
    }
    var newDevice = {
      devicename: this.deviceForm.value.vehicleNo,
      deviceid: deviceid,
      // des: this.des,
      // model: model[0],

      typdev: "Tracker",
      // emailid: this.emailid,
      Mileage: "10",
      phn: this.deviceForm.value.contactNo,
      sim_number: this.deviceForm.value.contactNo,
      created_by: this.userId,
      supAdmin: this.sup_admin,
      // driver_name: this.driver,
      // contact_number: this.dcontact,
      device_model: model[0],
      expdate: new Date(this.expDate),
      user: data._id,
      // user: that.is_same_dealer_customer == true ? data._id : this.userId,  //db_20242104
      bussinessType: 1,
      // License : this.licenseVal,
      // deviceDistanceVariation:this.selcetedSign+(this.deviceDistanceVariation?this.deviceDistanceVariation:'0')

      // Dealer:this.dealerObj?this.dealerObj:this.sup_admin
    };
    //  if (this.custtype) {
    //   newDevice['Dealer'] = this.userId;
    // } else if((this.custtype == false)&&(window.localStorage['Custumer'] == 'ON') ) {
    newDevice["Dealer"] = this.userId;
    // }

    //  hrdwr: this.deviceForm.value.sim1,
    //         hrdwr1: this.deviceForm.value.sim1,
    if (this.deviceForm.value.sim1) {
      newDevice["hrdwr"] = this.deviceForm.value.sim1;
    }
    if (this.deviceForm.value.sim1) {
      newDevice["sim_number"] = this.deviceForm.value.sim1;
    }
    if (this.deviceForm.value.sim2) {
      newDevice["sim_number2"] = this.deviceForm.value.sim2;
    }

    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.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.pin) {
      newDevice["transportOfficePin"] = this.deviceForm.value.pin;
    }

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

    if (type) {
      newDevice["typeOfVehicle"] = type[0];
    }
    if (type) {
      newDevice["vehicleType"] = type[0];
    }

    // if(this.transportOfficeCity){
    //   newDevice['transportOfficeCity'] = this.transportOfficeCity;
    // }
    if (this.deviceForm.value.state) {
      newDevice["transportOfficeState"] = this.deviceForm.value.state;
    }
    if (this.deviceForm.value.iccid) {
      newDevice["IccidNo"] = this.deviceForm.value.iccid;
      
    }
    if (this.vahanID) {
      newDevice["vahanID"] = this.vahanID;
    }

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

    if (this.deviceImg != undefined) {
      newDevice["deviceImage"] = this.deviceImg;
    }

    if (this.deviceForm.value.vehicleCategory) {
      newDevice["vehicleCategory"] = this.deviceForm.value.vehicleCategory;
    }
    if (this.deviceForm.value.rtoOffice) {
      newDevice["rto"] = this.deviceForm.value.rtoOffice;
    }
    console.log("imageuploadDocument", this.imageuploadObject);
    if (this.imageuploadObject.length != 0) {
      newDevice["customerType"] = this.deviceForm.value.customerType;
      newDevice["imageDoc"] = this.imageuploadObject;
    }

    if (this.deviceForm.value.mfdyear != "") {
      newDevice["mfdyear"] = this.deviceForm.value.mfdyear;
      // newDevice["manufacturingYear"] = this.deviceForm.value.mfdyear;
    }

    if (this.deviceForm.value.fuelType != "")
      newDevice["fuelType"] = this.deviceForm.value.fuelType;
    if (this.deviceForm.value.m2mprovider != "")
      newDevice["m2mprovider"] = this.deviceForm.value.m2mprovider;
    if (this.deviceForm.value.sim_provider != "")
      newDevice["sim_provider"] = this.deviceForm.value.sim_provider;
    if (this.deviceForm.value.sim_provider2 != "")
      newDevice["sim_provider2"] = this.deviceForm.value.sim_provider2;
    if (this.deviceForm.value.vahanID != "")
      newDevice["vahanID"] = this.deviceForm.value.vahanID;

    if (this.deviceForm.value.customer_city != "")
      newDevice["customer_city"] = this.deviceForm.value.customer_city;

    if (this.deviceForm.value.customer_state != "")
      newDevice["customer_state"] = this.deviceForm.value.customer_state;

    if (this.deviceForm.value.customer_pin != "")
      newDevice["customer_pin"] = this.deviceForm.value.customer_pin;

    this.Load = false;
    this.contactService.addKycDevice(newDevice).subscribe(
      (device) => {
        console.log(device);

  //db_20242104
  /*        if (that.is_same_dealer_customer == false) {
          
          that.contactService
            .ShareDevice(
              that.deviceForm.value.contactNo,
              that.userId,
              device._id
            )
            .subscribe((ShareDevice_res: any) => {
              console.log("ShareDevice_res=>", ShareDevice_res);
            });
          
        }  */

        window.localStorage["DataUpdate"] = "True";
        that.data_descip = "Device Added Successfully";
        launch_toast();
        that.router.navigateByUrl("dashboard");
      },
      // this.Load = false

      (err: any) => {
        console.log(err.status);
        console.log(err);
        swal("Something Went Wrong");
        let msg = JSON.parse(err._body);

        if (err.status == 400) {
          console.log(JSON.parse(err._body).deviceObj);
          var dupObj = JSON.parse(err._body).deviceObj;
          if (msg.message == "EngineNo already exists") {
            that.data_descip = msg.message;
          } else if (msg.message == "ChassisNo already exists") {
            that.data_descip = msg.message;
          } else {
            that.data_descip = "Duplicate Device ID (IMEI)";
          }
          that.launch_toast();
          var devicesupAdmin = dupObj.supAdmin;
          var deviceDealer = dupObj.Dealer;
          var devOwner = dupObj.user;
          //
        } else {
          var message;
          if (err.status == 401) {
            message = "Access Denied !!!";
            this.data_descip = "Access Denied !!!";
            launch_toast();
          } else {
            message = "Network Error !!!";
            this.data_descip = "Network Error !!!";
            launch_toast();
          }
          console.log(err);

          this._flashMessagesService.show(message, {
            cssClass: "alert-danger",
            timeout: 2000,
          });
          // this.Load = false
        }
      }
    );
    function launch_toast() {
      // console.log(divid);
      var x = document.getElementById("toast");
      if (x != null && x != undefined) {
        x.className = "show";
      }
      //console.log(x);

      setTimeout(function () {
        if (x != null && x != undefined) {
          x.className = x.className.replace("show", "");
        }
      }, 1500);
    }
  }
  removeSpecialChar() {
    if (this.deviceForm.value.device_id) {
      this.deviceForm.controls.device_id.setValue(
        this.deviceForm.value.device_id
          .replaceAll(/[^0-9 ]/g, "")
          .replaceAll(" ", "")
      );
    }
  }
  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;
  is_same_dealer_customer: any = null;
  onSearchChange(value) {
    let that = this;
    this.userFound = false;
    this.contactMessage = "";
    console.log(value);
    var phone = this.deviceForm.value.contactNo;
    if (phone.length == 10) {
      console.log("KLDJNDKjk");
      debugger
      this.contactService
        .get("/users/searchUserByPhone?user=" + this.userId + "&phone=" + phone)
        .subscribe(
          (res: any) => {
            that.contactService
              .get(
                "/users/searchUserByPhone?user=" +
                  that.userId +
                  "&phone=" +
                  that.deviceForm.value.dealerFollowup
              )
              .subscribe((resp2: any) => {
                debugger
                if (resp2.data[0]._id != res.data[0].Dealer) {
                  that.is_same_dealer_customer = false;
                } else if (resp2.data[0]._id == res.data[0].Dealer) {
                  that.is_same_dealer_customer = true;
                }
              });
            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:'',
                first_name: res.data[0].first_name
                  ? res.data[0].first_name
                  : "",
                last_name: res.data[0].last_name ? res.data[0].last_name : "",
                email: res.data[0].email ? res.data[0].email : "",
              });
              this.user = res.data[0];
              this.userFound = true;
              this.deviceForm.controls.first_name.disable();
              this.deviceForm.controls.last_name.disable();
              this.deviceForm.controls.email.disable();
            } else {
              this.deviceForm.patchValue({
                first_name: "",
                last_name: "",
                email: "",
              });
              this.userFound = false;
              this.contactMessage =
                res.message != "Mobile Number not found in db"
                  ? res.message
                  : "";
              this.deviceForm.controls.first_name.enable();
              this.deviceForm.controls.last_name.enable();
              this.deviceForm.controls.email.enable();

              console.log("this.contactMessage", this.contactMessage);
            }
          },
          (err) => {
            console.log(err);
            this.contactMessage = err.error.message;
            console.log("this.contactMessage err", this.contactMessage);
          }
        );
    }
  }
  device_Model: any;
  getDeviceModel() {
    let _org = JSON.parse(localStorage.ORG);
    // this.contactService
    //   .get("/deviceModel/getDeviceModel?input=Nippon")
    this.contactService
      .get("/deviceModel/getDeviceModel?org=" + _org._id)
      // 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);
        }
        console.log("this.device_Model", this.device_Model);
        console.log(devname);
        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: 394,
        placeholder: "Select model",
        filter: true,
        single: true,
        selectAll: false,
      });
      $("#vehicleType").multipleSelect({
        width: 394,
        placeholder: "Select Type",
        filter: true,
        single: true,
        selectAll: false,
      });
      $("#inventory").multipleSelect({
        width: 394,
        placeholder: "Select IMEI",
        filter: true,
        single: true,
        selectAll: false,
      });
    }, 100);
  }
  invalidEmeiSelected = false;
  checkDeviceEMI(id) {
    console.log("checkDeviceEMI");
    this.contactService.checkDeviceId(id).subscribe((res) => {
      try {
        this.invalidEmeiSelected = res["_body"] != "No device Found";
      } catch (error) {}
    });
  }
  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);
  }
  showNAME(name) {
    let n = name;
    return n.split("/").at(-1).slice(-15);
  }

  selectedFile: File;
  index;
  onFileChanged(event, i, data) {
    this.index = i;
    // data.image = event.target.files[0].name;
    this.selectedFile = <File>event.target.files[0];
    console.log(this.selectedFile);
    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;
    }
    this.imageuploadObject[this.index].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: any) => {
        this.Load = false;
        this.ifuploadArr = true;

        data.image = res._body;
        //   this.uploadStatus = 'Uploaded';
        this.data_descip = "Image Uploaded";
        this.launch_toast();
        console.log(res);
        var resImage = "";
        resImage = res["_body"];
        console.log(res["_body"]);
        this.imageuploadObject[this.index].image = resImage;
        console.log(this.imageuploadObject);
        // console.log(res);
        this.selectedFile = undefined;
      },
      (err) => {
        this.selectedFile = undefined;
        this.Load = false;
        this.data_descip = "Internal server error , try again";
        this.launch_toast();
        this._flashMessagesService.show("Internal server error , try again", {
          cssClass: "alert-success",
          timeout: 2000,
        });
      }
    );
  }

  allowDrop(event: DragEvent) {
    event.preventDefault(); // Prevent the default handling of the event (which would prevent drop)
  }

  // Handle the dropped files
  onDrop(event: DragEvent) {
    event.preventDefault();

    // Get the files from the drop event
    var files = event.dataTransfer ? event.dataTransfer.files : [];
    if (files && files.length > 0) {
      const file = files[0];
      const validTypes = ['image/jpeg', 'image/jpg', 'image/png'];

      // Validate the file type
      if (!validTypes.includes(file.type)) {
        swal("Upload Error", "Please upload a valid file type (.jpeg, .jpg, .png)", "error");
        return; // Prevent further processing of invalid file
      }

      // If valid, process the file as if it was selected through the input
      const inputEvent = {
        target: { files: files },
      };
      this.onFileChanged(inputEvent, this.index, {});
    }
  }
  ifuploadArr: boolean;
  uploadStatus: any = "Upload";
  onUpload(imgIndex) {
    console.log(imgIndex);

    // console.log("selected file name =>",this.selectedFile.name);
    if (!this.selectedFile) {
      swal("Upload Error", "Please choose file before upload !!!", "error");
    } else {
      this.imageuploadObject[this.index].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';
          this.data_descip = "Image Uploaded";
          this.launch_toast();
          console.log(res);
          var resImage = "";
          resImage = res["_body"];
          console.log(res["_body"]);
          this.imageuploadObject[this.index].image = resImage;
          console.log(this.imageuploadObject);
          // console.log(res);
          this.selectedFile = undefined;
        },
        (err) => {
          this.selectedFile = undefined;
          this.Load = false;
          this.data_descip = "Internal server error , try again";
          this.launch_toast();
          this._flashMessagesService.show("Internal server error , try again", {
            cssClass: "alert-success",
            timeout: 2000,
          });
        }
      );
    }
  }
  documentType(docType) {
    console.log("doctypeObject=>", docType);
  }

  inventoryManagement: Boolean = false;
  inventory = [];
  getUserSetting(userId) {
    this.contactService
      .post("/users/get_user_setting", { uid: userId })
      .subscribe((res: any) => {
        this.inventoryManagement = res.inventoryManagement;
        if (this.inventoryManagement) {
          console.log(
            this.userId,
            (this.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
            ? this.userId
            : this.sup_admin
            ? this.sup_admin
            : this.userId;
          console.log(user);

          this.contactService
            .get("/Device_inventory/getInventoryDropdown?user=" + this.userId)
            .subscribe((res: any) => {
              this.inventory = res;
              this.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;
      });
  }
  cityList;
  newcityList: any = [];
  newonStateChange(event) {
    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;
    //   });
  }
  onStateChange(event) {
    let that = this;
    that.contactService
      .get("/RTO_master/getCity?state=" + event.target.value)
      .subscribe((res: any) => {
        that.cityList = _.sortBy(res, "city");
      });
  }
  RTO;
  newonCityChange(event) {
    this.contactService
      .get("/RTO_master/getRTO?city=" + event.target.value)
      .subscribe((res: any) => {
        //this.RTO = res;
      });
  }
  onCityChange(event) {
    this.contactService
      .get("/RTO_master/getRTO?city=" + event.target.value)
      .subscribe((res: any) => {
        this.RTO = res;
      });
  }
  back() {
    this.location.back();
  }
  imageURL: any;
  index2;
  selectedDeviceFile: File;
  data_descip: any;
  onDeviceImageChanged(event, index) {
    this.index2 = index;
    this.selectedDeviceFile = <File>event.target.files[0];
    if (this.selectedDeviceFile) {
      this.Load = true;
      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;
      }
      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[this.index2]){
            this.deviceImg[this.index2] = res["_body"];
            //  }else{
            //    this.deviceImg.push(res['_body'])
            //  }
          }
          this.selectedDeviceFile = undefined;
          console.log("this.deviceImg", this.deviceImg);
          this.data_descip = "Image Uploaded";
          launch_toast();
          this.Load = false;
        },
        (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);
    }
  }
  deviceImg = ["", "", ""];
  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[this.index2]){
            this.deviceImg[this.index2] = res["_body"];
            //  }else{
            //    this.deviceImg.push(res['_body'])
            //  }
          }
          this.selectedDeviceFile = undefined;
          console.log("this.deviceImg", this.deviceImg);
          this.data_descip = "Image Uploaded";
          launch_toast();
          this.Load = false;
        },
        (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);
    }
  }
  launch_toast() {
  
    var x = document.getElementById("toast");
    //console.log(x);
    if (x != null) {
      x.className = "show";
      setTimeout(function () {
        x.className = x.className.replace("show", "");
      }, 5000);
    }
  }

  image;
  docName;
  openModal(template: TemplateRef<any>, doc) {
    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);
  }
}
