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 { Customercontact } from './customercontact';
import { CustomercontactService } from './customercontact.service';
import { CustomerService } from '../customer/customer.service';
import { Customer  } from '../customer/customer';
@Component({
    selector: 'app-customercontact',
    templateUrl: './customercontact.component.html',
    styleUrls: ['./customercontact.component.css']
})
export class CustomercontactComponent implements OnInit {
    sendMenuId: number;
    sendPageName = 'CustomerContact';
    // action rights
    _menuId: any;
    _actionRights: any;
    readOnly = false; add = false; edit = false; delete = false;
    customercontactForm: FormGroup;
    customercontacts: Customercontact[] = [];
    customercontactsactive: Customercontact[] = [];
    customercontact: Customercontact;
    deleteResult: boolean;
    postresult: boolean;
    putDResult: boolean;
    customercontactModalRef: BsModalRef;
    operation: string;
    userid: number;
    customercontactid: 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 = 'customercontact'; // set default
    reverse = false;
    actionRights: any;
    customerlist: Customer[];
    constructor(private router: Router, private toastr: ToastrService, private dialogService: DialogService,
        private formBuilder: FormBuilder, private modalService: BsModalService,
        private customercontactservice: CustomercontactService,
        private CustomerService: CustomerService) {
        // get rights for the logged in user for the particular component
        if (this.router.getCurrentNavigation().extras.state !== undefined) {
            localStorage.setItem('CustomerContact_menuid', this.router.getCurrentNavigation().extras.state.menuid);
            localStorage.setItem('CustomerContact_userRights', this.router.getCurrentNavigation().extras.state.action);
            this.actionRights = [];
            this.actionRights = this.router.getCurrentNavigation().extras.state.action;
        } else {
            this.actionRights = [];
            // this.actionRights = localStorage.getItem('MailTemplate_userRights');
            this.actionRights = localStorage.getItem('CustomerContact_userRights'); // new
        }
    }

    ngOnInit() {
        this.customercontactForm = this.formBuilder.group({
            customercontactid: [0],
            customerid: [0, [Validators.required]],
            address: [''],
            email: [''],
            contactnumber: [''],
            active: [''],
            iconnectcode: [0]
        });
        this.searchText = '';
        this.getAll();
        // for action rights
        this.GetCustomer();
        this.getUserRights();
    }

    getactiveinactive(showallp) {
        this.customercontactsactive = [];
        this.showall = showallp;
        this.showallstatus = showallp;
        if (this.showall === true) {
            this.showall = false;
            this.customercontacts.forEach(data => {
                if (data.active === 1) {
                    this.customercontactsactive.push(data);
                }
            });
            this.customercontacts = [];
            this.customercontacts = this.customercontactsactive;
        } else {
            this.showall = true;
            this.customercontacts = [];
            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.customercontactModalRef.hide();
    }

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


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

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

    Post(customercontact: Customercontact) {

        this.submitted = true;

      //  if ((customercontact.customerid === undefined)) {
         //   this.toastr.error('CustomerContact should not be empty');
         //   return;
      //  }

        if (customercontact.iconnectcode == null) {
            customercontact.iconnectcode = 0;
        }

        let msg = null;

        this.userid = +localStorage.getItem('userid');
       // customercontact.name = customercontact.name.trim(); // new
        customercontact.customerid = +customercontact.customerid; // new
        if(customercontact.contactnumber){
            customercontact.contactnumber = customercontact.contactnumber.toString(); 
            }
        if (this.operation === 'add') {

            customercontact.createdby = this.userid;
            msg = 'Record Added Successfully';
            console.log(customercontact);
            this.customercontactservice.Post(customercontact).subscribe(res => {
                console.log(res);
                if (res.status === 200) {
                    if (res !== undefined) {
                        if (res.body !== 0) {
                            this.customercontactModalRef.hide();
                            this.getAll();
                            this.toastr.success('Data added successfully');
                           // this.clearForm(); // new
                        } else { this.toastr.warning('Record already exists.'); }
                    }
                }
            },
                error => {
                    this.toastr.error('Error while doing the operation');
                    this.postresult = false;
                });
        } else if (this.operation = 'update') {
            customercontact.updatedby = this.userid;
            msg = 'Record updated successfully';
            console.log(customercontact);
            this.customercontactservice.Put(customercontact).subscribe(res => {
                if (customercontact.iconnectcode == null) {
                    customercontact.iconnectcode = 0;
                }
                if (res.status === 200) {
                    if (res !== undefined) {
                        if (res.body !== 0) {
                            this.customercontactModalRef.hide();
                           // this.GetCustomer();
                            this.getAll();                            
                            this.toastr.success('Data updated successfully');
                           // this.clearForm(); // new
                        } 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.checked) {
            this.customercontactForm.controls['active'].setValue(1);
        } else {
            this.customercontactForm.controls['active'].setValue(0);
        }
    }

    OpenConfirmTemplate(customercontact) {
        if (customercontact.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.customercontact = customercontact;
                    this.Delete();
                }
            });
    }

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

    }

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

    openCustomerContactModal(template: TemplateRef<any>, type, customercontact?: Customercontact) {

        this.operation = type;

        if (type === 'update') {
            this.customercontactForm.controls['customercontactid'].setValue(customercontact.customercontactid);
            this.customercontactForm.controls['customerid'].setValue(customercontact.customerid); // newline
           // this.customercontactForm.controls['name'].setValue(customercontact.name);  // new
            this.customercontactForm.controls['address'].setValue(customercontact.address);
            this.customercontactForm.controls['email'].setValue(customercontact.email);
            this.customercontactForm.controls['contactnumber'].setValue(customercontact.contactnumber);
            this.customercontactForm.controls['iconnectcode'].setValue(customercontact.iconnectcode);
            this.customercontactForm.controls['active'].setValue(customercontact.active);
            this.customercontact = customercontact;
        }
        if (type === 'add') {
            this.customercontactForm.controls['customercontactid'].setValue(0);
            this.customercontactForm.controls['customerid'].setValue(0); // newline
          //  this.customercontactForm.controls['name'].setValue('');  // new
            this.customercontactForm.controls['address'].setValue('');
            this.customercontactForm.controls['email'].setValue('');
            this.customercontactForm.controls['contactnumber'].setValue('');
            this.customercontactForm.controls['iconnectcode'].setValue(0);
            this.customercontactForm.controls['active'].setValue(1);
        }
        this.customercontactModalRef = this.modalService.show(template, this.config);

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

    }
    GetCustomer() {
        this.customerlist = [];
        this.CustomerService.GetActive().subscribe(
          res => {
            if (res[0] != null && res[0] !== undefined) {
              this.customerlist = JSON.parse(res[0]);
            }
          });
      }
}
