import { Component, OnInit, TemplateRef, ViewChild, ElementRef } from '@angular/core';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { FormGroup, FormBuilder, Validators, FormArray, FormControl, ValidatorFn } from '@angular/forms';
import { DialogService } from 'ng2-bootstrap-modal';
import { ProjectMasterService } from '../../masters/projectmaster/projectmaster.service';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { MailtemplateService } from '../../masters/mailtemplate/mailtemplate.service';
import { MailTemplate } from '../../masters/mailtemplate/mailtemplate';
import { UserService } from '../../masters/user/user.service';
import { UnitService } from '../../masters/unit/unit.service';
import { ServerService } from '../../masters/server/server.service';
import { ProjectDefinition, StageFollowup } from '../projectconfiguration/projectdefinition';
import { ProjectConfigurationService } from './projectconfiguration.service';
import { CustomercontactService } from 'src/app/masters/customercontact/customercontact.service';
import { WorkFlow } from 'src/app/workflowconfiguration/workflow/workflow';
import { Projectdefinitionmaster } from '../projectdefinitionmaster/projectdefinitionmaster';
import { WorkflowconfigurationService } from '../../workflowconfiguration/workflowconfiguration/workflowconfiguration.service';
import * as mermaid from 'mermaid';
import * as mermaidAPI from 'mermaid';
import * as $ from 'jquery';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { NgxSpinnerService } from 'ngx-spinner';

@Component({
  selector: 'app-projectconfiguration',
  templateUrl: './projectconfiguration.component.html',
  styleUrls: ['./projectconfiguration.component.css']
})
export class ProjectconfigurationComponent implements OnInit {
  @ViewChild('mermaid', { static: false }) mermaidDiv: ElementRef;
  @ViewChild('mermaidfinish', { static: false })
  private _mermaidFinishDiv: ElementRef;
  public get mermaidFinishDiv(): ElementRef {
    return this._mermaidFinishDiv;
  }
  public set mermaidFinishDiv(value: ElementRef) {
    this._mermaidFinishDiv = value;
  }
  // variables for environment
  displayStep1 = true;
  displayStep2 = false;
  displayStep3 = false;
  displayStep4 = false;
  displayStep5 = false;

  // list variables
  projectListActive: any = [];
  contactListActive: any = [];
  projectManagerListActive: any = [];
  unitListActive: any = [];
  FTPServerListActive: any = [];
  fileServerListActive: any = [];

  // formgroup
  projectConfigurationForm: FormGroup;
  projectDefinitions: ProjectDefinition[];
  projectDefinition: ProjectDefinition;
  submitted = false;

  // other variables
  action: string;

