argos/dmp-frontend/src/app/form/dynamic-form.component.ts

284 lines
9.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Component, Input, OnInit, AfterViewChecked, ViewChild } from '@angular/core';
import { FormGroup, Validators } from '@angular/forms';
import { NgForm } from '@angular/forms';
import { Router, ActivatedRoute, ParamMap, Params } from '@angular/router';
import 'rxjs/add/operator/switchMap';
//import { FieldBase } from '../../app/form/fields/field-base';
import { FieldControlService } from '../../app/services/field-control.service';
import { ServerService } from '../../app/services/server.service';
import { dataModelBuilder } from '../../app/services/dataModelBuilder.service';
import { DataModel } from '../entities/DataModel';
import { GroupBase } from './dynamic-form-group/group-base';
import { PaginationService } from '../../app/services/pagination.service';
import { TokenService, TokenProvider } from '../services/login/token.service';
import { ModalComponent } from '../modal/modal.component';
import { AngularDraggableModule } from 'angular2-draggable';
import './../../assets/xml2json.min.js';
declare var X2JS: any;
var flatten = require('flat');
declare var $ :any;
//import * as $ from '../../../node_modules/jquery/dist/jquery'
import * as scroll from '../../assets/jquery.scrollTo.min.js';
@Component({
selector: 'dynamic-form',
templateUrl: './dynamic-form.component.html',
styleUrls: ['./dynamic-form.component.css'],
providers: [FieldControlService, ServerService, dataModelBuilder]
})
export class DynamicFormComponent implements OnInit {
@Input() dataModel: DataModel = new DataModel();
form: FormGroup;
payLoad = '';
@Input() dirtyValues: number = 0;
// pagination object
@Input() pagination: any = {};
id: string;
datasetId: string;
//datasetProperties:string;
private fragment: string;
xml2jsonOBJ: any;
expandedForm : boolean = false;
expandedToc : boolean = true;
constructor(private qcs: FieldControlService, private serverService: ServerService, private dataModelService: dataModelBuilder, private router: Router,
private route: ActivatedRoute, private pagerService: PaginationService, private tokenService: TokenService) {
this.form = this.qcs.toFormGroup(new Array(), new Array());
this.xml2jsonOBJ = new X2JS();
}
getSubForm(subformName) {
return this.form.controls[subformName];
}
ngOnInit() {
this.route.fragment.subscribe(fragment => { this.fragment = fragment; }); //navigate to certain section of the page
//let id = this.route.snapshot.paramMap.get('id'); //get the project id
let sub = this.route.params.subscribe(params => {
this.id = params.id;
this.datasetId = params.datasetId;
//this.datasetProperties = params.datasetProperties
});
this.serverService.getDatasetByID(this.datasetId).subscribe(
(data) => {
var flatList;
var formValues = "";
if (data.properties) {
console.log("Found already submitted form, loading that one!");
formValues = JSON.parse(data.properties);
flatList = flatten(formValues);
//this.patchForm(flatList);
}
//η κληση για το dataset profile pou htan prin pio panw anexarthth
this.serverService.getDatasetProfileByID(this.id).subscribe(
response => {
console.log("response");
console.log(response);
const data = response;
//replace the xmls {model,view,rule} definitions with json -- https://github.com/abdmob/x2js library
data.definition = this.xml2jsonOBJ.xml_str2json(data.definition);
data.ruleset.definition = this.xml2jsonOBJ.xml_str2json(data.ruleset.definition);
data.viewstyle.definition = this.xml2jsonOBJ.xml_str2json(data.viewstyle.definition);
//can be converted back to xml (which shouldn't be needed) with this.xml2jsonOBJ.json2xml_str
console.log("this.serverService.getFields");
console.log("data.dataset")
console.log(data.definition)
console.log(data.ruleset.definition)
console.log(data.viewstyle.definition)
this.dataModel = new DataModel();
this.dataModel = this.dataModelService.getDataModel(data, formValues); //get formvalues and acossiate them with fields
this.form = this.qcs.toFormGroup(this.dataModel.fields, this.dataModel.groups);
this.form.valueChanges.subscribe(data => {
// console.log('Form changes', data);
let dirtyValuesArray: Array<any> = [];
let count = 0;
let countDirtyValues = 0;
let percentage = 0;
Object.keys(this.form.controls).forEach((c) => {
//count++;
let currentControl = this.form.controls[c];
if (currentControl.dirty)
dirtyValuesArray.push(currentControl.value);
});
Object.keys(this.form.value).forEach((c) => {
//count++;
Object.keys(this.form.value[c]).forEach((item) => {
let value = this.form.value[c][item]
if (typeof(value) == "string") value.trim();
if(typeof(value)== "boolean") value.toString();
if (value != undefined && value != "")
countDirtyValues++; //TODO REMOVE SPACES FROM EMPTY STRING
});
});
this.dataModel.groups.forEach(grp => {
grp.groupFields.forEach((fld) => {
if (fld.visible == true || fld.visible == "true")
count++;
// if (fld.value != undefined && fld.value != " ")
// countDirtyValues++;
});
});
//console.log(count);
// var percentage = Math.floor(dirtyValuesArray.length * 100 / count);
percentage = Math.floor(countDirtyValues * 100 / count);
this.dirtyValues = percentage;
})
//this.form = this.qcs.toFormGroup(this.fields);
console.log("SUMMARY: ======>");
console.log(this.dataModel);
console.log(this.form);
this.route.paramMap //this is how i get the projects's id
// initialize to page 1
this.setPage(1);
},
err => {
console.log("There was an error fetching the data from server");
console.log(err);
}
);
//end- klhsh gia to dataset profiel
},
(err) => {
});
}
scrollToElemID(elemID) {
scroll("#" + elemID);
}
private patchForm(flatList: any) {
debugger;
for (var prop in flatList) {
if (flatList.hasOwnProperty(prop)) {
if (prop.endsWith('.id') || prop.endsWith('.answer') || prop.endsWith('.value')) continue;
//console.log("updating value of "+prop +" to "+flatList[prop].valueOf())
this.form.get(prop).setValue(flatList[prop].valueOf());
}
}
//this.form.get("namingConventionGroup.nonamingConventionA213").setValue("TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT");
}
ngAfterViewChecked(): void { //navigate to certain section of the page
try {
document.querySelector('#' + this.fragment).scrollIntoView();
} catch (e) { }
}
submitForm(){
this.serverService.getDatasetByID(this.datasetId).subscribe(
(data) => {
//is xml, so transform them to xml (it's json)
//data.properties = this.xml2jsonOBJ.json2xml_str(JSON.stringify(this.form.value));
data.properties = JSON.stringify(this.form.value);
this.serverService.setDataset(data).subscribe((data) => {
console.log("Updated dataset");
this.router.navigate(['/workspace'], { queryParams: { /*returnUrl: this.state.url*/ }});
//VALE EDW NA SE PIGAINEI PISW KAI NA SOU VGAZEI ENA MHNYMA SUCCESS... (to success tha to valw egw an thes)
},
(err) => {
});
},
(err) => {
});
}
onSubmit() {
this.submitForm();
this.payLoad = JSON.stringify(this.form.value);
}
SaveFinalize(){
$("#confirmModal").modal("hide");
this.submitForm();
}
shouldIShow(element) { //pagination , pages are declared in xml for every groupfield
if (this.pagination.currentPage == element.page){
return true;
}
else
return false;
}
setPage(page: number) {
if (page < 1 || page > this.pagination.totalPages) {
return;
}
var pagesize = 4;
// get pagination object from service
this.pagination = this.pagerService.getPagination(this.dataModel.groups, this.dataModel.groups.length, page, pagesize);
//get current page of items
// this.dataModel.sections.forEach(section => {
// if (section.groupFields.length > 0) {
// section.groupFields = this.dataModel.groups.slice(this.pagination.startIndex, this.pagination.endIndex + 1);
// }
// });
//this.dataModel.groups = this.dataModel.groups.slice(this.pagination.startIndex, this.pagination.endIndex + 1);
}
signOut2() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
localStorage.removeItem('currentUser');
});
this.tokenService.setToken(null); //kanonika prepei na mpei mesa sthn function.....
}
}