import { Component, OnInit, TemplateRef, ViewChild, ElementRef } from '@angular/core';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { WorkFlow } from 'src/app/workflowconfiguration/workflow/workflow';
import { ToastrService } from 'ngx-toastr';
import { WorkFlowService } from '../workflow/workflow.service';
import { FormGroup, Validators, FormBuilder, FormArray } from '@angular/forms';
import { MailtemplateService } from '../../masters/mailtemplate/mailtemplate.service';
import { FiletypeService } from '../../masters/filetype/filetype.service';
import { StageService } from 'src/app/masters/stage/stage.service';
import { Stage } from 'src/app/masters/stage/stage';
import { WorkflowconfigurationService } from './workflowconfiguration.service';
import { WorkFlowDefinition, InOutFile } from './workflowconfiguration';
import { ChecklistService } from '../../masters/checklist/checklist.service';
import * as mermaid from 'mermaid';
import * as mermaidAPI from 'mermaid';
import * as $ from 'jquery';
import { Stagetype } from 'src/app/masters/stagetype/stagetype';
import { Application } from 'src/app/masters/application/application';
import { Unit } from 'src/app/masters/unit/unit';
import { ApplicationService } from 'src/app/masters/application/application.service';
import { UnitService } from 'src/app/masters/unit/unit.service';
import { StagetypeService } from 'src/app/masters/stagetype/stagetype.service';
import { AllocationtypeService } from 'src/app/masters/allocationtype/allocationtype.service';
import { AllocationType } from 'src/app/masters/allocationtype/allocationtype';
import { Router } from '@angular/router';
import { DialogService } from 'ng2-bootstrap-modal';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { FbeditorComponent } from '../../Shared/fbeditor/fbeditor.component';
import * as XLSX from 'xlsx';
import * as FileSaver from 'file-saver';
type AOA = any[][];
import { NgxSpinnerService } from 'ngx-spinner';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
import { HttpClient } from '@angular/common/http';
import { FeatureService } from 'src/app/masters/feature/feature.service';
import { AppurlService } from 'src/app/masters/appurl/appurl.service';
@Component({
  selector: 'app-workflowconfiguration',
  templateUrl: './workflowconfiguration.component.html',
  styleUrls: ['./workflowconfiguration.component.css']
})

export class WorkflowconfigurationComponent implements OnInit {


