import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material';
import { Router } from '@angular/router';
import { DialogService } from 'ng2-bootstrap-modal';
import { BsModalRef, BsModalService, ModalOptions } from 'ngx-bootstrap';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { DashboardService } from 'src/app/dashboard/dashboard.service';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { StatecodeService } from '../statecode/statecode.service';
import { category_model } from './category_model';
import { CategorymasterService } from './categorymaster.service';

@Component({
  selector: 'app-categorymaster',
  templateUrl: './categorymaster.component.html',
  styleUrls: ['./categorymaster.component.css']
})
export class CategorymasterComponent implements OnInit {
  p = 1; public searchText: string;
  operation:any;
  itemsPerPage = 10;
  categoryModalRef: BsModalRef;
  categoryForm: FormGroup;
  category_data: category_model;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };
  showall = true;
  showallstatus = false;
  actionRights: any; _menuId: any; readOnly: boolean; add: boolean =true; edit: boolean =true; delete: boolean; submitShow: boolean;
  useridnew: string = localStorage.getItem('userid');
  key = 'categoryname';
  categoryactive:category_model[]=[];
  reverse = false;
  categorylst:category_model[]=[];
  constructor(
    private categoryservice: CategorymasterService,
    private router: Router,
    private dialog: MatDialog,
    private formBuilder: FormBuilder,
    private modalService: BsModalService,
    private SpinnerService: NgxSpinnerService,
    private dashboardservice: DashboardService,
    private dialogService: DialogService,
    private toastr: ToastrService) { 
      if (this.router.getCurrentNavigation().extras.state !== undefined) {
        localStorage.setItem('Category_menuid', this.router.getCurrentNavigation().extras.state.menuid);
        localStorage.setItem('Category_userRights', this.router.getCurrentNavigation().extras.state.action);
        this.actionRights = [];
        this.actionRights = this.router.getCurrentNavigation().extras.state.action;
      } else {
        this.actionRights = [];
        this.actionRights = localStorage.getItem('Category_userRights');
      }
    }

  ngOnInit(): void {
    this.categoryForm = this.formBuilder.group({
      categoryid: [''],
      categoryname : ['', [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.onload();
  }

  onload(){
    this.categoryservice.Get_all().subscribe(res => {
      debugger;
      this.categorylst = res.body;
      console.log('categorylst',this.categorylst)
       this.SpinnerService.hide();
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Error while getting State code data');
    });
  }

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

  clearForm(){
    this.categoryForm.controls['categoryid'].setValue(0)
      this.categoryForm.controls['categoryname'].setValue('');
      this.categoryForm.controls['active'].setValue(0);
      this.categoryModalRef.hide();
      this.add=false;
      this.edit=false;
  }

  OpenConfirmTemplate(item: category_model) {
    let confmsg;
debugger;
    if (item.active === 0) {
      confmsg = 'activate';
      item.active=1;
    } else {
      confmsg = 'deactivate';
      item.active =0;
    }
    this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Please Confirm',
        message: 'Are you sure you want to ' + confmsg + ' this record ?',
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe((isConfirmed) => {
        if (isConfirmed) {
          this.Delete(item);
        }

      });
  }
  Delete(item:category_model){
    debugger;
    var inputData = [];
    inputData.push({
      updatedby: Number(localStorage.getItem('userid')),
      active:item.active,
      categoryid:item.categoryid
    })

    this.categoryservice.Active_category(inputData[0]).subscribe(res => {
      debugger;
      if(item.active == 0){
        this.toastr.success('Inactive the record successfully');
        
      }else{
        this.toastr.success('Active the record successfully');
      }
      this.onload();
  }, error => {
      this.toastr.error(error.error);
  });
  }

  getactiveinactive(showallp) {
    this.SpinnerService.show();
    this.categoryactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.categorylst.forEach(data => {
        if (data.active === 1) {
          this.categoryactive.push(data);
        }
      });
      this.categorylst = [];
      this.categorylst = this.categoryactive;
    } else {
      this.showall = true;
      this.categorylst = [];
      this.onload();
    }
    this.SpinnerService.hide();
  }

  Post(item:category_model){
    debugger;
    if(this.categoryForm.valid){
    
      if(this.operation==='add'){
        var inputData = [];
        inputData.push({
          categoryname: item.categoryname,
          createdby: Number(localStorage.getItem('userid')),
          active:1,
        });
    
        this.categoryservice.Add_category(inputData[0]).subscribe(res => {
          debugger;
          this.categoryModalRef.hide();
          this.toastr.success('Successfully Added.');
          this.onload();
         //this.user_option=false;
        
      }, error => {
          this.toastr.error(error.error);
      });
      }else if(this.operation ==='update'){
        var inputData = [];
        inputData.push({
          categoryid :item.categoryid,
          categoryname: item.categoryname,
          updatedby: Number(localStorage.getItem('userid')),
          active:item.active
        });
    
        this.categoryservice.Edit_category(inputData[0]).subscribe(res => {
          debugger;
          this.categoryModalRef.hide();
          this.toastr.success('Successfully Updated.');
    this.onload();
         //this.user_option=false;
        
      }, error => {
          this.toastr.error(error.error);
      });
    
      }
    
    }else{
      this.toastr.error('Please fill the Required fields.');
    
    }
    
      }
      ChangeActive(e) {
        if (e.currentTarget.checked) {
          this.categoryForm.controls['active'].setValue(1);
        } else {
          this.categoryForm.controls['active'].setValue(0);
        }
      }
 
      openCheckListModal(template: TemplateRef<any>, type, item?: category_model) {
        debugger;
            this.operation = type;
        
            if (type === 'update') {
              this.categoryForm.controls['categoryid'].setValue(item.categoryid);
              this.categoryForm.controls['categoryname'].setValue(item.categoryname);
              this.categoryForm.controls['active'].setValue(item.active);
              this.add=false;
              this.edit=true;
        
            this.category_data = item;
            }
            if (type === 'add') {
              this.categoryForm.controls['categoryname'].setValue('');
              this.categoryForm.controls['active'].setValue(0);
              this.edit=false;
              this.add=true;
            }
            this.categoryModalRef = this.modalService.show(template, this.config);
        
            const aa = document.getElementsByClassName('modal-content');
            aa[0].classList.remove('modal-content');
          }
}
