import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { OutlineconfigurationService } from './outlineconfiguration.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { Stage } from 'src/app/masters/stage/stage';
import { ProjectdefinitionmasterService } from '../projectdefinitionmaster/projectdefinitionmaster.service';
import { OutlineService } from '../outline/outline.service';
import { Router } from '@angular/router';
import { HeadingLevel } from 'src/app/masters/headinglevel/headinglevel';
import { HeadinglevelService } from 'src/app/masters/headinglevel/headinglevel.service';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { DialogService } from 'ng2-bootstrap-modal';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { ProjectConfigurationService } from '../projectconfiguration/projectconfiguration.service';
import { Outline, OutlineConfig } from './outline';
import { SmartchartService } from '../../Shared/smartchart/smartchart.service';
import { Smartchart } from '../../Shared/smartchart/smartchart';
import { ToolsetService } from 'src/app/masters/toolset/toolset.service';
import { Toolset } from 'src/app/masters/toolset/toolset';
import { SmartchartComponent } from 'src/app/Shared/smartchart/smartchart.component';
import { Plugins } from 'src/app/masters/plugin/plugin';
import { PluginService } from 'src/app/masters/plugin/plugin.service';
import { ProjectMasterService } from 'src/app/masters/projectmaster/projectmaster.service';
declare var $: any;
@Component({
  selector: 'app-outlineconfiguration',
  templateUrl: './outlineconfiguration.component.html',
  styleUrls: ['./outlineconfiguration.component.css']
})
export class OutlineconfigurationComponent implements OnInit {
  outlineconfigForm: FormGroup;
  outlineForm: FormGroup;
  toolsets: Toolset[] = [];
  orgtoolsets: Toolset[] = [];
  stages: Stage[] = [];
  userid: number;
  projectdefinitions: any;
  headerList: any = [];
  levelList: any = [];
  levelnames: string;
  selectedIndex = 0;
  textBoxTocuhed: boolean;
  _dropdownSettings: any;
  _dropdownSettings2: any;
  _userselectedItems: any = [];
  outlineconfigid = 0;
  projectid: any;
  projectdid: any;
  toolsetid: any;
  issmartchart: any;
  newsalert: any;
  isnotapplicable: any;
  saveAs = false;
  headinglevels: HeadingLevel[] = [];
  headinglevelsactive: HeadingLevel[] = [];
  headinglevel: HeadingLevel;
  // smartChartModalRef: BsModalRef;
  confmsg: string;
  selectedRow = -1;
  outlines: Outline[] = [];
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered modal-lg',
    ignoreBackdropClick: true
  };
  btnName = 'Add';
  smartChartSeqModalRef: BsModalRef;
  formElement: any;
  _cleanedFormElement: any;
  _fieldAliasList: any;
  parsedFormElement: any;
  smartChartConfigHtmlData: any;
  htmlData: any;
  smartChartDisplaySeq = [];
  smartChartName = '';
  smartchartconfigid = 0;
  // variables for environment
  displayStep1 = true;
  displayStep2 = false;
  displayStep3 = false;
  displayStep4 = false;
  displayStep5 = false;
  plugins: any;
  orgplugin: any;
  ckeConfig: any;
  ckeConfig1: any;
  plainvanillaTemplateModalRef: BsModalRef;
  plugin: Plugins[] = [];
  pluginsactive: Plugins[] = [];
  outlinedetails: any;
  projects: any = [];
  projectListtmp: any = [];
  projectListactive: any = [];
  highhierarchyorder: number;
  highhierarchydetail: any = [];
  outlineDeleteModalRef: BsModalRef;
  headerListFormap: any = [];
  outlineconfigMapForm: FormGroup;
  deletedoutlineconfigdetailid: number;
  // steppper two
  displayS2Step1 = true;
  displayS2Step2 = false;
  displayS2Step3 = false;

  selectedDetails: any = [];
  selectedHeaderFormap: string;
  selectedHeadernumberFormap: string;
  oldtoolsetid: any;
  outlineMasterModalRef: BsModalRef;
  searchText2: string;
  p = 1;
  itemsPerPage = 10;
  userMappedProjectDefList: any = [];
  actionRights: any;
  smartChartButtonDisabled = false;
  @ViewChild('outlineDeleteTemplate', { static: false }) outlineDeleteTemplate1: TemplateRef<any>;
  constructor(
    private formBuilder: FormBuilder,
    private SpinnerService: NgxSpinnerService,
    private toastr: ToastrService,
    private projectdefinitionservice: ProjectdefinitionmasterService,
    private outlineconfigurationservice: OutlineconfigurationService,
    private outlineservice: OutlineService,
    private router: Router,
    private headinglevelservice: HeadinglevelService,
    private modalService: BsModalService,
    private dialogService: DialogService,
    private projectConfigurationService: ProjectConfigurationService,
    private smartchartService: SmartchartService,
    private toolsetservice: ToolsetService,
    private _SmartchartComponent: SmartchartComponent,
    private pluginservice: PluginService,
    private projectMasterService: ProjectMasterService,
  ) {
    // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('OutlineConfiguration_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('OutlineConfiguration_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('OutlineConfiguration_userRights');
    }
    const navigation = this.router.getCurrentNavigation();

    const state = navigation.extras.state as {
      outlineconfigid: any,
      projectid: any,
      projectdid: any,
      toolsetid: any,
      issmartchart: any,
      newsalert: any,
      isnotapplicable: any,
      outlines: any,
      saveAs: boolean,
    };
    if (state !== null && state !== undefined) {
      this.outlineconfigid = state.outlineconfigid;
      this.projectid = state.projectid;
      this.projectdid = state.projectdid;
      this.toolsetid = state.toolsetid;
      this.issmartchart = state.issmartchart;
      this.newsalert = state.newsalert;
      this.isnotapplicable = state.isnotapplicable;
      this.outlines = state.outlines;
      this.saveAs = state.saveAs;
      this.oldtoolsetid = state.toolsetid;
    }
  }
  ngOnInit(): void {
    this.outlineconfigForm = this.formBuilder.group({
      outlineconfigid: [''],
      outlineconfigdetailid: [],
      headinglevelid: [1, [Validators.required]],
      mandatorysection: ['1', [Validators.required]],
      headingtext: ['', [Validators.required]],
      readonlymode: [true],
      demotext: [''],
      instruction: [''],
      watermarktext: [''],
      headingnumber: [''],
      maxlength: [0],
      enablelengthvalidation: [false],
      donotallowcontent: [false],
      plainvanilla: [''],
      sequenceno: [''],
      parentoutlineconfigdetailid: [''],
      topicurl: ['']
    });

    this.outlineForm = this.formBuilder.group({
      outlineconfigid: [0],
      projectid: [0],
      toolsetid: [0],
      projectdid: [0],
      issmartchart: [false],
      newsalert: [false],
      isnotapplicable: [false],
    });

    // Mapping header on delete
    this.outlineconfigMapForm = this.formBuilder.group({
      outlineconfigdetailid: ['0'],
      maptoheading: ['1'],
    });

    // For multiselect dropdown property setup
    this._dropdownSettings = {
      singleSelection: false,
      idField: 'pluginid',
      textField: 'displayname',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      itemsShowLimit: 7,
      allowSearchFilter: true
    };
    this._dropdownSettings2 = {
      singleSelection: false,
      idField: 'pluginid',
      textField: 'displayname',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      allowSearchFilter: false,
      closeDropDownOnSelection: false
    };
    this._userselectedItems = [];
    this.userid = +localStorage.getItem('userid');
    this.getAllPlugin();
    this.getAllOutline();
    this.loadOutlineData();
    this.loadProject();
    this.loadToolset();
    if (this.projectdid) {
      // this.onchangeproject(this.projectdid);
      this.getProjectDefition(this.projectid);
    }
    this.getoutline();
    this.getAllHeadlingLevel();
    this.LoadFieldList();
    this.htmlData = '';
    this.ckeConfig = {
      allowedContent: false,
      extraPlugins: 'divarea',
      forcePasteAsPlainText: true,
      //   toolbarGroups: [
      //     { 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' ] },
      //     { 'name': 'editing', 'groups': [ 'find', 'selection', 'spellchecker', 'editing' ] },
      //     { 'name': 'forms', 'groups': [ 'forms' ] }
      // ],
      // tslint:disable-next-line: max-line-length
      removeButtons: 'Save,Subscript,Superscript,NumberedList,BulletedList,Link,Unlink,HorizontalRule,NewPage,Preview,Print,Templates,Replace,SelectAll,Form,Checkbox,Radio,TextField,Textarea,Find,Select,Button,ImageButton,HiddenField,JustifyLeft,JustifyCenter,JustifyRight,JustifyBlock,CopyFormatting,CreateDiv,BidiLtr,BidiRtl,Language,Flash,Smiley,PageBreak,Iframe,TextColor,BGColor,ShowBlocks,Cut,Copy,Paste,Table,Image,Format,Source,Maximize,Anchor,SpecialChar,PasteFromWord,PasteText,Scayt,Undo,Redo,Strike,RemoveFormat,Indent,Outdent,Blockquote,Underline,About'
    };
    this.ckeConfig1 = {
      allowedContent: false,
      extraPlugins: 'divarea',
      forcePasteAsPlainText: true,
      readOnly: true,
      //   toolbarGroups: [
      //     { 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' ] },
      //     { 'name': 'editing', 'groups': [ 'find', 'selection', 'spellchecker', 'editing' ] },
      //     { 'name': 'forms', 'groups': [ 'forms' ] }
      // ],
      // tslint:disable-next-line: max-line-length
      removeButtons: 'Save,Subscript,Superscript,NumberedList,BulletedList,Link,Unlink,HorizontalRule,NewPage,Preview,Print,Templates,Replace,SelectAll,Form,Checkbox,Radio,TextField,Textarea,Find,Select,Button,ImageButton,HiddenField,JustifyLeft,JustifyCenter,JustifyRight,JustifyBlock,CopyFormatting,CreateDiv,BidiLtr,BidiRtl,Language,Flash,Smiley,PageBreak,Iframe,TextColor,BGColor,ShowBlocks,Cut,Copy,Paste,Table,Image,Format,Source,Maximize,Anchor,SpecialChar,PasteFromWord,PasteText,Scayt,Undo,Redo,Strike,RemoveFormat,Indent,Outdent,Blockquote,Underline,About,Bold,Italic,Font,FontSize,Formatting'
    };
  }

  loadProject() {
    this.projects = [];
    this.projectListactive = [];
    this.projectListtmp = [];
    this.projectMasterService.Get().subscribe(res => {
      if (res !== undefined && res !== null && res[0] !== undefined && res[0] !== null) {
        if (JSON.parse(res[0]).length > 0) {
          this.projectListtmp = JSON.parse(res[0]);
          this.projectListtmp.forEach(i => {
            this.projects.push({
              projectid: i.projectid,
              projectcode: i.projectcode,
              projectname: i.projectname,
              projectlocation: i.projectlocation,
              description: i.description,
              active: i.active
            });
          });
          this.projects = this.projects.filter(p => p.active === 1);
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  loadToolset() {
    this.SpinnerService.show();
    this.toolsets = [];
    this.toolsetservice.Get().subscribe(res => {
      if (res !== undefined && res != null && res[0] !== undefined && res[0] != null) {
        if (JSON.parse(res[0]).length > 0) {
          this.toolsets = JSON.parse(res[0]);
          this.orgtoolsets = JSON.parse(res[0]);
          this.toolsets = this.toolsets.filter(r => r.active === 1);
        }
      }
      this.loadPlugin();
      console.log('this.toolsets=', this.toolsets);
      this.SpinnerService.hide();
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Error while getting data');
    });
  }

  changetoolset(toolset) {
    this.toolsetid = +toolset;
    this.loadPlugin();
  }

  // get all outline details based on user
  getAllOutline() {
    this.outlines = [];
    const inputData = new Object({
      userid: this.userid,
    });
    this.outlineservice.Get(inputData).subscribe(res => {
      if (res.body[0] != null && res.body[0] !== undefined) {
        this.outlines = JSON.parse(res.body[0]);
        console.log('this.outlines=', this.outlines);
        this.outlines = this.outlines.filter(y => y.active === 1);
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  changeProject(project) {
    this.getProjectDefition(+project);
  }
  // load plugin based on toolset
  loadPlugin() {
    const toolsetPlugin = this.toolsets.filter(t => t.toolsetid === this.toolsetid);
    if (toolsetPlugin.length) {
      // this.orgplugin = toolsetPlugin[0].plugins;
      this.plugins = toolsetPlugin[0].plugins;
      this.getAllPlugin1();
    }
  }

  // load all plugin
  getAllPlugin1() {
    this.plugin = [];
    this.pluginsactive = [];
    this.pluginservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.plugin = JSON.parse(res[0]);
        this.plugin = this.plugin.filter(p => p.active === 1);
        this.plugin.forEach(element => {
          if (this.plugins.filter(p => p.pluginid === element.pluginid).length <= 0) {
            this.plugins.push(element);
          }
        });
        if (this.projectdid) {
          this.onchangeproject(this.projectdid);
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  // load all plugin
  getAllPlugin() {
    this.plugin = [];
    this.pluginsactive = [];
    this.pluginservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.plugin = JSON.parse(res[0]);
        this.plugin = this.plugin.filter(p => p.active === 1);
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  onUserSelect(eve, wfdid, index) {
    //   const input = [];
    //   this.stages[index].pluginids.push({ pluginid: eve.pluginid, plugin: eve.plugin });
  }

  onchangeproject(projectdid) {
    this.stages = [];
    const inputFlowChartData = new Object({
      projectdefinitionid: +projectdid,
    });
    this.SpinnerService.show();
    this.projectConfigurationService.GetByIdProjectDefWorkflowwithOutline(inputFlowChartData).subscribe(async (response) => {
      this.stages = JSON.parse(response.body[0]);
      console.log('this.stages=', this.stages);
      const inputData = new Object({
        outlineconfigid: this.outlineconfigid,
      });
      this.outlineconfigurationservice.GetByoutlineconfigid(inputData).subscribe(async (res1) => {
        const orgmappedStageMovement = JSON.parse(res1.body[0]);
        // For original toolset getting
        const toolsetPlugin = this.orgtoolsets.filter(t => t.toolsetid === this.toolsetid);
        if (toolsetPlugin.length) {
          this.orgplugin = toolsetPlugin[0].plugins;
        }
        if (orgmappedStageMovement) {
          if (this.stages) {
            this.stages.forEach(i => {
              const plugobj = orgmappedStageMovement.filter(s => s.stageid === i.stageid);
              if (plugobj.length) {
                i.outlineconfigstagemappingid = plugobj[0].outlineconfigstagemappingid;
                console.log('this.orgplugin=', this.orgplugin);
                console.log('plugobj[0].pluginids=', plugobj[0].pluginids);
                if (this.oldtoolsetid === this.toolsetid) {
                  if (JSON.parse(plugobj[0].pluginids)) {
                    i.pluginids = JSON.parse(plugobj[0].pluginids);
                    i.pluginids = i.pluginids.filter(p => p.active === 1);
                  } else {
                    i.pluginids = this.orgplugin;
                  }
                } else {
                  i.pluginids = this.orgplugin;
                }
              }
            });
          }
          this.SpinnerService.hide();
        } else {
          if (this.stages) {
            this.stages.forEach(i => {
              i.pluginids = this.orgplugin;
            });
          }
        }
        this.SpinnerService.hide();
      }, err => { this.toastr.error('Error in getting Workflow records'); });
      console.log('this.stages=', this.stages);
    }, err => { this.toastr.error('Error in getting Workflow records'); });
  }

  saveStageMovement() {
    const inputData: any = [];
    const mappedstages = this.stages;
    // this.stages.forEach(stage => {
    for (let i = 0; i < mappedstages.length; i++) {
      if (mappedstages[i].pluginids) {
        mappedstages[i].pluginids.forEach(p => {
          if (p) {
            p.active = 1;
          }
        });
      }
      this.plugins.forEach(element => {
        if (mappedstages[i].pluginids) {
          if (!mappedstages[i].pluginids.filter(p => p.pluginid === element.pluginid).length) {
            // mappedstages[i].pluginids.push({
            //   pluginid: element.pluginid,
            //   plugin: element.plugin,
            //   active: 0
            // });
          }
        }
      });
      inputData.push(
        {
          outlineconfigstagemappingid: mappedstages[i].outlineconfigstagemappingid,
          outlineconfigid: this.outlineconfigid,
          stageid: mappedstages[i].stageid,
          pluginids: JSON.stringify(mappedstages[i].pluginids ? mappedstages[i].pluginids : null),
          createdby: this.userid,
          updatedby: this.userid
        });
    }
    this.outlineconfigurationservice.UpdateOutlineStageMapping(inputData).subscribe(res => {
      if (res.body !== undefined && res.body != null && res.body[0] !== undefined &&
        res.body[0] !== null) {
        this.toastr.success('Stage plugin mapping saved successfully');
      }
    });
  }


  getProjectDefition(projectid) {
    const input = [];
    input.push({ userid: this.userid });
    this.projectdefinitions = [];
    let projectDefinitionsTmp = [];
    this.projectdefinitionservice.getAllWOWFByUserId(input[0]).subscribe(res => {
      if (res.body[0] !== null && res.body[0] !== undefined) {
        projectDefinitionsTmp = JSON.parse(res.body[0]);
        if (this.outlines.length) {
          // For remove duplicate project and projectdefinision
          if (projectid && (this.outlineconfigid === 0 || this.outlineconfigid === undefined)) {
            // if (projectid && this.saveAs) {
            const afterfilter = this.outlines.filter(o => o.projectid === projectid);
            afterfilter.forEach(o => {
              if (o.projectdid !== this.projectdid) {
                const value = projectDefinitionsTmp.findIndex(e => e.projectdefinitionid === o.projectdid);
                if (value !== -1) {
                  projectDefinitionsTmp.splice(value, 1);
                }
              }
            });
            this.projectdefinitions = projectDefinitionsTmp.map(k => ({
              projectdefinitionid: k.projectdefinitionid,
              projectid: k.projectid,
              project_subtitle: k.project_subtitle,
              projectname: k.projectname,
              active: k.active
            }));
            this.projectdefinitions = this.projectdefinitions.filter(y => y.active === 1 && y.projectid === +projectid);
          } else {
            this.projectdefinitions = projectDefinitionsTmp.map(k => ({
              projectdefinitionid: k.projectdefinitionid,
              projectid: k.projectid,
              project_subtitle: k.project_subtitle,
              projectname: k.projectname,
              active: k.active
            }));
            this.projectdefinitions = this.projectdefinitions.filter(y => y.active === 1 && y.projectid === +projectid);
          }
        } else {
          console.log('calling else');
          if (projectid) {
            const afterfilter = this.outlines.filter(o => o.projectid === projectid);
            afterfilter.forEach(o => {
              const value = projectDefinitionsTmp.findIndex(e => e.projectdefinitionid === o.projectdid);
              if (value !== -1) {
                projectDefinitionsTmp.splice(value, 1);
              }
            });

            this.projectdefinitions = projectDefinitionsTmp.map(k => ({
              projectdefinitionid: k.projectdefinitionid,
              projectid: k.projectid,
              project_subtitle: k.project_subtitle,
              projectname: k.projectname,
              active: k.active
            }));
            this.projectdefinitions = this.projectdefinitions.filter(y => y.active === 1 && y.projectid === +projectid);
          }
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  getAllHeadlingLevel() {
    this.headinglevels = [];
    this.headinglevelsactive = [];
    this.headinglevelservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.headinglevels = JSON.parse(res[0]);
        this.headinglevels = this.headinglevels.filter(h => h.active === 1);
        this.headinglevels = this.headinglevels.sort(function (a, b) {
          return a.hierarchyorder - b.hierarchyorder;
        });
        // find max hierarchy value
        this.highhierarchyorder = Math.max.apply(Math, this.headinglevels.map(function (o) { return o.hierarchyorder; }));
        this.highhierarchydetail = this.headinglevels.find(h => h.hierarchyorder === this.highhierarchyorder);
        console.log('headinglevels=', this.headinglevels);
        console.log('highhierarchyorder=', this.highhierarchyorder);
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  Post(outlineconfig) {
    console.log('outlineconfig=', outlineconfig);
    if ((outlineconfig.headingtext === undefined) || (outlineconfig.headingtext.trim() === '')) {
      this.toastr.error('Heading should not be empty');
      return;
    }

    if (outlineconfig.topicurl != null && outlineconfig.topicurl !== '') {
      var validurl = this.isValidURL(outlineconfig.topicurl);

      if (outlineconfig.topicurl && !validurl) {
        this.toastr.error('Topic Url should be proper URL');
        return;
      }
    }

    if (this.outlineconfigid) {
      outlineconfig.outlineconfigid = this.outlineconfigid;
      if (!outlineconfig.outlineconfigdetailid) {
        const inputData: any = [];
        inputData.push(
          {
            outlineconfigid: this.outlineconfigid,
            outlineconfigdetailid: 0,
            headinglevelid: +outlineconfig.headinglevelid,
            mandatorysection: +outlineconfig.mandatorysection,
            headingtext: outlineconfig.headingtext,
            readonlymode: outlineconfig.readonlymode === true ? 1 : 0,
            demotext: outlineconfig.demotext,
            instruction: outlineconfig.instruction,
            watermarktext: outlineconfig.watermarktext,
            headingnumber: outlineconfig.headingnumber,
            maxlength: outlineconfig.maxlength,
            enablelengthvalidation: outlineconfig.enablelengthvalidation === true ? 1 : 0,
            donotallowcontent: outlineconfig.donotallowcontent === true ? 1 : 0,
            plainvanilla: outlineconfig.plainvanilla,
            sequenceno: outlineconfig.sequenceno,
            parentoutlineconfigdetailid: outlineconfig.parentoutlineconfigdetailid,
            topicurl: outlineconfig.topicurl,
            createdby: this.userid,
            active: 1,
          });
        outlineconfig.headinglevelid = +outlineconfig.headinglevelid;
        outlineconfig.parentoutlineconfigdetailid = 0;
        outlineconfig.outlineconfigdetailid = 0;
        outlineconfig.sequenceno = 1;
        this.outlineconfigurationservice.Post(inputData).subscribe(res => {
          if (res.status === 200) {
            if (res !== undefined) {
              if (res.body !== 0) {
                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');
          });

      } else {
        const inputData: any = [];
        inputData.push(
          {
            outlineconfigid: this.outlineconfigid,
            outlineconfigdetailid: outlineconfig.outlineconfigdetailid,
            headinglevelid: +outlineconfig.headinglevelid,
            mandatorysection: +outlineconfig.mandatorysection,
            headingtext: outlineconfig.headingtext,
            readonlymode: outlineconfig.readonlymode === true ? 1 : 0,
            demotext: outlineconfig.demotext,
            instruction: outlineconfig.instruction,
            watermarktext: outlineconfig.watermarktext,
            headingnumber: outlineconfig.headingnumber,
            maxlength: outlineconfig.maxlength,
            enablelengthvalidation: outlineconfig.enablelengthvalidation === true ? 1 : 0,
            donotallowcontent: outlineconfig.donotallowcontent === true ? 1 : 0,
            plainvanilla: outlineconfig.plainvanilla,
            sequenceno: outlineconfig.sequenceno,
            parentoutlineconfigdetailid: outlineconfig.parentoutlineconfigdetailid,
            topicurl: outlineconfig.topicurl,
            updatedby: this.userid,
            active: 1,
          });
        outlineconfig.updatedby = this.userid;
        this.outlineconfigurationservice.Put(inputData).subscribe(res => {
          if (res.status === 200) {
            if (res !== undefined) {
              if (res.body !== 0) {
                this.headerList.forEach(element => {
                  const foundNode = this.SavegetNodeById(element, outlineconfig.outlineconfigdetailid,
                    JSON.parse(res.body)[0]);
                  if (foundNode) {
                    foundNode.headinglevelid = JSON.parse(res.body)[0].headinglevelid;
                    foundNode.mandatorysection = JSON.parse(res.body)[0].mandatorysection;
                    foundNode.headingtext = JSON.parse(res.body)[0].headingtext;
                    foundNode.readonlymode = JSON.parse(res.body)[0].readonlymode;
                    foundNode.demotext = JSON.parse(res.body)[0].demotext;
                    foundNode.instruction = JSON.parse(res.body)[0].instruction;
                    foundNode.watermarktext = JSON.parse(res.body)[0].watermarktext;
                    foundNode.headingnumber = JSON.parse(res.body)[0].headingnumber;
                    foundNode.maxlength = JSON.parse(res.body)[0].maxlength;
                    foundNode.enablelengthvalidation = JSON.parse(res.body)[0].enablelengthvalidation;
                    foundNode.donotallowcontent = JSON.parse(res.body)[0].donotallowcontent;
                    foundNode.plainvanilla = JSON.parse(res.body)[0].plainvanilla;
                    foundNode.sequenceno = JSON.parse(res.body)[0].sequenceno;
                    foundNode.topicurl = JSON.parse(res.body)[0].topicurl;
                  }
                  return;
                });
                this.reset();
                this.toastr.success('Data updated successfully');
              } else { this.toastr.warning('Record already exists.'); }
            }
          }
        },
          error => {
            this.toastr.error('Error while doing the operation');
          });
      }
    } else {
      this.toastr.error('Save outline and proceed');
      this.SpinnerService.hide();
    }
  }

  PrePostHeading(outlineconfig) {
    console.log('outlineconfig=', outlineconfig);
    if (this.outlineconfigid) {
      outlineconfig.outlineconfigid = this.outlineconfigid;
      // add config details
      if (!outlineconfig.outlineconfigdetailid) {
        const inputData: any = [];
        inputData.push(
          {
            outlineconfigid: this.outlineconfigid,
            outlineconfigdetailid: 0,
            headinglevelid: +outlineconfig.headinglevelid,
            mandatorysection: +outlineconfig.mandatorysection,
            headingtext: outlineconfig.headingtext,
            readonlymode: outlineconfig.readonlymode,
            demotext: outlineconfig.demotext,
            instruction: outlineconfig.instruction,
            watermarktext: outlineconfig.watermarktext,
            headingnumber: outlineconfig.headingnumber,
            maxlength: outlineconfig.maxlength,
            enablelengthvalidation: outlineconfig.enablelengthvalidation,
            donotallowcontent: outlineconfig.donotallowcontent,
            plainvanilla: outlineconfig.plainvanilla,
            sequenceno: outlineconfig.sequenceno,
            parentoutlineconfigdetailid: outlineconfig.parentoutlineconfigdetailid,
            createdby: this.userid,
            active: 1,
          });
        this.outlineconfigurationservice.Post(inputData).subscribe(res => {
          if (res.status === 200) {
            if (res !== undefined) {
              if (res.body !== 0) {
                this.headerList.push({
                  'outlineconfigdetailid': JSON.parse(res.body)[0].outlineconfigdetailid,
                  'headingtext': outlineconfig.headingtext,
                  'sequenceno': this.headerList.length + 1,
                  'parentoutlineconfigdetailid': 0,
                  'levels': [],
                  'headinglevelid': JSON.parse(res.body)[0].headinglevelid,
                  'mandatorysection': JSON.parse(res.body)[0].mandatorysection,
                  'readonlymode': JSON.parse(res.body)[0].readonlymode,
                  'demotext': JSON.parse(res.body)[0].demotext,
                  'instruction': JSON.parse(res.body)[0].instruction,
                  'watermarktext': JSON.parse(res.body)[0].watermarktext,
                  'headingnumber': JSON.parse(res.body)[0].headingnumber,
                  'maxlength': JSON.parse(res.body)[0].maxlength,
                  'enablelengthvalidation': JSON.parse(res.body)[0].enablelengthvalidation,
                  'donotallowcontent': JSON.parse(res.body)[0].donotallowcontent,
                  'plainvanilla': JSON.parse(res.body)[0].plainvanilla,
                  'topicurl': JSON.parse(res.body)[0].topicurl
                });
                this.selectedRow = JSON.parse(res.body)[0].outlineconfigdetailid;
                this.reset();
              } else { this.toastr.warning('Record already exists.'); }
            }
          }
        },
          error => {
            console.log(error);
            this.toastr.error('Error while doing the operation');
          });
        this.SpinnerService.hide();
      } else {
        const inputData: any = [];
        // update config details
        inputData.push(
          {
            outlineconfigid: this.outlineconfigid,
            outlineconfigdetailid: outlineconfig.outlineconfigdetailid,
            headinglevelid: +outlineconfig.headinglevelid,
            mandatorysection: +outlineconfig.mandatorysection,
            headingtext: outlineconfig.headingtext,
            readonlymode: outlineconfig.readonlymode,
            demotext: outlineconfig.demotext,
            instruction: outlineconfig.instruction,
            watermarktext: outlineconfig.watermarktext,
            headingnumber: outlineconfig.headingnumber,
            maxlength: outlineconfig.maxlength,
            enablelengthvalidation: outlineconfig.enablelengthvalidation,
            donotallowcontent: outlineconfig.donotallowcontent,
            plainvanilla: outlineconfig.plainvanilla,
            sequenceno: outlineconfig.sequenceno,
            parentoutlineconfigdetailid: outlineconfig.parentoutlineconfigdetailid,
            updatedby: this.userid,
            active: 1,
          });
        this.outlineconfigurationservice.Put(inputData).subscribe(res => {
          if (res.status === 200) {
            if (res !== undefined) {
              this.reset();
              if (res.body !== 0) {
              } else { this.toastr.warning('Record already exists.'); }
            }
          }
        },
          error => {
            this.toastr.error('Error while doing the operation');
          });
        this.SpinnerService.hide();
      }
    } else {
      this.toastr.error('Save outline and proceed');
      this.SpinnerService.hide();
    }
  }

  PreLevelPost(outlineconfig) {
    console.log('outlineconfig=', outlineconfig);
    if (this.outlineconfigid) {
      outlineconfig.outlineconfigid = this.outlineconfigid;
      if (!outlineconfig.outlineconfigdetailid) {
        const inputData: any = [];
        inputData.push(
          {
            outlineconfigid: this.outlineconfigid,
            outlineconfigdetailid: 0,
            headinglevelid: +outlineconfig.headinglevelid,
            mandatorysection: +outlineconfig.mandatorysection,
            headingtext: outlineconfig.headingtext,
            readonlymode: outlineconfig.readonlymode === true ? 1 : 0,
            demotext: outlineconfig.demotext,
            instruction: outlineconfig.instruction,
            watermarktext: outlineconfig.watermarktext,
            headingnumber: outlineconfig.headingnumber,
            maxlength: outlineconfig.maxlength,
            enablelengthvalidation: outlineconfig.enablelengthvalidation === true ? 1 : 0,
            donotallowcontent: outlineconfig.donotallowcontent === true ? 1 : 0,
            plainvanilla: outlineconfig.plainvanilla,
            sequenceno: outlineconfig.sequenceno,
            parentoutlineconfigdetailid: outlineconfig.parentoutlineconfigdetailid,
            createdby: this.userid,
            active: 1,
          });
        this.outlineconfigurationservice.Post(inputData).subscribe(res => {
          if (res.status === 200) {
            if (res !== undefined) {
              if (res.body !== 0) {
                this.headerList.forEach(element => {
                  const foundNode = this.PostgetNodeById(element, outlineconfig.parentoutlineconfigdetailid,
                    JSON.parse(res.body)[0].outlineconfigdetailid);
                  if (foundNode) {
                    foundNode.levels.push({
                      'outlineconfigdetailid': JSON.parse(res.body)[0].outlineconfigdetailid,
                      'headingtext': foundNode.headingtext + 'child' + (foundNode.levels.length + 1),
                      'sequenceno': foundNode.levels.length + 1,
                      'parentoutlineconfigdetailid': outlineconfig.parentoutlineconfigdetailid,
                      'levels': [],
                      'headinglevelid': JSON.parse(res.body)[0].headinglevelid,
                      'mandatorysection': JSON.parse(res.body)[0].mandatorysection,
                      'readonlymode': JSON.parse(res.body)[0].readonlymode,
                      'demotext': JSON.parse(res.body)[0].demotext,
                      'instruction': JSON.parse(res.body)[0].instruction,
                      'watermarktext': JSON.parse(res.body)[0].watermarktext,
                      'headingnumber': JSON.parse(res.body)[0].headingnumber,
                      'maxlength': JSON.parse(res.body)[0].maxlength,
                      'enablelengthvalidation': JSON.parse(res.body)[0].enablelengthvalidation,
                      'donotallowcontent': JSON.parse(res.body)[0].donotallowcontent,
                      'plainvanilla': JSON.parse(res.body)[0].plainvanilla,
                    });
                  }
                  return;
                });
              } else { this.toastr.warning('Record already exists.'); }
            }
          }
        },
          error => {
            console.log(error);
            this.toastr.error('Error while doing the operation');
          });
        this.SpinnerService.hide();
      } else {
        const inputData: any = [];
        inputData.push(
          {
            outlineconfigid: this.outlineconfigid,
            outlineconfigdetailid: outlineconfig.outlineconfigdetailid,
            headinglevelid: +outlineconfig.headinglevelid,
            mandatorysection: +outlineconfig.mandatorysection,
            headingtext: outlineconfig.headingtext,
            readonlymode: outlineconfig.readonlymode === true ? 1 : 0,
            demotext: outlineconfig.demotext,
            instruction: outlineconfig.instruction,
            watermarktext: outlineconfig.watermarktext,
            headingnumber: outlineconfig.headingnumber,
            maxlength: outlineconfig.maxlength,
            enablelengthvalidation: outlineconfig.enablelengthvalidation === true ? 1 : 0,
            donotallowcontent: outlineconfig.donotallowcontent === true ? 1 : 0,
            plainvanilla: outlineconfig.plainvanilla,
            sequenceno: outlineconfig.sequenceno,
            parentoutlineconfigdetailid: outlineconfig.parentoutlineconfigdetailid,
            updatedby: this.userid,
            active: 1,
          });
        this.outlineconfigurationservice.Put(inputData).subscribe(res => {
          if (res.status === 200) {
            if (res !== undefined) {
              if (res.body !== 0) {
              } else { this.toastr.warning('Record already exists.'); }
            }
          }
        },
          error => {
            this.toastr.error('Error while doing the operation');
          });
        this.SpinnerService.hide();
      }
    } else {
      this.toastr.error('Save outline and proceed');
      this.SpinnerService.hide();
    }
  }

  addheader(data) {
    console.log('headingtext=', data.headingtext);
    if ((data.headingtext === undefined) || (data.headingtext.trim() === '')) {
      this.toastr.error('Heading should not be empty');
      return;
    }
    this.SpinnerService.show();
    const outlineconfig = {
      'levels': [],
      'outlineconfigdetailid': 0,
      'headinglevelid': +data.headinglevelid,
      'mandatorysection': +data.mandatorysection,
      'headingtext': data.headingtext,
      'readonlymode': data.readonlymode === true ? 1 : 0,
      'demotext': data.demotext,
      'instruction': data.instruction,
      'watermarktext': data.watermarktext,
      'headingnumber': data.headingnumber,
      'maxlength': data.maxlength,
      'enablelengthvalidation': data.enablelengthvalidation === true ? 1 : 0,
      'donotallowcontent': data.donotallowcontent === true ? 1 : 0,
      'plainvanilla': data.plainvanilla,
      'sequenceno': this.headerList.length + 1,
      'parentoutlineconfigdetailid': 0,
      'topicurl': data.topicurl,
      'createdby': this.userid,
      'active': 1,
    };
    this.PrePostHeading(outlineconfig);
  }

  addlevel(data, headingtext) {
    console.log('headingtext=', data);
    console.log('headingtext=', headingtext);
    this.SpinnerService.show();
    this.headerList.forEach(element => {
      const foundNode = this.getNodeById(element, data.outlineconfigdetailid);
      if (foundNode) {
        const outlineconfig = {
          'outlineconfigdetailid': 0,
          'headingtext': foundNode.headingtext + 'child' + (foundNode.levels.length + 1),
          'sequenceno': foundNode.levels.length + 1,
          'parentoutlineconfigdetailid': data.outlineconfigdetailid,
          'levels': [],
          'headinglevelid': (+data.headinglevelid + 1) >= this.highhierarchyorder ?
            +this.highhierarchydetail.headinglevelid : (+data.headinglevelid + 1)
        };
        this.PreLevelPost(outlineconfig);
      }
      return;
    });
  }

  getNodeById(currentNode, outlineconfigdetailid) {
    if (currentNode.outlineconfigdetailid === outlineconfigdetailid) {
      return currentNode;
    }
    for (let node = 0; node < currentNode.levels.length; node++) {
      const foundNode = this.getNodeById(currentNode.levels[node], outlineconfigdetailid);
      if (foundNode) {
        const outlineconfig = {
          'outlineconfigdetailid': 0,
          'headingtext': foundNode.headingtext + 'child' + (foundNode.levels.length + 1),
          'sequenceno': foundNode.levels.length + 1,
          'parentoutlineconfigdetailid': outlineconfigdetailid,
          'levels': [],
          'headinglevelid': (+foundNode.headinglevelid + 1) >= this.highhierarchyorder ?
            +this.highhierarchydetail.headinglevelid : (+foundNode.headinglevelid + 1)
        };
        this.PreLevelPost(outlineconfig);
        break;
      }
    }
    return undefined;
  }

  PostgetNodeById(currentNode, outlineconfigdetailid, responseId) {
    if (currentNode.outlineconfigdetailid === outlineconfigdetailid) {
      return currentNode;
    }
    for (let node = 0; node < currentNode.levels.length; node++) {
      const foundNode = this.PostgetNodeById(currentNode.levels[node], outlineconfigdetailid, responseId);
      if (foundNode) {
        foundNode.levels.push({
          'outlineconfigdetailid': responseId,
          'headingtext': foundNode.headingtext + 'child' + (foundNode.levels.length + 1),
          'sequenceno': foundNode.levels.length + 1,
          'parentoutlineconfigdetailid': outlineconfigdetailid,
          'levels': [],
          'headinglevelid': (+foundNode.headinglevelid + 1) >= this.highhierarchyorder ?
            +this.highhierarchydetail.headinglevelid : (+foundNode.headinglevelid + 1)
        });
        break;
      }
    }
    return undefined;
  }

  SavegetNodeById(currentNode, outlineconfigdetailid, response) {
    if (currentNode.outlineconfigdetailid === outlineconfigdetailid) {
      return currentNode;
    }
    for (let node = 0; node < currentNode.levels.length; node++) {
      const foundNode = this.SavegetNodeById(currentNode.levels[node], outlineconfigdetailid, response);
      if (foundNode) {
        foundNode.headinglevelid = +response.headinglevelid;
        foundNode.mandatorysection = +response.mandatorysection;
        foundNode.headingtext = response.headingtext;
        foundNode.readonlymode = response.readonlymode;
        foundNode.demotext = response.demotext;
        foundNode.instruction = response.instruction;
        foundNode.watermarktext = response.watermarktext;
        foundNode.headingnumber = response.headingnumber;
        foundNode.maxlength = response.maxlength;
        foundNode.enablelengthvalidation = response.enablelengthvalidation;
        foundNode.donotallowcontent = response.donotallowcontent;
        foundNode.plainvanilla = response.plainvanilla;
        foundNode.sequenceno = response.sequenceno;
        break;
      }
    }
    return undefined;
  }

  selectuser(selectuser, event) {
    console.log('selected=', selectuser);

    console.log('event=', event);
  }

  loadOutlineData() {
    this.headerList = [];
    if (this.outlineconfigid) {
      this.outlineconfigurationservice.getOutlineByoutlineconfigId(this.outlineconfigid).subscribe(res => {
        if (res !== undefined && res != null && res.length > 0) {
          res.forEach(i => {
            if (i !== undefined) {
              this.headerList.push(JSON.parse(i));
            }
          });
        }
        console.log('this.headerList=', this.headerList);
      }, error => { this.toastr.error('Error while getting data'); });
    } else {
      this.headerList = [];
    }
  }

  bindPlainvannila(data) {
    this.plainvanillaTemplateModalRef.hide();
    this.outlineconfigForm.controls['plainvanilla'].setValue(data.value.plainvanilla);
  }

  getdetails(data) {
    this.selectedRow = data.outlineconfigdetailid;
    if (data.outlineconfigdetailid) {
      this.outlineconfigForm.controls['outlineconfigid'].setValue(data.outlineconfigid);
      this.outlineconfigForm.controls['outlineconfigdetailid'].setValue(data.outlineconfigdetailid);
      this.outlineconfigForm.controls['headinglevelid'].setValue(data.headinglevelid);
      if (data.mandatorysection) {
        this.outlineconfigForm.controls['mandatorysection'].setValue(data.mandatorysection.toString());
      } else {
        this.outlineconfigForm.controls['mandatorysection'].setValue('0');
      }
      this.outlineconfigForm.controls['headingtext'].setValue(data.headingtext ? data.headingtext : '');
      this.outlineconfigForm.controls['readonlymode'].setValue(data.readonlymode === 1 ? true : false);
      this.outlineconfigForm.controls['demotext'].setValue(data.demotext ? data.demotext : '');
      this.outlineconfigForm.controls['instruction'].setValue(data.instruction);
      this.outlineconfigForm.controls['watermarktext'].setValue(data.watermarktext);
      this.outlineconfigForm.controls['headingnumber'].setValue(data.headingnumber);
      this.outlineconfigForm.controls['maxlength'].setValue(data.maxlength ? data.maxlength : 0);
      this.outlineconfigForm.controls['enablelengthvalidation'].setValue(data.enablelengthvalidation === 1 ? true : false);
      this.outlineconfigForm.controls['donotallowcontent'].setValue(data.donotallowcontent === 1 ? true : false);
      this.outlineconfigForm.controls['plainvanilla'].setValue(data.plainvanilla ? data.plainvanilla : '');
      this.outlineconfigForm.controls['sequenceno'].setValue(data.sequenceno);
      this.outlineconfigForm.controls['parentoutlineconfigdetailid'].setValue(data.parentoutlineconfigdetailid);
      this.outlineconfigForm.controls['topicurl'].setValue(data.topicurl);
    } else {
      this.outlineconfigForm.reset();
      this.outlineconfigForm.controls['demotext'].setValue('');
      this.outlineconfigForm.controls['maxlength'].setValue(0);
      this.outlineconfigForm.controls['headinglevelid'].setValue(1);
      this.outlineconfigForm.controls['mandatorysection'].setValue('1');
      this.outlineconfigForm.controls['headingtext'].setValue(data.headingtext);
      this.outlineconfigForm.controls['readonlymode'].setValue(true);
      this.outlineconfigForm.controls['enablelengthvalidation'].setValue(false);
      this.outlineconfigForm.controls['donotallowcontent'].setValue(false);
      this.outlineconfigForm.controls['plainvanilla'].setValue('');
      this.outlineconfigForm.controls['topicurl'].setValue(data.topicurl);
    }
  }

  reset() {
    this.selectedRow = -1;
    this.outlineconfigForm.reset();
    this.outlineconfigForm.controls['demotext'].setValue('');
    this.outlineconfigForm.controls['maxlength'].setValue(0);
    this.outlineconfigForm.controls['headinglevelid'].setValue(1);
    this.outlineconfigForm.controls['mandatorysection'].setValue('1');
    this.outlineconfigForm.controls['headingtext'].setValue('');
    this.outlineconfigForm.controls['readonlymode'].setValue(true);
    this.outlineconfigForm.controls['enablelengthvalidation'].setValue(false);
    this.outlineconfigForm.controls['donotallowcontent'].setValue(false);
    this.outlineconfigForm.controls['plainvanilla'].setValue('');
    this.outlineconfigForm.controls['topicurl'].setValue('');
  }


  Postoutline(outline) {
    console.log('outline=', outline);
    outline.projectid = +outline.projectid;
    outline.projectdid = +outline.projectdid;
    outline.toolsetid = +outline.toolsetid;
    if (!+outline.projectid) {
      this.toastr.error('Project should not be empty');
      return;
    } else if (!+outline.toolsetid) {
      this.toastr.error('Toolset should not be empty');
      return;
    } else if (!+outline.projectdid) {
      this.toastr.error('Project definition should not be empty');
      return;
    }
    outline.issmartchart = outline.issmartchart === true ? 1 : 0;
    outline.newsalert = outline.newsalert === true ? 1 : 0;
    outline.isnotapplicable = outline.isnotapplicable === true ? 1 : 0;
    if (this.saveAs) {
      outline.outlineconfigid = this.saveAs ? 0 : this.outlineconfigid;
    }
    this.SpinnerService.show();
    if (!outline.outlineconfigid) {
      if (this.saveAs) {
        const inputData = new Object({
          outlineconfigid: this.outlineconfigid,
          projectid: +outline.projectid,
          toolsetid: +outline.toolsetid,
          projectdid: +outline.projectdid,
          issmartchart: outline.issmartchart,
          newsalert: outline.newsalert,
          isnotapplicable: outline.isnotapplicable,
        });
        this.outlineservice.SaveAsOutline(inputData).subscribe(res => {
          if (res !== undefined && res != null && res.length > 0) {
            console.log('res=', res);
            if (+res[0] !== 0) {
              this.outlineconfigid = +res[0];
              this.outlineForm.controls['outlineconfigid'].setValue(this.outlineconfigid);
              this.loadOutlineData();
              if (+outline.issmartchart === 1) {
                this.saveAsSmartChart(outline.projectid, outline.projectdid);
              }
              this.toastr.success('Data saved successfully');
              this.SpinnerService.hide();
              this.saveAs = false;
            } else {
              this.SpinnerService.hide();
              this.toastr.warning('Record already exists.');
            }
          }
        }, error => {
          this.SpinnerService.hide();
          this.toastr.error('Error while getting data');
        });
      } else {
        outline.createdby = this.userid;
        this.outlineservice.Post(outline).subscribe(res => {
          if (res.status === 200) {
            if (res !== undefined) {
              if (res.body !== 0) {
                this.outlineconfigid = res.body;
                this.outlineForm.controls['outlineconfigid'].setValue(this.outlineconfigid);
                this.toastr.success('Data saved successfully');
                this.SpinnerService.hide();
              } else {
                this.SpinnerService.hide();
                this.toastr.warning('Record already exists.');
              }
            }
          }
        },
          error => {
            console.log(error);
            this.SpinnerService.hide();
            this.toastr.error('Error while doing the operation');
          });
      }
    } else {
      outline.updatedby = this.userid;
      this.outlineservice.Put(outline).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.outlineconfigid = res.body;
              this.toastr.success('Data updated successfully');
              this.SpinnerService.hide();
            } else { this.toastr.warning('Record already exists.'); }
          }
        }
      },
        error => {
          this.SpinnerService.hide();
          this.toastr.error('Error while doing the operation');
        });
    }
  }

  getoutline() {
    if (this.outlineconfigid) {
      this.outlineForm.controls['outlineconfigid'].setValue(this.outlineconfigid);
      this.outlineForm.controls['projectid'].setValue(this.projectid);
      this.outlineForm.controls['toolsetid'].setValue(this.toolsetid);
      this.outlineForm.controls['projectdid'].setValue(this.projectdid);
      this.outlineForm.controls['issmartchart'].setValue(this.issmartchart === 1 ? true : false);
      this.outlineForm.controls['newsalert'].setValue(this.newsalert === 1 ? true : false);
      this.outlineForm.controls['isnotapplicable'].setValue(this.isnotapplicable === 1 ? true : false);
    } else {
    }
  }

  onItemSelect(item: any) {
    this.textBoxTocuhed = true;
  }

  onItemDeSelect(item: any) {
    this.textBoxTocuhed = true;
  }

  OpenConfirmTemplate(outlinedetails, template: TemplateRef<any>) {
    this.openoutlineDeleteModal(this.outlineDeleteTemplate1, outlinedetails);
    this.selectedDetails = outlinedetails;
  }

  openoutlineDeleteModal(template: TemplateRef<any>, outlineConfig?: OutlineConfig) {
    this.displayS2Step1 = true;
    this.displayS2Step2 = false;
    this.outlineDeleteModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
    this.headerListFormap = [];
    this.deletedoutlineconfigdetailid = outlineConfig.outlineconfigdetailid;
    this.headerListFormap = this.flat(this.headerList);
    this.headerListFormap = this.headerListFormap.filter(h => h.outlineconfigdetailid !== outlineConfig.outlineconfigdetailid);
    this.selectedHeaderFormap = outlineConfig.headingtext;
    this.selectedHeadernumberFormap = outlineConfig.headingnumber;
    console.log('this.headerListFormap', this.flat(this.headerList));
  }

  onMappedHeaderChange(event) {
    console.log('event=', event);
  }

  PostHeaderListForMap(outlineconfigdetailid) {
    console.log('event=', event);
    if (+outlineconfigdetailid === 0) {
      this.toastr.error('Heading should not be empty');
      return;
    }
    const inputData = new Object({
      newoutlineconfigdetailid: +outlineconfigdetailid,
      outlineconfigdetailid: this.deletedoutlineconfigdetailid
    });
    this.outlineconfigurationservice.HeaderMapping(inputData).subscribe(res => {
      if (res.status === 200) {
        if (res !== undefined) {
          if (res.body !== 0) {
            this.toastr.success('Moved successfully');
            this.loadOutlineData();
            this.outlineDeleteModalRef.hide();
          } else { this.toastr.warning('Record already exists.'); }
        }
      }
    },
      error => {
        console.log(error);
        this.outlineDeleteModalRef.hide();
        this.toastr.error('Error while doing the operation');
      });

  }

  flat(array) {
    var result = [];
    array.forEach(a => {
      if (a.outlineconfigdetailid === this.deletedoutlineconfigdetailid) {
        return;
      }
      result.push(a);
      if (Array.isArray(a.levels)) {
        result = result.concat(this.flat(a.levels));
      }
    });
    return result;
  }
  ignore() {
    this.Delete(this.selectedDetails);
    this.outlineDeleteModalRef.hide();
  }

  onStepChange2(eve) {
    if (eve.selectedStep.state === 'step1') {
      this.displayS2Step1 = true;
      this.displayS2Step2 = false;
    } else if (eve.selectedStep.state === 'step2') {
      this.displayS2Step1 = false;
      this.displayS2Step2 = true;
    }
  }
  Delete(data) {
    console.log('headingtext=', data);
    let msg;
    msg = 'Record deleted successfully';
    const inputData = new Object({
      outlineconfigdetailid: data.outlineconfigdetailid,
      active: 0
    });
    this.outlineconfigurationservice.Delete(inputData).subscribe(res => {
      this.toastr.success(msg);
      this.loadOutlineData();
    },
      error => { });
  }

  getNodeByIdFordelete(currentNode, outlineconfigdetailid) {
    if (currentNode.outlineconfigdetailid === outlineconfigdetailid) {
      return currentNode;
    }
    for (let node = 0; node < currentNode.levels.length; node++) {
      const foundNode = this.getNodeById(currentNode.levels[node], outlineconfigdetailid);
      if (foundNode) {
        const outlineconfig = {
          'outlineconfigdetailid': 0,
          'headingtext': foundNode.headingtext + 'child' + (foundNode.levels.length + 1),
          'sequenceno': foundNode.levels.length + 1,
          'parentoutlineconfigdetailid': outlineconfigdetailid,
          'levels': [],
          'headinglevelid': (+foundNode.headinglevelid + 1) >= this.highhierarchyorder ?
            +this.highhierarchydetail.headinglevelid : (+foundNode.headinglevelid + 1)
        };
        this.PreLevelPost(outlineconfig);
        break;
      }
    }
    return undefined;
  }

  /*openSmartChartPopUp(template: TemplateRef<any>) {
    if (this.outlineconfigid > 0) {
      this.smartChartModalRef = this.modalService.show(template, this.config);
      const aa = document.getElementsByClassName('modal-content');
      aa[0].classList.remove('modal-content');
    } else {
      this.toastr.error('Outline config should get saved');
      return;
    }
  }*/

  getfrmValue($event, smartChartPopup) {
    this.formElement = $event;
    let projectDefinitionsName = '';
    let projectname = '';
    if (+this.outlineForm.controls['projectdid'].value > 0) {
      let d = this.projectdefinitions.filter(i => i.projectdefinitionid === +this.outlineForm.controls['projectdid'].value);
      if (d.length !== 0) {
        projectDefinitionsName = d[0].project_subtitle;
      }
    }
    if (+this.outlineForm.controls['projectid'].value > 0) {
      let st = this.projects.filter(i => i.projectid === +this.outlineForm.controls['projectid'].value);
      if (st.length !== 0) {
        projectname = st[0].projectname;
      }
    }
    if (projectDefinitionsName !== '' && projectname !== '') {
      this.smartChartName = projectname.toLowerCase() + projectDefinitionsName.toLowerCase() + this.outlineconfigid;
    }
    this.openFormPopup(smartChartPopup);

  }

  async openFormPopup(smartChartPopup: TemplateRef<any>) {
    // console.log(JSON.parse(this.formElement).length);
    this.smartChartButtonDisabled = true;
    if (JSON.parse(this.formElement).length !== 0 && this.formElement !== null && this.formElement !== undefined) {
      let res: any;
      res = this.dataValidation(this.formElement);
      if (res !== '') {
        this.toastr.error('Master data should get selected for ' + res);
        this.smartChartButtonDisabled = false;
        return;
      }
      this.smartChartDisplaySeq = [];
      this.smartChartDisplaySeq = await this.getFormConfigDisplayField(this.smartchartconfigid);
      //console.log(this.btnName);
      // console.log(this.smartChartDisplaySeq) ;
      this._cleanedFormElement = this.btnName === 'Add' ?
        this.controlNameChange(this.formElement) : this.controlNameChangeUpdate(this.formElement, this.htmlData);
      this.smartChartConfigHtmlData = this._cleanedFormElement;
      this.userid = +localStorage.getItem('userid');
      this.smartChartSeqModalRef = this.modalService.show(smartChartPopup, this.config);
      const aa = document.getElementsByClassName('modal-content');
      aa[0].classList.remove('modal-content');
      this.parsedFormElement = JSON.parse(this.smartChartConfigHtmlData);
      console.log(this.parsedFormElement);
      this.parsedFormElement.forEach((element, index) => {
        // element['label']  =  element.label.replace(/&nbsp;/g, ' ');
        element['label'] = this.replaceHtml(element.label.toString());
        //this.removeSpace(element.label);
       // element['displaystatus'] = this.btnName === 'Edit' ? this.getDisplayStatus(element) : false;
       // element['editordisplaystatus'] = this.btnName === 'Edit' ? this.getEditorDisplayStatus(element) : false;
       element['displaystatus'] = this.btnName === 'Edit' ?  this.getDisplayStatus(element)  : 0;
       element['editordisplaystatus'] = this.btnName === 'Edit' ?  this.getEditorDisplayStatus(element) : 0;
        element['iseditable'] = this.btnName === 'Edit' ? this.getIsEditable(element) : false;
        //element['sequence'] = this.btnName === 'Edit' ? this.getSequenceNumber(element) : index + 1;
        element['sequence'] = index + 1;// this.btnName === 'Edit' ? this.getSequenceNumber(element) : index + 1;
        element['active'] = true;
      });
    } else {
      this.smartChartButtonDisabled = false;
      this.toastr.error('Smart chart value should not be empty');
    }
  }

  async getFormConfigDisplayField(smartChartConfigid) {
    return await this.smartchartService.getFormConfigDisplayField(smartChartConfigid).toPromise().then(res => res);
  }

  /* getFormConfigDisplayField(smartChartConfigid) {
     this.smartChartDisplaySeq = [];
     this.smartchartService.getFormConfigDisplayField(smartChartConfigid).subscribe((result) => {
 
       this.smartChartDisplaySeq = result;
     });
   }*/

   getDisplayStatus(element) {
    let value = this.smartChartDisplaySeq.findIndex(x => x.formcontrolname === element.formcontrolname);
    if (value !== -1) {
     // return this.smartChartDisplaySeq[value].displaystatus === 1 ? true : false;
     return this.smartChartDisplaySeq[value].displaystatus;
    } else {
      return false;
    }
  }

  dataValidation(data) {
    let label = '';
    let controlList = JSON.parse(data);
    if ((controlList !== undefined) && (controlList.length !== 0)) {
      controlList.forEach(item => {
        if (((item.type === 'select') && (item.description === 'Masters')) ||
          ((item.type === 'radio-group') && (item.description === 'Masters')) || ((item.type === 'checkbox-group') &&
            (item.description === 'Masters') && (item.values.length > 1))) {
          let valueList = item.values;
          if ((valueList !== undefined) && (valueList.length !== 0)) {
            let s = valueList.filter(e => e.selected === true);
            if (s === undefined || s.length === 0) {
              label = item.label;
              return label;
            }
          }
        }
      });
    }
    return label;
  }

  controlNameChangeUpdate(newformdata, oldformdata) {
    if ((newformdata !== undefined) && (newformdata !== null)) {
      let newarr = JSON.parse(newformdata);
      let oldarr = JSON.parse(oldformdata);
      let totalCount = newarr.length;
      if (newarr.length > 0) {
        newarr.forEach((item, index) => {
          let s = oldarr.filter(e => e.type === item.type && e.label === item.label);
          if ((s !== undefined) && (s.length === 0)) {
            let alias = this._fieldAliasList.filter(e => e.fieldlabel === item.type);
            if ((item.name !== undefined) && (item.formcontrolname === undefined)) {
              if (alias.length !== 0) {
                if (item.label === undefined) {
                  if (item.type === 'checkbox-group') {
                    item.label = item.values[0].label;
                  }
                }
                let name = alias[0].fieldalias + (item.label === undefined ? '' : item.label) + totalCount;
                item.name = name;
              } else {
                item.name = item.label + totalCount;
              }
              totalCount = totalCount + 1;
            }
            if ((item.name === undefined) && (item.formcontrolname === undefined))//if name is empty
            {
              if (alias.length !== 0) {
                let name = alias[0].fieldalias + (item.label === undefined ? '' : item.label) + totalCount;
                item.name = name;
              } else {
                item.name = item.label + totalCount;
              }
              totalCount = totalCount + 1;
            }
            item.name = this.removeSpace(item.name);
            if (item.name !== undefined) {
              let txt = this.removeSpecialCharacters(item.name);
              newarr[index]['formcontrolname'] = txt;
            }
          } else {
            if (s[0].formcontrolname !== undefined && s[0].formcontrolname !== null) {
              let txt = this.removeSpecialCharacters(s[0].formcontrolname);
              newarr[index]['formcontrolname'] = txt;
              newarr[index]['name'] = s[0].name;
              if (s[0].description !== undefined) {
                newarr[index]['description'] = s[0].description;
              }
            } else {
              newarr[index]['formcontrolname'] = item.name;
            }
          }
          if (((item.type === 'select') && (item.description === 'Masters'))
            || ((item.type === 'radio-group') && (item.description === 'Masters')) ||
            ((item.type === 'checkbox-group') && (item.description === 'Masters') && (item.values.length > 1))) {
            let valueList = item.values;
            if ((valueList !== undefined) && (valueList.length !== 0)) {
              let s = valueList.filter(e => e.selected === true);
              if (s !== undefined || s.length !== 0) {
                newarr[index]['tablename'] = s[0].label;
              }
            }
          }
          if (item.type === 'file') {
            let chkExists = oldarr.filter(e => e.type === 'hidden' && e.formcontrolname === item.formcontrolname + 'size');
            console.log(chkExists);
            if (chkExists.length === 0) {
              newarr.push({ 'type': 'hidden', 'name': item.formcontrolname + 'size', 'formcontrolname': item.formcontrolname + 'size' });
            }
            // newarr.push({ 'type': 'hidden', 'name': item.formcontrolname + 'size', 'formcontrolname': item.formcontrolname + 'size' });
          }
        });
        return JSON.stringify(newarr);
      }
    }
  }

  removeSpace(givenText) {
    let b = '';
    let replaceTxt = givenText.replace(/&nbsp;/g, ' ');
    let removeSpace = replaceTxt.split(/(\s+)/);
    if (removeSpace.length != 0) {
      removeSpace.forEach(a => {
        b = b + a.trim();
      });
    }
    return b.trim();
  }

  removeSpecialCharacters(text) {
    let cleanedTxt = text.replace(/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g, '');
    return cleanedTxt;
  }
  controlNameChange(data) {
    let arr1 = [];
    if ((data !== undefined) && (data !== null)) {
      let arr = JSON.parse(data);
      // get list of field alias name   
      if (arr.length > 0) {
        arr.forEach((item, index) => {
          if (item.name !== 'issendnotification' && item.type !== 'hidden') {
            if (item.name !== undefined) {
              let alias = this._fieldAliasList.filter(e => e.fieldlabel === item.type);
              let ind = index + 1;
              if (alias.length !== 0) {
                //if label is undefined
                if (item.label === undefined) {
                  if (item.type === 'checkbox-group') {
                    item.label = item.values[0].label;
                  }
                }
                let name = alias[0].fieldalias + (item.label === undefined ? '' : item.label) + ind;
                item.name = name;
              } else {
                item.name = item.label + ind;
              }
              let b = '';
              let replaceTxt = item.name.replace(/&nbsp;/g, ' ');
              let removeSpace = replaceTxt.split(/(\s+)/);
              if (removeSpace.length !== 0) {
                removeSpace.forEach(a => {
                  b = b + a.trim();
                });
                item.name = b.trim();
              }
            } else {
              let alias = this._fieldAliasList.filter(e => e.fieldlabel === item.type);
              let ind = index + 1;
              if (alias.length !== 0) {
                let name = alias[0].fieldalias + (item.label === undefined ? '' : item.label) + ind;
                item.name = name;
              } else {
                item.name = item.label + ind;
              }
              let b = '';
              let replaceTxt = item.name.replace(/&nbsp;/g, ' ');
              let removeSpace = replaceTxt.split(/(\s+)/);
              if (removeSpace.length !== 0) {
                removeSpace.forEach(a => {
                  b = b + a.trim();
                });
                item.name = b.trim();
              }
            }
            if (item.name !== undefined) {
              let txt = this.removeSpecialCharacters(item.name);
              arr[index]['formcontrolname'] = txt;
            }
            if (((item.type === 'select') && (item.description === 'Masters')) ||
              ((item.type === 'radio-group') &&
                (item.description === 'Masters')) || ((item.type === 'checkbox-group')
                  && (item.description === 'Masters') && (item.values.length > 1))) {
              let valueList = item.values;
              if ((valueList !== undefined) && (valueList.length !== 0)) {
                let s = valueList.filter(e => e.selected === true);
                if (s !== undefined || s.length !== 0) {
                  arr[index]['tablename'] = s[0].label;
                }
              }
            }
            if (item.type === 'file') {
              let chkExists = arr.filter(e => e.type === 'hidden' && e.formcontrolname === item.formcontrolname + 'size');
              if (chkExists.length === 0) {
                arr.push({ 'type': 'hidden', 'name': item.formcontrolname + 'size', 'formcontrolname': item.formcontrolname + 'size' });
              }
              // arr.push({ 'type': 'hidden', 'name': item.formcontrolname + 'size', 'formcontrolname': item.formcontrolname + 'size' });
            }
          }
        });
        return JSON.stringify(arr);
      }
    }

  }

  LoadFieldList() {
    this.smartchartService.getFieldAlias().subscribe((res) => {
      if (res !== undefined) {
        this._fieldAliasList = res;
      }
    });
  }

  checkChange(event) {
    this.parsedFormElement.forEach(formElement => {
      formElement.displaystatus = event.target.checked;
    });
  }
  // Calling final step
  loadFinishOutlineConfig(stepper) {
    if (!this.saveAs) {
      if (this.outlineconfigid > 0) {
        this.displayStep1 = false;
        this.displayStep2 = false;
        this.displayStep3 = false;
        this.displayStep4 = false;
        this.displayStep5 = true;
        const inputData = new Object({
          outlineconfigid: this.outlineconfigid
        });
        if (this.outlineForm.get('issmartchart').value === true && this.htmlData !== undefined &&
          this.htmlData !== null && this.htmlData !== '') {
          this.loadhtmldata(this.htmlData);
        }
        this.outlineservice.getByID(inputData).subscribe(resp => {
          this.outlinedetails = JSON.parse(resp.body[0])[0];
          console.log('outlinedetails=', this.outlinedetails);
        }, error => { });
      }
      else {
        this.toastr.warning('Outline should be selected');
      }
    } else {
      this.toastr.warning('Save outline config and proceed');
    }
  }

  finishoutlineConfig() {
    this.router.navigate(['projectconfiguration/outlinemaster']);
  }

  smartChartConfigSubmit(parsedFormElement) {
    let postValue = [];
    parsedFormElement.forEach(element => {
      if (element.type !== 'hidden' && element.type !== 'header') {
        postValue.push({
          formcontrolname: element.formcontrolname,
          type: element.type,
          name: element.label,
          displaystatus: element.displaystatus,//element.displaystatus ? 1 : 0,
          editordisplaystatus: element.editordisplaystatus,//element.editordisplaystatus ? 1 : 0,
          iseditable: element.iseditable ? 1 : 0,
          sequence: element.sequence,
          tablename: element.tablename,
          createdby: localStorage.getItem('userid'),
          createdon: new Date(),
          active: element.active ? 1 : 0
        });
      }
      if (element.type === 'header') {
        postValue.push({
          formcontrolname: element.formcontrolname,
          type: element.type,
          name: element.label,
          //displaystatus: element.displaystatus ? 1 : 0,
          //editordisplaystatus: element.editordisplaystatus ? 1 : 0,
          displaystatus: element.displaystatus,//element.displaystatus ? 1 : 0,
          editordisplaystatus: element.editordisplaystatus,//element.editordisplaystatus ? 1 : 0,
          iseditable: element.iseditable ? 1 : 0,
          sequence: element.sequence,
          tablename: element.tablename,
          createdby: localStorage.getItem('userid'),
          createdon: new Date(),
          active: element.active ? 1 : 0
        });
      }
    });
    let inputData = [];
    inputData.push({ smartConfigAdd: JSON.stringify(postValue) });
    console.log(inputData);
    this.postSmartChartConfig(inputData);
  }

  getSequenceNumber(element) {
    let value = this.smartChartDisplaySeq.findIndex(x => x.formcontrolname === element.formcontrolname);
    if (value !== -1) {
      return this.smartChartDisplaySeq[value].sequence;
    } else {
      return 0;
    }
  }

  getEditorDisplayStatus(element) {
    let value = this.smartChartDisplaySeq.findIndex(x => x.formcontrolname === element.formcontrolname);
    if (value !== -1) {
      //return this.smartChartDisplaySeq[value].editordisplaystatus === 1 ? true : false;
      return this.smartChartDisplaySeq[value].editordisplaystatus;
    } else {
      return false;
    }
  }

  getIsEditable(element) {
    let value = this.smartChartDisplaySeq.findIndex(x => x.formcontrolname === element.formcontrolname);
    if (value !== -1) {
      return this.smartChartDisplaySeq[value].iseditable === 1 ? true : false;
    } else {
      return false;
    }
  }


  checkChangeIsEdit(event) {
    this.parsedFormElement.forEach(formElement => {
      formElement.iseditable = event.target.checked;
    });
  }


  postSmartChartConfig(inputData) {
    this.SpinnerService.show();
    if (this.outlineconfigid > 0) {
      if (this.smartChartName !== '') {
        let s = this.removeSpecialCharacters(this.smartChartName);
        this.smartChartName = s;
        const smartConfigAdd = JSON.parse(inputData[0].smartConfigAdd);
        const checked = smartConfigAdd.filter(x => x.displaystatus == 1);
        if (checked.length === 0) {
          this.toastr.error('Please select atleast one GM/CM View field');
          this.SpinnerService.hide();
          return;
        }
        const checked1 = smartConfigAdd.filter(x => x.editordisplaystatus == 1);
        if (checked1.length === 0) {
          this.toastr.error('Please select atleast one Authors View field');
          this.SpinnerService.hide();
          return;
        }
        let smartChart: Smartchart[];
        smartChart = [];
        if (this.btnName === 'Add') {
          smartChart.push({
            smartchartconfigid: 0, createdby: this.userid,
            active: 1, htmldata: this._cleanedFormElement, outlineconfigid: this.outlineconfigid,
            smartchartname: this.smartChartName, smartconfigadd: inputData[0].smartConfigAdd,
            createdon: '', modifiedby: 0, modifiedon: ''
          });
          this.smartchartService.postSmartChart(smartChart[0]).subscribe(
            (res) => {
              if (res.body !== 0) {
                this.toastr.success('Smart Chart added successfully');
                this.smartChartButtonDisabled = false;
                this.SpinnerService.hide();
                this.clearForm();
                this.btnName = 'Edit';
                this.smartChartSeqModalRef.hide();
                this.loadSmartChart();
              } else {
                this.toastr.error('Smart Chart Config exists already');
                this.smartChartButtonDisabled = false;
                this.SpinnerService.hide();
              }
            }, error => {
              this.toastr.error('Smart Chart Configuration not completed successfully');
              this.smartChartButtonDisabled = false;
              this.SpinnerService.hide();
            });
        }
        if (this.btnName === 'Edit') {
          smartChart.push({
            smartchartconfigid: this.smartchartconfigid, createdby: 0,
            active: 1, htmldata: this._cleanedFormElement,
            outlineconfigid: this.outlineconfigid, smartchartname: this.smartChartName,
            smartconfigadd: inputData[0].smartConfigAdd, createdon: '',
            modifiedby: this.userid, modifiedon: ''
          });
          this.smartchartService.putSmartChart(smartChart[0]).subscribe(
            (res) => {
              if (res.body !== 0) {
                this.toastr.success('Smart Chart updated successfully');
                this.smartChartButtonDisabled = false;
                this.clearForm();
                this.smartChartSeqModalRef.hide();
                this.SpinnerService.hide();
                this.loadSmartChart();
              } else {
                this.toastr.error('Smart Chart Config exists already');
                this.smartChartButtonDisabled = false;
                this.SpinnerService.hide();
              }
            }, error => {
              this.toastr.error('Smart Chart Configuration not completed successfully');
              this.smartChartButtonDisabled = false;
              this.SpinnerService.hide();
            });
        }
      } else {
        this.toastr.error('Project definition and track should be selected');
        this.smartChartButtonDisabled = false;
        this.SpinnerService.hide();
        return;
      }
    } else {
      this.toastr.error('Outline config should get saved');
      this.smartChartButtonDisabled = false;
      this.SpinnerService.hide();
      return;
    }
  }

  clearForm() {

    this.formElement = ''; this._cleanedFormElement = '';
  }

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

  loadOutlineConfig(stepper) {
    if (!this.saveAs) {
      if (this.outlineconfigid > 0) {
        this.displayStep1 = false;
        this.displayStep2 = false;
        this.displayStep3 = true;
        this.displayStep4 = false;
        this.displayStep5 = false;
      } else {
        this.toastr.warning('Outline should be selected');
      }

    } else {
      this.toastr.warning('Save outline config and proceed');
    }
  }

  onStepChange(eve) {
    if (eve.selectedStep.state === 'project') {
      this.loadProjectDefinition();
    } else if (eve.selectedStep.state === 'stagemovement') {
      this.loadStagemovement('');
    } else if (eve.selectedStep.state === 'outlineConfig') {
      this.loadOutlineConfig('');
    } else if (eve.selectedStep.state === 'smartchart') {
      this.loadSmartChart();
    } else if (eve.selectedStep.state === 'finish') {
      this.loadFinishOutlineConfig('');
    }
  }

  loadStagemovement(stepper) {
    if (!this.saveAs) {
      if (this.outlineconfigid > 0) {
        this.displayStep1 = false;
        this.displayStep2 = true;
        this.displayStep3 = false;
        this.displayStep4 = false;
        this.displayStep5 = false;
        if (stepper) {
          if (stepper.selected.state === 'project') {
            stepper.next();
          }
        }
      } else {
        this.toastr.warning('Outline should be selected');
      }
    } else {
      this.toastr.warning('Save outline config and proceed');
    }
  }

  loadSmartChart() {
    this.SpinnerService.show();
    if (!this.saveAs) {
      console.log(this.outlineconfigid);
      if (this.outlineconfigid > 0) {
        this.displayStep1 = false;
        this.displayStep2 = false;
        this.displayStep3 = false;
        this.displayStep4 = true;
        // for loading the smartchart in add or edit mode
        let smartChartExists = false;

        if (this.outlineconfigid > 0) {
          const inputData = [];
          inputData.push({
            outlineconfigid: this.outlineconfigid
          });
          this.outlineservice.getByID(inputData[0]).subscribe(res => {
            if (res.body[0] !== undefined && res.body[0] !== null) {
              let data = JSON.parse(res.body[0]);
              if (data.length > 0) {
                if (data[0].smartchartconfigid !== null && data[0].smartchartconfigid > 0) {
                  smartChartExists = true;
                  this.btnName = 'Edit';
                  this.smartchartconfigid = +data[0].smartchartconfigid;
                  const input = [];
                  input.push({ smartchartconfigid: this.smartchartconfigid });
                  this.smartchartService.getByID(input[0]).subscribe(response => {
                    if (response.body !== undefined && response.body !== null && response.body.length > 0) {
                      let htmlData = response.body[0].htmldata;
                      this.htmlData = htmlData;
                      this._SmartchartComponent.setValue(htmlData);
                      this.SpinnerService.hide();
                    }
                  }, err => { this.toastr.error(err); this.SpinnerService.hide(); });
                } else {
                  this.htmlData = '';
                  this._SmartchartComponent.clearBuilder();
                  this.SpinnerService.hide();
                }
              }
            }
          }, err => { this.toastr.error(err); this.SpinnerService.hide(); });
        } else {
          this.toastr.error('Outline config should get saved');
          this.SpinnerService.hide();
          return;
        }
      } else {
        this.SpinnerService.hide();
        this.toastr.warning('Project definition should be selected');

      }
    } else {
      this.SpinnerService.hide();
      this.toastr.warning('Save outline config and proceed');
    }
  }

  openskillModal(template: TemplateRef<any>) {
    this.plainvanillaTemplateModalRef = this.modalService.show(template, this.config);
  }

  loadhtmldata(formdata: any) {
    var data = JSON.parse(formdata);
    if (data.length > 0) {
      data.forEach((item) => {
        if (item.description == 'Masters') {
          item.description = '';
        }
      });
    }
    console.log(data);
    const formData = JSON.stringify(data);
    console.log(formData);
    const escapeEl = document.createElement("textarea");
    const code = document.getElementById("markup");
    const addLineBreaks = html => html.replace(new RegExp("><", "g"), "><");
    const $markup = $("<div/>");
    $markup.formRender({ formData });
    code.innerHTML = addLineBreaks($markup.formRender("html"));

  }
  checkChangeEditor(event) {
    this.parsedFormElement.forEach(formElement => {
      formElement.editordisplaystatus = event.target.checked;
    });
  }
  // method to search the user mapped project subtitle
  async openSearchWindow(template: TemplateRef<any>) {
    this.SpinnerService.show();
    this.searchText2 = '';
    this.outlineMasterModalRef = this.modalService.show(template, this.config);
    this.SpinnerService.hide();
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }
  // method to bind the project definition details
  onSearchClick(item) {
    console.log('item=', item);
    if (item !== null && item !== undefined) {
      this.outlineconfigid = item.outlineconfigid;
      this.projectid = item.projectid;
      this.projectdid = item.projectdid;
      this.toolsetid = item.toolsetid;
      this.issmartchart = item.issmartchart;
      this.newsalert = item.newsalert;
      this.isnotapplicable = item.isnotapplicable;
      this.saveAs = false;
      this.oldtoolsetid = item.toolsetid;
      this.outlineMasterModalRef.hide();
      if (this.projectdid) {
        this.getProjectDefition(this.projectid);
      }
      this.getoutline();
      this.loadOutlineData();
      this.loadPlugin();
    }
  }

  replaceHtml(data: string): string {
    var res = '';
    if (data) {
      res = data.replace(/&nbsp;/g, ' ');
      res = res.replace(/(<([^>]+)>)/g, '');
      return res;
    }
  }


  saveAsSmartChart(projectid, projectdid) {
    if (this.outlineconfigid > 0) {
      let projectDefinitionsName = '';
      let projectname = '';
      if (+projectdid > 0) {
        let d = this.projectdefinitions.filter(i => i.projectdefinitionid === +projectdid);
        if (d.length !== 0) {
          projectDefinitionsName = d[0].project_subtitle;
        }
      }
      if (+projectid > 0) {
        let st = this.projects.filter(i => i.projectid === +projectid);
        if (st.length !== 0) {
          projectname = st[0].projectname;
        }
      }
      if (projectDefinitionsName !== '' && projectname !== '') {
        this.smartChartName = projectname.toLowerCase() + projectDefinitionsName.toLowerCase() + this.outlineconfigid;
      }
      const inputData = [];
      inputData.push({
        outlineconfigid: this.outlineconfigid
      });
      let s = this.removeSpecialCharacters(this.smartChartName);
      this.smartChartName = s;
      this.outlineservice.getByID(inputData[0]).subscribe(async res => {
        let data = JSON.parse(res.body[0]);
        if (data.length > 0) {
          if (data[0].smartchartconfigid !== null && data[0].smartchartconfigid > 0) {
            this.smartchartconfigid = +data[0].smartchartconfigid;
            console.log(this.smartchartconfigid);
            const input = [];
            input.push({ smartchartconfigid: this.smartchartconfigid });
            let result = await this.getBySmartChartID(input[0]);
            if (result.body !== undefined && result.body !== null && result.body.length > 0) {
              let htmlData = result.body[0].htmldata;
              this.htmlData = htmlData;
              this.smartChartDisplaySeq = [];
              this.smartChartDisplaySeq = await this.getFormConfigDisplayField(this.smartchartconfigid);
              let smartChart: Smartchart[];
              smartChart = [];
              smartChart.push({
                smartchartconfigid: 0, createdby: this.userid,
                active: 1, htmldata: this.htmlData, outlineconfigid: this.outlineconfigid,
                smartchartname: this.smartChartName, smartconfigadd: JSON.stringify(this.smartChartDisplaySeq),
                createdon: '', modifiedby: 0, modifiedon: ''
              });
              this.smartchartService.postSmartChart(smartChart[0]).subscribe(
                (response) => {
                  if (response.body !== 0) {
                    this.toastr.success('Smart Chart added successfully');
                    this._SmartchartComponent.setValue(htmlData);
                  }
                }, err => { this.toastr.error('Error while adding smart chart data'); });
            }
          }
        }
      }, err => { this.toastr.error('Error while getting outline config detail'); });
    }
  }

  async getBySmartChartID(input) {
    return await this.smartchartService.getByID(input).toPromise().then(res => res);
  }
  isValidURL(string) {
    if (string) {
      var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
      return (res !== null);
    }
  };
  gecmviewChange(event,i){
    this.parsedFormElement[i].displaystatus = event.target.value;
  }
  gecmviewcheckall(event) {
    this.parsedFormElement.forEach(formElement => {
      formElement.displaystatus =  event.target.value;
    }); 
  }

  authorviewcheckall(event){
    this.parsedFormElement.forEach(formElement => {
      formElement.editordisplaystatus =  event.target.value;
    });
  }
  authorviewChange(event,i){
    this.parsedFormElement[i].editordisplaystatus = event.target.value;
  }
}
