import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { User } from 'src/app/masters/user/user';
import { UserService } from 'src/app/masters/user/user.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { Userrolemapping } from '../userrolemapping/userrolemapping';
import { DualListComponent } from 'angular-dual-listbox';
import { ProjectConfigurationService } from 'src/app/projectconfiguration/projectconfiguration/projectconfiguration.service';
import { UserstagemappingService } from './userstagemapping.service';
import { Userstagemapping } from './userstagemapping';
import { Jobmaster } from 'src/app/jobconfiguration/jobmaster/jobmaster';
import { Department } from 'src/app/masters/department/department';
import { DepartmentService } from 'src/app/masters/department/department.service';
import * as $ from 'jquery';
import { timeout } from 'rxjs/operators';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { DialogService } from 'ng2-bootstrap-modal';
import { Router } from '@angular/router';
import { AppurlService } from 'src/app/masters/appurl/appurl.service';
import { FeatureService } from 'src/app/masters/feature/feature.service';
@Component({
  selector: 'app-userstagemapping',
  templateUrl: './userstagemapping.component.html',
  styleUrls: ['./userstagemapping.component.css']
})
export class UserstagemappingComponent implements OnInit {
  userStageForm: FormGroup;
  userList: User[] = [];
  projectDefinitions: any[] = [];
  uniqueProjectDefinitions: any[] = [];
  states: any[] = [];
  pwdid = '';
  projectdefinitionid: number;
  selectedUserList: Userstagemapping[] = [];
  selectedUserListf: Userstagemapping[] = [];
  orgselectedUserList: Userstagemapping[] = [];
  formTocuhed = false;
  filter = true;
  userid: number;
  format = {
    add: 'Add', remove: 'Remove', all: 'All', none: 'None',
    direction: DualListComponent.LTR, draggable: true, filter: true
  };

  departments: Department[] = [];

  _ddlStagetypeSettings: {};
  textBoxTocuhed: boolean;
  _producttypeselected: any = [];
  job = {} as Jobmaster;
  jobs: any = [];
  overalllist: Department[] = [];
  overalldepartmentlist: any = [];
  departmentlist: any = [];
  projectmaplist: any = [];
  addandremovestage: any = [];
  userdeplist = [];
  projectmaplist_overall: any = [];
  overallprojectmaplist = [];
  projectmaplist_overall_orginal = [];
  useridmapprojlist: any = [];

  useridmapproj = '';
  useridmapprojid: number;
  selectedIndex = 0;
  departdisplayname = '';
  my = { search: '' };
  isstagealreadymap = false;
  stageactive = false;
  selectedprojectdefinition: number;
  selectedstage: number;
  FeatureselectedItemsCheckIn: any = [];
  FeatureselectedItemsCheckOut: any = [];
  FeatureselectedItemsInProgress: any = [];
  actionRights: any;
  checkinweburl = false;
  checkinserviceurl = false;
  checkoutweburl = false;
  checkoutserviceurl = false;
  inprogressweburl = false;
  inprogressserviceurl = false;
  appurlsData: any[] = [];
  appurlsweb: any[] = [];
  feature: any[] = [];
  featureactive: any[] = [];
  constructor(
    private router: Router,
    private formBuilder: FormBuilder,
    private userservice: UserService,
    private SpinnerService: NgxSpinnerService,
    private toastr: ToastrService,
    private projectConfigurationService: ProjectConfigurationService,
    private userstagemappingService: UserstagemappingService,
    private departmentservice: DepartmentService,
    private dialogService: DialogService,
    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('UserStageMapping_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('UserStageMapping_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('UserStageMapping_userRights');
    }

  }

  ngOnInit() {
    this.userStageForm = this.formBuilder.group({
      stagemappingid: [0],
      projectdefinitionid: [0],
      pwdid: [[]],
      userid: [],
      active: [1],
    });
    this.userid = +localStorage.getItem('userid');
    // this.loadProjectDefinitions();
    this.GetAllDepartment();
    this.getApprlsData();
    this.getAllFeatures();
    this._ddlStagetypeSettings = {
      singleSelection: false,
      idField: 'pwdid',
      textField: 'stagename_alias',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      itemsShowLimit: 7,
      allowSearchFilter: true
    };

  }