  // local storage variables
  userid: number;
  auto_job_creation1 = false;
  auto_job_creation0 = false;
  projectListTmp: any = [];
  projectListInPopup: any = [];
  searchText: string;
  searchText2: string;
  // pop up variables
  projectDefinitionModalRef: BsModalRef;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };
  userMappedProjectDefListTmp: any;
  userMappedProjectDefList: any;
  n = 1;
  itemsPerPage = 10;
  projectDefinitionId: number;
  projectDefinitionIdFromMaster: number;
  WorkFlow: WorkFlow[] = [];
  projectdefinitionmst: Projectdefinitionmaster[] = [];
  PsearchText: string;
  tatflowstagefollowup: any = [];
  Hours = 'Hours';
  Days = 'Days';
  Weeks = 'Weeks';

  selectedWorkflowId: number;
  selectedProjectDefinitionId: number;
  selectedWorkflowName: string;
  graphDefinitionString = '';
  dropdownSettings = {};
  stageForm: FormGroup;
  operation: string;
  mailTemplates: MailTemplate[] = [];
  mailList: any[];
  userlist: any[];
  _userselectedItems: any = [];
  textBoxTocuhed: boolean;
  _dropdownSettings: any;
  _mailGroupList: any = [];
  stageModalRef: BsModalRef;
  type = '';
  projectDefinitionDetails: any;
  iscurrent: boolean;
  workFlowData: any;
  tatFlowList: any;
  deleteResult: boolean;
  stagefollowupactive: StageFollowup[] = [];
  stagefollowups: StageFollowup[] = [];
  stagefollowup: StageFollowup;

  readOnly = false; add = false; edit = true; delete = true;
  showall = true;
  showallstatus = false;
  key = 'remaindertype';
  reverse = false;
  confmsg: string;
  p = 1;
  actionRights: any; //
  _currentdefinitionid = 0;
  tatflowsummary: any;
  stagefollowupsFull: StageFollowup[] = [];
  tathours = 0;
  tattype = '';
  _currentstageid = 0;
  _currentstage = '';
  stageflowsearchText: string;
  stagefollowupindex = 0;
  workflowcalled = false;
  q=1;
  constructor(
    private projectMasterService: ProjectMasterService,
    private router: Router,
    private toastr: ToastrService,
    private formBuilder: FormBuilder,
    private dialogService: DialogService,
    private userService: UserService,
    private unitService: UnitService,
    private serverService: ServerService,
    private projectConfigurationService: ProjectConfigurationService,
    private customercontactservice: CustomercontactService,
    private modalService: BsModalService,
    private workflowconfigurationService: WorkflowconfigurationService,
    private mailtemplateService: MailtemplateService,
    private SpinnerService: NgxSpinnerService,
  ) {
    const navigation = this.router.getCurrentNavigation();
    const state = navigation.extras.state as {
      projectdefinitionid: any;
    };
    if (state !== null && state !== undefined) {
      this.projectDefinitionIdFromMaster = state.projectdefinitionid;
    }
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Projectconfiguration_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Projectconfiguration_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Projectconfiguration_userRights');
    }
  }

  ngOnInit() {
    this.stageForm = this.formBuilder.group({
      stagefollowupid: [''],
      stageid: [''],
      remaindertype: ['', [Validators.required]],
      mailtemplateid: ['', [Validators.required]],
      emailcc: ['', [Validators.required]],
      remainderorder: ['', [Validators.required]],
      intervaltype: ['', [Validators.required]],
      followupinterval: ['', [Validators.required]],
      active: ['']
    });
    this.projectConfigurationForm = this.formBuilder.group({
      projectdefinitionid: [''],
      project_subtitle: ['', [Validators.required]],
      projectid: ['', [Validators.required]],
      projectmanager: ['', [Validators.required]],
      jobno_prefix: ['', [Validators.required]],
      jobno_length: [0, [Validators.required]],
      // default_unit: ['', [Validators.required]],
      default_unit: [''],
      approx_volume: [0],
      root_directory: ['', [Validators.required]],
      // fileserver: ['', [Validators.required]],
      fileserver: [''],
      ftpserver: [''],
      customer_contact: [''],
      active: [''],
      project_theam: [''],
      auto_job_creation: ['']
    });

    this.action = 'add';
    this.showallstatus = false;
    this.loadActiveProjectList();
    this.loadActiveCustomerContact();
    this.loadActiveProjectManager();
    this.loadActiveUnit();
    this.loadActiveServer();
    this.loadWorkflow();
    this.loadProjectDefinitionMaster();
    this.loadmailtemplate();
    this.loadUserMailid();
    this.GetTATdetails();
    if (this.projectDefinitionIdFromMaster !== undefined && this.projectDefinitionIdFromMaster !== null &&
      this.projectDefinitionIdFromMaster > 0) {
      this.loadProjectDefinitionInEditMode(this.projectDefinitionIdFromMaster, localStorage.getItem('userid'));
    } else {
      this.auto_job_creation0 = true;
      this.projectConfigurationForm.controls['projectid'].setValue(0);
      this.projectConfigurationForm.controls['projectmanager'].setValue(0);
      this.projectConfigurationForm.controls['customer_contact'].setValue(0);
      this.projectConfigurationForm.controls['fileserver'].setValue(0);
      this.projectConfigurationForm.controls['ftpserver'].setValue(0);
      this.projectConfigurationForm.controls['default_unit'].setValue(0);
      this.projectConfigurationForm.controls['project_theam'].setValue(0);
    }
  }
  loadProjectDefinition() {
    this.displayStep1 = true;
    this.displayStep2 = false;
    this.displayStep3 = false;
    this.displayStep4 = false;
  }
  loadWorkFlowMapping(stepper) {
    if (this.projectDefinitionId > 0) {
      this.displayStep1 = false;
      this.displayStep2 = true;
      this.displayStep3 = false;
      this.displayStep4 = false;
      this._currentstage = '';
      this.stagefollowups = [];
      this.stagefollowupsFull = [];
      const item = [];
      item.push({ projectdefinitionid: this.projectDefinitionId, project_subtitle: this.selectedWorkflowName });
      // if (this.workflowcalled === false) {
        // this.loadFlowChart(item[0], 'project');
        if (stepper) {
          if (stepper.selected.state === 'projectDefinition') {
            stepper.next();
          }
        }
        // console.log('checking 1..');
        this.loadFlowChart(item[0], 'project');
      // }
    } else {
      this.toastr.warning('Project definition should be selected');
    }
  }
  async loadStageFollowup() {

    if (this.projectDefinitionId > 0) {
      this.displayStep1 = false;
      this.displayStep2 = false;
      this.displayStep3 = true;
      this.displayStep4 = false;
      this._currentstage = '';
      this.stageflowsearchText = '';
      if (this.type === 'master') {
        await this.loadStageWorkFlow(this.selectedWorkflowId);
      } else if (this.type === 'project') {
        await this.loadStageWorkFlow(this.selectedProjectDefinitionId);
      }

      if (this.tatflowstagefollowup.length) {
        this._currentstageid = this.tatflowstagefollowup[0].stageid;
        this._currentstage = this.tatflowstagefollowup[0].stagename_alias;
        this.loadFollowupDetail(this._currentstageid);
      }
    } else {
      this.toastr.warning('Project definition should be selected');
    }
  }
  // method to load active project details
  loadActiveProjectList() {
    this.projectListActive = [];
    this.projectMasterService.getActiveProject().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.projectListActive = this.projectListTmp
            .map(i => ({ projectid: i.projectid, projectname: i.projectname + '(' + i.projectcode + ')' }));
        }
      }
    });
  }

  // method to load active customer contact details
  loadActiveCustomerContact() {
    this.contactListActive = [];
    this.customercontactservice.GetActive().subscribe(res => {
      if (res !== undefined && res !== null && res[0] !== undefined && res[0] !== null) {
        if (JSON.parse(res[0]).length > 0) {
          let contactListTmp: any[];
          contactListTmp = JSON.parse(res[0]);
          this.contactListActive = contactListTmp.map(i => ({ customercontactid: i.customercontactid, name: i.name }));
        }
      }
    });
  }

  // method to load pm role mapped user list
  loadActiveProjectManager() {
    this.projectManagerListActive = [];
    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.projectManagerListActive = pmListTmp
            .map(i => ({ projectmanager: i.userid, projectmanagername: i.firstname }));
        }
      }
    });
  }

  // method to load active unit master
  loadActiveUnit() {
    this.unitListActive = [];
    this.unitService.GetActive().subscribe(res => {
      if (res !== undefined && res !== null && res[0] !== undefined && res[0] !== null) {
        if (JSON.parse(res[0]).length > 0) {
          let unitListTmp: any[];
          unitListTmp = JSON.parse(res[0]);
          this.unitListActive = unitListTmp.map(i => ({ default_unit: i.unitid, unitname: i.unitname }));
        }
      }
    });
  }

  loadActiveServer() {
    this.FTPServerListActive = [];
    this.fileServerListActive = [];
    this.serverService.GetActive().subscribe(res => {
      if (res !== undefined && res !== null && res[0] !== undefined && res[0] !== null) {
        if (JSON.parse(res[0]).length > 0) {
          let serverListTmp: any[];
          serverListTmp = JSON.parse(res[0]);
          this.fileServerListActive = serverListTmp.filter(i => i.servertypeid === 1)
            .map(i => ({ fileserver: i.serverid, fileservername: i.server }));
          this.FTPServerListActive = serverListTmp.filter(i => i.servertypeid === 2)
            .map(i => ({ ftpserver: i.serverid, ftpservername: i.server }));
        }
      }
    });
  }
  loadWorkflow() {
    this.WorkFlow = [];
    this.projectConfigurationService.GetWorkflow().subscribe(res => {
      if (res !== undefined && res !== null && res[0] !== undefined && res[0] !== null) {
        if (JSON.parse(res[0]).length > 0) {
          this.WorkFlow = JSON.parse(res[0]);
        }
      }
    });
  }

  loadProjectDefinitionMaster() {
    this.projectdefinitionmst = [];
    this.projectConfigurationService.GetProjectWorkflowDef().subscribe(
      res => {
        if (res !== undefined && res !== null && res[0] !== undefined && res[0] !== null) {
          if (JSON.parse(res[0]).length > 0) {
            this.projectdefinitionmst = JSON.parse(res[0]);
          }
        }
      }
    );
  }
  get g() { return this.projectConfigurationForm.controls; }

  Post(projectDefinition: ProjectDefinition) {
    this.submitted = true;
    this.userid = +localStorage.getItem('userid');
    if (this.action === 'add') {
      this.projectConfigurationForm.controls['projectdefinitionid'].setValue(0);
      this.projectConfigurationForm.controls['active'].setValue(1);
    }
    if (this.projectConfigurationForm.valid) {
      if (this.projectConfigurationForm.get('projectid').value === 0) {
        this.toastr.error('Project Name should be selected');
        return;
      }
      // if (this.projectConfigurationForm.get('customer_contact').value === 0) {
      //   this.toastr.error('Customer Contact should be selected');
      //   return;
      // }
      if (this.projectConfigurationForm.get('projectmanager').value === 0) {
        this.toastr.error('Project Manager should be selected');
        return;
      }
      if (this.projectConfigurationForm.get('default_unit').value === 0) {
        this.toastr.error('Default Unit should be selected');
        return;
      }
      if (this.projectConfigurationForm.get('fileserver').value === 0) {
        this.toastr.error('File Server should be selected');
        return;
      }
      if (this.projectConfigurationForm.get('ftpserver').value === 0) {
        this.toastr.error('FTP server should be selected');
        return;
      }
      if (this.projectConfigurationForm.get('project_theam').value === 0) {
        this.toastr.error('Project Theme should be selected');
        return;
      }
      if (projectDefinition.auto_job_creation === null) {
        if (this.auto_job_creation1 === true) {
          projectDefinition.auto_job_creation = 1;
        } else {
          projectDefinition.auto_job_creation = 0;
        }
      }
      if (projectDefinition.auto_job_creation.toString() === '') {
        if (this.auto_job_creation1 === true) {
          projectDefinition.auto_job_creation = 1;
        } else {
          projectDefinition.auto_job_creation = 0;
        }
      }
      projectDefinition.fileserver = +projectDefinition.fileserver;
      projectDefinition.ftpserver = +projectDefinition.ftpserver;
      projectDefinition.projectid = +projectDefinition.projectid;
      projectDefinition.projectmanager = +projectDefinition.projectmanager;
      projectDefinition.customer_contact = +projectDefinition.customer_contact;
      projectDefinition.default_unit = +projectDefinition.default_unit;
      if (this.action === 'add') {
       

        projectDefinition.projectdefinitionid = 0;
        projectDefinition.active = 1;
        projectDefinition.createdby = this.userid;
        this.projectConfigurationService.Post(projectDefinition).subscribe(res => {
          if (res.body !== undefined && res.body !== null && res.body > 0) {
            this.toastr.success('Project information added successfully');
            this.clearForm();
          } else {
            this.toastr.error('Project Subtitle  Already Exsist');
          }
        }, err => { this.toastr.error(err); });
      }
      if (this.action === 'update') {
        projectDefinition.projectdefinitionid = this.projectDefinitionId;
        projectDefinition.updatedby = this.userid;
        this.projectConfigurationService.Put(projectDefinition).subscribe(res => {
          if (res.body !== undefined && res.body !== null && res.body > 0) {
            this.toastr.success('Project information updated successfully');
            this.clearForm();
          } else {
            this.toastr.error('Project Subtitle  Already Exsist');
          }
        }, err => { this.toastr.error(err); });
      }
    }
  }
  // cancel button and control refresh method
  clearForm() {
    this.submitted = false;
    this.action = 'add';
    this.projectConfigurationForm.reset();
    this.auto_job_creation0 = true;
    this.projectConfigurationForm.controls['projectid'].setValue(0);
    this.projectConfigurationForm.controls['projectmanager'].setValue(0);
    this.projectConfigurationForm.controls['customer_contact'].setValue(0);
    this.projectConfigurationForm.controls['fileserver'].setValue(0);
    this.projectConfigurationForm.controls['ftpserver'].setValue(0);
    this.projectConfigurationForm.controls['default_unit'].setValue(0);
    this.projectConfigurationForm.controls['project_theam'].setValue(0);
    this.projectDefinitionId = 0;
    this.selectedWorkflowName = '';
    this.selectedProjectDefinitionId = 0;
  }

  // method to search the user mapped project subtitle
  async openSearchWindow(template: TemplateRef<any>) {
    this.userid = +localStorage.getItem('userid');
    this.SpinnerService.show();
    //  let input = [];
    this.userMappedProjectDefList = [];
    // input.push({ userid: this.userid });
    this.searchText = '';
    let _projectDefinitionMapped: any;
    _projectDefinitionMapped = await this.userMappedProjectDefinition(this.userid);
    // this.projectConfigurationService.getByUserId(input[0]).subscribe(res => {
    if (_projectDefinitionMapped !== undefined && _projectDefinitionMapped !== null &&
      _projectDefinitionMapped[0] !== undefined && _projectDefinitionMapped[0] !== null) {
      if (JSON.parse(_projectDefinitionMapped[0]).length > 0) {
        this.userMappedProjectDefListTmp = JSON.parse(_projectDefinitionMapped[0]);
        this.userMappedProjectDefList = this.userMappedProjectDefListTmp.map(i => ({
          projectdefinitionid: i.projectdefinitionid,
          project_subtitle: i.project_subtitle, projectname: i.projectname
        }));
      }
    }
    // }, err => { this.toastr.error(err); });

    if (this.projectListTmp.length > 0) {
      this.projectListInPopup = this.projectListTmp.map(j => ({
        projectid: j.projectid,
        projectname: j.projectname + '(' + j.projectcode + ')'
      }));
    }
    this.projectDefinitionModalRef = this.modalService.show(template, this.config);
    this.SpinnerService.hide();
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }

  // method to bind the project definition details
  onSearchClick(item) {
    this.projectDefinitionId = 0;
    const tmpList = this.userMappedProjectDefListTmp.filter(i => i.projectdefinitionid === item.projectdefinitionid);
    this.selectedWorkflowName = item.project_subtitle;
    if (tmpList.length > 0) {
      this.projectDefinitionId = item.projectdefinitionid;
      this.projectConfigurationForm.controls['project_subtitle'].setValue(tmpList[0].project_subtitle);
      this.projectConfigurationForm.controls['projectid'].setValue(tmpList[0].projectid);
      this.projectConfigurationForm.controls['customer_contact'].setValue(tmpList[0].customer_contact);
      this.projectConfigurationForm.controls['projectmanager'].setValue(tmpList[0].projectmanager);
      this.projectConfigurationForm.controls['jobno_prefix'].setValue(tmpList[0].jobno_prefix);
      this.projectConfigurationForm.controls['jobno_length'].setValue(tmpList[0].jobno_length);
      this.projectConfigurationForm.controls['approx_volume'].setValue(tmpList[0].approx_volume);
      this.projectConfigurationForm.controls['root_directory'].setValue(tmpList[0].root_directory);
      this.projectConfigurationForm.controls['default_unit'].setValue(tmpList[0].default_unit);
      this.projectConfigurationForm.controls['fileserver'].setValue(tmpList[0].fileserver);
      this.projectConfigurationForm.controls['ftpserver'].setValue(tmpList[0].ftpserver);
      this.projectConfigurationForm.controls['active'].setValue(tmpList[0].active);
      this.auto_job_creation1 = false;
      this.auto_job_creation0 = false;
      if (tmpList[0].auto_job_creation === 1) {
        this.auto_job_creation1 = true;
      } else {
        this.auto_job_creation0 = true;
      }
      this.action = 'update';
      this.projectConfigurationForm.controls['project_theam'].setValue(tmpList[0].project_theam);
    }
    if(this.projectDefinitionModalRef){
      this.projectDefinitionModalRef.hide();
    }
  }

  // method to bind the search grid on project get selected
  onProjectChange(eve) {
    this.userMappedProjectDefList = [];
    let selectedProjectId: number;
    selectedProjectId = +eve.target.value;
    if(selectedProjectId > 0) {
      this.userMappedProjectDefList = this.userMappedProjectDefListTmp.filter(m => m.projectid === selectedProjectId).map(i => ({
        projectdefinitionid: i.projectdefinitionid,
        project_subtitle: i.project_subtitle, projectname: i.projectname
      }));
    } else {
      this.userMappedProjectDefList = this.userMappedProjectDefListTmp.map(i => ({
        projectdefinitionid: i.projectdefinitionid,
        project_subtitle: i.project_subtitle, projectname: i.projectname
      }));
    }
  }

  async userMappedProjectDefinition(userId) {
    const inputData = [];
    inputData.push({
      userid: userId
    });
    return await this.projectConfigurationService.getByUserId(inputData[0]).toPromise().then(res => res.body);
  }

  async loadProjectDefinitionInEditMode(projectDefinitionId, userId) {
    let _projectDefinitionMapped: any;
    _projectDefinitionMapped = await this.userMappedProjectDefinition(+userId);
    if (_projectDefinitionMapped !== undefined && _projectDefinitionMapped !== null &&
      _projectDefinitionMapped[0] !== undefined && _projectDefinitionMapped[0] !== null) {
      if (JSON.parse(_projectDefinitionMapped[0]).length > 0) {
        this.userMappedProjectDefListTmp = JSON.parse(_projectDefinitionMapped[0]);
        const data = [];

        data.push({ projectdefinitionid: projectDefinitionId });
        this.onSearchClick(data[0]);
      }
    }
  }

  async loadStageWorkFlow(deffid: number) {
    this.tatflowstagefollowup = [];
    const input: any = [];
    if (this.type === 'project') {
      input.push({ projectdefinitionid: deffid, mode: 'projdefstage' });
    } else {
      input.push({ workflowdefinitionid: deffid, mode: 'projworkflowdefstage' });
    }
    await this.projectConfigurationService.GetStageFolowup(input[0]).toPromise().then(
      res => {
        if (res !== undefined && res !== null && res.body[0] !== undefined && res.body[0] !== null) {
          this.tatflowstagefollowup = JSON.parse(res.body[0]);
        }
      }, err => { this.toastr.error(err); });
  }
  // method to load flowchart for the selected workflowid
  async loadFlowChart(item, type) {
    this.workflowcalled = true;
    this.selectedWorkflowId = 0;
    this.selectedProjectDefinitionId = 0;
    this.selectedWorkflowName = '';
    this.type = type;
    if (this.type === 'master') {
      this.iscurrent = false;
      if (item.workflowid !== undefined && item.workflowid !== null && item.workflowid > 0) {
        // this.projectDefinitionId = item.projectdefinitionid; 
        this.selectedWorkflowId = +item.workflowid;
        this.selectedWorkflowName = item.workflowname;
        let resultChart = [];
        resultChart = await this.loadWorkFlowChart(item.workflowid);
        if (resultChart !== undefined && resultChart !== null && resultChart[0] !== undefined && resultChart[0] !== null) {
          let result = '';
          result = JSON.parse(resultChart[0]);
          this.flowChartRender(result, 'mermaid');
        } else {
          this.graphDefinitionString = '';
        }
      } else {
        this.clearMermaidDiv('mermaid');
      }
    }
    if (this.type === 'project') {
      const inputFlowChartData = [];
      if (item.projectdefinitionid !== undefined && item.projectdefinitionid !== null && item.projectdefinitionid > 0) {
        this.selectedProjectDefinitionId = item.projectdefinitionid;
        this.selectedWorkflowName = item.project_subtitle;
        inputFlowChartData.push({ projectdefinitionid: this.selectedProjectDefinitionId });
        this.projectConfigurationService.getByIdProjectDefWorkflow(inputFlowChartData[0]).subscribe(async (response) => {
          if (response.body !== undefined && response.body !== null && response.body[0] !== undefined && response.body[0] !== null) {
            if (JSON.parse(response.body[0]).length > 0) {
              this.iscurrent = true;
              this.workFlowData = JSON.parse(response.body[0]);
              let projectFlowChart = [];
              projectFlowChart = await this.loadProjectFlowChart(item.projectdefinitionid);
              if (projectFlowChart !== undefined && projectFlowChart !== null && projectFlowChart[0] !== undefined
                && projectFlowChart[0] !== null) {
                let result = '';
                result = JSON.parse(projectFlowChart[0]);
                this.graphDefinitionString = result;
                this.flowChartRender(result, 'mermaid');
              } else {
                this.graphDefinitionString = '';
              }
            } else {
              this.clearMermaidDiv('mermaid');
            }
          }
        }, err => { this.toastr.error('Error in getting Workflow records'); });
      }
    }
  }

  // method to bind flow chart in the mermaid div
  flowChartRender(result, node) {
    this.SpinnerService.show();
    result = result.replace(/\^ /g, '\n');
    result = result.replace(/\^/g, '\n');
    result = result.replace(/\\n/g, '\n');
    mermaidAPI.initialize({ startOnLoad: false, theme: 'forest' });

    // mermaid.initialize({ theme: 'forest' });
    let graphDefinition = '';
    graphDefinition = 'graph TB\n' + result;
    this.graphDefinitionString = graphDefinition;
    if (node === 'mermaid') {
      const element: any = this.mermaidDiv.nativeElement;
      $('#mermaid').text(graphDefinition);
      element.innerHTML = '';
      if (result !== '') {
        try {
          const parseable = mermaidAPI.parse(graphDefinition);
          if (parseable === undefined) {
            mermaidAPI.render('graphDiv', graphDefinition, (svgCode, bindFunctions) => {
              element.innerHTML = svgCode;
            });

          } else {
            this.toastr.error('WorkFlow chart is not well formed');
          }
        } catch (e) {
          this.toastr.error('WorkFlow chart is not well formed');

        }
      } else {
        this.toastr.error('WorkFlow chart is not well formed');
      }
      this.SpinnerService.hide();
    }
    if (node === 'mermaidfinish') {
      const element: any = this.mermaidFinishDiv.nativeElement;
      $('#mermaidfinish').text(graphDefinition);
      element.innerHTML = '';
      if (result !== '') {
        try {
          const parseable = mermaidAPI.parse(graphDefinition);
          if (parseable === undefined) {
            mermaidAPI.render('graphDiv2', graphDefinition, (svgCode, bindFunctions) => {
              element.innerHTML = svgCode;
            });
          } else {
            this.toastr.error('WorkFlow chart is not well formed');
          }
        } catch (e) {
          this.toastr.error('WorkFlow chart is not well formed');
        }
      } else {
        this.toastr.error('WorkFlow chart is not well formed');
      }
    }
    this.SpinnerService.hide();
  }

  // method to download flow chart
  downloadflowchart(node, workflowName) {
    const s = document.getElementById(node);
    if (s != null && s !== undefined) {
      this.SpinnerService.show();
      const image = new Image();
      const xml = new XMLSerializer().serializeToString(s);
      image.src = 'data:image/svg+xml;base64,' + window.btoa(xml);
      image.onload = function () {
        const canvas = document.createElement('canvas');
        canvas.width = $($('#' + node)[0]).width();
        canvas.height = $($('#' + node)[0]).height();
        const context = canvas.getContext('2d');
        context.drawImage(image, 0, 0);
        const a = document.createElement('a');
        a.download = workflowName + '.png';
        a.href = canvas.toDataURL('image/png');
        document.body.appendChild(a);
        a.click();
      };
      this.SpinnerService.hide();
    }
  }
  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));
        }
      }
    }
    );
  }
  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]);
        }
      }
    });
  }
  onItemSelect(item: any) {
    this.textBoxTocuhed = true;
  }
  onItemDeSelect(item: any) {
    this.textBoxTocuhed = true;
  }
  cancelForm() {
    this.stageModalRef.hide();
    this._userselectedItems = [];
  }
  openStageModal(template: TemplateRef<any>, type, stage: any) {
    this.stageflowsearchText = '';
    this.operation = type;

    if (type === 'update') {
      this.stageForm.controls['stagefollowupid'].setValue(stage.stagefollowupid);
      this.stageForm.controls['remaindertype'].setValue(stage.remaindertype);
      this.stageForm.controls['mailtemplateid'].setValue(stage.mailtemplateid);
      // this.stageForm.controls['emailid'].setValue(stage.);
      this.stageForm.controls['remainderorder'].setValue(stage.remainderorder);
      this.stageForm.controls['intervaltype'].setValue(stage.intervaltype);
      this.stageForm.controls['followupinterval'].setValue(stage.followupinterval);
      this.stageForm.controls['active'].setValue(stage.active);
      this.stageForm.controls['stageid'].setValue(stage.stageid);

      this.stagefollowup = stage;
      let _selectedItems = [];
      this._userselectedItems = [];
      _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]);
      });
      // let reduced: any;
      //   _selectedItems.forEach(element => {
      //     reduced = this.userlist.filter(u => u.emailid === element).reduce(function(filtered, option) {
      //      var someNewValue = { userid: option.userid, emailid: option.emailid };
      //      filtered.push(someNewValue);
      //      // this._userselectedItems = filtered;
      //   return filtered;
      // }, [] ); this._userselectedItems.push(reduced[0]); });
    }
    if (type === 'add') {
      this.stageForm.controls['stagefollowupid'].setValue(0);
      this.stageForm.controls['remaindertype'].setValue('Select');
      this.stageForm.controls['mailtemplateid'].setValue(0);
      this.stageForm.controls['emailcc'].setValue(0);
      this.stageForm.controls['remainderorder'].setValue(1);
      this.stageForm.controls['intervaltype'].setValue(0);
      this.stageForm.controls['followupinterval'].setValue(1);
      this.stageForm.controls['active'].setValue(1);
      this.stageForm.controls['stageid'].setValue(stage.stageid);
      // _userselectedItems
      // this.stageForm.patchValue({
      //   stagefollowupid:'',
      // });
      // this.stageForm.value.stagefollowupid = 0;
    }
    this.stageModalRef = this.modalService.show(template, this.config);

    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
    this.stagedetailBind(stage.stageid, stage.stagename_alias);

  }
  loadProjectDefinitionFinish() {
    this.clearMermaidDiv('mermaid');
    if (this.projectDefinitionId > 0) {
      this.displayStep1 = false;
      this.displayStep2 = false;
      this.displayStep3 = false;
      this.displayStep4 = true;
      const input = [];
      this.tatflowsummary = [];
      input.push({ projectdefinitionid: this.projectDefinitionId });  // projectDefinitionId
      this.projectConfigurationService.getByIdWithMasterValue(input[0]).subscribe(async (res) => {
        if (res.body !== undefined && res.body !== null && res.body[0] !== undefined && res.body[0] !== null) {
          const data = JSON.parse(res.body[0]);
          this.projectDefinitionDetails = data[0];
          //  if (this.workFlowData !== undefined && this.workFlowData !== null && this.workFlowData.length > 0) {
          if (this.iscurrent) { // current project flow
            this.tatFlowList = [];
            //  this.projectConfigurationService.getCurrentFlowProject(input[0]).subscribe(async (response) => {
            //  if (response.body !== undefined && response.body !== null && response.body[0] !== undefined
            //   && response.body[0] !== null) {
            //  if (JSON.parse(response.body[0]).length > 0) {
            //  this.tatflowsummary = JSON.parse(response.body[0]);
            // this.tatFlowList = this.tatflowsummary.filter(j => j.isserver === 0);
            this.tatFlowList = this.tatflowstagefollowup.filter(j => j.isserver === 0);
            this.tatflowsummary = this.tatflowstagefollowup;
            let projectFlowChart = [];
            projectFlowChart = await this.loadProjectFlowChart(this.projectDefinitionId);
            if (projectFlowChart !== undefined && projectFlowChart !== null && projectFlowChart[0] !== undefined
              && projectFlowChart[0] !== null) {
              let result = '';
              result = JSON.parse(projectFlowChart[0]);
              this.graphDefinitionString = result;
              this.flowChartRender(result, 'mermaidfinish');
            } else {
              this.clearMermaidDiv('mermaidfinish');
            }
            //  }
            // }
            //  }, err => { this.toastr.error('Error in Followup Records'); });
          } else { // flow from workflow definition master
            const inputWorkflowId = [];
            inputWorkflowId.push({ wfid: this.selectedWorkflowId });
            this.tatFlowList = [];
            //  this.projectConfigurationService.getCurrentFlowWorkflow(inputWorkflowId[0]).subscribe(async (flowRes) => {
            //    if (flowRes.body !== undefined && flowRes.body !== null && flowRes.body[0] !== undefined
            //     && flowRes.body[0] !== null) {
            //   if (JSON.parse(flowRes.body[0]).length > 0) {
            //    this.tatflowsummary = JSON.parse(flowRes.body[0]);
            // this.tatFlowList = this.tatFlow.filter(j => j.isserver === 0);
            this.tatFlowList = this.tatflowstagefollowup.filter(j => j.isserver === 0);
            this.tatflowsummary = this.tatflowstagefollowup;
            let workFlowChart = [];
            workFlowChart = await this.loadWorkFlowChart(this.selectedWorkflowId);
            if (workFlowChart !== undefined && workFlowChart !== null && workFlowChart[0]
              !== undefined && workFlowChart[0] !== null) {
              let result = '';
              result = JSON.parse(workFlowChart[0]);
              this.graphDefinitionString = result;
              this.flowChartRender(result, 'mermaidfinish');
            } else {
              this.clearMermaidDiv('mermaidfinish');
            }
            // }
            //  }
            // }, err => { this.toastr.error('Error in Followup Records'); });
          }
          // }
        }
      }, err => { this.toastr.error(err); });
    } else {
      this.toastr.warning('Project definition not get selected');
    }

  }
  // method to get flow chart by workflowid
  async loadWorkFlowChart(workflowId) {
    const inputChartData = [];
    inputChartData.push({ wfid: workflowId });
    return await this.workflowconfigurationService.getFlowChart(inputChartData[0]).toPromise().then(res => res.body);
  }
  // method to get flow chart by projectdefinitionid
  async loadProjectFlowChart(projectDefinitionId) {
    const inputChartData = [];
    inputChartData.push({ projectdefinitionid: projectDefinitionId });
    return await this.projectConfigurationService.getFlowChart(inputChartData[0]).toPromise().then(res => res.body);
  }

  // clear the graph div element
  clearMermaidDiv(div) {
    this.graphDefinitionString = '';
    if (div === 'mermaid') {
      const element: any = this.mermaidDiv.nativeElement;
      element.innerHTML = '';
    }
    if (div === 'mermaidfinish') {
      const element: any = this.mermaidFinishDiv.nativeElement;
      element.innerHTML = '';
    }
  }
  SaveStage(stagefollowup: StageFollowup) {
    // console.log(stagefollowup);
    let emailtmp;
    // stagefollowup.projectdefinitionid = this._currentdefinitionid;
    stagefollowup.projectdefinitionid = this.projectDefinitionId;
    if (stagefollowup.emailcc.length > 0) {
      emailtmp = stagefollowup.emailcc;
      const eid = emailtmp.map(e => e.emailid);
      stagefollowup.emailcc = JSON.stringify(eid);
    } else {
      stagefollowup.emailcc = '';
    }
    stagefollowup.mailtemplateid = +stagefollowup.mailtemplateid;
    if (this.operation === 'add') {
      stagefollowup.createdby = this.userid;
      this.projectConfigurationService.PostStageFollowup(stagefollowup).subscribe(res => {
        if (res.body !== undefined && res.body !== null && res.body > 0) {
          this.toastr.success('StageFollowup added successfully');
          this.cancelForm();
          this.loadFollowupDetail(this._currentstageid);
        } else {
          stagefollowup.emailcc = emailtmp;
          this.toastr.error('StageFollowup Already Exsist');
        }
      }, err => { this.toastr.error(err); });
    } else if (this.operation === 'update') {
      stagefollowup.updatedby = this.userid;

      this.projectConfigurationService.PutStageFollowup(stagefollowup).subscribe(res => {
        if (res.body !== undefined && res.body !== null && res.body > 0) {
          this.toastr.success('StageFollowup updated successfully');
          this.cancelForm();
          this.loadFollowupDetail(this._currentstageid);
        } else {
          stagefollowup.emailcc = emailtmp;
          this.toastr.error('StageFollowup Already Exsist');
        }
      }, err => { this.toastr.error(err); });
    }
  }
  getactiveinactive(showallp) {
    this.stagefollowupactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.stagefollowups.forEach(data => {
        if (data.active === 1) {
          this.stagefollowupactive.push(data);
        }
      });
      this.stagefollowups = [];
      this.stagefollowups = this.stagefollowupactive;
    } else {
      this.showall = true;
      this.stagefollowups = [];
      // this.getAll();
      this.loadFollowupDetail(this._currentstageid);
    }

  }
  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }
  OpenConfirmTemplate(stagefollowup, template: TemplateRef<any>) {
    if (stagefollowup.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.stagefollowup = stagefollowup;
          this.Delete();
        }
      });
  }
  Delete() {
    let msg;
    if (this.stagefollowup.active === 0) {
      this.stagefollowup.active = 1;
      msg = 'Record activated successfully';
    } else {
      this.stagefollowup.active = 0;
      msg = 'Record deactivated successfully';
    }
    this.userid = +localStorage.getItem('userid');
    this.stagefollowup.updatedby = this.userid;
    this.projectConfigurationService.DeleteStageFollowup(this.stagefollowup).subscribe(res => {
      this.toastr.success(msg);
      // this.getAll();
      this.loadFollowupDetail(this._currentstageid);
    },
      error => { this.deleteResult = false; });
  }

  loadFollowupDetail(stageid) {
    this.stagefollowups = [];
    this.stagefollowupactive = [];
    this.projectConfigurationService.GetStageFollowupdetail().subscribe(res => {
      // this.stagefollowups = JSON.parse(res[0]);
      this.stagefollowupsFull = JSON.parse(res[0]);
      if (this.showallstatus === true) {
        if (this.stagefollowupsFull.length > 0) {
          this.stagefollowups = this.stagefollowupsFull.filter(s => s.active === 1 && s.stageid === stageid &&
            s.projectdefinitionid === this.projectDefinitionId);
        } else {
          this.stagefollowups = [];
        }
      } else if (this.stagefollowupsFull.length > 0) {
        this.stagefollowups = this.stagefollowupsFull.filter(s => s.stageid === stageid &&
          s.projectdefinitionid === this.projectDefinitionId);
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

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

  // method to save project workflow definition
  finishProjectConfig() {
    this.SpinnerService.show();
    if (this.tatflowsummary !== undefined && this.tatflowsummary !== null && this.tatflowsummary.length > 0) {
      const inputData = []; let projectWorkflowDefinition = []; const inOutFiles = [];
      inputData.push({ projectdefinitionid: this.projectDefinitionId });
      // check project workflow definition exists or not
      this.projectConfigurationService.getByIdProjectDefWorkflow(inputData[0]).subscribe((response) => {
        if (response.body !== undefined && response.body !== null && response.body[0] !== undefined && response.body[0] !== null) {
          if (JSON.parse(response.body[0]).length > 0) { // updating the existing project workflow definition
            let existingData = [];
            existingData = JSON.parse(response.body[0]);
            projectWorkflowDefinition = this.formProjectWorkflowInput(existingData, this.tatflowsummary, 'update');
            this.projectConfigurationService.updateProjectWorkflow(projectWorkflowDefinition).subscribe((updateRes) => {
              if (updateRes.body !== undefined && updateRes.body !== null && updateRes.body[0] !==
                undefined && updateRes.body[0] !== null) {
                if (JSON.parse(updateRes.body[0]).length > 0) {
                  this.toastr.success('Project configuration updated successfully');
                  this.router.navigate(['/projectconfiguration/projectdefinitionmaster']);
                } else {
                  this.toastr.error('Project configuration failed');
                }
              }
            }, err => { this.toastr.error('Project configuration failed'); });
          }
          this.SpinnerService.hide();
        } else { // adding new project workflow definition

          projectWorkflowDefinition = this.formProjectWorkflowInput([], this.tatflowsummary, 'insert');
          console.log(projectWorkflowDefinition);
          this.projectConfigurationService.addProjectWorkflow(projectWorkflowDefinition).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.toastr.success('Project configuration inserted successfully');
                this.router.navigate(['/projectconfiguration/projectdefinitionmaster']);
              } else {
                this.toastr.error('Project configuration failed');
              }
            }
          }, err => { this.toastr.error('Project configuration failed'); });
        }
      });
    } else {
      this.toastr.error('Please select workflow then proceed.');
    }
    this.SpinnerService.hide();
  }

  // method to form projectworkflow definition motel
  formProjectWorkflowInput(existingData, tatFlow, mode) {
    const projectWorkflowDefinitionTmp = [];
    if (mode === 'insert') {
      tatFlow.forEach(i => {
        projectWorkflowDefinitionTmp.push({
          pwdid: 0, projectdefinitionid: this.projectDefinitionId, wfdid: i.wfdid, stageid: i.stageid, stage_type: i.stagetype,
          stagename_alias: i.stagename_alias, parallelstage: i.parallelstage, nextstage: i.nextstage,
          movebackstage: i.movebackstage, resetstage: i.resetstage, process_without_file: i.process_without_file,
          hidebypass: i.hidebypass, hidereverse: i.hidereverse, merged_lot: i.merged_lot, unmerge_lot: i.unmerge_lot,
          file_movement: i.file_movement, allocation_mode: i.allocation_mode, benchmark: i.benchmark,
          folder_name: i.folder_name, show_file_browser: i.show_file_browser, unit: i.unit, checkin_app: i.checkin_app,
          checkout_app: i.checkout_app, file_server: null, active: i.active, createdby: +this.userid, createdon: '',
          allocationtype: i.allocationtype, StageOrder: i.stageorder, signoffnotification: i.signoffnotification,
          mailtemplate: i.mailtemplate, inprocessapp: i.inprocessapp, mailattachment: i.mailattachment,
          checklistlog: i.checklistlog, checklisttemplateid: i.checklisttemplateid, acknowledgement: i.acknowledgement,
          ackmailtemplate: i.ackmailtemplate, pmnotification: i.pmnotification, pmmailtemplate: i.pmmailtemplate,
          tathours: i.tathours, tattype: i.tattype, querycompilation: i.querycompilation,
          querycomtemplateid: i.querycomtemplateid, querybatch: i.querybatch, backmatterstart: i.backmatterstart,
          projectmetafields: i.workflowmetafields, islotenable: i.islotenable,
          checkinappfeature: i.checkinappfeature,
          checkoutappfeature: i.checkoutappfeature,
          inprocessappfeature: i.inprocessappfeature,
          multiplemoveback:i.multiplemoveback
        });
      });
      return projectWorkflowDefinitionTmp;
    }
    if (mode === 'update') {
      console.log(tatFlow);
      console.log(existingData);
      tatFlow.forEach(item => {
        let tmp = [];
        tmp = existingData.filter(x => x.stageid === item.stageid && x.projectdefinitionid === this.projectDefinitionId && x.active === 1
           && x.wfdid === item.wfdid );
        if (tmp !== undefined && tmp !== null && tmp.length > 0) {
          let tmp1 = [];
           tmp1 = tatFlow.filter(x => x.stageid === tmp[0].stageid && x.active === 1
           && x.wfdid === tmp[0].wfdid );
           if (tmp1 !== undefined && tmp1 !== null && tmp1.length > 0) {
            projectWorkflowDefinitionTmp.push({
              pwdid: tmp[0].pwdid, projectdefinitionid: this.projectDefinitionId, wfdid: tmp[0].wfdid, stageid: tmp[0].stageid,
              stage_type: tmp1[0].stage_type ? tmp1[0].stage_type : tmp1[0].stagetype, stagename_alias: tmp1[0].stagename_alias, 
              parallelstage: tmp1[0].parallelstage,
              nextstage: tmp1[0].nextstage, movebackstage: tmp1[0].movebackstage, resetstage: tmp1[0].resetstage,
              process_without_file: tmp1[0].process_without_file, hidebypass: tmp1[0].hidebypass, hidereverse: tmp1[0].hidereverse,
              merged_lot: tmp1[0].merged_lot, unmerge_lot: tmp1[0].unmerge_lot, file_movement: tmp1[0].file_movement,
              allocation_mode: tmp1[0].allocation_mode, benchmark: tmp1[0].benchmark, folder_name: tmp1[0].folder_name,
              show_file_browser: tmp1[0].show_file_browser, unit: tmp1[0].unit, checkin_app: tmp1[0].checkin_app,
              checkout_app: tmp1[0].checkout_app, file_server: +tmp1[0].file_server, active: tmp1[0].active,
              updatedby: +this.userid, allocationtype: tmp1[0].allocationtype, StageOrder: tmp1[0].stageorder,
              signoffnotification: tmp1[0].signoffnotification, mailtemplate: tmp1[0].mailtemplate, inprocessapp: tmp1[0].inprocessapp,
              mailattachment: tmp1[0].mailattachment, checklistlog: tmp1[0].checklistlog,
              checklisttemplateid: tmp1[0].checklisttemplateid, acknowledgement: tmp1[0].acknowledgement,
              ackmailtemplate: tmp1[0].ackmailtemplate, pmnotification: tmp1[0].pmnotification, pmmailtemplate: tmp1[0].pmmailtemplate,
              tathours: tmp1[0].tathours, tattype: tmp1[0].tattype, querycompilation: tmp1[0].querycompilation,
              querycomtemplateid: tmp1[0].querycomtemplateid, querybatch: tmp1[0].querybatch, backmatterstart: tmp1[0].backmatterstart,
              projectmetafields: tmp1[0].projectmetafields, islotenable: tmp1[0].islotenable,
              checkinappfeature: tmp1[0].checkinappfeature,
              checkoutappfeature: tmp1[0].checkoutappfeature,
              inprocessappfeature: tmp1[0].inprocessappfeature,
              multiplemoveback:tmp1[0].multiplemoveback
            });
           } else {
            projectWorkflowDefinitionTmp.push({
              pwdid: tmp[0].pwdid, projectdefinitionid: this.projectDefinitionId, wfdid: tmp[0].wfdid, stageid: tmp[0].stageid,
              stage_type: tmp[0].stage_type, stagename_alias: tmp[0].stagename_alias, parallelstage: tmp[0].parallelstage,
              nextstage: tmp[0].nextstage, movebackstage: tmp[0].movebackstage, resetstage: tmp[0].resetstage,
              process_without_file: tmp[0].process_without_file, hidebypass: tmp[0].hidebypass, hidereverse: tmp[0].hidereverse,
              merged_lot: tmp[0].merged_lot, unmerge_lot: tmp[0].unmerge_lot, file_movement: tmp[0].file_movement,
              allocation_mode: tmp[0].allocation_mode, benchmark: tmp[0].benchmark, folder_name: tmp[0].folder_name,
              show_file_browser: tmp[0].show_file_browser, unit: tmp[0].unit, checkin_app: tmp[0].checkin_app,
              checkout_app: tmp[0].checkout_app, file_server: +tmp[0].file_server, active: tmp[0].active,
              updatedby: +this.userid, allocationtype: tmp[0].allocationtype, StageOrder: tmp[0].stageorder,
              signoffnotification: tmp[0].signoffnotification, mailtemplate: tmp[0].mailtemplate, inprocessapp: tmp[0].inprocessapp,
              mailattachment: tmp[0].mailattachment, checklistlog: tmp[0].checklistlog,
              checklisttemplateid: tmp[0].checklisttemplateid, acknowledgement: tmp[0].acknowledgement,
              ackmailtemplate: tmp[0].ackmailtemplate, pmnotification: tmp[0].pmnotification, pmmailtemplate: tmp[0].pmmailtemplate,
              tathours: tmp[0].tathours, tattype: tmp[0].tattype, querycompilation: tmp[0].querycompilation,
              querycomtemplateid: tmp[0].querycomtemplateid, querybatch: tmp[0].querybatch, backmatterstart: tmp[0].backmatterstart,
              projectmetafields: tmp[0].projectmetafields, islotenable: tmp[0].islotenable,
              checkinappfeature: tmp[0].checkinappfeature,
              checkoutappfeature: tmp[0].checkoutappfeature,
              inprocessappfeature: tmp[0].inprocessappfeature,
              multiplemoveback:tmp[0].multiplemoveback
            });
           }          
        } else {
          projectWorkflowDefinitionTmp.push({
            pwdid: 0, projectdefinitionid: this.projectDefinitionId, wfdid: item.wfdid, stageid: item.stageid,
            stage_type: item.stagetype, stagename_alias: item.stagename_alias, parallelstage: item.parallelstage,
            nextstage: item.nextstage, movebackstage: item.movebackstage, resetstage: item.resetstage,
            process_without_file: item.process_without_file, hidebypass: item.hidebypass, hidereverse: item.hidereverse,
            merged_lot: item.merged_lot, unmerge_lot: item.unmerge_lot, file_movement: item.file_movement,
            allocation_mode: item.allocation_mode, benchmark: item.benchmark, folder_name: item.folder_name,
            show_file_browser: item.show_file_browser, unit: item.unit, checkin_app: item.checkin_app,
            checkout_app: item.checkout_app, file_server: null, active: item.active, createdby: +this.userid,
            allocationtype: item.allocationtype, StageOrder: item.stageorder, signoffnotification: item.signoffnotification,
            mailtemplate: item.mailtemplate, inprocessapp: item.inprocessapp, mailattachment: item.mailattachment,
            checklistlog: item.checklistlog, checklisttemplateid: item.checklisttemplateid, acknowledgement: item.acknowledgement,
            ackmailtemplate: item.ackmailtemplate, pmnotification: item.pmnotification, pmmailtemplate: item.pmmailtemplate,
            tathours: item.tathours, tattype: item.tattype, querycompilation: item.querycompilation,
            querycomtemplateid: item.querycomtemplateid, querybatch: item.querybatch, backmatterstart: item.backmatterstart,
            projectmetafields: item.workflowmetafields, islotenable: item.islotenable,
            checkinappfeature: item.checkinappfeature,
            checkoutappfeature: item.checkoutappfeature,
            inprocessappfeature: item.inprocessappfeature,
            multiplemoveback:item.multiplemoveback
          });
        }
      });
      console.log(projectWorkflowDefinitionTmp);
      return projectWorkflowDefinitionTmp;
    }
  }
  /*formProjectWorkflowInput(existingData, tatFlow, mode) {
    const projectWorkflowDefinitionTmp = [];
    if (mode === 'insert') {
      tatFlow.forEach(i => {
        projectWorkflowDefinitionTmp.push({
          pwdid: 0, projectdefinitionid: this.projectDefinitionId, wfdid: i.wfdid, stageid: i.stageid, stage_type: i.stagetype,
          stagename_alias: i.stagename_alias, parallelstage: i.parallelstage, nextstage: i.nextstage,
          movebackstage: i.movebackstage, resetstage: i.resetstage, process_without_file: i.process_without_file,
          hidebypass: i.hidebypass, hidereverse: i.hidereverse, merged_lot: i.merged_lot, unmerge_lot: i.unmerge_lot,
          file_movement: i.file_movement, allocation_mode: i.allocation_mode, benchmark: i.benchmark,
          folder_name: i.folder_name, show_file_browser: i.show_file_browser, unit: i.unit, checkin_app: i.checkin_app,
          checkout_app: i.checkout_app, file_server: '', active: i.active, createdby: +this.userid, createdon: '',
          allocationtype: i.allocationtype, StageOrder: i.stageorder, signoffnotification: i.signoffnotification,
          mailtemplate: i.mailtemplate, inprocessapp: i.inprocessapp, mailattachment: i.mailattachment,
          checklistlog: i.checklistlog, checklisttemplateid: i.checklisttemplateid, acknowledgement: i.acknowledgement,
          ackmailtemplate: i.ackmailtemplate, pmnotification: i.pmnotification, pmmailtemplate: i.pmmailtemplate,
          tathours: i.tathours, tattype: i.tattype, querycompilation: i.querycompilation,
          querycomtemplateid: i.querycomtemplateid, querybatch: i.querybatch, backmatterstart: i.backmatterstart,
          projectmetafields: i.workflowmetafields, islotenable: i.islotenable,
          checkinappfeature: i.checkinappfeature,
          checkoutappfeature: i.checkoutappfeature,
          inprocessappfeature: i.inprocessappfeature,
        });
      });
      return projectWorkflowDefinitionTmp;
    }

    if (mode === 'update') {
      tatFlow.forEach(item => {
        let tmp = [];
        tmp = existingData.filter(x => x.stageid === item.stageid && x.projectdefinitionid === this.projectDefinitionId);
        if (tmp !== undefined && tmp !== null && tmp.length > 0) {
          projectWorkflowDefinitionTmp.push({
            pwdid: tmp[0].pwdid, projectdefinitionid: this.projectDefinitionId, wfdid: tmp[0].wfdid, stageid: tmp[0].stageid,
            stage_type: tmp[0].stage_type, stagename_alias: tmp[0].stagename_alias, parallelstage: tmp[0].parallelstage,
            nextstage: tmp[0].nextstage, movebackstage: tmp[0].movebackstage, resetstage: tmp[0].resetstage,
            process_without_file: tmp[0].process_without_file, hidebypass: tmp[0].hidebypass, hidereverse: tmp[0].hidereverse,
            merged_lot: tmp[0].merged_lot, unmerge_lot: tmp[0].unmerge_lot, file_movement: tmp[0].file_movement,
            allocation_mode: tmp[0].allocation_mode, benchmark: tmp[0].benchmark, folder_name: tmp[0].folder_name,
            show_file_browser: tmp[0].show_file_browser, unit: tmp[0].unit, checkin_app: tmp[0].checkin_app,
            checkout_app: tmp[0].checkout_app, file_server: tmp[0].file_server, active: tmp[0].active,
            updatedby: +this.userid, allocationtype: tmp[0].allocationtype, StageOrder: tmp[0].stageorder,
            signoffnotification: tmp[0].signoffnotification, mailtemplate: tmp[0].mailtemplate, inprocessapp: tmp[0].inprocessapp,
            mailattachment: tmp[0].mailattachment, checklistlog: tmp[0].checklistlog,
            checklisttemplateid: tmp[0].checklisttemplateid, acknowledgement: tmp[0].acknowledgement,
            ackmailtemplate: tmp[0].ackmailtemplate, pmnotification: tmp[0].pmnotification, pmmailtemplate: tmp[0].pmmailtemplate,
            tathours: tmp[0].tathours, tattype: tmp[0].tattype, querycompilation: tmp[0].querycompilation,
            querycomtemplateid: tmp[0].querycomtemplateid, querybatch: tmp[0].querybatch, backmatterstart: tmp[0].backmatterstart,
            projectmetafields: tmp[0].projectmetafields, islotenable: tmp[0].islotenable,
            checkinappfeature: tmp[0].checkinappfeature,
            checkoutappfeature: tmp[0].checkoutappfeature,
            inprocessappfeature: tmp[0].inprocessappfeature,
          });
        } else {
          projectWorkflowDefinitionTmp.push({
            pwdid: 0, projectdefinitionid: this.projectDefinitionId, wfdid: item.wfdid, stageid: item.stageid,
            stage_type: item.stagetype, stagename_alias: item.stagename_alias, parallelstage: item.parallelstage,
            nextstage: item.nextstage, movebackstage: item.movebackstage, resetstage: item.resetstage,
            process_without_file: item.process_without_file, hidebypass: item.hidebypass, hidereverse: item.hidereverse,
            merged_lot: item.merged_lot, unmerge_lot: item.unmerge_lot, file_movement: item.file_movement,
            allocation_mode: item.allocation_mode, benchmark: item.benchmark, folder_name: item.folder_name,
            show_file_browser: item.show_file_browser, unit: item.unit, checkin_app: item.checkin_app,
            checkout_app: item.checkout_app, file_server: '', active: item.active, createdby: +this.userid,
            allocationtype: item.allocationtype, StageOrder: item.stageorder, signoffnotification: item.signoffnotification,
            mailtemplate: item.mailtemplate, inprocessapp: item.inprocessapp, mailattachment: item.mailattachment,
            checklistlog: item.checklistlog, checklisttemplateid: item.checklisttemplateid, acknowledgement: item.acknowledgement,
            ackmailtemplate: item.ackmailtemplate, pmnotification: item.pmnotification, pmmailtemplate: item.pmmailtemplate,
            tathours: item.tathours, tattype: item.tattype, querycompilation: item.querycompilation,
            querycomtemplateid: item.querycomtemplateid, querybatch: item.querybatch, backmatterstart: item.backmatterstart,
            projectmetafields: item.workflowmetafields, islotenable: item.islotenable,
            checkinappfeature: item.checkinappfeature,
            checkoutappfeature: item.checkoutappfeature,
            inprocessappfeature: item.inprocessappfeature,
          });
        }
      });
      return projectWorkflowDefinitionTmp;
    }
  }*/
  stagedetailBind(id, stage) {
    // this.tatflow
    this._currentstageid = id;
    this.stagefollowups = [];
    this.stageflowsearchText = '';
    this._currentstage = stage;

    if (this.showallstatus === true) {
      if (this.stagefollowupsFull) {
        this.stagefollowups = this.stagefollowupsFull.filter(s => s.active === 1 && s.stageid === id
          && s.projectdefinitionid === this.projectDefinitionId);
      } else {
        this.stagefollowups = [];
      }
    } else if (this.stagefollowupsFull) {
      this.stagefollowups = this.stagefollowupsFull.filter(s => s.stageid === id && s.projectdefinitionid === this.projectDefinitionId);
    }
  }
  settat(index, data, mode) {
    if (mode === 'tathour' && data.target.value !== '7') {
      this.tatflowstagefollowup[index].tathours = +data.target.value;
    }
    if (mode === 'tattype' && data.target.value !== 'Days') {
      this.tatflowstagefollowup[index].tattype = data.target.value;
    }
  }
  GetTATdetails() {
    this.projectConfigurationService.GetTATdetails().subscribe(
      res => {
        console.log(res);
        this.tathours = res.tathours;
        this.tattype = res.tattype;
      }
    );
  }

  onStepChange(eve) {
    if (eve.selectedStep.state === 'projectDefinition') {
      this.loadProjectDefinition();
    } else if (eve.selectedStep.state === 'workFlow') {
      this.loadWorkFlowMapping('');
    } else if (eve.selectedStep.state === 'stagefollowup') {
      this.loadStageFollowup();
    } else if (eve.selectedStep.state === 'finish') {
      this.loadProjectDefinitionFinish();
    }
  }
  /*onStepChange(eve) {
    if (eve.selectedStep.state === 'projectDefinition') {
      this.loadProjectDefinition();
    }
    if (this.projectDefinitionId !== undefined && this.projectDefinitionId > 0) { //stagefollowup
    if (eve.selectedStep.state === 'workFlow') {
      this.loadWorkFlowMapping();
    }
    if (eve.selectedStep.state === 'stagefollowup') {
      this.loadStageFollowup();
    }
    if (eve.selectedStep.state === 'finish') {
      this.loadProjectDefinitionFinish();
    }
  } else {
    this.loadProjectDefinition();
    this.toastr.error('Project definition should be selected');
  }
  }*/
  showStageFollowup() {
    this.displayStep1 = false;
    this.displayStep2 = false;
    this.displayStep3 = true;
    this.displayStep4 = false;
  }
  checkallocationtype(id, tatobj): boolean {
    let retval: boolean;
    if (id === 0) { this.stagefollowupindex = id; }
    retval = tatobj.allocationtype === 4 || tatobj.isserver === 1 ? false : true;
    if (retval) { this.stagefollowupindex = this.stagefollowupindex + 1; }
    return retval;
  }
}
