import { Component, OnInit, TemplateRef, ElementRef, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { Jobmaster } from '../jobmaster/jobmaster';
import { ProjectConfigurationService } from 'src/app/projectconfiguration/projectconfiguration/projectconfiguration.service';
import { ToastrService } from 'ngx-toastr';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
import { ProjectDefinition } from 'src/app/projectconfiguration/projectconfiguration/projectdefinition';
import { JobmasterService } from '../jobmaster/jobmaster.service';
import { ModalOptions, BsModalService, BsModalRef } from 'ngx-bootstrap';
import { JobdefinitionService } from './jobdefinition.service';
import * as mermaid from 'mermaid';
import * as mermaidAPI from 'mermaid';
import * as $ from 'jquery';
import { NgxSpinnerService } from 'ngx-spinner';
import { JobmetaService } from '../../masters/jobmeta/jobmeta.service';
@Component({
  selector: 'app-jobdefinition',
  templateUrl: './jobdefinition.component.html',
  styleUrls: ['./jobdefinition.component.css']
})
export class JobdefinitionComponent implements OnInit {
  @ViewChild('mermaid', { static: false }) mermaidDiv: ElementRef;
  @ViewChild('mermaidfinish', { static: false }) mermaidFinishDiv: ElementRef;
  callType: any;
  metadtalist1 = [];
  tatflow = [];
  Benchmarklst = [];

  p = 1;
  searchText: string;
  itemsPerPage = 10;
  reverse = false;
  key = 'projectname';

  projectcode_display: any;
  displayStep1 = true;
  displayStep2 = false;
  displayStep3 = false;
  displayStep4 = false;

  bechmarkdet: any[] = [];
  job = {} as Jobmaster;
  userid: number;
  jobid: number;
  projects: any[] = [];
  jobDefinitionForm: FormGroup;
  projectid: number;
  projectdefinitionid: number;
  projectdefinitions: ProjectDefinition[] = [];
  jobs: Jobmaster[] = [];
  jobsOrg: Jobmaster[] = [];
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };
  JobModalRef: BsModalRef;
  jobMetadataTemplate: BsModalRef;
  projectflow: any;
  selectedJobInfo: any;
  graphDefinitionString = '';
  workflowName = '';
  forms: FormGroup;
  jobdefinition: FormArray;
  jobItem: any = [];
  isjobflow = false;
  tathours = 0;
  tattype = '';
  projectsUnique = [];
  _svgCode: any;
  actionRights: any;
  jobMetaDataModalRef: BsModalRef;
  selectedfieldname: any;
  fieldvalue: any;
  jobMetadata: any = [];
  selectedfieldid: any;
  constructor(
    private router: Router,
    private formBuilder: FormBuilder,
    private toastr: ToastrService,
    private modalService: BsModalService,
    private projectConfigurationService: ProjectConfigurationService,
    private jobmasterservice: JobmasterService,
    private jobdefinitionservice: JobdefinitionService,
    private SpinnerService: NgxSpinnerService,
    private jobMetaService: JobmetaService
  ) {
    // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('JobDefinition_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('JobDefinition_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('JobDefinition_userRights');
    }
    const navigation = this.router.getCurrentNavigation();
    const state = navigation.extras.state as {
      projectid: any,
      projectdefinitionid: any,
      jobno: any,
      jobid: any,
      title: any,
      startdate: any,
      enddate: any,
      project_subtitle: any;
      projectname: any;
      totallots: any;
      isdaterequired: any;
      jobmetadata: any;
      validjobmeta: any;
    };

    if (state !== null && state !== undefined) {
      this.job.projectid = state.projectid;
      this.job.projectdefinitionid = state.projectdefinitionid;
      this.job.jobid = state.jobid;
      this.job.title = state.title;
      this.job.jobno = state.jobno;
      this.job.startdate = state.startdate;
      this.job.enddate = state.enddate;
      this.job.project_subtitle = state.project_subtitle;
      this.job.projectname = state.projectname;
      this.job.totallots = state.totallots;
      this.job.isdaterequired = state.isdaterequired;
      console.log(state.validjobmeta);
      if (state.validjobmeta !== undefined && state.validjobmeta !== null) {
        this.job.jobmetadata = state.validjobmeta;
      }
    }
  }

  ngOnInit() {
    this.jobDefinitionForm = this.formBuilder.group({
      jobid: [0],
      projectid: [0],
      projectdefinitionid: [0],
      isdaterequired: [0],
      selectedDaterange: [],
      jobno: [''],
      title: [''],
      isbn: [],
      totallots: [''],
      startdate: [''],
      enddate: [''],
      jobstatus: ['']
    });

    this.selectedfieldid = 0;
    this.forms = this.formBuilder.group({
      jobdefinition: this.formBuilder.array([])
    });
    this.userid = +localStorage.getItem('userid');
    this.getAllJobs();
    this.getProjects();
    this.GetTATdetails();
    this.getJobMetaFields();
    this.projectflow = [];
  }

  getAllJobs() {
    this.jobs = [];
    const user = new Object({
      userid: this.userid
    });
    this.jobdefinitionservice.GetAllByUserId(user).subscribe(res => {
      if (res.body[0] != null && res.body[0] !== undefined) {
        this.jobs = JSON.parse(res.body[0]);
        this.jobsOrg = this.jobs;
      }

      // For stage navigation
      if (Object.keys(this.job).length !== 0) {
        this.onflowchanged(this.job);
      }

    }, error => { this.toastr.error('Error while getting data'); });
  }


  getProjects() {
    this.projects = [];
    const user = new Object({
      userid: this.userid
    });
    this.projectConfigurationService.getByUserId(user).subscribe(res => {
      if (res.body[0] != null && res.body[0] !== undefined) {
        this.projects = JSON.parse(res.body[0]);
        this.projectsUnique = this.projects.filter(
          (project, i, arr) => arr.findIndex(p => p.projectid === project.projectid) === i
        );
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  onchangeproject() {
    this.projectid = +this.jobDefinitionForm.controls['projectid'].value;
    console.log('this.projectid=', this.projectid);
    console.log('this.projects=', this.projects);
    const timer = setInterval(() => {
      if (this.projects.length) {
        clearTimeout(timer);
        console.log('this.projects=', this.projects);
        this.projectdefinitions = this.projects.filter(p => p.projectid === this.projectid);
      }
    }, 200);
    console.log('this.projectdefinitions=', this.projectdefinitions);
  }

  onChangeProjectDefinition() {
    this.projectdefinitionid = +this.jobDefinitionForm.controls['projectdefinitionid'].value;
    this.jobs = this.jobsOrg.filter(j => j.projectid === this.projectid && j.projectdefinitionid === this.projectdefinitionid);
    if (Object.keys(this.jobs[0]).length !== 0) {
      // this.jobDefinitionForm.controls['jobid'].setValue(this.jobs[0].jobid);
    } else {
      // this.jobDefinitionForm.controls['jobid'].setValue(0);
    }
  }

  openserachwindow(template: TemplateRef<any>) {
    this.getAllJobs();
    this.JobModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
    // }, error => { this.toastr.error('Error while getting data'); });
  }

  onsearchclick(job) {
    // this.workflow = wf;
    this.JobModalRef.hide();
    this.onflowchanged(job);
  }

  onflowchanged(job) {
    this.jobDefinitionForm.controls['projectid'].setValue(job.projectid);
    this.jobDefinitionForm.controls['projectdefinitionid'].setValue(job.projectdefinitionid);
    this.jobDefinitionForm.controls['title'].setValue(job.title);
    this.jobDefinitionForm.controls['startdate'].setValue(job.startdate);
    this.jobDefinitionForm.controls['enddate'].setValue(job.enddate);
    this.jobDefinitionForm.controls['jobid'].setValue(job.jobid);
    this.jobDefinitionForm.controls['totallots'].setValue(job.totallots);
    this.jobDefinitionForm.controls['jobno'].setValue(job.jobno);
    this.jobDefinitionForm.controls['isdaterequired'].setValue(job.isdaterequired);
    this.jobDefinitionForm.controls['selectedDaterange'].setValue([new Date(job.startdate), new Date(job.enddate)]);
    if (job.jobmetadata !== undefined && job.jobmetadata !== null && job.jobmetadata.length > 0) {
      this.metadtalist1 = job.jobmetadata;
    }
    this.onchangeproject();
    this.onChangeProjectDefinition();
    this.selectedJobInfo = job;
    this.projectflow = [];
  }

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

  loadJobDefinition() {
    this.displayStep1 = true;
    this.displayStep2 = false;
    this.displayStep3 = false;
    this.displayStep4 = false;
  }

  loadWorkflowMapping(stepper) {
    if (this.projectdefinitionid) {
      this.displayStep1 = false;
      this.displayStep2 = true;
      this.displayStep3 = false;
      this.displayStep4 = false;
      if (this.projectflow.length === 0) {
        let input = [];
        this.SpinnerService.show();
        input.push({ jobid: this.selectedJobInfo.jobid });
        this.jobdefinitionservice.getByJobId(input[0]).subscribe(async (res) => {
          if (res.body !== undefined && res.body !== null && res.body[0] !== undefined && res.body[0] !== null &&
            (JSON.parse(res.body[0]).length > 0)) {
            // get job workflow
            this.isjobflow = true;
            this.projectflow = JSON.parse(res.body[0]);
            console.log(this.projectflow);
            let jobFlowChart = [];
            this.workflowName = this.selectedJobInfo.project_subtitle;
            // jobFlowChart = await this.loadJobFlowChart(this.selectedJobInfo.jobid);
            jobFlowChart = await this.loadProjectFlowChart(this.selectedJobInfo.projectdefinitionid);
            if (jobFlowChart !== undefined && jobFlowChart !== null && jobFlowChart[0] !== undefined
              && jobFlowChart[0] !== null) {
              let result = '';
              result = JSON.parse(jobFlowChart[0]);
              this.flowChartRender(result, 'mermaid');
            } else {
              this.clearMermaidDiv('mermaid');
            }
            if (stepper) {
              if (stepper.selected.state === 'JobDefinition') {
                stepper.next();
              }
            }
            this.SpinnerService.hide();
          } else { // get project definition workflow
            input = [];
            input.push({ projectdefinitionid: this.selectedJobInfo.projectdefinitionid });
            this.projectConfigurationService.getCurrentFlowProject(input[0]).subscribe(async (response) => {
              if (response.body !== undefined && response.body !== null && response.body[0] !== undefined && response.body[0] !== null &&
                (JSON.parse(response.body[0]).length > 0)) {
                this.isjobflow = false;
                let projectFlowChart = [];
                this.projectflow = JSON.parse(response.body[0]);
                console.log(this.projectflow);
                this.workflowName = this.selectedJobInfo.project_subtitle;
                projectFlowChart = await this.loadProjectFlowChart(this.selectedJobInfo.projectdefinitionid);
                if (projectFlowChart !== undefined && projectFlowChart !== null && projectFlowChart[0] !== undefined
                  && projectFlowChart[0] !== null) {
                  let result = '';
                  result = JSON.parse(projectFlowChart[0]);
                  this.flowChartRender(result, 'mermaid');
                } else {
                  this.clearMermaidDiv('mermaid');
                }
                if (stepper) {
                  if (stepper.selected.state === 'JobDefinition') {
                    stepper.next();
                  }
                }
              }
            }, err => { this.toastr.error(err); });
            this.SpinnerService.hide();
          }
        }, err => { this.toastr.error(err); });
      }
      if (stepper) {
        if (stepper.selected.state === 'JobDefinition') {
          stepper.next();
        }
      }
    } else {
      this.toastr.warning('Please choose any job');
    }

  }

  // 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);
  }

  // method to get flow chart by workflowid
  async loadJobFlowChart(jobid) {
    const inputChartData = [];
    inputChartData.push({ jobid: jobid });
    return await this.jobdefinitionservice.getFlowChart(inputChartData[0]).toPromise().then(res => res.body);
  }


  // clear the graph div element
  clearMermaidDiv(div) {
    this.projectflow = [];
    if (div === 'mermaid') {
      const element: any = this.mermaidDiv.nativeElement;
      element.innerHTML = '';
    }
    if (div === 'mermaidfinish') {
      const element: any = this.mermaidFinishDiv.nativeElement;
      element.innerHTML = '';
    }
  }


  // method to bind flow chart in the mermaid div
  flowChartRender(result, node) {
    result = result.replace(/\^ /g, '\n');
    result = result.replace(/\^/g, '\n');
    result = result.replace(/\\n/g, '\n');
    mermaid.initialize({ startOnLoad: false });
    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');
      }

      // mermaidAPI.render('graphDiv', graphDefinition, (svgCode, bindFunctions) => {
      //   element.innerHTML = svgCode;
      //   this._svgCode = svgCode;
      // });
    }
    if (node === 'mermaidfinish') {
      const element: any = this.mermaidFinishDiv.nativeElement;
      console.log(graphDefinition);
      $('#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');
      }

      // mermaidAPI.render('graphDiv1', graphDefinition, (svgCode, bindFunctions) => {
      //   console.log(this._svgCode);
      //   element.innerHTML = this._svgCode;
      // });
    }
  }


  // method to download flow chart
  downloadflowchart(node, workflowName) {
    this.SpinnerService.show();
    const s = document.getElementById(node);
    if (s != null && s !== undefined) {

      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();
    }
  }


  loadFinish() {
    this.displayStep1 = false;
    this.displayStep2 = false;
    this.displayStep3 = false;
    this.displayStep4 = true;
  }
  initCaseRows() {

    return this.formBuilder.group({
      stageid: [],
      stagename_alias: [''],
      tathours: [0],
      tattype: [null]
    });
  }


  loadTATConfiguration() {
    if (this.projectdefinitionid) {
      this.displayStep1 = false;
      this.displayStep2 = false;
      this.displayStep3 = true;
      this.displayStep4 = false;
      this.jobid = this.jobDefinitionForm.value.jobid;
      if (this.isjobflow) {
        this.jobdefinitionservice.GetTatFlowByJobId(this.jobid).subscribe(res => {
          if (res.body[0] != null && res.body[0] !== undefined) {
            this.tatflow = JSON.parse(res.body[0]);
            this.tatflow.map(t => {
              t.tattype === null ? t.tattype = this.tattype : t.tattype = t.tattype,
                t.tathours === null ? t.tathours = this.tathours : t.tathours = t.tathours;
            }
            );
            // this.forms.value.jobdefinition = [];
            this.forms.setControl('jobdefinition', this.formBuilder.array([]));
            this.tatflow.forEach(e => {
              this.jobdefinition = this.forms.get('jobdefinition') as FormArray;
              this.jobdefinition.push(this.initCaseRows());
            });
            this.forms.controls.jobdefinition.patchValue(this.tatflow);
            console.log('this.tatflow=', this.tatflow);
          }
        }, function (error) { this.toastr.error('Error while getting data'); });

      } else {
        this.jobdefinitionservice.GetTatFlowByProjectId(this.projectdefinitionid).subscribe(res => {
          if (res.body[0] != null && res.body[0] !== undefined) {
            this.tatflow = JSON.parse(res.body[0]);
            this.tatflow.map(t => {
              t.tattype === null ? t.tattype = this.tattype : t.tattype = t.tattype,
                t.tathours === null ? t.tathours = this.tathours : t.tathours = t.tathours;
            }
            );
            this.forms.setControl('jobdefinition', this.formBuilder.array([]));
            this.tatflow.forEach(e => {
              this.jobdefinition = this.forms.get('jobdefinition') as FormArray;
              this.jobdefinition.push(this.initCaseRows());
            });
            this.forms.controls.jobdefinition.patchValue(this.tatflow);
            console.log('this.tatflow=', this.tatflow);
          }
        }, function (error) { this.toastr.error('Error while getting data'); });
      }

    } else {
      this.toastr.warning('Please choose any job');
    }
  }

  async loadSummary() {
    if (this.projectdefinitionid) {
      this.tatflow = [];
      this.forms.value.jobdefinition.forEach(element => {
        this.tatflow.push(element);
      });
      this.jobItem = [];
      this.jobItem.push(this.selectedJobInfo);
      this.displayStep1 = false;
      this.displayStep2 = false;
      this.displayStep3 = false;
      this.displayStep4 = true;
      if (this.isjobflow === true) {
        let jobFlowChart = [];
        this.workflowName = this.selectedJobInfo.project_subtitle;
        console.log(this.selectedJobInfo);
        // jobFlowChart = await this.loadJobFlowChart(this.selectedJobInfo.jobid);
        jobFlowChart = await this.loadProjectFlowChart(this.selectedJobInfo.projectdefinitionid);
        if (jobFlowChart !== undefined && jobFlowChart !== null && jobFlowChart[0] !== undefined
          && jobFlowChart[0] !== null) {
          let result = '';
          result = JSON.parse(jobFlowChart[0]);
          this.flowChartRender(result, 'mermaidfinish');
        } else {
          this.clearMermaidDiv('mermaidfinish');
        }
      }
      if (this.isjobflow === false) {
        let projectFlowChart = [];
        this.workflowName = this.selectedJobInfo.project_subtitle;
        projectFlowChart = await this.loadProjectFlowChart(this.selectedJobInfo.projectdefinitionid);
        if (projectFlowChart !== undefined && projectFlowChart !== null && projectFlowChart[0] !== undefined
          && projectFlowChart[0] !== null) {
          let result = '';
          result = JSON.parse(projectFlowChart[0]);
          this.flowChartRender(result, 'mermaidfinish');
        } else {
          this.clearMermaidDiv('mermaidfinish');
        }
      }
    } else {
      this.toastr.warning('Please choose any job');
    }
  }
  saveJobWorkflow() {
    let jobWorkflowDefinition = [];
    if (this.projectflow.length > 0) {
      if (this.isjobflow === true) {
        jobWorkflowDefinition = this.formJobWorkflowInput(this.projectflow, 'update');
        this.jobdefinitionservice.updateJobWorkflow(jobWorkflowDefinition).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('Job configuration inserted successfully');
              this.router.navigate(['/jobconfiguration/jobmaster']);
            } else {
              this.toastr.error('Project configuration failed');
            }
          }
        }, err => { this.toastr.error('Project configuration failed'); });
      }
      if (this.isjobflow === false) {
        jobWorkflowDefinition = this.formJobWorkflowInput(this.projectflow, 'insert');
        this.jobdefinitionservice.addJobWorkflow(jobWorkflowDefinition).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('Job configuration inserted successfully');
              this.router.navigate(['/jobconfiguration/jobmaster']);
            } else {
              this.toastr.error('Project configuration failed');
            }
          }
        }, err => { this.toastr.error('Project configuration failed'); });
      }
    }
  }

  // method to form projectworkflow definition motel
  formJobWorkflowInput(projectflow, mode) {
    //  let jobWorkflowDefinitionTmp: JobWorkflowDefinition[] = [];
    const jobWorkflowDefinitionTmp = [];
    let tathours: any; let tattype: any;
    if (mode === 'insert') {

      this.tatflow.map(t => {
        t.tattype === this.tattype ? t.tattype = null : t.tattype = t.tattype,
          t.tathours === this.tathours ? t.tathours = null : t.tathours = t.tathours;
      });
      projectflow.forEach(i => {
        const data = this.tatflow.filter(j => i.stageid === j.stageid && i.stagename_alias === j.stagename_alias);
        tathours = ''; tattype = '';
        if (data.length > 0) {
          tathours = data[0].tathours;
          tattype = data[0].tattype;
        } else {
          tathours = i.tathours;
          tattype = i.tattype;
        }
        jobWorkflowDefinitionTmp.push({
          active: 1, stageid: i.stageid, jobid: this.selectedJobInfo.jobid, stagename_alias: i.stagename_alias,
          wfdid: i.wfdid, allocationtype: i.allocationtype, allocation_mode: i.allocation_mode, checkin_app: i.checkin_app,
          checkout_app: i.checkout_app, file_movement: i.file_movement, folder_name: i.folder_name, hidebypass: i.hidebypass,
          hidereverse: i.hidereverse, merged_lot: i.merged_lot, movebackstage: i.movebackstage, nextstage: i.nextstage,
          parallelstage: i.parallelstage, process_without_file: i.process_without_file, resetstage: i.resetstage,
          show_file_browser: i.show_file_browser, stage_type: i.stage_type, unit: i.unit, benchmark: i.benchmark,
          unmerge_lot: i.unmerge_lot, signoffnotification: i.signoffnotification, mailtemplate: i.mailtemplate,
          inprocessapp: i.inprocessapp, createdby: +this.userid, stageorder: i.stageorder, mailattachment: i.mailattachment,
          checklistlog: i.checklistlog, checklisttemplateid: i.checklisttemplateid, acknowledgement: i.acknowledgement,
          ackmailtemplate: i.ackmailtemplate, pmnotification: i.pmnotification, pmmailtemplate: i.pmmailtemplate,
          tathours: tathours, tattype: tattype, querycompilation: i.querycompilation, querycomtemplateid: i.querycomtemplateid,
          querybatch: i.querybatch, backmatterstart: i.backmatterstart, islotenable: i.islotenable,
          multiplemoveback: i.multiplemoveback
        });
      });
      return jobWorkflowDefinitionTmp;
    }
    if (mode === 'update') {
      this.tatflow.map(t => {
        t.tattype === this.tattype ? t.tattype = null : t.tattype = t.tattype,
          t.tathours === this.tathours ? t.tathours = null : t.tathours = t.tathours;
      });
      projectflow.forEach(item => {
        const data = this.tatflow.filter(j => item.stageid === j.stageid && item.stagename_alias === j.stagename_alias);
        tathours = ''; tattype = '';
        if (data.length > 0) {
          tathours = data[0].tathours;
          tattype = data[0].tattype;
        } else {
          tathours = item.tathours;
          tattype = item.tattype;
        }
        jobWorkflowDefinitionTmp.push({
          active: 1, stageid: item.stageid, jobid: this.selectedJobInfo.jobid, stagename_alias: item.stagename_alias,
          wfdid: item.wfdid, allocationtype: item.allocationtype, allocation_mode: item.allocation_mode,
          checkin_app: item.checkin_app, checkout_app: item.checkout_app, file_movement: item.file_movement,
          folder_name: item.folder_name, hidebypass: item.hidebypass, hidereverse: item.hidereverse, merged_lot: item.merged_lot,
          movebackstage: item.movebackstage, nextstage: item.nextstage,
          parallelstage: item.parallelstage, process_without_file: item.process_without_file, resetstage: item.resetstage,
          show_file_browser: item.show_file_browser, stage_type: item.stage_type, unit: item.unit, benchmark: item.benchmark,
          unmerge_lot: item.unmerge_lot, signoffnotification: item.signoffnotification, mailtemplate: item.mailtemplate,
          inprocessapp: item.inprocessapp, updatedby: +this.userid, stageorder: item.stageorder, mailattachment: item.mailattachment,
          checklistlog: item.checklistlog, checklisttemplateid: item.checklisttemplateid, acknowledgement: item.acknowledgement,
          ackmailtemplate: item.ackmailtemplate, pmnotification: item.pmnotification, pmmailtemplate: item.pmmailtemplate,
          tathours: tathours, tattype: tattype, querycompilation: item.querycompilation, querycomtemplateid: item.querycomtemplateid,
          querybatch: item.querybatch, backmatterstart: item.backmatterstart, islotenable: item.islotenable,
          jobworkflowid: item.jobworkflowid, multiplemoveback: item.multiplemoveback
        });
      });
      return jobWorkflowDefinitionTmp;
    }
  }

  settat(index, data, mode) {
    if (mode === 'tathour' && data.target.value !== '7') {
      this.tatflow[index].tathours = data.target.value;
    }
    if (mode === 'tattype' && data.target.value !== 'Days') {
      this.tatflow[index].tattype = data.target.value;
    }
  }
  GetTATdetails() {
    this.projectConfigurationService.GetTATdetails().subscribe(
      res => {
        console.log(res);
        this.tathours = res.tathours;
        this.tattype = res.tattype;
      }
    );
  }
  AddModelJob(jobmaster: Jobmaster) {
    if (this.projectdefinitionid) {
      this.SpinnerService.show();
      console.log('jobmaster=', jobmaster);
      jobmaster.updatedby = this.userid;
      jobmaster.startdate = this.jobDefinitionForm.value.selectedDaterange[0];
      jobmaster.enddate = this.jobDefinitionForm.value.selectedDaterange[1];
      // jobmaster.jobmetadata = JSON.stringify(this.metadtalist1);
      jobmaster.jobmetadata = JSON.stringify(this.metadtalist1.map(i => ({ jobmetaid: i.jobmetaid, FieldValue: i.FieldValue })));
      console.log('jobmaster.startdate=', jobmaster.startdate);
      console.log('jobmaster.enddate=', jobmaster.enddate);
      this.jobmasterservice.Put(jobmaster).subscribe(res => {
        this.SpinnerService.hide();
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.toastr.success('Data updated successfully');
            } else { this.toastr.warning('Record already exists.'); }
          }
        }
      },
        error => {
          this.toastr.error('Error while doing the operation');
          this.SpinnerService.hide();
        });
    } else {
      this.toastr.warning('Please choose any job');
      this.SpinnerService.hide();
    }
  }
  onStepChange(eve) {
    if (eve.selectedStep.state === 'JobDefinition') {
      this.loadJobDefinition();
    } else if (eve.selectedStep.state === 'workFlow') {
      this.loadWorkflowMapping('');
    } else if (eve.selectedStep.state === 'TATConfiguration') {
      this.loadTATConfiguration();
    } else if (eve.selectedStep.state === 'finish') {
      this.loadSummary();
    }
  }
  OpenMetaData(template: TemplateRef<any>) {
    this.jobMetaDataModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }
  // AddMetaData(){    
  //   if(this.selectedfieldname === undefined || this.selectedfieldname === null || this.selectedfieldname === 0 ){
  //     this.toastr.error('Select the field name');
  //     return false;
  //   }
  //   if(this.fieldvalue === undefined || this.fieldvalue === null || this.fieldvalue === '' ){
  //     this.toastr.error('Select the field value');
  //     return false;
  //   }
  //   this.metadtalist1.push({
  //     FieldName: this.selectedfieldname,
  //     FieldValue: this.fieldvalue
  // });
  // this.selectedfieldname = 0;
  // this.fieldvalue = '';
  // }
  AddMetaData() {
    if (this.selectedfieldid === undefined || this.selectedfieldid === null || this.selectedfieldid === 0) {
      this.toastr.error('Select the field name');
      return false;
    }
    if (this.fieldvalue === undefined || this.fieldvalue === null || this.fieldvalue === '') {
      this.toastr.error('Select the field value');
      return false;
    }
    if (this.metadtalist1.length > 0) {
      var res = this.metadtalist1.filter(a => a.FieldName === this.selectedfieldid);
    }
    if (res && res.length > 0) {
      this.toastr.warning('Field already selected');
      return;
    } else {
      const data = this.jobMetadata.filter(i => i.jobmetaid === +this.selectedfieldid);
      if (data.length > 0) {
        this.selectedfieldname = data[0].jobmeta;
      }
      this.metadtalist1.push({
        jobmetaid: this.selectedfieldid,
        FieldName: this.selectedfieldname,
        FieldValue: this.fieldvalue
      });
    }

    this.selectedfieldid = 0;
    this.fieldvalue = '';

  }
  getJobMetaFields() {
    this.jobMetaService.GetActive().subscribe(res => {
      if (res.length > 0) {

        this.jobMetadata = JSON.parse(res[0]);

      }

    }, err => {
      this.toastr.error('Error While geting JobMetaData');
    });
  }
}