  @ViewChild('mermaid', { static: false }) mermaidDiv: ElementRef;
  operation: string;
  workflows = [];
  workflow: any = [];
  WorkFlowDefinition: WorkFlowDefinition;
  stages = [];
  showallstatus = false;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };
  workflowModalRef: BsModalRef;
  p = 1;
  searchText: string;
  itemsPerPage = 10;
  workflowForm: FormGroup;
  workflowconfigurationForm: FormGroup;
  reverse = false;
  MappedStage: any = [];
  userid: number;
  activeMailTemplate: any = [];
  activeFileType: any = [];
  inputFileType: any[] = [];
  outputFileType: any[] = [];
  activeChecklist: any = [];
  mappedStageMovement: any = [];
  mappedStageList: any = [];
  displayStep1 = true;
  displayStep2 = false;
  displayStep3 = false;
  responsestages = [];
  applications: Application[] = [];
  stagecongifchanged = false;
  units: Unit[] = [];
  stagetypes: Stagetype[] = [];
  allocationtypes: AllocationType[] = [];
  stageFilter = '';
  workFlowIdFromMaster: any;
  workFlowNameFromMaster: any;
  workFlowDescriptionFromMaster: any;
  selectedStage = undefined;
  Selectedallocationtype = undefined;
  SelectedApplicationtype = undefined;
  Selectedcheckoutapp = undefined;
  Selectedunit = undefined;
  Selectedstagetype = undefined;
  stageconfigForm: FormGroup;
  selectedRow = -1;
  key = 'workflowname';
  InOutFile: InOutFile[];
  graphDefinitionString: string;
  isMetaFieldsChk = false;
  // data: AOA = [[1, 2], [3, 4]];

  // pop up variables
  metaFieldModalRef: BsModalRef;
  isexecuted = false;
  // form builder varaibales
  formElement: any;
  feature1: Application;
  feature2: Application;
  feature3: Application;
  FeatureselectedItemsCheckIn: any = [];
  FeatureselectedItemsCheckOut: any = [];
  FeatureselectedItemsInProgress: any = [];
  mappedNextStageList: any = [];
  multipleMoveBackList: any = [];
  MultipleMoveBackDDLSettings = {
    singleSelection: false,
    idField: 'stageid',
    textField: 'stagename_alias',
    selectAllText: 'Select All',
    unSelectAllText: 'UnSelect All',
    // itemsShowLimit: 7,
    allowSearchFilter: true
  };
  actionRights: any;
  checkinweburl = false;
  checkinserviceurl = false;
  checkoutweburl = false;
  checkoutserviceurl = false;
  inprogressweburl = false;
  inprogressserviceurl = false;
  appurlsData: any[] = [];
  appurlsweb: any[] = [];
  feature: any[] = [];
  featureactive: any[] = [];
  publicationtypelist = [];
  Online = 'Online'; Print='Print'; Both = 'Both';
  constructor(
    private modalService: BsModalService,
    private formBuilder: FormBuilder,
    private toastr: ToastrService,
    private workflowservice: WorkFlowService,
    private stageservice: StageService,
    private workflowconfigurationservice: WorkflowconfigurationService,
    private mailtemplateservice: MailtemplateService,
    private filetypeservice: FiletypeService,
    private checklistservice: ChecklistService,
    private applicationservice: ApplicationService,
    private unitservice: UnitService,
    private stagetypeservice: StagetypeService,
    private allocationtypeservice: AllocationtypeService,
    private router: Router,
    private dialogService: DialogService,
    private fbEditor: FbeditorComponent,
    private SpinnerService: NgxSpinnerService,
    private httpClient: HttpClient,
    private featureservice: FeatureService,
    private appurlservice: AppurlService
  ) {
    // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('WorkFlowConfiguration_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('WorkFlowConfiguration_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('WorkFlowConfiguration_userRights');
    }
    const navigation = this.router.getCurrentNavigation();

    const state = navigation.extras.state as {
      workflowid: any;

      workflowname: any;

      description: any;

    };

    if (state !== null && state !== undefined) {

      this.workFlowIdFromMaster = state.workflowid;

      this.workFlowNameFromMaster = state.workflowname;

      this.workFlowDescriptionFromMaster = state.description;

    }
  }

  ngOnInit() {
    this.userid = +localStorage.getItem('userid');
    this.searchText = '';
    this.workflows = [];
    this.workflowservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.workflows = JSON.parse(res[0]);
        this.workflows = this.workflows.filter(w => w.active === 1);
      }
    }, error => { this.toastr.error('Error while getting data'); });
    this.getApprlsData();
    this.getAllFeatures();
    this.loadMailTemplate();
    this.loadFileType();
    this.loadChecklist();
    this.loadApplication();
    this.loadunits();
    this.loadStageType();
    this.loadAllocationType();
    this.loadpublicationtype();
    if (this.workFlowIdFromMaster !== undefined && this.workFlowIdFromMaster !== null && this.workFlowIdFromMaster > 0) {
      const input = [];
      input.push({
        'workflowid': this.workFlowIdFromMaster, 'workflowname': this.workFlowNameFromMaster,
        'description': this.workFlowDescriptionFromMaster
      });
      this.workflow = [];
      this.workflow = input[0];
      this.onflowchanged();
    }
    this.selectedStage = [];


    this.stageconfigForm = this.formBuilder.group({
      wfdid: [],
      inputfiletype: new FormArray([]),
      outputFileType: new FormArray([]),
      inoutfiletype: new FormArray([]),
      inputfile: [0],
      outputfile: [0],
      allocationtype: [0],
      unit: [0],
      stagetype: [0],
      checkin_app: [0],
      checkout_app: [0],
      inprocessapp: [0],
      checklisttemplateid: [0],
      ackmailtemplate: [0],
      pmmailtemplate: [0],
      signoffnotification: [0],
      mailtemplate: [0],
      mailattachment: [0],
      checklistlog: [0],
      acknowledgement: [0],
      pmnotification: [0],
      querycomtemplateid: [0],
      querycompilation: [0],
      querybatch: [0],
      merged_lot: [0],
      process_without_file: [0],
      backmatterstart: [0],
      IsMetaFields: [0],
      islotenable: [0],
      publicationtype: [0],
    });
  }

  loadFlowChart() {
    if (this.workflow !== undefined && this.workflow != null && this.workflow['workflowid'] > 0) {
      const stagetypeFilter = [];
      let MappedStageValidate = [];
      this.workflow.wfid = this.workflow.workflowid;
      const inputData: any = [];
      inputData.push({
        wfid: this.workflow.workflowid
      });
      this.workflowconfigurationservice.GetById(inputData[0]).subscribe(wfresponse => {
        MappedStageValidate = JSON.parse(wfresponse.body[0]);
        if (MappedStageValidate != null) {
          MappedStageValidate.forEach((stage, index) => {
            console.log('stage=', stage.stagetype);
            if (stage.stagetype === null) {
              stagetypeFilter.push(stage.stagename_alias);
            }
          });
          if (stagetypeFilter.length > 0) {
            this.toastr.warning('Please choose stage type for following stages <br>' + stagetypeFilter.toString(), '',
              { enableHtml: true });
            return;
          } else {
            this.displayStep1 = false;
            this.displayStep2 = false;
            this.displayStep3 = true;
            const inputFlowChartData = [];
            inputFlowChartData.push({
              wfid: this.workflow['workflowid']
            });
            this.workflowconfigurationservice.getFlowChart(inputFlowChartData[0]).subscribe(res => {
              if (res.body !== undefined && res.body !== null && res.body[0] !== undefined && res.body[0] !== null) {
                let result = '';
                result = JSON.parse(res.body[0]);
                result = result.replace(/\^ /g, '\n');
                result = result.replace(/\^/g, '\n');
                result = result.replace(/\\n/g, '\n');

                const element: any = this.mermaidDiv.nativeElement;
                let graphDefinition = '';
                console.log(graphDefinition);
                graphDefinition = 'graph TB\n' + result;
                this.graphDefinitionString = graphDefinition;
                $('#mermaid').text(graphDefinition);
                element.innerHTML = '';
                mermaidAPI.render('graphDiv', graphDefinition, (svgCode, bindFunctions) => {
                  element.innerHTML = svgCode;
                });

              }
            });
          }
        } else {
          this.toastr.warning('Please choose any one workflow stage');
        }
      }, error => { this.toastr.error('Error while getting workflow data'); });
    } else {
      this.toastr.warning('Please choose any workflow');
    }
  }
  onflowchanged() {
    this.responsestages = [];
    this.stageservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.responsestages = JSON.parse(res[0]);
        if (this.showallstatus === true) {
          this.responsestages = this.responsestages.filter(s => s.active === 1);
        }
        this.workflow.wfid = this.workflow.workflowid;
        const inputData: any = [];
        inputData.push({
          wfid: this.workflow.workflowid
        });
        this.workflowconfigurationservice.GetById(inputData[0]).subscribe(wfresponse => {
          console.log('res=', wfresponse);
          this.MappedStage = JSON.parse(wfresponse.body[0]);
          if (this.MappedStage != null) {
            this.MappedStage.forEach((value) => {
              this.responsestages = this.responsestages.filter((item) => {
                return item.stageid !== value.stageid;
              });
            });
            this.selectedRow = 0;
            this.loadselectedstageconfig(0);

          } else {
            this.MappedStage = [];
            this.clearsaveconfig();
          }
          this.stages = this.responsestages;
        }, error => { this.toastr.error('Error while getting workflow data'); });
      }
    }, error => { this.toastr.error('Error while getting stage data'); });
  }


  get g() { return this.workflowconfigurationForm.controls; }
  // function to load mail template in dropdown
  loadMailTemplate() {
    this.activeMailTemplate = [];
    let tmpList = [];
    this.mailtemplateservice.GetActive().subscribe(res => {
      if (res !== undefined && res != null && res[0] !== undefined && res[0] != null) {
        if (JSON.parse(res[0]).length > 0) {
          tmpList = JSON.parse(res[0]);
          tmpList.forEach(i => {
            this.activeMailTemplate.push({
              mailtemplateid: i.mailtemplateid,
              mailtemplatename: i.mailtemplatename,
            });
          });
        }
      }
    });

  }
  loadAllocationType() {
    this.allocationtypes = [];
    this.allocationtypeservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.allocationtypes = JSON.parse(res[0]);
        this.allocationtypes = this.allocationtypes.filter(a => a.active === 1);
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }
  // function to load in out file types
  loadFileType() {
    this.activeFileType = [];
    this.filetypeservice.GetActive().subscribe(res => {
      if (res !== undefined && res != null && res[0] !== undefined && res[0] != null) {
        if (JSON.parse(res[0]).length > 0) {
          this.activeFileType = JSON.parse(res[0]);
        }
      }
    });
  }
  // method to load active checklist in dropdown
  loadChecklist() {
    this.activeChecklist = [];
    this.checklistservice.GetActive().subscribe(res => {
      if (res !== undefined && res != null && res[0] !== undefined && res[0] != null) {
        if (JSON.parse(res[0]).length > 0) {
          this.activeChecklist = JSON.parse(res[0]);
        }
      }
    });
  }

  // method to show the stage movement stage
  async loadStageMovement(stepper) {
    if (this.workflow !== undefined && this.workflow != null && this.workflow['workflowid'] > 0) {
      const stagetypeFilter = [];
      let MappedStageValidate = [];
      this.workflow.wfid = this.workflow.workflowid;
      const inputData: any = [];
      inputData.push({
        wfid: this.workflow.workflowid
      });
      await this.workflowconfigurationservice.GetById(inputData[0]).subscribe(wfresponse => {
        MappedStageValidate = JSON.parse(wfresponse.body[0]);
        if (MappedStageValidate != null) {
          MappedStageValidate.forEach((stage, index) => {
            console.log('stage=', stage.stagetype);
            if (stage.stagetype === null) {
              stagetypeFilter.push(stage.stagename_alias);
            }
          });
          if (stagetypeFilter.length > 0) {
            this.toastr.warning('Please choose stage type for following stages <br>' + stagetypeFilter.toString(), '',
              { enableHtml: true });
            return;
          } else {
            if (stepper.selected.state === 'definestages') {
              stepper.next();
            }
            this.displayStep1 = false;
            this.displayStep2 = true;
            this.displayStep3 = false;
            // this.mappedStageMovement = [];
            this.mappedStageList = [];
            const inputData: any = [];
            inputData.push({
              wfid: this.workflow['workflowid']
            });
            this.workflowconfigurationservice.GetById(inputData[0]).subscribe(res => {
              if (res.body !== undefined && res.body != null) {
                if (JSON.parse(res.body[0]).length > 0) {
                  this.mappedStageMovement = JSON.parse(res.body[0]);
                  // console.log(this.mappedStageMovement);
                  this.mappedStageList = [];
                  this.multipleMoveBackList = [];
                  this.mappedStageMovement.forEach((d, i) => {
                    if (d.multiplemoveback) {
                      if (d.multiplemoveback.includes('\\')) {
                        this.multipleMoveBackList[i] = JSON.parse(JSON.parse(d.multiplemoveback));
                      } else {
                        this.multipleMoveBackList[i] = JSON.parse(d.multiplemoveback);
                      }

                    } else {
                      this.multipleMoveBackList[i] = null;
                    }

                  });

                  this.mappedStageList = this.mappedStageMovement.map(i => ({ stageid: i.stageid, stagename_alias: i.stagename_alias }));
                  this.mappedNextStageList = this.mappedStageMovement.filter(e => e.nextstage === null);
                  if (this.mappedNextStageList.length === this.mappedStageList.length) {
                    this.mappedStageList.forEach((m, index) => {
                      if (this.mappedStageList.length - 1 === index) {
                        this.mappedStageMovement[index].nextstage = null;
                      } else {
                        this.mappedStageMovement[index].nextstage = this.mappedStageList[index + 1].stageid;
                      }
                    });
                  }
                }
              }
            });
          }
        } else {
          this.toastr.warning('Please choose any one workflow stage');
        }
      }, error => { this.toastr.error('Error while getting workflow data'); });
    } else {
      this.toastr.warning('Please choose any workflow');
    }
  }
  // method to show add new stage
  loadAddNew() {
    this.displayStep1 = true;
    this.displayStep2 = false;
    this.displayStep3 = false;
  }
  openserachwindow(template: TemplateRef<any>) {
    this.SpinnerService.show();
    this.operation = 'add';
    this.workflowservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.workflows = JSON.parse(res[0]);
        this.workflows = this.workflows.filter(w => w.active === 1);
        this.workflowModalRef = this.modalService.show(template, this.config);
        this.SpinnerService.hide();
      }
      const aa = document.getElementsByClassName('modal-content');
      aa[0].classList.remove('modal-content');
    }, error => { this.toastr.error('Error while getting data'); });
  }

  onsearchclick(wf) {
    this.workflow = wf;
    this.workflowModalRef.hide();
    this.onflowchanged();
  }

  addStage(stage) {
    this.workflow.wfdid = 0;
    this.workflow.stageid = stage.stageid;
    this.workflow.stagename_alias = stage.stage;
    this.workflow.stageorder = this.MappedStage.length + 1;
    this.workflow.wfid = this.workflow.workflowid;
    this.workflow.createdby = this.userid;
    this.workflowconfigurationservice.Post(this.workflow).subscribe(res => {
      if (res.status === 200) {
        if (res !== undefined) {
          if (res.body !== 0) {
            this.MappedStage.push(JSON.parse(res.body[0])[0]);
            const ind = this.stages.findIndex(x => x.stageid === stage.stageid);
            let indx = 0;
            indx = this.MappedStage.length > 0 ? this.MappedStage.length - 1 : 0;
            this.selectedRow = indx;
            this.loadselectedstageconfig(indx);

            this.stages.splice(ind, 1);
            this.toastr.success('Data added successfully');
          } else { this.toastr.warning('Record already exists.'); }
        }
      }
    },
      error => {
        console.log(error);
        this.toastr.error('Error while doing the operation');


      });
  }

  removeStage(stage) {
    this.workflow.wfdid = this.MappedStage[stage].wfdid;
    this.workflow.active = 0;
    this.workflow.updatedby = this.userid;
    this.workflowconfigurationservice.Delete(this.workflow).subscribe(res => {
      if (res.status === 200) {
        if (res !== undefined) {
          if (res.body !== 0) {
            const obj = {
              stageid: this.MappedStage[stage].stageid,
              stage: this.MappedStage[stage].stagename_alias,
            };
            this.stages.push(obj);
            this.MappedStage.splice(stage, 1);
            this.toastr.success('Data removed successfully');
          } else { this.toastr.warning('Record already exists.'); }
        }




      }
    },
      error => {
        console.log(error);
        this.toastr.error('Error while doing the operation');
      });
  }

  moveUpChoice(index) {
    if (index > 0) {
      this.MappedStage.splice(index - 1, 0, this.MappedStage.splice(index, 1)[0]);
    }
  }

  moveDownChoice(index) {
    const newPosition = index + 1;
    if (index < this.MappedStage.length) {
      this.MappedStage.splice(newPosition, 0, this.MappedStage.splice(index, 1)[0]);
    }
  }

  loadApplication() {
    this.applications = [];
    this.applicationservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.applications = JSON.parse(res[0]);
        this.applications = this.applications.filter(a => a.active === 1);
        console.log('Application=', this.applications);
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  loadunits() {
    this.units = [];
    this.unitservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.units = JSON.parse(res[0]);
        this.units = this.units.filter(u => u.active === 1);
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  loadStageType() {
    this.stagetypes = [];
    this.stagetypeservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.stagetypes = JSON.parse(res[0]);
        this.stagetypes = this.stagetypes.filter(u => u.active === 1);
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  // method to save the stagemovement
  saveStageMovement() {
    const inputData: any = [];
    this.mappedStageMovement.forEach((i, ind) => {

      let movebackstages = null;
      this.multipleMoveBackList.forEach((s, j) => {
        if (ind === j) {
          if (s && s.length > 0) {
            movebackstages = JSON.stringify(s);
          }
        }
      });

      inputData.push(
        {
          wfdid: i.wfdid,
          wfid: i.wfid,
          parallelstage: +i.parallelstage > 0 ? +i.parallelstage : 0,
          nextstage: +i.nextstage > 0 ? + i.nextstage : 0,
          movebackstage: +i.movebackstage > 0 ? + i.movebackstage : 0,
          // resetstage: JSON.stringify(i.resetstage),
          multiplemoveback: movebackstages,
          // resetstage: +i.resetstage > 0 ? + i.resetstage : 0,
          updatedby: this.userid
        });
    });
    this.workflowconfigurationservice.UpdateStageMovement(inputData).subscribe(res => {
      if (res.body !== undefined && res.body != null && res.body[0] !== undefined &&
        res.body[0] !== null && JSON.parse(res.body[0]).length > 0) {
        this.toastr.success('Stage Movement saved successfully');
      }
    });
  }

  SaveOrder() {
    this.MappedStage.forEach((stage, index) => {
      stage.stageorder = index + 1;
    });
    this.MappedStage.workflowmetafields = '';
    this.workflowconfigurationservice.UpdateStageOrder(this.MappedStage).subscribe(res => {
      if (res.body !== undefined && res.body != null) {
        if (res.body[0] !== undefined && res.body[0] != null && JSON.parse(res.body[0]).length > 0) {
          this.toastr.success('Stage Movement saved successfully');
        }
      }
    });
  }
  // method to get changed stage

  changeStage(eve, wfdid, index, type) {

    if (type === 'Parallel') {

      const parallelStageId = eve.target.selectedOptions[0].value;

      const m = this.mappedStageMovement.findIndex(item => item.wfdid === wfdid);

      if (m === index) {

        this.mappedStageMovement[index]['parallelstage'] = parallelStageId;
      }

    }
    if (type === 'Next') {
      const nextStageId = eve.target.selectedOptions[0].value;
      const m = this.mappedStageMovement.findIndex(item => item.wfdid === wfdid);
      if (m === index) {
        this.mappedStageMovement[index]['nextstage'] = nextStageId;
      }
    }

    if (type === 'Moveback') {
      const moveBackStageId = eve.target.selectedOptions[0].value;
      const m = this.mappedStageMovement.findIndex(item => item.wfdid === wfdid);
      if (m === index) {
        this.mappedStageMovement[index]['movebackstage'] = moveBackStageId;
      }
    }

    if (type === 'Reset') {
      // const resetStageId = eve.target.selectedOptions[0].value;
      const resetStageId = eve.stageid;
      const m = this.mappedStageMovement.findIndex(item => item.wfdid === wfdid);
      if (m === index) {
        // this.mappedStageMovement[index]['resetstage'] = resetStageId;
        this.mappedStageMovement[index]['multiplemoveback'] = this.multipleMoveBackList[index];
      }
    }
  }

  // method for input or output file type adding
  AddinputOutputfileType(eve, type) {
    const fileTypeId = + eve.target.selectedOptions[0].value;
    const fileType = eve.target.selectedOptions[0].text;
    if (this.workflow.wfdid) {
      const workflowdefid = this.workflow.wfdid;
      if (type === 'inputFileType') {
        let inputresult = [];
        if (this.inputFileType.length) {
          inputresult = this.inputFileType.filter(item1 => item1.filemode === 1 && item1.filetype === fileTypeId);
        }
        if (inputresult === undefined || inputresult.length === 0) {
          this.inputFileType.push({
            workflowdefid: workflowdefid,
            filetypeid: fileTypeId,
            filetype: fileTypeId,
            filevalue: fileType,
            filemode: 1
          });
          this.stagecongifchanged = true;
        }
      }
      if (type === 'outputFileType') {
        let outputresult = [];
        if (this.outputFileType.length) {
          outputresult = this.outputFileType.filter(item1 => item1.filemode === 2 && item1.filetype === fileTypeId);
        }
        if (outputresult === undefined || outputresult.length === 0) {
          this.outputFileType.push({
            workflowdefid: workflowdefid,
            filetypeid: fileTypeId,
            filetype: fileTypeId,
            filevalue: fileType,
            filemode: 2
          });
          this.stagecongifchanged = true;
        }
      }
    }
  }

  // method to remove the input or output file types
  // method to remove the input or output file types
  RemoveInOutFileType(filetype, type) {
    if (type === 'inputFileType') {
      this.inputFileType.forEach((item, index) => {
        if (item.filetype === filetype) {
          this.inputFileType.splice(index, 1);
          this.stagecongifchanged = true;
        }
      });
    }
    if (type === 'outputFileType') {
      this.outputFileType.forEach((item, index) => {
        if (item.filetype === filetype) {
          this.outputFileType.splice(index, 1);
          this.stagecongifchanged = true;
        }
      });
    }
  }

  async savestageconfig() {
    if (this.workflow.wfdid === undefined) {
      this.toastr.warning('Pleas choose any stage');
      return;
    }
    this.stageconfigForm.value.inoutfiletype = [];
    this.inputFileType.forEach(element => {
      this.stageconfigForm.value.inoutfiletype.push(element);
    });
    this.outputFileType.forEach(element => {
      this.stageconfigForm.value.inoutfiletype.push(element);
    });

    this.stageconfigForm.value.wfdid = this.workflow.wfdid;
    this.stageconfigForm.value.workflowdefid = this.workflow.wfdid;

    this.stageconfigForm.value.signoffnotification = this.stageconfigForm.value.signoffnotification === true ? 1 : 0;
    this.stageconfigForm.value.allocationtype = +this.stageconfigForm.value.allocationtype !== 0 ?
      +this.stageconfigForm.value.allocationtype : null;
    this.stageconfigForm.value.unit = +this.stageconfigForm.value.unit !== 0 ? +this.stageconfigForm.value.unit : null;

    this.stageconfigForm.value.stagetype = +this.stageconfigForm.value.stagetype !== 0 ? +this.stageconfigForm.value.stagetype : null;
    this.stageconfigForm.value.checkin_app = +this.stageconfigForm.value.checkin_app !== 0 ? +this.stageconfigForm.value.checkin_app : null;
    this.stageconfigForm.value.checkout_app = +this.stageconfigForm.value.checkout_app !== 0 ?
      +this.stageconfigForm.value.checkout_app : null;

    this.stageconfigForm.value.inprocessapp = +this.stageconfigForm.value.inprocessapp !== 0 ?
      +this.stageconfigForm.value.inprocessapp : null;
    this.stageconfigForm.value.checklisttemplateid = +this.stageconfigForm.value.checklisttemplateid !== 0 ?
      + this.stageconfigForm.value.checklisttemplateid : null;
    this.stageconfigForm.value.ackmailtemplate = +this.stageconfigForm.value.ackmailtemplate !== 0 ?
      +this.stageconfigForm.value.ackmailtemplate : null;

    this.stageconfigForm.value.pmmailtemplate = +this.stageconfigForm.value.pmmailtemplate !== 0 ?
      +this.stageconfigForm.value.pmmailtemplate : null;
    this.stageconfigForm.value.mailtemplate = +this.stageconfigForm.value.mailtemplate !== 0 ?
      +this.stageconfigForm.value.mailtemplate : null;
    this.stageconfigForm.value.mailattachment = this.stageconfigForm.value.mailattachment === true ? 1 : 0;

    this.stageconfigForm.value.checklistlog = this.stageconfigForm.value.checklistlog === true ? 1 : 0;
    this.stageconfigForm.value.acknowledgement = this.stageconfigForm.value.acknowledgement === true ? 1 : 0;
    this.stageconfigForm.value.pmnotification = this.stageconfigForm.value.pmnotification === true ? 1 : 0;

    this.stageconfigForm.value.querycomtemplateid = +this.stageconfigForm.value.querycomtemplateid !== 0 ?
      +this.stageconfigForm.value.querycomtemplateid : null;
    this.stageconfigForm.value.querycompilation = this.stageconfigForm.value.querycompilation === true ? 1 : 0;
    this.stageconfigForm.value.querybatch = this.stageconfigForm.value.querybatch === true ? 1 : 0;

    this.stageconfigForm.value.merged_lot = this.stageconfigForm.value.merged_lot === true ? 1 : 0;
    this.stageconfigForm.value.process_without_file = this.stageconfigForm.value.process_without_file === true ? 1 : 0;
    this.stageconfigForm.value.backmatterstart = this.stageconfigForm.value.backmatterstart === true ? 1 : 0;

    this.stageconfigForm.value.islotenable = this.stageconfigForm.value.islotenable === true ? 1 : 0;
    this.stageconfigForm.value.updatedby = this.userid;

    this.stageconfigForm.value.checkinappfeature = this.FeatureselectedItemsCheckIn;
    this.stageconfigForm.value.checkoutappfeature = this.FeatureselectedItemsCheckOut;
    this.stageconfigForm.value.inprocessappfeature = this.FeatureselectedItemsInProgress;
    // supplement type added
    this.stageconfigForm.value.publicationtype = this.stageconfigForm.value.publicationtype;
    console.log('savestageconfig=', this.stageconfigForm.value);

    await (await this.workflowconfigurationservice.PostStageConfig(this.stageconfigForm.value)).subscribe(async res => {
      if (res.body !== undefined && res.body != null) {
        this.toastr.success('Stage config saved successfully');
        this.stagecongifchanged = false;

        if (this.stageconfigForm.value.inoutfiletype.length) {
          await this.workflowconfigurationservice.UpdateInOutFile(this.stageconfigForm.value.inoutfiletype).subscribe(async res1 => {
            if (res1.body !== undefined && res1.body != null) {
              this.loadselectedstageconfig(this.selectedRow);
            }
          });
        } else {
          this.workflowconfigurationservice.UpdateInOutFileOnEmpty(this.stageconfigForm.value).subscribe(res1 => {
            if (res1.body !== undefined && res1.body != null) {
              this.loadselectedstageconfig(this.selectedRow);
            }
          });
        }
      }
    });
  }

  onconfigchanged() {
    this.stagecongifchanged = true;
  }

  onappconfigchanged1() {
    console.log('calling');
    this.stagecongifchanged = true;

    this.applicationservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {


        this.applications = JSON.parse(res[0]);
        this.applications = this.applications.filter(a => a.active === 1);
        console.log('Application=', this.applications);
        this.feature1 = this.applications.find(f => f.applicationid === +this.stageconfigForm.value.checkin_app);
        this.FeatureselectedItemsCheckIn = [];
        const feature1a = [];
        if (this.WorkFlowDefinition.checkinappfeature != null && this.WorkFlowDefinition.checkinappfeature.length) {
          this.featureactive.forEach(element => {
            if (this.feature1.webappfeature.
              filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
              feature1a.push(this.feature1.webappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
            }
          });
          console.log('this.feature1a', feature1a);
          // if (this.WorkFlowDefinition.checkinappfeature) {
          feature1a.filter(w => w.active === 1).forEach(element => {
            if ((this.WorkFlowDefinition.checkinappfeature.filter(u => u.mdata === element.mdata)
              .map(i => i)).length > 0) {
              this.FeatureselectedItemsCheckIn.push((this.WorkFlowDefinition.checkinappfeature.filter(u => u.mdata === element.mdata)
                .map(i => ({
                  metadataid: element.metadataid,
                  mdata: element.mdata,
                  active: i.active,
                  appurlid: element.appurlid,
                })))[0]);
            } else {
              element.active = 0;
              this.FeatureselectedItemsCheckIn.push(element);
            }
          });
        } else {
          if (this.feature1) {
            this.featureactive.forEach(element => {
              if (this.feature1.webappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                this.feature1.webappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; });
              }
            });

            this.FeatureselectedItemsCheckIn = this.feature1.webappfeature.filter(w => w.active === 1).map(f => ({
              metadataid: f.metadataid,
              mdata: f.mdata,
              active: 0,
              appurlid: f.appurlid,
            }));
          }
        }
        this.appurlsData.forEach(element => {
          this.FeatureselectedItemsCheckIn.filter(f => f.appurlid === element.appurlid)
            .map(f => { f.urltype = element.urltype; return f; });
        });
        console.log('FeatureselectedItemsCheckIn=', this.FeatureselectedItemsCheckIn);
        this.checkinweburl = false;
        if (this.FeatureselectedItemsCheckIn.filter(f => f.urltype === 'weburl').length > 0) {
          this.checkinweburl = true;
        }
        this.checkinserviceurl = false;
        if (this.FeatureselectedItemsCheckIn.filter(f => f.urltype === 'serviceurl').length > 0) {
          this.checkinserviceurl = true;
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });

  }

  onappconfigchanged2() {
    console.log('calling');
    this.stagecongifchanged = true;

    this.applicationservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {

        this.applications = JSON.parse(res[0]);
        this.applications = this.applications.filter(a => a.active === 1);
        console.log('Application=', this.applications);
        this.feature2 = this.applications.find(f => f.applicationid === +this.stageconfigForm.value.checkout_app);
        this.FeatureselectedItemsCheckOut = [];

        const feature2a = [];
        if (this.WorkFlowDefinition.checkoutappfeature != null && this.WorkFlowDefinition.checkoutappfeature.length) {
          this.featureactive.forEach(element => {
            if (this.feature2.webappfeature.
              filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
              feature2a.push(this.feature2.webappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
            }
          });
          console.log('this.feature2a', feature2a);

          feature2a.filter(w => w.active === 1).forEach(element => {
            if ((this.WorkFlowDefinition.checkoutappfeature.filter(u => u.mdata === element.mdata)
              .map(i => i)).length > 0) {
              this.FeatureselectedItemsCheckOut.push(
                (this.WorkFlowDefinition.checkoutappfeature.filter(u => u.mdata === element.mdata)
                  .map(i => ({
                    metadataid: element.metadataid,
                    mdata: element.mdata,
                    active: i.active,
                    appurlid: element.appurlid,
                  })))[0]);
            } else {
              element.active = 0;
              this.FeatureselectedItemsCheckOut.push(element);
            }
          });
        } else {
          if (this.feature2) {
            this.featureactive.forEach(element => {
              if (this.feature2.webappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                this.feature2.webappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; });
              }
            });
            this.FeatureselectedItemsCheckOut = this.feature2.webappfeature.filter(w => w.active === 1).map(f => ({
              metadataid: f.metadataid,
              mdata: f.mdata,
              active: 0,
              appurlid: f.appurlid,
            }));
          }
        }

        this.appurlsData.forEach(element => {
          this.FeatureselectedItemsCheckOut.filter(f => f.appurlid === element.appurlid)
            .map(f => { f.urltype = element.urltype; return f; });
        });
        console.log('FeatureselectedItemsCheckOut=', this.FeatureselectedItemsCheckOut);
        this.checkoutweburl = false;
        if (this.FeatureselectedItemsCheckOut.filter(f => f.urltype === 'weburl').length > 0) {
          this.checkoutweburl = true;
        }
        this.checkoutserviceurl = false;
        if (this.FeatureselectedItemsCheckOut.filter(f => f.urltype === 'serviceurl').length > 0) {
          this.checkoutserviceurl = true;
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  onappconfigchanged3() {
    this.stagecongifchanged = true;
    this.applicationservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.applications = JSON.parse(res[0]);
        this.applications = this.applications.filter(a => a.active === 1);
        console.log('Application=', this.applications);
        this.feature3 = this.applications.find(f => f.applicationid === +this.stageconfigForm.value.inprocessapp);
        this.FeatureselectedItemsInProgress = [];
        // if (this.WorkFlowDefinition.inprocessappfeature) {
        const feature3a = [];
        if (this.WorkFlowDefinition.inprocessappfeature != null && this.WorkFlowDefinition.inprocessappfeature.length) {
          this.featureactive.forEach(element => {
            if (this.feature3.webappfeature.
              filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
              feature3a.push(this.feature3.webappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
            }
          });
          console.log('this.feature3a', feature3a);
          feature3a.filter(w => w.active === 1).forEach(element => {
            if ((this.WorkFlowDefinition.inprocessappfeature.filter(u => u.mdata === element.mdata)
              .map(i => i)).length > 0) {
              this.FeatureselectedItemsInProgress.push(
                (this.WorkFlowDefinition.inprocessappfeature.filter(u => u.mdata === element.mdata)
                  .map(i => ({
                    metadataid: element.metadataid,
                    mdata: element.mdata,
                    active: i.active,
                    appurlid: element.appurlid,
                  })))[0]);
            } else {
              element.active = 0;
              this.FeatureselectedItemsInProgress.push(element);
            }
          });
        } else {
          if (this.feature3) {
            this.featureactive.forEach(element => {
              if (this.feature3.webappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                this.feature3.webappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; });
              }
            });
            this.FeatureselectedItemsInProgress = this.feature3.webappfeature.filter(w => w.active === 1).map(f => ({
              metadataid: f.metadataid,
              mdata: f.mdata,
              active: 0,
              appurlid: f.appurlid,
            }));
          }
        }
        this.appurlsData.forEach(element => {
          this.FeatureselectedItemsInProgress.filter(f => f.appurlid === element.appurlid)
            .map(f => { f.urltype = element.urltype; return f; });
        });
        console.log('FeatureselectedItemsInProgress=', this.FeatureselectedItemsInProgress);
        this.inprogressweburl = false;
        if (this.FeatureselectedItemsInProgress.filter(f => f.urltype === 'weburl').length > 0) {
          this.inprogressweburl = true;
        }
        this.inprogressserviceurl = false;
        if (this.FeatureselectedItemsInProgress.filter(f => f.urltype === 'serviceurl').length > 0) {
          this.inprogressserviceurl = true;
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

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

  loadStageConfig(index) {
    if (this.stagecongifchanged === true) {
      this.dialogService.addDialog(CommondialogComponent,
        {
          title: 'Please Confirm',
          message: 'Would you like to save changes? ' + this.selectedStage.stagename_alias,
          hclass: 'modelsuccess',
          oktext: 'Yes',
          canceltext: 'No',
          okshow: true,
          cancelshow: true
        }).subscribe(async (isConfirmed) => {
          if (isConfirmed) {
            this.selectedRow = index;
            await this.savestageconfig();
          } else {
            if (this.workflow.wfdid !== this.MappedStage[index].wfdid) {
              this.loadselectedstageconfig(index);
              this.selectedRow = index;
            }
          }
        }
        );
    } else {
      if (this.workflow.wfdid !== this.MappedStage[index].wfdid) {
        this.loadselectedstageconfig(index);
        this.selectedRow = index;
      }
    }
  }

  getApprlsData() {
    this.appurlservice.Get().subscribe(res => {
      if (res.status === 200) {
        this.appurlsData = JSON.parse(res.body[0]);
        this.appurlsData = this.appurlsData.filter(e => e.active === 1);
      }
    }, err => {
      this.toastr.error('Error while geting apprls');
    });
  }

  getAllFeatures() {
    this.feature = [];
    this.featureactive = [];
    this.featureservice.Get().subscribe(res => {
      this.feature = JSON.parse(res[0]);
      console.log('this.metadatas=', this.feature);
      this.featureactive = this.feature.filter(f => f.active === 1);
    }, error => { this.toastr.error('Error while getting data'); });
  }

  loadselectedstageconfig(index) {
    this.stagecongifchanged = false;
    this.workflow.wfdid = this.MappedStage[index].wfdid;
    this.selectedStage = this.MappedStage[index];
    const inputData: any = [];
    inputData.push({
      wfdid: this.MappedStage[index].wfdid
    });
    this.workflowconfigurationservice.GetByWfdId(inputData[0]).subscribe(wfdresponse => {
      console.log('wfdresponse=', wfdresponse);
      this.WorkFlowDefinition = JSON.parse(wfdresponse.body[0])[0];
      this.WorkFlowDefinition.workflowdefid = this.WorkFlowDefinition.wfdid;
      this.workflowconfigurationservice.IOGetByWfdId(this.WorkFlowDefinition).subscribe(iofileresponse => {
        console.log('iofileresponse=', iofileresponse);
        this.InOutFile = JSON.parse(iofileresponse.body[0]);
        if (this.InOutFile) {
          this.inputFileType = this.InOutFile.filter(i => i.filemode === 1);
          this.inputFileType.map(i => i.filevalue = i.filetype_s);
          this.outputFileType = this.InOutFile.filter(i => i.filemode === 2);
          this.outputFileType.map(i => i.filevalue = i.filetype_s);
        } else {
          this.inputFileType = [];
          this.outputFileType = [];
        }
      });

      this.stageconfigForm.controls['inputfile'].setValue(0);
      this.stageconfigForm.controls['outputfile'].setValue(0);

      this.stageconfigForm.controls['unit'].setValue(this.WorkFlowDefinition.unit != null ?
        this.WorkFlowDefinition.unit : 0);
      this.stageconfigForm.controls['unit'].setValue(this.WorkFlowDefinition.unit != null ?
        this.WorkFlowDefinition.unit : 0);

      this.stageconfigForm.controls['signoffnotification'].setValue(this.WorkFlowDefinition.signoffnotification === 1 ? true : false);
      this.stageconfigForm.controls['allocationtype'].setValue(this.WorkFlowDefinition.allocationtype != null ?
        this.WorkFlowDefinition.allocationtype : 0);
      this.stageconfigForm.controls['unit'].setValue(this.WorkFlowDefinition.unit != null ?
        this.WorkFlowDefinition.unit : 0);

      this.stageconfigForm.controls['stagetype'].setValue(this.WorkFlowDefinition.stagetype != null ?
        this.WorkFlowDefinition.stagetype : 0);

      this.stageconfigForm.controls['checkin_app'].setValue(this.WorkFlowDefinition.checkin_app != null ?
        this.WorkFlowDefinition.checkin_app : 0);

      // For checkin application
      this.applications = [];
      this.applicationservice.Get().subscribe(res => {
        if (res[0] != null && res[0] !== undefined) {
          this.applications = JSON.parse(res[0]);
          this.applications = this.applications.filter(a => a.active === 1);
          console.log('Application=', this.applications);
          this.feature1 = this.applications.find(f => f.applicationid === this.WorkFlowDefinition.checkin_app);
          this.FeatureselectedItemsCheckIn = [];
          const feature1a = [];
          if (this.WorkFlowDefinition.checkinappfeature != null && this.WorkFlowDefinition.checkinappfeature.length) {
            this.featureactive.forEach(element => {
              console.log('this.feature1.webappfeature=', this.feature1.webappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
              if (this.feature1.webappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                feature1a.push(this.feature1.webappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
              }
            });
            console.log('this.feature1a', feature1a);
            feature1a.filter(w => w.active === 1).forEach(element => {
              if ((this.WorkFlowDefinition.checkinappfeature.filter(u => u.mdata === element.mdata)
                .map(i => i)).length > 0) {
                this.FeatureselectedItemsCheckIn.push((this.WorkFlowDefinition.checkinappfeature.filter(u => u.mdata === element.mdata)
                  .map(i => ({
                    metadataid: element.metadataid,
                    mdata: element.mdata,
                    active: i.active,
                    appurlid: element.appurlid,
                  })))[0]);
              } else {
                element.active = 0;
                this.FeatureselectedItemsCheckIn.push(element);
              }
            });
          } else {
            if (this.feature1) {
              this.featureactive.forEach(element => {
                if (this.feature1.webappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                  this.feature1.webappfeature.
                    filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; });
                }
              });
              this.FeatureselectedItemsCheckIn = this.feature1.webappfeature.filter(w => w.active === 1).map(f => ({
                metadataid: f.metadataid,
                mdata: f.mdata,
                active: 0,
                appurlid: f.appurlid,
              }));
            }
          }
          this.appurlsData.forEach(element => {
            this.FeatureselectedItemsCheckIn.filter(f => f.appurlid === element.appurlid)
              .map(f => { f.urltype = element.urltype; return f; });
          });
          console.log('FeatureselectedItemsCheckIn=', this.FeatureselectedItemsCheckIn);
          this.checkinweburl = false;
          if (this.FeatureselectedItemsCheckIn.filter(f => f.urltype === 'weburl').length > 0) {
            this.checkinweburl = true;
          }
          this.checkinserviceurl = false;
          if (this.FeatureselectedItemsCheckIn.filter(f => f.urltype === 'serviceurl').length > 0) {
            this.checkinserviceurl = true;
          }
        }
      }, error => { this.toastr.error('Error while getting data'); });


      // For checkout_app application
      this.stageconfigForm.controls['checkout_app'].setValue(this.WorkFlowDefinition.checkout_app != null ?
        this.WorkFlowDefinition.checkout_app : 0);
      this.applications = [];
      this.applicationservice.Get().subscribe(res => {
        if (res[0] != null && res[0] !== undefined) {
          this.applications = JSON.parse(res[0]);
          this.applications = this.applications.filter(a => a.active === 1);
          this.feature2 = this.applications.find(f => f.applicationid === this.WorkFlowDefinition.checkout_app);
          this.FeatureselectedItemsCheckOut = [];
          // if (this.WorkFlowDefinition.checkoutappfeature) {

          const feature2a = [];
          if (this.WorkFlowDefinition.checkoutappfeature != null && this.WorkFlowDefinition.checkoutappfeature.length) {
            this.featureactive.forEach(element => {
              console.log('this.feature2.webappfeature=', this.feature2.webappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
              if (this.feature2.webappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                feature2a.push(this.feature2.webappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
              }
            });
            console.log('this.feature1a', feature2a);
            feature2a.filter(w => w.active === 1).forEach(element => {
              if ((this.WorkFlowDefinition.checkoutappfeature.filter(u => u.mdata === element.mdata)
                .map(i => i)).length > 0) {
                this.FeatureselectedItemsCheckOut.push((this.WorkFlowDefinition.checkoutappfeature.filter(u => u.mdata === element.mdata)
                  .map(i => ({
                    metadataid: element.metadataid,
                    mdata: element.mdata,
                    active: i.active,
                    appurlid: element.appurlid,
                  })))[0]);
              } else {
                element.active = 0;
                this.FeatureselectedItemsCheckOut.push(element);
              }
            });
          } else {
            if (this.feature2) {
              this.featureactive.forEach(element => {
                if (this.feature2.webappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                  this.feature2.webappfeature.
                    filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; });
                }
              });

              this.FeatureselectedItemsCheckOut = this.feature2.webappfeature.filter(w => w.active === 1).map(f => ({
                metadataid: f.metadataid,
                mdata: f.mdata,
                active: 0,
                appurlid: f.appurlid,
              }));
            }
          }

          this.appurlsData.forEach(element => {
            this.FeatureselectedItemsCheckOut.filter(f => f.appurlid === element.appurlid)
              .map(f => { f.urltype = element.urltype; return f; });
          });
          console.log('FeatureselectedItemsCheckOut=', this.FeatureselectedItemsCheckOut);
          this.checkoutweburl = false;
          if (this.FeatureselectedItemsCheckOut.filter(f => f.urltype === 'weburl').length > 0) {
            this.checkoutweburl = true;
          }
          this.checkoutserviceurl = false;
          if (this.FeatureselectedItemsCheckOut.filter(f => f.urltype === 'serviceurl').length > 0) {
            this.checkoutserviceurl = true;
          }

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

      this.stageconfigForm.controls['inprocessapp'].setValue(this.WorkFlowDefinition.inprocessapp != null ?
        this.WorkFlowDefinition.inprocessapp : 0);

      // For inprocessapp application
      this.applications = [];
      this.applicationservice.Get().subscribe(res => {
        if (res[0] != null && res[0] !== undefined) {
          this.applications = JSON.parse(res[0]);
          this.applications = this.applications.filter(a => a.active === 1);
          this.feature3 = this.applications.find(f => f.applicationid === this.WorkFlowDefinition.inprocessapp);
          this.FeatureselectedItemsInProgress = [];
          // if (this.WorkFlowDefinition.inprocessappfeature) {
          const feature3a = [];
          if (this.WorkFlowDefinition.inprocessappfeature != null && this.WorkFlowDefinition.inprocessappfeature.length) {
            this.featureactive.forEach(element => {
              console.log('this.feature3.webappfeature=', this.feature3.webappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
              if (this.feature3.webappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                feature3a.push(this.feature3.webappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
              }
            });
            console.log('this.feature3a', feature3a);
            feature3a.filter(w => w.active === 1).forEach(element => {
              if ((this.WorkFlowDefinition.inprocessappfeature.filter(u => u.mdata === element.mdata)
                .map(i => i)).length > 0) {
                this.FeatureselectedItemsInProgress.push(
                  (this.WorkFlowDefinition.inprocessappfeature.filter(u => u.mdata === element.mdata)
                    .map(i => ({
                      metadataid: element.metadataid,
                      mdata: element.mdata,
                      active: i.active,
                      appurlid: element.appurlid,
                    })))[0]);
              } else {
                element.active = 0;
                this.FeatureselectedItemsInProgress.push(element);
              }
            });
          } else {
            if (this.feature3) {
              this.featureactive.forEach(element => {
                if (this.feature3.webappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                  this.feature3.webappfeature.
                    filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; });
                }
              });
              this.FeatureselectedItemsInProgress = this.feature3.webappfeature.filter(w => w.active === 1).map(f => ({
                metadataid: f.metadataid,
                mdata: f.mdata,
                active: 0,
                appurlid: f.appurlid,
              }));
            }
          }
          this.appurlsData.forEach(element => {
            this.FeatureselectedItemsInProgress.filter(f => f.appurlid === element.appurlid)
              .map(f => { f.urltype = element.urltype; return f; });
          });
          console.log('FeatureselectedItemsInProgress=', this.FeatureselectedItemsInProgress);
          this.inprogressweburl = false;
          if (this.FeatureselectedItemsInProgress.filter(f => f.urltype === 'weburl').length > 0) {
            this.inprogressweburl = true;
          }
          this.inprogressserviceurl = false;
          if (this.FeatureselectedItemsInProgress.filter(f => f.urltype === 'serviceurl').length > 0) {
            this.inprogressserviceurl = true;
          }
        }
      }, error => { this.toastr.error('Error while getting data'); });

      this.stageconfigForm.controls['checklisttemplateid'].setValue(this.WorkFlowDefinition.checklisttemplateid != null ?
        this.WorkFlowDefinition.checklisttemplateid : 0);
      this.stageconfigForm.controls['ackmailtemplate'].setValue(this.WorkFlowDefinition.ackmailtemplate != null ?
        this.WorkFlowDefinition.ackmailtemplate : 0);

      this.stageconfigForm.controls['pmmailtemplate'].setValue(this.WorkFlowDefinition.pmmailtemplate != null ?
        this.WorkFlowDefinition.pmmailtemplate : 0);
      this.stageconfigForm.controls['mailtemplate'].setValue(this.WorkFlowDefinition.mailtemplate != null ?
        this.WorkFlowDefinition.mailtemplate : 0);
      this.stageconfigForm.controls['mailattachment'].setValue(this.WorkFlowDefinition.mailattachment === 1 ? true : false);

      this.stageconfigForm.controls['checklistlog'].setValue(this.WorkFlowDefinition.checklistlog === 1 ? true : false);
      this.stageconfigForm.controls['acknowledgement'].setValue(this.WorkFlowDefinition.acknowledgement === 1 ? true : false);
      this.stageconfigForm.controls['pmnotification'].setValue(this.WorkFlowDefinition.pmnotification === 1 ? true : false);

      this.stageconfigForm.controls['querycomtemplateid'].setValue(this.WorkFlowDefinition.querycomtemplateid != null ?
        this.WorkFlowDefinition.querycomtemplateid : 0);
      this.stageconfigForm.controls['querycompilation'].setValue(this.WorkFlowDefinition.querycompilation === 1 ? true : false);
      this.stageconfigForm.controls['querybatch'].setValue(this.WorkFlowDefinition.querybatch === 1 ? true : false);

      this.stageconfigForm.controls['merged_lot'].setValue(this.WorkFlowDefinition.merged_lot === 1 ? true : false);
      this.stageconfigForm.controls['process_without_file'].setValue(this.WorkFlowDefinition.process_without_file === 1 ? true : false);
      this.stageconfigForm.controls['backmatterstart'].setValue(this.WorkFlowDefinition.backmatterstart === 1 ? true : false);

      this.stageconfigForm.controls['islotenable'].setValue(this.WorkFlowDefinition.islotenable === 1 ? true : false);
      this.stageconfigForm.controls['publicationtype'].setValue(this.WorkFlowDefinition.publicationtype);
      if (this.WorkFlowDefinition.workflowmetafields !== null) {
        this.isMetaFieldsChk = true;
      } else {
        this.isMetaFieldsChk = false;
      }
    }, error => { this.toastr.error('Error while getting workflow data'); });
  }

  // method to redirect the page to workflow master page
  finishWorkFlowConfig() {
    this.toastr.success('Workflow defined successfully.');
    this.router.navigate(['/workflowconfiguration/workflow']);
  }

  // method to download flow chart
  downloadflowchart(node, workflowName) {
    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();
      };
    }
  }

  // method to show the add meta field button
  metaFieldChecked(eve) {
    if (eve.target.checked === true) {
      this.isMetaFieldsChk = true;
    } else {
      this.isMetaFieldsChk = false;
    }
  }

  // method to save the meta fields details of the stage
  saveStageConfigMetaFields(template: TemplateRef<any>) {
    this.metaFieldModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }

  getfrmValue($event) {
    this.formElement = $event;
    if (this.formElement !== undefined && this.formElement !== null && JSON.parse(this.formElement).length > 0) {
      let metaFields = [];
      const tmp = JSON.parse(this.formElement);
      metaFields = tmp.map((item, index) => {
        item.workflowdid = this.selectedStage.wfdid; return item;
      });
      const metaFieldsInput = [];
      metaFieldsInput.push({
        wfdid: this.selectedStage.wfdid, wfid: this.selectedStage.wfid,
        workflowmetafields: JSON.stringify(metaFields), updatedby: this.userid,
      });
      this.workflowconfigurationservice.UpdateStageMetaFields(metaFieldsInput[0]).subscribe(res => {
        if (res.body !== undefined && res.body != null && res.body[0] !== undefined &&
          res.body[0] !== null && JSON.parse(res.body[0]).length > 0) {
          this.metaFieldModalRef.hide();
          this.toastr.success('Metafields saved successfully.');
        }
      }, err => { this.toastr.error(err); });
    } else {
      this.toastr.error('Metafields cannot be empty.');
    }
  }
  onStepChange(eve) {
    if (eve.selectedStep.state === 'workflowDefinitionStep') {
      this.loadAddNew();
    }
    if (eve.selectedStep.state === 'stage') {
      this.loadStageMovement('');
    }
    if (eve.selectedStep.state === 'review') {
      this.loadFlowChart();
    }
  }
  clearsaveconfig() {

    this.inputFileType = [];
    this.outputFileType = [];

    this.stageconfigForm.controls['inputfile'].setValue(0);
    this.stageconfigForm.controls['outputfile'].setValue(0);

    this.stageconfigForm.controls['unit'].setValue(0);
    this.stageconfigForm.controls['unit'].setValue(0);

    this.stageconfigForm.controls['signoffnotification'].setValue(false);
    this.stageconfigForm.controls['allocationtype'].setValue(0);
    this.stageconfigForm.controls['unit'].setValue(0);

    this.stageconfigForm.controls['stagetype'].setValue(0);
    this.stageconfigForm.controls['checkin_app'].setValue(0);
    this.stageconfigForm.controls['checkout_app'].setValue(0);

    this.stageconfigForm.controls['inprocessapp'].setValue(0);
    this.stageconfigForm.controls['checklisttemplateid'].setValue(0);
    this.stageconfigForm.controls['ackmailtemplate'].setValue(0);

    this.stageconfigForm.controls['pmmailtemplate'].setValue(0);
    this.stageconfigForm.controls['mailtemplate'].setValue(0);
    this.stageconfigForm.controls['mailattachment'].setValue(false);

    this.stageconfigForm.controls['checklistlog'].setValue(false);
    this.stageconfigForm.controls['acknowledgement'].setValue(false);
    this.stageconfigForm.controls['pmnotification'].setValue(false);

    this.stageconfigForm.controls['querycomtemplateid'].setValue(0);
    this.stageconfigForm.controls['querycompilation'].setValue(false);
    this.stageconfigForm.controls['querybatch'].setValue(false);

    this.stageconfigForm.controls['merged_lot'].setValue(false);
    this.stageconfigForm.controls['process_without_file'].setValue(false);
    this.stageconfigForm.controls['backmatterstart'].setValue(false);

    this.stageconfigForm.controls['islotenable'].setValue(false);
    this.stageconfigForm.controls['publicationtype'].setValue('');
  }

  exportAsXLSX(): void {
    // this.exportAsExcelFile(this.data, 'sample');
    this.httpClient.get('assets/images/sample_workflow.xlsx', { responseType: 'blob' }).subscribe(datas => {
      console.log(datas);
      const reader: FileReader = new FileReader();
      reader.onload = (e: any) => {
        const bstr: string = e.target.result;
        const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });

        // For sheet 1
        /* grab first sheet */
        const wsname: string = wb.SheetNames[0];
        const ws: XLSX.WorkSheet = wb.Sheets[wsname];

        const allocationtypesjson = this.allocationtypes.map(a => ({ AllocationTypes: a.allocationtype }));
        const allocationtypesworksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(allocationtypesjson);
        console.log('allocationtypesworksheet', allocationtypesworksheet);

        const stagetypesjson = this.stagetypes.map(a => ({ StageTypes: a.stagetype }));
        const stagetypesworksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(stagetypesjson);
        console.log('stagetypesworksheet', stagetypesworksheet);

        const activeFileTypejson = this.activeFileType.map(a => ({ InputOutputFileType: a.filetype }));
        const activeFileTypeworksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(activeFileTypejson);
        console.log('activeFileTypeworksheet', activeFileTypeworksheet);

        const applicationsjson = this.applications.map(a => ({ CheckInOut_Application: a.application }));
        const applicationsworksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(applicationsjson);
        console.log('applicationsworksheet', applicationsworksheet);

        const unitsjson = this.units.map(a => ({ Units: a.unitname }));
        const unitsworksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(unitsjson);
        console.log('unitsworksheet', unitsworksheet);

        const activeMailTemplatejson = this.activeMailTemplate.map(a => ({ MailTemplate: a.mailtemplatename }));
        const activeMailTemplateworksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(activeMailTemplatejson);
        console.log('activeMailTemplateworksheet', activeMailTemplateworksheet);

        const activeChecklistjson = this.activeChecklist.map(a => ({ CheckList: a.checklist }));
        const activeChecklistworksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(activeChecklistjson);
        console.log('activeChecklistworksheet', activeChecklistworksheet);

        wb.SheetNames.push('AllocationTypes');
        wb.Sheets['AllocationTypes'] = allocationtypesworksheet; // First workbook is named "Sheet1", you can change it

        wb.SheetNames.push('StageTypes');
        wb.Sheets['StageTypes'] = stagetypesworksheet;

        wb.SheetNames.push('InputOutputFileType');
        wb.Sheets['InputOutputFileType'] = activeFileTypeworksheet;

        wb.SheetNames.push('CheckInOut_Application');
        wb.Sheets['CheckInOut_Application'] = applicationsworksheet;

        wb.SheetNames.push('Units');
        wb.Sheets['Units'] = unitsworksheet;

        wb.SheetNames.push('MailTemplate');
        wb.Sheets['MailTemplate'] = activeMailTemplateworksheet;

        wb.SheetNames.push('CheckList');
        wb.Sheets['CheckList'] = activeChecklistworksheet;
        const excelBuffer: any = XLSX.write((wb), { bookType: 'xlsx', type: 'array' });
        this.saveAsExcelFile(excelBuffer, 'sample_workflow');
      };
      reader.readAsBinaryString(datas);
    });
  }

  public exportAsExcelFile(json: any[], excelFileName: string): void {
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
    console.log(worksheet);
    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xls', type: 'array' });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }

  private saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], { type: EXCEL_TYPE });
    FileSaver.saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
  }

  onFileChange(evt: any) {
    /* wire up file reader */
    const target: DataTransfer = <DataTransfer>(evt.target);
    if (target.files.length !== 1) {
      this.toastr.error('Cannot use multiple files');
    }
    const reader: FileReader = new FileReader();
    reader.onload = (e: any) => {
      /* read workbook */
      const bstr: string = e.target.result;
      const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });

      // For sheet 1
      /* grab first sheet */
      const wsname: string = wb.SheetNames[0];
      const ws: XLSX.WorkSheet = wb.Sheets[wsname];

      /* save data */
      const wfData = <AOA>(XLSX.utils.sheet_to_json(ws, { header: 1 }));
      console.log(wfData);
      const workflow = {
        workflowname: wfData[1][1],
        description: wfData[1][2],
        createdby: this.userid,
      };

      // For sheet 2
      /* grab first sheet */
      const wsname1: string = wb.SheetNames[1];

      const ws1: XLSX.WorkSheet = wb.Sheets[wsname1];
      /* save data */
      const wfdefinitionData = <AOA>(XLSX.utils.sheet_to_json(ws1, { header: 1 }));
      console.log(wfdefinitionData);
      const metaFieldsInput = [];
      this.SpinnerService.show();
      this.stageservice.Get().subscribe(res => {
        if (res[0] != null && res[0] !== undefined) {
          this.responsestages = JSON.parse(res[0]);
          if (this.showallstatus === true) {
            this.responsestages = this.responsestages.filter(s => s.active === 1);
          }

          wfdefinitionData.forEach((w, inx) => {
            // console.log(w);
            // console.log(inx);
            if (inx > 0 && w.length && w[0]) {
              const allocationtype = this.allocationtypes.filter(m => m.allocationtype === w[4]);
              const stageType = this.stagetypes.filter(m => m.stagetype === w[6]);
              const checkinApp = this.applications.filter(m => m.application === w[7]);
              const CheckoutApp = this.applications.filter(m => m.application === w[8]);

              const parallelstage = this.responsestages.filter(m => m.stage === w[27]);
              const nextstage = this.responsestages.filter(m => m.stage === w[28]);
              const movebackstage = this.responsestages.filter(m => m.stage === w[29]);
              const resetstage = this.responsestages.filter(m => m.stage === w[30]);

              const unit = this.units.filter(m => m.unitname === w[5]);
              const inprocessapp = this.applications.filter(m => m.application === w[9]);

              const ackmailtemplate = this.activeMailTemplate.filter(m => m.mailtemplatename === w[16]);
              const pmmailtemplate = this.activeMailTemplate.filter(m => m.mailtemplatename === w[18]);
              const mailtemplate = this.activeMailTemplate.filter(m => m.mailtemplatename === w[11]);
              const checklisttemplateid = this.activeChecklist.filter(m => m.checklist === w[14]);
              const querycomtemplateid = this.activeMailTemplate.filter(m => m.mailtemplatename === w[20]);

              metaFieldsInput.push({
                id: inx,
                stage: w[1],
                wfdid: 0,
                workflowdefid: 0,
                Input_file_type: w[2],
                Output_file_type: w[3],

                allocationtype: allocationtype[0] ? allocationtype[0].allocationtypeid : null,
                stagetype: stageType[0] ? stageType[0].stagetypeid : null,

                checkin_app: checkinApp[0] ? checkinApp[0].applicationid : null,
                checkout_app: CheckoutApp[0] ? CheckoutApp[0].applicationid : null,

                parallelstage: parallelstage[0] ? parallelstage[0].stageid : 0,
                nextstage: nextstage[0] ? nextstage[0].stageid : 0,
                movebackstage: movebackstage[0] ? movebackstage[0].stageid : 0,
                resetstage: resetstage[0] ? resetstage[0].stageid : 0,

                signoffnotification: w[10] === true ? 1 : 0,
                unit: unit[0] ? unit[0].unitid : null,
                inprocessapp: inprocessapp[0] ? inprocessapp[0].applicationid : null,
                checklisttemplateid: checklisttemplateid[0] ? checklisttemplateid[0].checklistid : null,
                ackmailtemplate: ackmailtemplate[0] ? ackmailtemplate[0].mailtemplateid : null,
                pmmailtemplate: pmmailtemplate[0] ? pmmailtemplate[0].mailtemplateid : null,
                mailtemplate: mailtemplate[0] ? mailtemplate[0].mailtemplateid : null,
                mailattachment: w[12] === true ? 1 : 0,
                checklistlog: w[13] === true ? 1 : 0,
                acknowledgement: w[15] === true ? 1 : 0,
                pmnotification: w[17] === true ? 1 : 0,
                querycomtemplateid: querycomtemplateid[0] ? querycomtemplateid[0].mailtemplateid : null,
                querycompilation: w[19] === true ? 1 : 0,
                querybatch: w[21] === true ? 1 : 0,
                merged_lot: w[22] === true ? 1 : 0,
                process_without_file: w[23] === true ? 1 : 0,
                backmatterstart: w[24] === true ? 1 : 0,
                islotenable: 0,
                updatedby: this.userid
              });
            }
          });
          console.log('metaFieldsInput=', metaFieldsInput);
          if ((workflow.workflowname.trim() === undefined) || (workflow.workflowname.trim() === '')) {
            this.toastr.error('WorkFlow should not be empty');
            return;
          }
          let msg = null;
          this.userid = +localStorage.getItem('userid');
          workflow.workflowname = workflow.workflowname.trim();
          workflow.createdby = this.userid;
          msg = 'Record Added Successfully';
          this.workflowservice.Post(workflow).subscribe(res => {
            if (res.status === 200) {
              if (res !== undefined) {
                if (res.body !== 0) {
                  const workflowid = res.body;
                  this.responsestages = [];
                  this.stageservice.Get().subscribe(res => {
                    if (res[0] != null && res[0] !== undefined) {
                      this.responsestages = JSON.parse(res[0]);
                      if (this.showallstatus === true) {
                        this.responsestages = this.responsestages.filter(s => s.active === 1);
                      }
                      metaFieldsInput.forEach((m, mindex) => {
                        let ind: any = this.responsestages.filter(x => x.stage === m.stage);
                        ind = ind[0];
                        // For new stage add
                        if (ind === undefined) {
                          if ((m.stage.trim() === undefined) || (m.stage.trim() === '')) {
                            this.toastr.error('Stage should not be empty');
                            return;
                          }
                          m.stage = m.stage.trim();
                          m.createdby = this.userid;
                          this.stageservice.Post(m).subscribe(res => {
                            if (res.status === 200) {
                              if (res !== undefined) {
                                if (res.body !== 0) {
                                  ind = [];
                                  ind.stageid = res.body;
                                  debugger;
                                } else { this.toastr.warning('Record already exists.'); }
                              }
                            }
                          },
                            error => {
                              this.toastr.error('Error while doing the operation');
                            });
                        }
                        const stagetimer = setInterval(() => {
                          if (ind !== undefined) {
                            clearTimeout(stagetimer);
                            const workflowObject: any = {};
                            workflowObject.wfdid = 0;
                            workflowObject.stageid = ind.stageid;
                            workflowObject.stagename_alias = m.stage;
                            workflowObject.stageorder = mindex + 1;
                            workflowObject.wfid = workflowid;
                            m.wfid = workflowid;
                            workflowObject.createdby = this.userid;
                            this.workflowconfigurationservice.Post(workflowObject).subscribe(res => {
                              if (res.status === 200) {
                                if (res !== undefined) {
                                  if (res.body !== 0) {
                                    const wfdobject = JSON.parse(res.body[0])[0];
                                    m.wfdid = wfdobject.wfdid;
                                    // save config

                                    this.workflowconfigurationservice.PostStageConfig(m).subscribe(res => {
                                      if (res.body !== undefined && res.body != null) {
                                        // this.toastr.success('Stage config saved successfully');
                                        mindex++;
                                        if (mindex === metaFieldsInput.length) {
                                          this.isexecuted = true;
                                        }

                                        this.inputFileType = [];
                                        this.outputFileType = [];
                                        m.Input_file_type = m.Input_file_type.split(',');
                                        m.Input_file_type.forEach(element => {
                                          const filedetails = this.activeFileType.filter(f => f.filetype === element);
                                          this.inputFileType.push({
                                            workflowdefid: wfdobject.wfdid,
                                            filetypeid: filedetails[0].filetypeid,
                                            filetype: filedetails[0].filetypeid,
                                            filevalue: filedetails[0].filetype,
                                            filemode: 1
                                          });
                                        });

                                        m.Output_file_type = m.Output_file_type.split(',');
                                        m.Output_file_type.forEach(element => {
                                          const Outputfiledetails = this.activeFileType.filter(f => f.filetype === element);
                                          this.outputFileType.push({
                                            workflowdefid: wfdobject.wfdid,
                                            filetypeid: Outputfiledetails[0].filetypeid,
                                            filetype: Outputfiledetails[0].filetypeid,
                                            filevalue: Outputfiledetails[0].filetype,
                                            filemode: 2
                                          });
                                        });

                                        const inoutfiletype = [];
                                        this.inputFileType.forEach(element => {
                                          inoutfiletype.push(element);
                                        });
                                        this.outputFileType.forEach(element => {
                                          inoutfiletype.push(element);
                                        });

                                        if (inoutfiletype.length) {
                                          this.workflowconfigurationservice.UpdateInOutFile(inoutfiletype).subscribe(res1 => {
                                            if (res1.body !== undefined && res1.body != null) {
                                            }
                                          });
                                        }
                                      }
                                    });

                                  } else {
                                    this.toastr.warning('Record already exists.');
                                  }
                                }
                              }
                            },
                              error => {
                                console.log(error);
                                this.toastr.error('Error while doing the operation');
                              });
                          }
                        });
                      }, 2000);

                      const timer = setInterval(() => {
                        // Stage movement check
                        if (this.isexecuted) {

                          clearTimeout(timer);
                          const inputData: any = [];
                          inputData.push({
                            wfid: workflowid
                          });
                          this.workflowconfigurationservice.GetById(inputData[0]).subscribe(res => {
                            if (res.body !== undefined && res.body != null) {
                              if (JSON.parse(res.body[0]).length > 0) {
                                this.mappedStageMovement = JSON.parse(res.body[0]);
                                const inputData: any = [];
                                this.mappedStageMovement.forEach(i => {
                                  let stageObject: any = metaFieldsInput.filter(meta => meta.wfdid === i.wfdid);
                                  stageObject = stageObject[0];
                                  inputData.push(
                                    {
                                      wfdid: i.wfdid,
                                      wfid: i.wfid,
                                      parallelstage: stageObject.parallelstage > 0 ? stageObject.parallelstage : 0,
                                      nextstage: stageObject.nextstage > 0 ? stageObject.nextstage : 0,
                                      movebackstage: stageObject.movebackstage > 0 ? stageObject.movebackstage : 0,
                                      resetstage: stageObject.resetstage > 0 ? stageObject.resetstage : 0,
                                      updatedby: this.userid
                                    });
                                });
                                this.workflowconfigurationservice.UpdateStageMovement(inputData).subscribe(res => {
                                  if (res.body !== undefined && res.body != null && res.body[0] !== undefined &&
                                    res.body[0] !== null && JSON.parse(res.body[0]).length > 0) {

                                    this.SpinnerService.hide();
                                    this.toastr.success('Workflow saved successfully');
                                  }
                                });
                              }
                            }
                          });
                        }
                      }, 2000);
                    }
                  }, error => { this.toastr.error('Error while getting stage data'); });
                  // this.toastr.success('Data added successfully');
                } else {
                  this.SpinnerService.hide();
                  this.toastr.warning('Work area already exists, Please choose another name');
                }
              }
            }
          },
            error => {
              this.toastr.error('Error while doing the operation');
            });
        }
      });
    };
    reader.readAsBinaryString(target.files[0]);
  }

  ChangeActive1(e) {
    if (e.currentTarget.checked) {
      this.FeatureselectedItemsCheckIn.filter(f => f.mdata === e.currentTarget.id).map(s => s.active = 1);
    } else {
      this.FeatureselectedItemsCheckIn.filter(f => f.mdata === e.currentTarget.id).map(s => s.active = 0);
    }
  }

  ChangeActive2(e) {
    if (e.currentTarget.checked) {
      this.FeatureselectedItemsCheckOut.filter(f => f.mdata === e.currentTarget.id).map(s => s.active = 1);
    } else {
      this.FeatureselectedItemsCheckOut.filter(f => f.mdata === e.currentTarget.id).map(s => s.active = 0);
    }
  }

  ChangeActive3(e) {
    if (e.currentTarget.checked) {
      this.FeatureselectedItemsInProgress.filter(f => f.mdata === e.currentTarget.id).map(s => s.active = 1);
    } else {
      this.FeatureselectedItemsInProgress.filter(f => f.mdata === e.currentTarget.id).map(s => s.active = 0);
    }
  }

  selectAll(eve, wfdid, index, type) {

    if (type === 'Reset') {
      this.multipleMoveBackList[index] = this.mappedStageList;
      const m = this.mappedStageMovement.findIndex(item => item.wfdid === wfdid);
      if (m === index) {
        this.mappedStageMovement[index]['multiplemoveback'] = this.multipleMoveBackList[index];
      }
    }
  }

  UnSelectMoveBack(index, type) {
    if (type === 'Reset') {
      this.multipleMoveBackList[index] = [];
      this.mappedStageMovement[index]['multiplemoveback'] = this.multipleMoveBackList[index];
    }
  }

  deSelect(idx, type) {
    if (type === 'Reset') {
      // this.multipleMoveBackList[idx] = [];
      this.mappedStageMovement[idx]['multiplemoveback'] = this.multipleMoveBackList[idx];
    }
  }
  loadpublicationtype() {
    this.publicationtypelist = [
      '',
    'Online',
    'Print',
  'Both'
  ];

    // this.workflowconfigurationservice.getsupplementtype().subscribe(res => {
    //   if (res[0] != null && res[0] !== undefined) {
    //     this.supplementtypelist = JSON.parse(res[0]);
    //     this.supplementtypelist = this.supplementtypelist.filter(u => u.active === 1);
    //   }
    // }, error => { this.toastr.error('Error while getting supplement type data'); });
  }
}
