import { Component, OnInit, TemplateRef } from '@angular/core';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { FormGroup, FormBuilder, Validators, FormArray, FormControl, ValidatorFn } from '@angular/forms';
import { CommondialogComponent } from '../../Shared/commondialog/commondialog.component';
import { DialogService } from 'ng2-bootstrap-modal';
import { ProjectMaster } from './projectmaster';
import { ProjectMasterService } from './projectmaster.service';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { CustomerService } from '../customer/customer.service';
import { CustomercontactService } from '../customercontact/customercontact.service';
import { NgxSpinnerService } from 'ngx-spinner';

@Component({
  selector: 'app-projectmaster',
  templateUrl: './projectmaster.component.html',
  styleUrls: ['./projectmaster.component.css']
})
export class ProjectmasterComponent implements OnInit {
  projectForm: FormGroup;
  projectMasters: ProjectMaster[];
  projectMaster: ProjectMaster;
  submitted = false;
  userid: number;
  p = 1;
  itemsPerPage = 10;
  confmsg: string;
  msg: string;
  searchText: string;
  key = 'Project Code';
  reverse = false;
  action: string;
  projectList: any = [];
  projectListtmp: any = [];
  projectListactive: any = [];
  showallstatus = false;
  showall = true;
  operation: string;
  activeCustomerList: any = [];
  activeCustomerListtmp: any = [];
  activeCustomerContactList: any = [];
  activeCustomerContactListtmp: any = [];
  projectModalRef: BsModalRef;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };
  actionRights: any;
  readOnly = false;
  add = false;
  edit = false;
  delete = false;

  constructor(
    private router: Router,
    private toastr: ToastrService,
    private projectMasterService: ProjectMasterService,
    private formBuilder: FormBuilder,
    private dialogService: DialogService,
    private modalService: BsModalService,
    private customerservice: CustomerService,
    private customercontactservice: CustomercontactService,
    private SpinnerService: NgxSpinnerService,
  ) {
    // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('ProjectMaster_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('ProjectMaster_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('ProjectMaster_userRights');
    }
  }

  ngOnInit() {
    this.projectForm = this.formBuilder.group({
      projectid: [''],
      projectcode: ['', [Validators.required]],
      projectname: ['', [Validators.required]],
      customerid: ['', [Validators.required]],
      customercontactid: ['', [Validators.required]],
      projectlocation: [''],
      project_type: [''],
      description: [''],
      active: ['']
    });
    this.action = 'add';
    this.loadExisitingProjectList();
    this.getUserRights();
  }

  // function to get the existing project details
  loadExisitingProjectList() {
    this.projectList = [];
    this.projectListactive = [];
    this.projectListtmp = [];
    this.projectMasterService.Get().subscribe(res => {
      if (res !== undefined && res !== null && res[0] !== undefined && res[0] !== null) {
        if (JSON.parse(res[0]).length > 0) {
          this.projectListtmp = JSON.parse(res[0]);
          this.projectListtmp.forEach(i => {
            this.projectList.push({
              projectid: i.projectid,
              projectcode: i.projectcode,
              projectname: i.projectname,
              projectlocation: i.projectlocation,
              description: i.description,
              active: i.active,
              createdbyname: i.createdbyname,
              updatedbyname: i.updatedbyname,
              startdate: i.startdate,
              enddate: i.enddate,
              createdon: i.createdon,
              updatedon: i.updatedon
            });
          });
          if (this.showallstatus === true) {
            this.projectList.forEach(data => {
              if (data.active === 1) {
                this.projectListactive.push(data);
              }
            });
            this.projectList = [];
            this.projectList = this.projectListactive;
          }
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  // get show all active function
  getactiveinactive(showallp) {
    this.projectListactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.projectList.forEach(data => {
        if (data.active === 1) {
          this.projectListactive.push(data);
        }
      });
      this.projectList = [];
      this.projectList = this.projectListactive;
    } else {
      this.showall = true;
      this.projectList = [];
      this.loadExisitingProjectList();
    }
  }

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

  // method to open the pop up to add the new project details
  async openProjectModal(template: TemplateRef<any>, type, projectMaster?: ProjectMaster) {
    this.SpinnerService.show();
    this.operation = type;
    let tmpData: any;
    this.activeCustomerList = [];
    tmpData = await this.loadActiveCustomer();
    if (tmpData !== null && tmpData !== undefined && tmpData[0] !== undefined && tmpData[0] !== null) {
      if (JSON.parse(tmpData[0]).length > 0) {
        this.activeCustomerListtmp = JSON.parse(tmpData[0]);
        this.activeCustomerList = this.activeCustomerListtmp
          .map(i => ({ customerid: i.customerid, customername: i.customername }));
      }
    }
    if (type === 'add') {
      this.projectForm.reset();
      this.projectForm.controls['projectid'].setValue(0);
      this.projectForm.controls['projectcode'].setValue('');
      this.projectForm.controls['projectname'].setValue('');
      this.projectForm.controls['active'].setValue(1);
      this.projectForm.controls['customerid'].setValue(0);
      this.projectForm.controls['customercontactid'].setValue(0);
    }
    if (type === 'update') {
      let _customerId: any; let _customerContactId: any;
      if (this.projectListtmp.filter(e => e.projectid === projectMaster.projectid)
        .map(e => e.customerid).length > 0) {
        _customerId = this.projectListtmp.filter(e => e.projectid === projectMaster.projectid)
          .map(e => e.customerid)[0];
      }
      if (this.projectListtmp.filter(e => e.projectid === projectMaster.projectid)
        .map(e => e.customercontactid).length > 0) {
        _customerContactId = this.projectListtmp.filter(e => e.projectid === projectMaster.projectid)
          .map(e => e.customercontactid)[0];
      }


      this.loadCustomerContact(_customerId, _customerContactId);
      this.projectForm.controls['projectid'].setValue(projectMaster.projectid);
      this.projectForm.controls['projectcode'].setValue(projectMaster.projectcode);
      this.projectForm.controls['projectname'].setValue(projectMaster.projectname);
      this.projectForm.controls['customerid'].setValue(_customerId);
      this.projectForm.controls['project_type'].setValue(projectMaster.project_type);
      this.projectForm.controls['projectlocation'].setValue(projectMaster.projectlocation);
      this.projectForm.controls['description'].setValue(projectMaster.description);
      this.projectForm.controls['active'].setValue(projectMaster.active);
    }
    this.SpinnerService.hide();
    this.projectModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }

  // mehod to load the active customer drop down list
  async loadActiveCustomer() {
    return await this.customerservice.GetActive().toPromise().then(res => res);
  }

  // method to load active customer contact drop down list
  oncustomerChanged(eve) {
    const selectedValue = eve.target.value;
    this.projectForm.controls['customerid'].setValue(selectedValue);
    this.loadCustomerContact(selectedValue, 0);
  }

  // method to load customer contact based on customer
  loadCustomerContact(customerId, customerContactId) {
    this.activeCustomerContactList = [];
    const customerInput: any = [];
    customerInput.push({ customerid: +customerId });
    this.customercontactservice.getContactByCustomerId(customerInput[0]).subscribe(res => {
      if (res.body !== undefined && res.body !== null && res.body[0] !== undefined && res.body[0] !== null) {
        if (JSON.parse(res.body[0]).length > 0) {
          this.activeCustomerContactListtmp = JSON.parse(res.body[0]);
          this.activeCustomerContactList = this.activeCustomerContactListtmp.filter(item => item.active === 1)
            .map(a => ({ customercontactid: a.customercontactid, name: a.name }));
        }
      }
      if (customerContactId > 0) {
        this.projectForm.controls['customercontactid'].setValue(customerContactId);
      } else {
        this.projectForm.controls['customercontactid'].setValue(0);
      }
    });
  }

  // method to selected customer contact value
  onCustomerContactChanged(eve) {
    const selectedContactId = eve.target.value;
    this.projectForm.controls['customercontactid'].setValue(selectedContactId);
  }

  // submit method to add and update the project master details

  Post(projectMaster: ProjectMaster) {
    this.submitted = true;
    this.userid = +localStorage.getItem('userid');
    if ((projectMaster.projectcode.trim() === undefined) || (projectMaster.projectcode.trim() === '')) {
      this.toastr.error('Project Code should not be empty');
      return;
    }
    if ((projectMaster.projectname.trim() === undefined) || (projectMaster.projectname.trim() === '')) {
      this.toastr.error('Project Name  should not be empty');
      return;
    }
    if (this.projectForm.valid) {
      if (this.valid()) {
        projectMaster.customercontactid = +projectMaster.customercontactid;
        projectMaster.customerid = +projectMaster.customerid;
        if (this.operation === 'add') {
          projectMaster.createdby = this.userid;
          projectMaster.active = 1;
          projectMaster.projectid = 0;
          this.projectMasterService.Post(projectMaster).subscribe(res => {
            if (res.body !== undefined && res.body !== null && res.body !== 0) {
              this.toastr.success('Data added successfully');
              this.projectModalRef.hide();
              this.loadExisitingProjectList();
              this.clearForm();
            } else {
              this.toastr.error('Project Already Exsist');
            }
          }, error => {
            this.toastr.error(error);
          });
        }

        if (this.operation === 'update') {
          projectMaster.updatedby = this.userid;
          if (projectMaster.active !== 0 && projectMaster.active !== 1) {
            let selectedActive: any;
            selectedActive = projectMaster.active;
            projectMaster.active = (selectedActive === true) ? 1 : 0;
          }
          this.projectMasterService.Put(projectMaster).subscribe(res => {
            if (res.body !== undefined && res.body !== null && res.body !== 0) {
              this.toastr.success('Data updated successfully');
              this.projectModalRef.hide();
              this.loadExisitingProjectList();
              this.clearForm();
            } else {
              this.toastr.error('Project Already Exsist');
            }
          }, error => {
            this.toastr.error(error);
          });

        }
      }
    }
    this.submitted = false;
  }

  // cancel button and control refresh method
  clearForm() {
    this.submitted = false;
    this.action = 'add';
    this.projectForm.reset();
    this.projectModalRef.hide();
  }

  // method to change the active status of the project
  ChangeActive(e) {
    if (e.currentTarget.checked) {
      this.projectForm.controls['active'].setValue(1);
    } else {
      this.projectForm.controls['active'].setValue(0);
    }
  }

  // function to activate or deactivate the mail template
  statusChange(item, option) {
    this.userid = +localStorage.getItem('userid');
    if (option === 'activate') {
      this.confmsg = 'activate';
      this.projectForm.value.active = 1;
      this.msg = 'Record activated successfully';
    } else {
      this.confmsg = 'deactivate';
      this.projectForm.value.active = 0;
      this.msg = 'Record deactivated successfully';
    }
    this.projectForm.value.projectid = item.projectid;
    this.projectForm.value.customerid = item.customerid;
    this.projectForm.value.customercontactid = item.customercontactid;
    this.projectForm.value.updatedby = this.userid;
    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.projectMasterService.Delete(this.projectForm.value).subscribe(
            (res) => {
              if (res.body !== 0) {
                this.toastr.success(this.msg);
                this.loadExisitingProjectList();
              }
            }, error => {
              this.toastr.error(error);
            });
        }
      });
  }

  // method to sort the grid columns
  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }


  // 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;
          }
        }
      });
    }
  }
  valid(): boolean {
    let retval = true;
    if (this.projectForm.get('customerid').value.toString() === '0') {
      this.toastr.error('Customer should be selected');
      retval = false;
    } if (this.projectForm.get('customercontactid').value.toString() === '0') {
      this.toastr.error('Customer Contact should be selected');
      retval = false;
    }
    return retval;
  }


}