  clear() {
    this.userList = [];
    this.orgselectedUserList = [];
    this.selectedUserList = [];
    // this.userStageForm.controls['pwdid'].setValue(0);
    this.userStageForm.controls['projectdefinitionid'].setValue(0);
  }

  loadProjectDefinitions() {
    // this.SpinnerService.show();
    this.projectDefinitions = [];
    this.userstagemappingService.Get().subscribe(res => {
      this.projectDefinitions = JSON.parse(res[0]);
      this.projectDefinitions = this.projectDefinitions.filter(d => d.active === 1);
      this.uniqueProjectDefinitions = [];
      this.projectDefinitions.map(
        x => this.uniqueProjectDefinitions.filter(
          a => a.projectdefinitionid === x.projectdefinitionid).length > 0 ? null : this.uniqueProjectDefinitions.push(x)
      );
      console.log(this.uniqueProjectDefinitions);
      this.SpinnerService.hide();
    }, error => { this.toastr.error('Error while getting data'); });
  }

  loadStage() {
    this.states = this.projectDefinitions.filter(d => d.projectdefinitionid === this.projectdefinitionid);
  }

  destinationChange(item: Userstagemapping[]) {
    if (this.pwdid) {
      // this.orgselectedUserList = this.orgselectedUserList.filter(s => s.pwdid !== this.pwdid);
      // for delete all org users:
      this.orgselectedUserList = [];
      item.forEach(element => {
        this.orgselectedUserList.push(element);
      });
    } else {
      this.orgselectedUserList = [];
      item.forEach(element => {
        this.orgselectedUserList.push(element);
      });
    }
    this.formTocuhed = true;
  }

