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 { environment } from 'src/environments/environment';
import toast from 'devextreme/ui/toast';
import { chartvalue_model } from './chartvaluesModel';
import { ChartvaluesService } from './chartvalues.service';

@Component({
  selector: 'app-chartvalues',
  templateUrl: './chartvalues.component.html',
  styleUrls: ['./chartvalues.component.css']
})
export class ChartvaluesComponent implements OnInit {
  
  p = 1; public searchText: string;
  operation:any;
  itemsPerPage = 10;
  chartvalueModalRef: BsModalRef;
  chartvalueForm: FormGroup;
  chartvalue_data: chartvalue_model;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };
  userid: string = localStorage.getItem("userid");
  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 = 'projection';
  chartvalueactive:chartvalue_model[]=[];
  reverse = false;
  chartvaluelst:chartvalue_model[]=[];
  baseUrl: string = environment.serviceUrl;
  stagelst:[];

  constructor(private chartvalueservice:ChartvaluesService,
    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('Chartvalue_menuid', this.router.getCurrentNavigation().extras.state.menuid);
        localStorage.setItem('Chartvalue_userRights', this.router.getCurrentNavigation().extras.state.action);
        this.actionRights = [];
        this.actionRights = this.router.getCurrentNavigation().extras.state.action;
      } else {
        this.actionRights = [];
        this.actionRights = localStorage.getItem('Chartvalue_userRights');
      }
    }

  ngOnInit(): void {
    this.chartvalueForm = this.formBuilder.group({
      chartmasterid: [''],
      projection: ['', [Validators.required]],
      lcl: ['', [Validators.required]],
      ucl: ['', [Validators.required]],
      stageid: [0, [Validators.required]],
      stagename: [''],
      active: ['']
    });
    this.searchText = '';
    this.onload();
  }

  onload(){
    this.chartvalueservice.Get_all().subscribe(res => {
      debugger;
      if(res.body != null && res.body != undefined)
      {
        console.log(res);
        this.chartvaluelst = JSON.parse( res.body.list);
        this.stagelst =  JSON.parse(res.body.stagelst);
      }
       this.SpinnerService.hide();
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Error while getting Error list data');
    });
  }

  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }
  
  clearForm(){
      this.chartvalueForm.controls['chartmasterid'].setValue(0)
      this.chartvalueForm.controls['projection'].setValue(0);
      this.chartvalueForm.controls['lcl'].setValue(0);
      this.chartvalueForm.controls['ucl'].setValue(0);
      this.chartvalueForm.controls['stageid'].setValue(0);
      this.chartvalueForm.controls['stagename'].setValue('');
      this.chartvalueForm.controls['active'].setValue(0);
      this.chartvalueModalRef.hide();
      this.add=false;
      this.edit=false;
  }

  
  OpenConfirmTemplate(item: chartvalue_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.Active(item);
        }

      });
  }

  Active(item:chartvalue_model){
    // debugger;
    var inputData = [];
    inputData.push({
      updatedby: Number(localStorage.getItem('userid')),
      active:item.active,
      chartmasterid:item.chartmasterid
    })

    this.chartvalueservice.Active_ChartValues(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.chartvalueactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.chartvaluelst.forEach(data => {
        if (data.active === 1) {
          this.chartvalueactive.push(data);
        }
      });
      this.chartvaluelst = [];
      this.chartvaluelst = this.chartvalueactive;
    } else {
      this.showall = true;
      this.chartvaluelst = [];
      this.onload();
    }
    this.SpinnerService.hide();
  }

  Post(item:chartvalue_model){
// debugger;
if(this.chartvalueForm.valid){
  if(Number(item.lcl) == 0){
    this.toastr.error('Please select the LCL')
    return;
  }
  if(Number(item.ucl) == 0){
    this.toastr.error('Please select the UCL')
    return;
  }
  if(Number(item.stageid) == 0){
    this.toastr.error('Please select the stage')
    return;
  }

  if(this.operation==='add'){
    var inputData = [];
    inputData.push({
      projection: item.projection,
      ucl: item.ucl,
      lcl: item.lcl,
      stageid: item.stageid,
      createdby: Number(localStorage.getItem('userid')),
      active:1
    });

    this.chartvalueservice.Add_ChartValues(inputData[0]).subscribe(res => {
      // debugger;
      this.chartvalueModalRef.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({
      chartmasterid :item.chartmasterid,
      projection: item.projection,
      ucl: item.ucl,
      lcl: item.lcl,
      stageid: item.stageid,
      updatedby: Number(localStorage.getItem('userid')),
      active:item.active,
    });

    this.chartvalueservice.Edit_ChartValues(inputData[0]).subscribe(res => {
      // debugger;
      this.chartvalueModalRef.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.chartvalueForm.controls['active'].setValue(1);
    } else {
      this.chartvalueForm.controls['active'].setValue(0);
    }
  }
  openchartvalueModal(template: TemplateRef<any>, type, item?: chartvalue_model) {
    debugger;
    this.operation = type;

    if (type === 'update') {
      this.chartvalueForm.controls['chartmasterid'].setValue(item.chartmasterid);
      this.chartvalueForm.controls['projection'].setValue(item.projection);
      this.chartvalueForm.controls['ucl'].setValue(item.ucl);
      this.chartvalueForm.controls['lcl'].setValue(item.lcl);
      this.chartvalueForm.controls['stageid'].setValue(item.stageid);
      this.chartvalueForm.controls['active'].setValue(item.active);
      this.add=false;
      this.edit=true;

    this.chartvalue_data = item;
    }
    if (type === 'add') {
      this.chartvalueForm.controls['chartmasterid'].setValue(0)
      this.chartvalueForm.controls['projection'].setValue('');
      this.chartvalueForm.controls['lcl'].setValue('');
      this.chartvalueForm.controls['ucl'].setValue('');
      this.chartvalueForm.controls['stageid'].setValue(0);
      this.chartvalueForm.controls['stagename'].setValue('');
      this.chartvalueForm.controls['active'].setValue(0);
      this.edit=false;
      this.add=true;
    }
    this.chartvalueModalRef = this.modalService.show(template, this.config);

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