import { Component, OnInit , TemplateRef} from '@angular/core';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { Router } from '@angular/router';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { ToastrService } from 'ngx-toastr';
import { DialogService } from 'ng2-bootstrap-modal';
import { Vendor } from './vendor';
import { VendorService } from './vendor.service';

@Component({
  selector: 'app-vendor',
  templateUrl: './vendor.component.html',
  styleUrls: ['./vendor.component.css']
})
export class VendorComponent implements OnInit {

  sendMenuId: number;
  sendPageName = 'Vendor';
  // action rights
  _menuId: any;
  _actionRights: any;
  readOnly = false; add = true; edit = true; delete = true;
  vendorForm: FormGroup;
  vendors: Vendor[] = [];
  vendorsactive: Vendor[] = [];
  vendor: Vendor;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  vendorModalRef: BsModalRef;
  operation: string;
  userid: number;
  vendorid: number;
  submitted = false;
  active: number;
  unamePattern: string;
  confmsg: string;
  p = 1; searchText: string;
  itemsPerPage = 10;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };
  showall = true;
  showallstatus = false;
  key = 'vendorname'; // set default
  reverse = false;
  actionRights: any;

  constructor(private router: Router, private toastr: ToastrService, private dialogService: DialogService,
    private formBuilder: FormBuilder, private modalService: BsModalService, private vendorservice: VendorService) {

      // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Vendor_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Vendor_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Vendor_userRights');
    }
     }

  ngOnInit(): void {
    this.vendorForm = this.formBuilder.group({
      vendorid: [''],
      username: ['', [Validators.required]],
      password: ['', [Validators.required]],
      mailid: ['', [Validators.required, Validators.email ]],
      vendorname: ['', [Validators.required]],
      mobile: [''],
      location: [''],
      active: ['']
    });
    this.searchText = '';
    // this.showallstatus = false;
    // this.showall = true;
    // this.showallstatus = false;
    // this.add = true;
    // this.edit = true;
    // this.delete = true;
   // this.submitShow = true;
    this.getAll();
    // for action rights
    this.getUserRights();
  }
  get g() { return this.vendorForm.controls; }
  getactiveinactive(showallp) {
    this.vendorsactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.vendors.forEach(data => {
        if (data.active === 1) {
          this.vendorsactive.push(data);
        }
      });
      this.vendors = [];
      this.vendors = this.vendorsactive;
    } else {
      this.showall = true;
      this.vendors = [];
      this.getAll();
    }
  }

  // function to get user rights
  getUserRights() {
    const btnToEnable = JSON.parse(this.actionRights);
    if (btnToEnable.length > 0) {
      this.readOnly = true;
      btnToEnable.forEach(d => {
        if (d !== undefined) {
          if (d === 2) {
            this.add = true;
          } else if (d === 3) {
            this.edit = true;
          } else if (d === 4) {
            this.delete = true;
          }
        }
      });
    }
  }

  clearForm() {
    this.vendorModalRef.hide();
  }

  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }


  getAll() {
    this.vendors = [];
    this.vendorsactive = [];
    this.vendorservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.vendors = JSON.parse(res[0]);
        if (this.showallstatus === true) {
          this.vendors.forEach(data => {
            if (data.active === 1) {
              this.vendorsactive.push(data);
            }
          });
          this.vendors = [];
          this.vendors = this.vendorsactive;
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });

  }

  Post(vendor: Vendor) {

    this.submitted = true;

    if ((vendor.vendorname.trim() === undefined) || (vendor.vendorname.trim() === '')) {
      this.toastr.error('Vendorname should not be empty');
      return;
    }

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    vendor.vendorname = vendor.vendorname.trim();
    if(vendor.mobile){
      vendor.mobile = vendor.mobile.toString();
      }
    if (this.operation === 'add') {

      vendor.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.vendorservice.Post(vendor).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body.message === '0') {
              this.vendorModalRef.hide();
              this.getAll();
              this.toastr.success('Data added successfully');
              this.clearForm();
            } else {
              // this.vendorModalRef.hide();
              this.toastr.warning(res.body.message);
            }
          }
        }
      },
        error => {
          this.toastr.error('Error while doing the operation');
          this.postresult = false;
        });
    } else if (this.operation = 'update') {
           vendor.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.vendorservice.Put(vendor).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body.message === '0') {
              this.vendorModalRef.hide();
              this.getAll();
              this.toastr.success('Data updated successfully');
              this.clearForm();
            } else {
              // this.toastr.warning('Record already exists.');
              this.toastr.warning(res.body.message);
          }
          }
        }
      },
        error => {
          this.toastr.error('Error while doing the operation');
          this.postresult = false;
        });
    }
    this.submitted = false;
  }

  ChangeActive(e) {
    if (e.currentTarget.checked) {
      this.vendorForm.controls['active'].setValue(1);
    } else {
      this.vendorForm.controls['active'].setValue(0);
    }
  } 

  OpenConfirmTemplate(vendor, template: TemplateRef<any>) {
    if (vendor.active === 0) {
      this.confmsg = 'activate';
    } else {
      this.confmsg = 'deactivate';
    }
    this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Please Confirm',
        message: 'Are you sure you want to ' + this.confmsg + ' this record ?',
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe((isConfirmed) => {
        if (isConfirmed) {
          this.vendor = vendor;
        //  this.vendor.contractstart = new Date('2020-02-27T20:53:02.299351');
        //  this.vendor.contractend = new Date('2020-02-27T20:53:02.299351');
          this.Delete();

        }
      });
  }

  Delete() {
    let msg;
    if (this.vendor.active === 0) {
      this.vendor.active = 1;
      msg = 'Record activated successfully';
    } else {
      this.vendor.active = 0;
      msg = 'Record deactivated successfully';
    }
    this.userid = +localStorage.getItem('userid');
    this.vendor.updatedby = this.userid;
    this.vendorservice.Delete(this.vendor).subscribe(res => {
      this.toastr.success(msg);
      this.getAll();
    },
      error => { this.deleteResult = false; });

  }

  hidePopup() {
    this.vendorModalRef.hide();
  }

  openVendorModal(template: TemplateRef<any>, type, vendor?: Vendor) {

    this.operation = type;

    if (type === 'update') {
      this.vendorForm.controls['vendorid'].setValue(vendor.vendorid);
      this.vendorForm.controls['username'].setValue(vendor.username);
      this.vendorForm.controls['password'].setValue(vendor.password);
      this.vendorForm.controls['mailid'].setValue(vendor.mailid);
      this.vendorForm.controls['vendorname'].setValue(vendor.vendorname);
      this.vendorForm.controls['mobile'].setValue(vendor.mobile);
      this.vendorForm.controls['location'].setValue(vendor.location);
      this.vendorForm.controls['active'].setValue(vendor.active);
      this.vendor = vendor;
    }
    if (type === 'add') {
      this.vendorForm.controls['vendorid'].setValue(0);
      this.vendorForm.controls['username'].setValue('');
      this.vendorForm.controls['password'].setValue('');
      this.vendorForm.controls['mailid'].setValue('');
      this.vendorForm.controls['vendorname'].setValue('');
      this.vendorForm.controls['mobile'].setValue('');
      this.vendorForm.controls['location'].setValue('');
      this.vendorForm.controls['active'].setValue(1);
    }
    this.vendorModalRef = this.modalService.show(template, this.config);

    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }
}