  saveUserStage() {
    this.userStageForm.value.pwdid.forEach(userStageList => {
      if (+userStageList.pwdid === 0) {
        this.toastr.warning('Please choose any stage');
        return;
      }
      this.SpinnerService.show();
      const selectedUserList = this.orgselectedUserList.map(element => ({
        stagemappingid: (element.stagemappingid) ? element.stagemappingid : 0,
        pwdid: userStageList.pwdid,
        userid: element.userid,
        active: 1,
        createdby: this.userid,
        updatedby: this.userid
      }));
      if (selectedUserList.length) {
        console.log('selectedUserList=', selectedUserList);
        this.userstagemappingService.Post(selectedUserList).subscribe(res => {
          this.SpinnerService.hide();
          if (res.status === 200) {
            if (res !== undefined) {
              if (res.body !== 0) {
                // this.GetMappedUserList();
                //  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 {
        this.userStageForm.value.pwdid = +userStageList.pwdid;
        this.userstagemappingService.UpdateUserStageOnEmpty(this.userStageForm.value).subscribe(res => {
          this.SpinnerService.hide();
          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');
          });
      }
    });
  }

  GetAllDepartment() {
    this.SpinnerService.show();
    this.departmentservice.GetByMappedUser().subscribe(res => {
      this.overalllist = JSON.parse(res[0]);
      console.log('overalllist=', this.overalllist);
      this.overalldepartmentlist = [];
      this.departmentlist = [];
      // 'userlist': { 'userid': this.overalllist[key].userid, 'username': this.overalllist[key].username }
      this.userdeplist = [];

      this.overalllist.forEach((value, key) => {
        this.overalldepartmentlist.push({
          'departmentid': this.overalllist[key].departmentid,
          'department': this.overalllist[key].department, 'userlist': []
        });
      });

      console.log('overalldepartmentlist=', this.overalldepartmentlist);

      this.departmentlist = this.removeDumplicateValue(this.overalldepartmentlist);
      console.log('departmentlist=', this.departmentlist);

      this.overalllist.forEach((value, key) => {
        this.userdeplist.push({
          'departmentid': this.overalllist[key].departmentid, 'userid': this.overalllist[key].userid,
          'username': this.overalllist[key].username
        });
      });


      this.departmentlist.forEach((value, key) => {

        const dplistid = this.departmentlist[key].departmentid;
        for (var i = 0; i < this.userdeplist.length; i++) {
          if (dplistid === this.userdeplist[i].departmentid) {
            this.departmentlist[key].userlist.push({ userid: this.userdeplist[i].userid });
          }
        }

      });
      this.SpinnerService.hide();
      // this.complete();
    },
      error => {
        console.log(error);
        // this.complete();
        this.SpinnerService.hide();
        this.toastr.error('Error while getting data');
      });
  }

  removeDumplicateValue(myArray) {
    const newArray = [];
    myArray.forEach((value, key) => {
      let exists = false;
      newArray.forEach((val2, key) => {
        if (value.departmentid === val2.departmentid) {
          exists = true;
        }
      });

      if (exists === false && value.departmentid !== '') {
        newArray.push(value);
      }
    });
    return newArray;
  }

  selectuser(userid, departmentname) {
    if (this.addandremovestage.length === 0) {
      this.LoadProjectDetails(userid);
      this.selectedIndex = userid;
      this.departdisplayname = departmentname;
    } else {
      const fol = this.addandremovestage[0].userid;
      if (fol !== userid) {
        this.dialogService.addDialog(CommondialogComponent,
          {
            title: 'Please Confirm',
            message: 'Would you like to save changes ?',
            hclass: 'modelsuccess',
            oktext: 'Yes',
            canceltext: 'No',
            okshow: true,
            cancelshow: true
          }).subscribe((isConfirmed) => {
            if (isConfirmed) {
              this.MapUserStagenew();
            } else {
              this.LoadProjectDetails(userid);
              this.selectedIndex = userid;
              this.departdisplayname = departmentname;
            }
          });
      }
    }
  }

  MapUserStagenew() {
    console.log(JSON.stringify('this.addandremovestage=', this.addandremovestage));
    if (+this.addandremovestage.length === 0) {
      this.toastr.warning('Please choose any stage');
      return;
    }
    this.SpinnerService.show();
    const selectedUserList = this.addandremovestage.map(element => ({
      stagemappingid: (element.stagemappingid) ? element.stagemappingid : 0,
      pwdid: element.projectworkflowid,
      userid: element.userid,
      active: element.active ? 1 : 0,
      checkinappfeature: element.mergecheckinappfeature ? element.mergecheckinappfeature.map(s => s.active ? ({
        metadataid: s.metadataid,
        mdata: s.mdata,
        active: 1
      }) : ({
        metadataid: s.metadataid,
        mdata: s.mdata,
        active: 0
      })) : [],
      checkoutappfeature: element.mergecheckoutappfeature ? element.mergecheckoutappfeature.map(s => s.active ? ({
        metadataid: s.metadataid,
        mdata: s.mdata,
        active: 1
      }) : ({
        metadataid: s.metadataid,
        mdata: s.mdata,
        active: 0
      })) : [],
      inprocessappfeature: element.mergeinprocessappfeature ? element.mergeinprocessappfeature.map(s => s.active ? ({
        metadataid: s.metadataid,
        mdata: s.mdata,
        active: 1
      }) : ({
        metadataid: s.metadataid,
        mdata: s.mdata,
        active: 0
      })) : [],
      createdby: this.userid,
      updatedby: this.userid
    }));


    if (selectedUserList.length) {
      console.log('selectedUserList=', selectedUserList);
      this.userstagemappingService.Post(selectedUserList).subscribe(res => {
        this.SpinnerService.hide();
        this.addandremovestage = [];
        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 {
      this.addandremovestage.value.pwdid = +this.addandremovestage.value.pwdid;
      this.userstagemappingService.UpdateUserStageOnEmpty(this.addandremovestage.value).subscribe(res => {
        this.SpinnerService.hide();
        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');
        });
    }
  }

  loaduserstagemapping_new(projdefid, pwdid, userid) {
    this.selectedprojectdefinition = projdefid;
    this.selectedstage = pwdid;
    if (this.selectedprojectdefinition != null && this.selectedstage != null) {
      // var response = $http({
      //     method: "get",
      //     url: "api/User_Satge_MappingApi/getUserStageMappingData_new",
      //     params: {
      //         projectdefinitionid: this.selectedprojectdefinition,
      //         pwdid: this.selectedstage,
      //         userid: userid
      //     }
      // });
      // response.then(function (d) {
      //     this.mappingstagelist = d.data;
      //     if (this.mappingstagelist.length === 0)
      //         this.isstagealreadymap = false;
      //     else
      //         if (this.mappingstagelist[0].disabled === true)
      //             this.isstagealreadymap = true;

      //     this.complete();
      // }, function (error) {
      //     console.log(error);
      //     this.complete();
      //     this.toastr.error('Error in loading user stage records');
      // });
    }
  }

  onchangestagemapping(pwdid, projdefid, userid, stagemappingid, active) {
    const dsd = '#bg' + pwdid + '';
    active = active.target.checked;
    $(dsd).css('background-color', '#ffff0b4f');
    console.log(this.projectmaplist_overall);
    if (typeof active === 'undefined') {
      active = false;
    }
    const alreadyadd = this.addandremovestage.filter(a => a.projectworkflowid === pwdid);
    if (alreadyadd.length === 1) {
      this.addandremovestage.filter(a => a.projectworkflowid === pwdid && a.userid === userid).map(p => p.active = active);
      $(dsd).css('background-color', '#fff');
    } else {
      this.addandremovestage.push({ 'projectworkflowid': pwdid, 'userid': userid, 'active': active, 'stagemappingid': stagemappingid });
    }
    console.log(this.addandremovestage);
  }

  onchangemergecheckinappfeature(pwdid, projdefid, userid, stagemappingid, feature, active) {
    const dsd = '#bg' + pwdid + '';
    active = active.target.checked;
    $(dsd).css('background-color', '#ffff0b4f');
    if (typeof active === 'undefined') {
      active = false;
    }
    const checkinlist = this.projectmaplist_overall.filter(p => p.projectdefinitionid === projdefid && p.stagemappingid === stagemappingid);
    checkinlist[0].mergecheckinappfeature.filter(me => me.metadataid === feature.metadataid).map(p => p.active = active);
    const alreadyadd = this.addandremovestage.filter(a => a.projectworkflowid === pwdid);
    if (alreadyadd.length === 1) {
      alreadyadd[0].mergecheckinappfeature = checkinlist[0].mergecheckinappfeature;
      $(dsd).css('background-color', '#fff');
    } else {
      this.addandremovestage.push({
        'projectworkflowid': pwdid, 'userid': userid, 'active': true, 'stagemappingid': stagemappingid,
        'mergecheckinappfeature': checkinlist[0].mergecheckinappfeature
      });
    }
    console.log(this.addandremovestage);
  }

  onchangemergecheckoutappfeature(pwdid, projdefid, userid, stagemappingid, feature, active) {
    const dsd = '#bg' + pwdid + '';
    active = active.target.checked;
    $(dsd).css('background-color', '#ffff0b4f');
    if (typeof active === 'undefined') {
      active = false;
    }
    const checkinlist = this.projectmaplist_overall.filter(p => p.projectdefinitionid === projdefid && p.stagemappingid === stagemappingid);
    checkinlist[0].mergecheckoutappfeature.filter(me => me.metadataid === feature.metadataid).map(p => p.active = active);
    const alreadyadd = this.addandremovestage.filter(a => a.projectworkflowid === pwdid);
    if (alreadyadd.length === 1) {
      alreadyadd[0].mergecheckoutappfeature = checkinlist[0].mergecheckoutappfeature;
      $(dsd).css('background-color', '#fff');
    } else {
      this.addandremovestage.push({
        'projectworkflowid': pwdid, 'userid': userid, 'active': true, 'stagemappingid': stagemappingid,
        'mergecheckoutappfeature': checkinlist[0].mergecheckoutappfeature
      });
    }
    console.log(this.addandremovestage);
  }

  onchangemergeinprocessappfeature(pwdid, projdefid, userid, stagemappingid, feature, active) {
    const dsd = '#bg' + pwdid + '';
    active = active.target.checked;
    $(dsd).css('background-color', '#ffff0b4f');
    if (typeof active === 'undefined') {
      active = false;
    }
    const checkinlist = this.projectmaplist_overall.filter(p => p.projectdefinitionid === projdefid && p.stagemappingid === stagemappingid);
    checkinlist[0].mergeinprocessappfeature.filter(me => me.metadataid === feature.metadataid).map(p => p.active = active);
    const alreadyadd = this.addandremovestage.filter(a => a.projectworkflowid === pwdid);
    if (alreadyadd.length === 1) {
      alreadyadd[0].mergeinprocessappfeature = checkinlist[0].mergeinprocessappfeature;
      $(dsd).css('background-color', '#fff');
    } else {
      this.addandremovestage.push({
        'projectworkflowid': pwdid, 'userid': userid, 'active': true, 'stagemappingid': stagemappingid,
        'mergeinprocessappfeature': checkinlist[0].mergeinprocessappfeature
      });
    }
    console.log(this.addandremovestage);
  }

  selectAll(projdefid, userid, active) {
    if (active.target.checked) {
      const selectList = this.projectmaplist_overall.filter(p => p.projectdefinitionid === projdefid);
      console.log('selectList=', selectList);
      this.projectmaplist_overall.filter(p => p.projectdefinitionid === projdefid).map(p => {
        p.active = 1;
        p.mergecheckinappfeature.map(e => e.active = 1);
      });
      this.projectmaplist_overall.filter(p => p.projectdefinitionid === projdefid).map(p => {
        p.active = 1;
        p.mergecheckoutappfeature.map(e => e.active = 1);
      });
      this.projectmaplist_overall.filter(p => p.projectdefinitionid === projdefid).map(p => {
        p.active = 1;
        p.mergeinprocessappfeature.map(e => e.active = 1);
      });
      this.addandremovestage = selectList.map(s => ({
        projectworkflowid: s.pwdid,
        userid: userid,
        active: active.target.checked,
        stagemappingid: s.stagemappingid,
        mergecheckinappfeature: s.mergecheckinappfeature,
        mergecheckoutappfeature: s.mergecheckoutappfeature,
        mergeinprocessappfeature: s.mergeinprocessappfeature
      })
      );
    } else {
      const selectList = this.projectmaplist_overall.filter(p => p.projectdefinitionid === projdefid);
      console.log('selectList=', selectList);
      this.projectmaplist_overall.filter(p => p.projectdefinitionid === projdefid).map(p => {
        p.active = 0;
        p.mergecheckinappfeature.map(e => e.active = 0);
      });
      this.projectmaplist_overall.filter(p => p.projectdefinitionid === projdefid).map(p => {
        p.active = 0;
        p.mergecheckoutappfeature.map(e => e.active = 0);
      });
      this.projectmaplist_overall.filter(p => p.projectdefinitionid === projdefid).map(p => {
        p.active = 0;
        p.mergeinprocessappfeature.map(e => e.active = 0);
      });
      this.addandremovestage = selectList.map(s => ({
        projectworkflowid: s.pwdid,
        userid: userid,
        active: active.target.checked,
        stagemappingid: s.stagemappingid,
        mergecheckinappfeature: s.mergecheckinappfeature,
        mergecheckoutappfeature: s.mergecheckoutappfeature,
        mergeinprocessappfeature: s.mergeinprocessappfeature
      })
      );
    }
    console.log('this.addandremovestage=', this.addandremovestage);
  }

  LoadProjectDetails(userid) {
    this.SpinnerService.show();
    this.userstagemappingService.GetProjectMappingUsers(userid).subscribe(res => {
      this.projectmaplist_overall = [];
      this.overallprojectmaplist = [];
      this.projectmaplist = [];
      this.SpinnerService.hide();
      this.projectmaplist_overall = JSON.parse(res.body[0]);
      this.projectmaplist_overall.filter(p => p.userid !== null).map(p => p.active = 1);
      this.projectmaplist_overall.filter(p => p.userid === null).map(p => p.active = 0);
      console.log('1 this.projectmaplist_overall=', this.projectmaplist_overall);
      this.projectmaplist_overall.forEach(elementlist => {

        // For checkin application
        this.FeatureselectedItemsCheckIn = [];
       // if (elementlist.checkinappfeature) {
          const feature1a = [];
          if (elementlist.checkinappfeature != null && elementlist.checkinappfeature.length) {
            if (elementlist.orgcheckinappfeature) {
            this.featureactive.forEach(element => {
              console.log('elementlist.orgcheckinappfeature=', elementlist.orgcheckinappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
              if (elementlist.orgcheckinappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                feature1a.push(elementlist.orgcheckinappfeature.
                  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 ((elementlist.checkinappfeature.filter(u => u.mdata === element.mdata)
                .map(i => i)).length > 0) {
                console.log('elementlist=', elementlist);
                this.FeatureselectedItemsCheckIn.push(
                  (elementlist.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 (elementlist.orgcheckinappfeature) {
            this.featureactive.forEach(element => {
              if (elementlist.orgcheckinappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                elementlist.orgcheckinappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; });
              }
            });
            this.FeatureselectedItemsCheckIn = elementlist.orgcheckinappfeature.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);
        if (this.FeatureselectedItemsCheckIn.filter(f => f.urltype === 'weburl').length > 0) {
          this.FeatureselectedItemsCheckIn.filter(f => f.urltype === 'weburl').map(f => { f.urltype = 'weburl'; return f; });
        }
        if (this.FeatureselectedItemsCheckIn.filter(f => f.urltype === 'serviceurl').length > 0) {
          this.FeatureselectedItemsCheckIn.filter(f => f.urltype === 'serviceurl').map(f => { f.urltype = 'serviceurl'; return f; });
        }

        // For checkout_app application
        this.FeatureselectedItemsCheckOut = [];
          const feature2a = [];
          if (elementlist.checkoutappfeature != null && elementlist.checkoutappfeature.length) {
            if (elementlist.orgcheckoutappfeature) {
            this.featureactive.forEach(element => {
              console.log('elementlist.checkoutappfeature=', elementlist.checkoutappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
              if (elementlist.checkoutappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                feature2a.push(elementlist.checkoutappfeature.
                  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 ((elementlist.checkoutappfeature.filter(u => u.mdata === element.mdata)
                .map(i => i)).length > 0) {
                console.log('elementlist=', elementlist);
                this.FeatureselectedItemsCheckOut.push(
                  (elementlist.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 (elementlist.orgcheckoutappfeature) {
            this.featureactive.forEach(element => {
              if (elementlist.orgcheckoutappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                elementlist.orgcheckoutappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; });
              }
            });
            this.FeatureselectedItemsCheckOut = elementlist.orgcheckoutappfeature.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);
        if (this.FeatureselectedItemsCheckOut.filter(f => f.urltype === 'weburl').length > 0) {
          this.FeatureselectedItemsCheckOut.filter(f => f.urltype === 'weburl').map(f => { f.urltype = 'weburl'; return f; });
        }
        if (this.FeatureselectedItemsCheckOut.filter(f => f.urltype === 'serviceurl').length > 0) {
          this.FeatureselectedItemsCheckOut.filter(f => f.urltype === 'serviceurl').map(f => { f.urltype = 'serviceurl'; return f; });
        }

        // For inprogress application
        this.FeatureselectedItemsInProgress = [];

       // if (elementlist.inprocessappfeature) {

          const feature3a = [];
          if (elementlist.inprocessappfeature != null && elementlist.inprocessappfeature.length) {
            if (elementlist.orginprocessappfeature) {
            this.featureactive.forEach(element => {
              console.log('elementlist.inprocessappfeature=', elementlist.inprocessappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
              if (elementlist.inprocessappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                  feature3a.push(elementlist.inprocessappfeature.
                  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 ((elementlist.inprocessappfeature.filter(u => u.mdata === element.mdata)
                .map(i => i)).length > 0) {
                console.log('elementlist=', elementlist);
                this.FeatureselectedItemsInProgress.push(
                  (elementlist.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 (elementlist.orginprocessappfeature) {
            this.featureactive.forEach(element => {
              if (elementlist.orginprocessappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                elementlist.orginprocessappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; });
              }
            });
            this.FeatureselectedItemsInProgress = elementlist.orginprocessappfeature.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);
        if (this.FeatureselectedItemsInProgress.filter(f => f.urltype === 'weburl').length > 0) {
          this.FeatureselectedItemsInProgress.filter(f => f.urltype === 'weburl').map(f => { f.urltype = 'weburl'; return f; });
        }
        if (this.FeatureselectedItemsInProgress.filter(f => f.urltype === 'serviceurl').length > 0) {
          this.FeatureselectedItemsInProgress.filter(f => f.urltype === 'serviceurl').map(f => { f.urltype = 'serviceurl'; return f; });
        }

        elementlist.mergecheckinappfeature = this.FeatureselectedItemsCheckIn;
        elementlist.mergecheckoutappfeature = this.FeatureselectedItemsCheckOut;
        elementlist.mergeinprocessappfeature = this.FeatureselectedItemsInProgress;

      });
      console.log('2 this.projectmaplist_overall=', this.projectmaplist_overall);
      console.log('this.FeatureselectedItemsCheckIn=', this.FeatureselectedItemsCheckIn);

      this.projectmaplist_overall_orginal = JSON.parse(res.body[0]);
      this.projectmaplist_overall_orginal.filter(p => p.userid !== null).map(p => p.active = 1);
      this.projectmaplist_overall_orginal.filter(p => p.userid === null).map(p => p.active = 0);
      this.projectmaplist_overall_orginal.forEach(elementlist => {
        this.FeatureselectedItemsCheckIn = [];
       // if (elementlist.checkinappfeature) {
        //  if (elementlist.orgcheckinappfeature) {
            const feature1a = [];
          if (elementlist.checkinappfeature != null && elementlist.checkinappfeature.length) {
            if (elementlist.orgcheckinappfeature) {
            this.featureactive.forEach(element => {
              console.log('elementlist.orgcheckinappfeature=', elementlist.orgcheckinappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
              if (elementlist.orgcheckinappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                feature1a.push(elementlist.orgcheckinappfeature.
                  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 ((elementlist.checkinappfeature.filter(u => u.mdata === element.mdata)
                .map(i => i)).length > 0) {
                console.log('elementlist=', elementlist);
                this.FeatureselectedItemsCheckIn.push(
                  (elementlist.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 (elementlist.orgcheckinappfeature) {
            this.featureactive.forEach(element => {
              if (elementlist.orgcheckinappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                elementlist.orgcheckinappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; });
              }
            });
            this.FeatureselectedItemsCheckIn = elementlist.orgcheckinappfeature.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);
        if (this.FeatureselectedItemsCheckIn.filter(f => f.urltype === 'weburl').length > 0) {
          this.FeatureselectedItemsCheckIn.filter(f => f.urltype === 'weburl').map(f => { f.urltype = 'weburl'; return f; });
        }
        if (this.FeatureselectedItemsCheckIn.filter(f => f.urltype === 'serviceurl').length > 0) {
          this.FeatureselectedItemsCheckIn.filter(f => f.urltype === 'serviceurl').map(f => { f.urltype = 'serviceurl'; return f; });
        }

        this.FeatureselectedItemsCheckOut = [];
        // if (elementlist.checkoutappfeature) {
          // if (elementlist.orgcheckoutappfeature) {
            const feature2a = [];
          if (elementlist.checkoutappfeature != null && elementlist.checkoutappfeature.length) {
            if (elementlist.orgcheckoutappfeature) {
            this.featureactive.forEach(element => {
              console.log('elementlist.checkoutappfeature=', elementlist.checkoutappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
              if (elementlist.checkoutappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                feature2a.push(elementlist.checkoutappfeature.
                  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 ((elementlist.checkoutappfeature.filter(u => u.mdata === element.mdata)
                .map(i => i)).length > 0) {
                console.log('elementlist=', elementlist);
                this.FeatureselectedItemsCheckOut.push(
                  (elementlist.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 (elementlist.orgcheckoutappfeature) {
            this.featureactive.forEach(element => {
              if (elementlist.orgcheckoutappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                elementlist.orgcheckoutappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; });
              }
            });
            this.FeatureselectedItemsCheckOut = elementlist.orgcheckoutappfeature.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);
        if (this.FeatureselectedItemsCheckOut.filter(f => f.urltype === 'weburl').length > 0) {
          this.FeatureselectedItemsCheckOut.filter(f => f.urltype === 'weburl').map(f => { f.urltype = 'weburl'; return f; });
        }
        if (this.FeatureselectedItemsCheckOut.filter(f => f.urltype === 'serviceurl').length > 0) {
          this.FeatureselectedItemsCheckOut.filter(f => f.urltype === 'serviceurl').map(f => { f.urltype = 'serviceurl'; return f; });
        }


        this.FeatureselectedItemsInProgress = [];
        // if (elementlist.inprocessappfeature) {
         // if (elementlist.orginprocessappfeature) {
            const feature3a = [];
            if (elementlist.inprocessappfeature != null && elementlist.inprocessappfeature.length) {
              if (elementlist.orginprocessappfeature) {
              this.featureactive.forEach(element => {
                console.log('elementlist.inprocessappfeature=', elementlist.inprocessappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]);
                if (elementlist.inprocessappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                    feature3a.push(elementlist.inprocessappfeature.
                    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 ((elementlist.inprocessappfeature.filter(u => u.mdata === element.mdata)
                .map(i => i)).length > 0) {
                console.log('elementlist=', elementlist);
                this.FeatureselectedItemsInProgress.push(
                  (elementlist.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 (elementlist.orginprocessappfeature) {
            this.featureactive.forEach(element => {
              if (elementlist.orginprocessappfeature.
                filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; })[0]) {
                elementlist.orginprocessappfeature.
                  filter(f => f.metadataid === element.metadataid).map(f => { f.appurlid = element.appurlid; return f; });
              }
            });
            this.FeatureselectedItemsInProgress = elementlist.orginprocessappfeature.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);
        if (this.FeatureselectedItemsInProgress.filter(f => f.urltype === 'weburl').length > 0) {
          this.FeatureselectedItemsInProgress.filter(f => f.urltype === 'weburl').map(f => { f.urltype = 'weburl'; return f; });
        }
        if (this.FeatureselectedItemsInProgress.filter(f => f.urltype === 'serviceurl').length > 0) {
          this.FeatureselectedItemsInProgress.filter(f => f.urltype === 'serviceurl').map(f => { f.urltype = 'serviceurl'; return f; });
        }

        elementlist.mergecheckinappfeature = this.FeatureselectedItemsCheckIn;
        elementlist.mergecheckoutappfeature = this.FeatureselectedItemsCheckOut;
        elementlist.mergeinprocessappfeature = this.FeatureselectedItemsInProgress;
      });

      this.useridmapprojlist = this.overalllist.filter(o => o.userid === userid)[0];
      this.useridmapproj = this.useridmapprojlist.username;
      this.useridmapprojid = this.useridmapprojlist.userid;
      console.log(this.projectmaplist_overall);
      console.log('projectmaplist_overall=', this.projectmaplist_overall);
      this.projectmaplist_overall.forEach((value, key) => {
        this.overallprojectmaplist.push({
          'projdefid': this.projectmaplist_overall[key].projectdefinitionid,
          'stagemappingid': this.projectmaplist_overall[key].stagemappingid,
          'projectname': this.projectmaplist_overall[key].project_subtitle,
          'checkinappfeature': this.projectmaplist_overall[key].checkinappfeature,
          'checkoutappfeature': this.projectmaplist_overall[key].checkoutappfeature,
          'inprocessappfeature': this.projectmaplist_overall[key].inprocessappfeature,
          'orgcheckinappfeature': this.projectmaplist_overall[key].orgcheckinappfeature,
          'orgcheckoutappfeature': this.projectmaplist_overall[key].orgcheckoutappfeature,
          'orginprocessappfeature': this.projectmaplist_overall[key].orginprocessappfeature,
        });
      });
      this.projectmaplist = this.removeDumplicateValueofprojectlist(this.overallprojectmaplist);
      console.log('this.projectmaplist=', this.projectmaplist);
    },
      error => {
        console.log(error);
        // this.complete();
        this.toastr.error('Error while getting data');
        this.SpinnerService.hide();
      });
  }

  clearsearch() {
    this.my = { search: '' };
    this.projectmaplist_overall = this.projectmaplist_overall_orginal;
  }

  removedisable() {
    this.isstagealreadymap = false;
  }

  removeDumplicateValueofprojectlist(myArray) {
    const newArray = [];
    myArray.forEach((value, key) => {
      let exists = false;
      newArray.forEach((val2, key) => {
        if (value.projdefid === val2.projdefid) {
          exists = true;
        }
      });
      if (exists === false && value.id !== '') {
        newArray.push(value);
      }
    });
    return newArray;
  }

  updateFilteredList() {
    console.log(this.my.search);
    if (this.my.search === '') {
      this.projectmaplist_overall = this.projectmaplist_overall_orginal;
    } else {
      this.projectmaplist_overall = this.projectmaplist_overall_orginal.filter(p =>
        p.stagename_alias.toLowerCase().includes(this.my.search.toLowerCase()));
    }
    // this.ol = this.projectmaplist_overall.length;
    console.log(this.projectmaplist_overall);
  }

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

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