import { Component, OnInit , TemplateRef} from '@angular/core';
import { ProjectFollowup } from './projectfollowup';
import { ProjectfollowupService } from './projectfollowup.service';
import { ToastrService } from 'ngx-toastr';
import { FormGroup, FormBuilder, Validators, FormArray, FormControl, ValidatorFn } from '@angular/forms';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { MailtemplateService } from '../../masters/mailtemplate/mailtemplate.service';
import { MailTemplate } from '../../masters/mailtemplate/mailtemplate';
import { ProjectdefinitionmasterService } from '../projectdefinitionmaster/projectdefinitionmaster.service';
import { UserService } from '../../masters/user/user.service';
import { DialogService } from 'ng2-bootstrap-modal';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
@Component({
  selector: 'app-projectfollowup',
  templateUrl: './projectfollowup.component.html',
  styleUrls: ['./projectfollowup.component.css']
})
export class ProjectfollowupComponent implements OnInit {

  projectfollowupactive:any = [];
  projectfollowups: ProjectFollowup[] = [];
  projectfollowup: ProjectFollowup;
  projectfollowupsFull: ProjectFollowup[] = [];
  showallstatus = false;
  itemsPerPage = 10;
  p = 1;
  readOnly = false; add = false; edit = true; delete = true;
  showall = true;
  projectForm: FormGroup;
  operation: string;
  projectModalRef: BsModalRef;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };
  projectflowsearchText: string;
  mailTemplates: MailTemplate[] = [];
  projectdefinitions:any=[];
  userid=0;
  userlist: any[];
  _dropdownSettings: any;
  _userselectedItems: any = [];
  key = 'remaindertype';
  reverse = false;
  confmsg: string;
  deleteResult: boolean;
  constructor(
    private projectfollowupService :ProjectfollowupService,   
    private toastr: ToastrService,
    private formBuilder: FormBuilder,
    private modalService: BsModalService,
    private mailtemplateService: MailtemplateService,
    private projectdefinitionservice: ProjectdefinitionmasterService,
    private userService: UserService,
    private dialogService: DialogService,
    ) {
   }

  ngOnInit(): void {
    this.userid = +localStorage.getItem('userid');
    this.loadFollowupDetail();
    this.loadprojectdefinitionbyuserid();
    this.loadmailtemplate();
    this.loadUserMailid();
    this.projectForm = this.formBuilder.group({
      projectfollowupid: [''],
      remaindertype: ['', [Validators.required]],
      projectdefinitionid: ['', [Validators.required]],
      mailtemplateid: ['', [Validators.required]],
      emailcc: ['', [Validators.required]],
      remainderorder: ['', [Validators.required]],
      intervaltype: ['', [Validators.required]],
      followupinterval: ['', [Validators.required]],
      active: ['']
    });
  }
  loadFollowupDetail() {
    this.projectfollowups = [];
    this.projectfollowupactive = [];
    this.projectfollowupService.GetProjectFolowup().subscribe(res => {
      debugger;
      if(res[0] !== null && res[0] !== undefined && res[0] !== ""){
        this.projectfollowupsFull = JSON.parse(res[0]);
        this.projectfollowups = this.projectfollowupsFull;
        if (this.showallstatus === true) {
          if (this.projectfollowupsFull.length > 0) {
            this.projectfollowups = this.projectfollowupsFull.filter(s => s.active === 1 );
          } else {
            this.projectfollowups = [];
          }
        } else if (this.projectfollowupsFull.length > 0) {
          this.projectfollowups = this.projectfollowupsFull;
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }
  getactiveinactive(showallp) {
    this.projectfollowupactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.projectfollowupactive=this.projectfollowups.filter(x=>x.active==1);
      this.projectfollowups = [];
      this.projectfollowups = this.projectfollowupactive;
    } else {
      this.showall = true;
      this.projectfollowups = [];
      this.projectfollowups =this.projectfollowupsFull;
    }

  }
  cancelForm() {
    this.projectModalRef.hide();
    this._userselectedItems= [];
  }
  openProjectModal(template: TemplateRef<any>, type, stage: any) {
    this.projectflowsearchText = '';
    this.operation = type;
    if (type === 'update') {
      this.projectForm.controls['projectfollowupid'].setValue(stage.projectfollowupid);
      this.projectForm.controls['projectdefinitionid'].setValue(stage.projectdefinitionid);
      this.projectForm.controls['remaindertype'].setValue(stage.remaindertype);
      this.projectForm.controls['mailtemplateid'].setValue(stage.mailtemplateid);
      this.projectForm.controls['remainderorder'].setValue(stage.remainderorder);
      this.projectForm.controls['intervaltype'].setValue(stage.intervaltype);
      this.projectForm.controls['followupinterval'].setValue(stage.followupinterval);
      this.projectForm.controls['active'].setValue(stage.active);
      this.projectfollowup = stage;
      let _selectedItems = [];
      this._userselectedItems = [];
      debugger;
      _selectedItems = JSON.parse(stage.emailcc);

      // const emailfilter =  [];
      _selectedItems.forEach(element => {
        this._userselectedItems.push((this.userlist.filter(u => u.emailid === element)
          .map(i => ({ userid: i.userid, emailid: i.emailid })))[0]);
      });
    }
    if (type === 'add') {
      this.projectForm.controls['projectfollowupid'].setValue(0);
      this.projectForm.controls['projectdefinitionid'].setValue(0);
      this.projectForm.controls['remaindertype'].setValue('Select');
      this.projectForm.controls['mailtemplateid'].setValue(0);
      this.projectForm.controls['remainderorder'].setValue(1);
      this.projectForm.controls['intervaltype'].setValue(0);
      this.projectForm.controls['followupinterval'].setValue(1);
      this.projectForm.controls['emailcc'].setValue(0);
      this.projectForm.controls['active'].setValue(1);
    }
    this.projectModalRef = this.modalService.show(template, this.config);

    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }
  loadmailtemplate() {
    this.mailTemplates = [];
    this.mailtemplateService.GetActive().subscribe(res => {
      if (res !== undefined && res != null && res[0] !== undefined && res[0] != null) {
        if (JSON.parse(res[0]).length > 0) {
          this.mailTemplates = JSON.parse(res[0]);
        }
      }
    });
  }
  loadprojectdefinitionbyuserid(){
    const input = [];
    
        input.push({ userid: this.userid });
        this.projectdefinitions = [];
        this.projectdefinitionservice.getAllByUserId(input[0]).subscribe(res => {
            if (res.body[0] !== null && res.body[0] !== undefined) {
              this.projectdefinitions  = JSON.parse(res.body[0]);
            }
          }, error => { this.toastr.error('Error while getting data'); });
  }
  loadUserMailid() {
    this._dropdownSettings = {
      singleSelection: false,
      idField: 'userid',
      textField: 'emailid',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      itemsShowLimit: 7,
      allowSearchFilter: true
    };
    this.userService.GetActive().subscribe(res => {
      if (res !== undefined && res !== null && res[0] !== undefined && res[0] !== null) {
        if (JSON.parse(res[0]).length > 0) {
          let pmListTmp: any[];
          pmListTmp = JSON.parse(res[0]);
          this.userlist = pmListTmp.sort((a, b) => a.emailid.localeCompare(b.emailid));
          console.log( this.userlist)
        }
      }
    }
    );
  }
  SaveProject(projectfollowup: ProjectFollowup) {
    debugger;
     console.log(projectfollowup);
    let emailtmp;
    if (projectfollowup.emailcc.length > 0) {
      emailtmp = projectfollowup.emailcc;
      const eid = emailtmp.map(e => e.emailid);
      projectfollowup.emailcc = JSON.stringify(eid);
    } else {
      projectfollowup.emailcc = '';
    }
    projectfollowup.mailtemplateid = +projectfollowup.mailtemplateid;
    projectfollowup.projectdefinitionid = +projectfollowup.projectdefinitionid;
    if (this.operation === 'add') {
      projectfollowup.createdby = this.userid;
      this.projectfollowupService.PostProjectFollowup(projectfollowup).subscribe(res => {
        if (res.body !== undefined && res.body !== null && res.body > 0) {
          this.toastr.success('ProjectFollowup added successfully');
          this.cancelForm();
          this.loadFollowupDetail();
        } else {
          projectfollowup.emailcc = emailtmp;
          this.toastr.error('ProjectFollowup Already Exsist');
        }
      }, err => { this.toastr.error(err); });
    } else if (this.operation === 'update') {
      projectfollowup.updatedby = this.userid;

      this.projectfollowupService.PutProjectFollowup(projectfollowup).subscribe(res => {
        if (res.body !== undefined && res.body !== null && res.body > 0) {
          this.toastr.success('ProjectFollowup updated successfully');
          this.cancelForm();
          this.loadFollowupDetail();
        } else {
          projectfollowup.emailcc = emailtmp;
          this.toastr.error('ProjectFollowup Already Exsist');
        }
      }, err => { this.toastr.error(err); });
    }
  }
  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }
  onItemSelect(item: any) {
    //this.textBoxTocuhed = true;
    console.log(item);
    console.log(this._userselectedItems)
   // this._userselectedItems.push((this.userlist.filter(u => u.emailid === item)
   // .map(i => ({ userid: i.userid, emailid: i.emailid })))[0]);
  }
  onItemDeSelect(item: any) {
    //this.textBoxTocuhed = true;
    //this._userselectedItems.((this.userlist.filter(u => u.emailid === item)
   // .map(i => ({ userid: i.userid, emailid: i.emailid })))[0]);
  }
  OpenConfirmTemplate(projectfollowup, template: TemplateRef<any>) {
    if (projectfollowup.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.projectfollowup = projectfollowup;
          this.Delete();
        }
      });
  }
  Delete() {
    let msg;
    if (this.projectfollowup.active === 0) {
      this.projectfollowup.active = 1;
      msg = 'Record activated successfully';
    } else {
      this.projectfollowup.active = 0;
      msg = 'Record deactivated successfully';
    }
    this.projectfollowup.updatedby = this.userid;
    this.projectfollowupService.DeleteStageFollowup(this.projectfollowup).subscribe(res => {
      this.toastr.success(msg);
      // this.getAll();
   this.loadFollowupDetail();
    },
      error => { this.deleteResult = false; });
  }

}
