import { Component, OnInit, TemplateRef } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DialogService } from 'ng2-bootstrap-modal';
import { BsModalRef, BsModalService, ModalOptions } from 'ngx-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { errormaster_model } from '../errormaster/errormaster_model';
import { Errorremarks_model } from './errorermarks';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { ErrorremarksService } from './errorremarks.service';
@Component({
  selector: 'app-errorremarks',
  templateUrl: './errorremarks.component.html',
  styleUrls: ['./errorremarks.component.css']
})
export class ErrorremarksComponent implements OnInit {

  errorcatergory:any="";
  errorid : number=0;
  errortype: string='';

  sendMenuId: number;
  sendPageName = 'lobList';
  // action rights
  _menuId: any;
  _actionRights: any;
  _lobid: number;
  _lob:string;
  submitShow: boolean;
  readOnly: boolean;
  add: boolean;
  edit: boolean;
  delete: boolean;
  errorremarksForm: FormGroup;
  errorremarksdetails: Errorremarks_model[] = [];
  errorremarksdetailsactive: Errorremarks_model[] = [];
  errorremarksdetail: Errorremarks_model;
  errorremarksactive: Errorremarks_model[] =[];
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  errorremarksModalRef: BsModalRef;
  operation: string;
  userid: number;
  loblistdetid: 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 = 'queestion'; // set default
  reverse = false;
  actionRights: any;

  constructor(private router: Router, private toastr: ToastrService, private dialogService: DialogService,
    private formBuilder: FormBuilder, private modalService: BsModalService, private errorremarksservice: ErrorremarksService,
    private route: ActivatedRoute) {  
    this.errorid= +this.route.snapshot.queryParamMap.get('errorid');
    this.errorcatergory= this.route.snapshot.queryParamMap.get('errorcategory');
    this.errortype= this.route.snapshot.queryParamMap.get('errortype');
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('ErrorRemarks_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('ErrorRemarks_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('ErrorRemarks_userRights');
    }
    }

  ngOnInit(): void {
     // for action rights
     this.readOnly = true;
     this.add = true;
     this.edit = true;
     this.delete = true;
     this.submitShow = true;

    this.errorremarksForm = this.formBuilder.group({
      errorremarksid: [''],
      errorid: [''],
      errorremarks: ['', [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.onload(this.errorid);
  }

  onload(data){
    this.errorremarksdetails = [];
    this.errorremarksactive = [];
    let input = [];
    let item = {
      errorid: this.errorid
    };
    input.push(item);
    this.errorremarksservice.GetbyErrorid(input[0]).subscribe(res => {
      if (res.body != null && res.body !== undefined) {
        console.log('res',res.body);
        this.errorremarksdetails = res.body;
        if (this.showallstatus === true) {
          this.errorremarksdetails.forEach(data => {
            if (data.active === 1) {
              this.errorremarksactive.push(data);
            }
          });
          this.errorremarksdetails = [];
          this.errorremarksdetails = this.errorremarksactive;
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });

  }

  getactiveinactive(showallp) {
    this.errorremarksactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.errorremarksdetails.forEach(data => {
        if (data.active === 1) {
          this.errorremarksactive.push(data);
        }
      });
      this.errorremarksdetails = [];
      this.errorremarksdetails = this.errorremarksactive;
    } else {
      this.showall = true;
      this.errorremarksdetails = [];
      this.onload(this._lobid);
    }
  }

  clearForm() {
    // for action rights
    if (this.add === true) {
      this.submitShow = true;
    } else {
      this.submitShow = false; }
    this.errorremarksModalRef.hide();
  }

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


  get g() { return this.errorremarksForm.controls; }

  Post(errorremarksdetails: Errorremarks_model) {

    this.submitted = true;

    if ((errorremarksdetails.errorremarks.trim() === undefined) || (errorremarksdetails.errorremarks.trim() === '')) {
      this.toastr.error('Error Remarks should not be empty');
      return;
    }

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    errorremarksdetails.errorremarks = errorremarksdetails.errorremarks.trim();
    errorremarksdetails.errorid = this.errorid;
    if (this.operation === 'add') {
      errorremarksdetails.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.errorremarksservice.Add_ErrorRemarks(errorremarksdetails).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.errorremarksModalRef.hide();
              this.onload(this.errorid);
              this.toastr.success('Data added successfully');
              this.clearForm();
            } else { this.toastr.warning('Record already exists.'); }
          }
        }
      },
        error => {
          this.toastr.error('Error while doing the operation');
          this.postresult = false;
        });
    } else if (this.operation = 'update') {
      this.submitShow = true;
      errorremarksdetails.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.errorremarksservice.Edit_ErrorRemarks(errorremarksdetails).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.errorremarksModalRef.hide();
              this.onload(this.errorid);
              this.toastr.success('Data updated successfully');
              this.clearForm();
            } else { this.toastr.warning('Record already exists.'); }
          }
        }
      },
        error => {
          this.toastr.error('Error while doing the operation');
          this.postresult = false;
        });
    }
    this.submitted = false;
  }

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

  OpenConfirmTemplate(loblistdetail, template: TemplateRef<any>) {
    if (loblistdetail.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.errorremarksdetail = loblistdetail;
          this.Delete();
        }
      });
  }

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

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

  openErrorModal(template: TemplateRef<any>, type, errorremarksdetails?: Errorremarks_model) {

    this.operation = type;

    if (type === 'update') {
      this.errorremarksForm.controls['errorremarksid'].setValue(errorremarksdetails.errorremarksid);
      this.errorremarksForm.controls['errorid'].setValue(errorremarksdetails.errorid);
      this.errorremarksForm.controls['errorremarks'].setValue(errorremarksdetails.errorremarks);
      this.errorremarksForm.controls['active'].setValue(errorremarksdetails.active);
      this.errorremarksdetail = errorremarksdetails;
    }
    if (type === 'add') {
      this.errorremarksForm.controls['errorremarksid'].setValue(0);
      this.errorremarksForm.controls['errorid'].setValue(this.errorid);
      this.errorremarksForm.controls['errorremarks'].setValue('');
      this.errorremarksForm.controls['active'].setValue(1);
    }
    this.errorremarksModalRef = this.modalService.show(template, this.config);

    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }
  Gotoerrorremarks() {
    this.router.navigate(['/masters/error']);
  }

}
