Старт

This commit is contained in:
2023-11-07 19:51:49 +06:00
commit 86542a157f
5002 changed files with 199551 additions and 0 deletions

View File

@ -0,0 +1,491 @@
//Объезды
class TDetours
{
constructor(map){
this.detours = []; //Список маршрутов
}
//Получаем список объектов
//Фильтруем объекты для заполнения в таблицу
filtering()
{
showProgressBar(document.getElementById('id5_detours'));
var data = {
name: document.getElementById("filter_name_detours").value
};
var req=createRequestObject();
req.onreadystatechange = function(thiz)
{
return function(){
if(req.readyState === 4){
var data=null;
try {
data = JSON.parse(req.responseText);
} catch (e) {
alert(e.message);
return;
}
if(data!=null)
{
if(data.errorMessage !== undefined && data.errorMessage!='')
{
alert(data.errorMessage);
return;
}
thiz.clear();
//Приходит JSON уже в объектах
//features = [];
for(i=0;i<data.length;i++)
{
var obj = new TDetour(thiz);
obj.id=data[i].id;
obj.name=data[i].name;
obj.count=data[i].count;
obj.date_start=data[i].date_start;
obj.date_end=data[i].date_end;
obj.lon=parseFloat(data[i].lon);
obj.lat=parseFloat(data[i].lat);
thiz.detours.push(obj);
}
thiz.fillRezDiv();
}
hideProgressBar(document.getElementById('id5_detours'));
};
}
}(this);
req.open("POST", '/monitoring/pscripts/detours.php?fn=1', true);
req.setRequestHeader("Content-type", "text/plain");
req.send(JSON.stringify(data));
/*
var data = {
name: "",
type: ""
};
$.ajax({
url: '/monitoring/pscripts/detours.php',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
type: "POST",
dataType: "json",
success: function(thiz){return function(data,status){
if(status=='success')
{
thiz.detours = []; //Удаляю старые объекты
g_vectorSourceDetours.clear(); //Удаляю все отображения
for(i=0;i<data.length;i++)
{
var obj = new TRoute();
obj.id=data[i].id;
obj.name=data[i].name;
obj.count=data[i].count;
thiz.detours.push(obj);
}
thiz.fillRezDiv();
}else
{
alert(status);
}
}}(this)
});
*/
}
//Заполнить результатом выборки DIV в виде таблицы
fillRezDiv()
{
var div=document.getElementById("id5_detours");
delChild(div);
div.innerHTML='<table id="thetable_detours" border="0" style="width:100%;" class="SShow"><thead><tr style="background-color: rgb(218, 218, 218);"><th></th><th id="cell_ch_D" style="width:1%;text-decoration:underline;cursor: pointer;">'+trt('View')+'.</th><th style="width: 90%;">'+trt('Bypass_name')+'</th><th style="width: 1%;">Дата начала</th><th style="width: 1%;">Дата окончания</th><th style="width: 1%;">'+trt('Points')+'</th></tr></thead><tbody></tbody></table>';
var theTable = document.getElementById('thetable_detours');
for(i=0;i<this.detours.length;i++)
{
let tr = document.createElement('tr');
let bgColor='';
if (i%2==0) bgColor='var(--row-color-1)'; else bgColor='var(--row-color-2)';
tr.style.backgroundColor=bgColor;
tr.onmouseover=function(){ this.style.backgroundColor='var(--btn-color2)'; };
tr.onmouseout=function(val1,val2){return function(){val1.style.backgroundColor=val2;}}(tr,bgColor);
//tr.id='cell_e_'+this.detours[i].id;
let td;
td = document.createElement('td');
td.style.cssText="width:24px;text-align:center;vertical-align:top;";
td.innerHTML='<img id="detours_down_btn_'+this.detours[i].id+'" src="/resources/images/right.png" alt="" style="cursor: pointer;">';
tr.appendChild(td);
td = document.createElement('td');
td.style.cssText="text-align: center;";
td.innerHTML='<input id="detours_ch_'+this.detours[i].id+'" type="checkbox"/>';
tr.appendChild(td);
td = document.createElement('td');
td.style.cursor='pointer';
td.innerHTML=this.detours[i].name;
td.onclick=function(detour){
return function(){
detour.goToCenter();
}
}(this.detours[i]);
tr.appendChild(td);
td = document.createElement('td');
td.style.cssText='cursor:pointer;text-align:right;';
td.innerHTML=this.detours[i].date_start;
td.onclick=function(detour){
return function(){
detour.goToCenter();
}
}(this.detours[i]);
tr.appendChild(td);
td = document.createElement('td');
td.style.cssText='cursor:pointer;text-align:right;';
td.innerHTML=this.detours[i].date_end;
td.onclick=function(detour){
return function(){
detour.goToCenter();
}
}(this.detours[i]);
tr.appendChild(td);
td = document.createElement('td');
td.style.cssText='cursor:pointer;text-align:right;';
td.innerHTML=this.detours[i].count;
td.onclick=function(detour){
return function(){
detour.goToCenter();
}
}(this.detours[i]);
tr.appendChild(td);
theTable.tBodies[0].appendChild(tr);
//Формирую раскрывающийся список
tr = document.createElement('tr');
tr.id=this.detours[i].id;
tr.style.cssText="background-color:var(--back-color-3);display:none";
td = document.createElement('td');
td.colSpan=6;
var html='<table style="width:100%;"><tr><td style="width:100%;border: 0;">';
html+=' ';
html+='</td><td valign="top" style="border: 0;"><img id="detour_del_'+this.detours[i].id+'" src="/resources/images/del24.png" alt="'+trt('Delete')+'" title="'+trt('Delete')+'" style="cursor:pointer;"></td><td valign="top" style="border: 0;"><img id="detour_edit_'+this.detours[i].id+'" src="/resources/images/edit24.png" alt="'+trt('Edit')+'" title="'+trt('Edit')+'" style="cursor:pointer;"></td></tr></table>';
td.innerHTML=html;
tr.appendChild(td);
theTable.tBodies[0].appendChild(tr);
var cell=document.getElementById("detours_ch_"+this.detours[i].id);
cell.onclick=function(route){
return function(){
var chb=document.getElementById("detours_ch_"+route.id);
route.setVisibility(chb.checked);
}
}(this.detours[i]);
//Кнопка разсрыть список
var btn=document.getElementById('detours_down_btn_'+this.detours[i].id);
btn.onclick=function(tr,thiz,id){ return function(){
var btn=document.getElementById('detours_down_btn_'+id);
if(btn.src.indexOf("right.png")!=-1)
{
btn.src = '/resources/images/down.png';
tr.style.display = 'table-row';
}else if(btn.src.indexOf("down.png")!=-1)
{
btn.src = '/resources/images/right.png';
tr.style.display = 'none';
}
}; }(tr,this,this.detours[i].id);
/*
//При щелчке по иконке календаря отображаем календарь выбора
//setCalendar("filter_date_route_start_"+this.detours[i].id,"filter_date_route_start_trigger_"+this.detours[i].id,-2);
//setCalendar("filter_date_route_end_"+this.detours[i].id,"filter_date_route_end_trigger_"+this.detours[i].id);
this.detours[i].getGeoJSON();
*/
//Кнопка удалить
btn=document.getElementById('detour_del_'+this.detours[i].id)
btn.onclick=function(thiz,id){ return function(){ thiz.deleteDetour({id:id}); }; }(this,this.detours[i].id);
//Кнопка редактировать
btn=document.getElementById('detour_edit_'+this.detours[i].id)
btn.onclick=function(thiz,id){ return function(){ thiz.editDetour({id:id}); }; }(this,this.detours[i].id);
}
//Количество элементов в дереве
var divCnt = document.getElementById("count_detours");
delChild(divCnt);
divCnt.appendChild(document.createTextNode(this.detours.length));
//По нажатию на заголовок инвертируем чекбуксы
divCnt = document.getElementById("cell_ch_D");
divCnt.onclick=function(thiz){
return function(){
thiz.hide();
}
}(this);
}
createDetour()
{
//В настройках передаю центр карты
let center=ol.proj.transform(g_map.getView().getCenter(), 'EPSG:3857','EPSG:4326');
let eRec = new EdtRec("");
eRec.eRecNa("Detours",-1,'<type n="Detours"><properties><prop n="name"><![CDATA['+document.getElementById("filter_name_detours").value+']]></prop><prop n="lat"><![CDATA['+center[1]+']]></prop><prop n="lon"><![CDATA['+center[0]+']]></prop></properties></type>');
eRec.win.onClose=function(thiz){ return function(){ thiz.filtering();};}(this);
}
//Удалить объезд
deleteDetour(settings)
{
if (typeof settings === 'string' || settings instanceof String)
{
try {
settings = JSON.parse(settings);
} catch (e) {
alert(e.message);
return;
}
}
if (confirm(trt("Do_you_really_want_to_delete_the_record")+'?')) {
var req=createRequestObject();
req.onreadystatechange = function(thiz)
{
return function(){
if(req.readyState === 4){
var data=null;
try {
data = JSON.parse(req.responseText);
} catch (e) {
alert(e.message);
return;
}
if(data!=null)
{
if(data.errorMessage !== undefined && data.errorMessage!='')
{
alert(data.errorMessage);
thiz.win.hideProgressBar();
}else
{
}
}
//Фильтрую список заново
thiz.filtering();
}
};
}(this);
req.open("POST", '/monitoring/pscripts/detours.php?fn=3', true);
req.setRequestHeader("Content-type", "text/plain");
req.send(JSON.stringify(settings));
this.filtering();
}
return true;
}
editDetour(settings)
{
if (typeof settings === 'string' || settings instanceof String)
{
try {
settings = JSON.parse(settings);
} catch (e) {
alert(e.message);
return;
}
}
var detour=this.getDetourByID(settings.id);
let eRec = new EdtRec("");
eRec.eRecNa("Detours",settings.id);
eRec.win.onClose=function(thiz,detour){ return function(){
detour.showPoints(false);
//thiz.filtering();
};}(this,detour);
if(detour!=null)
{
detour.showPoints(true);
detour.setVisibility(true);
}
}
//Вернуть объект TDetour по идентификатору
getDetourByID(id)
{
for(var i=0;i<this.detours.length;i++)
{
if(this.detours[i].id==id)
return this.detours[i];
}
return null;
}
clear()
{
//Удаляю геометриию
for(var i=0;i<this.detours.length;i++)
{
this.detours[i].setVisibility(false);
}
this.detours = [];
}
//Инвертировать видимость маршрутов
hide()
{
for(var i=0;i<this.detours.length;i++)
{
this.detours[i].setVisibility(!this.detours[i].getVisibility());
}
}
}
class TDetour
{
constructor(detours)
{
this.id='';
this.feature=null; //Объект который отображается на карте
this.shP=false; //Показывать ли точки для редактирования
this.detours=detours;
this.visible=false; //По умолчанию всё видим
}
getVisibility()
{
return this.visible;
}
//Отобразить объект на карте
setVisibility(val)
{
var chb=document.getElementById("detours_ch_"+this.id);
if(val)
{
if(!chb.checked) chb.checked=true;
if(this.feature==null)
{
this.getGeoJSON(); //Подгружаем объект с сервера
}else
{
//Проверяю чтобы заново не добавить
var exists=false;
var features=g_vectorSourceDetours.getFeatures();
for(var i=0;i<features.length;i++)
{
if(features[i]==this.feature)
{
exists=true;
break;
}
}
if(!exists)
g_vectorSourceDetours.addFeature(this.feature);
}
}else{
if(chb!=null && chb.checked) chb.checked=false;
if(this.feature!=null)
{
g_vectorSourceDetours.removeFeature(this.feature);
this.showPoints(false);
}
}
this.visible=val;
}
goToCenter()
{
var point=ol.proj.transform([this.lon, this.lat], 'EPSG:4326','EPSG:3857');
g_map.getView().setCenter(point);
if(g_map.getView().getZoom()<9)
g_map.getView().setZoom(9);
}
//Отобразить точки для редактирования
showPoints(val)
{
//alert("showPoints="+val);
this.shP=val;
if(this.shP)
enableEditPoints(this.feature);
else
disableEditPoints(this.feature);
return true;
}
//Запросить гео данные для построения объекта на карте
getGeoJSON()
{
if(this.feature!=null) return;
var data = {
id: this.id
};
$.ajax({
url: '/monitoring/pscripts/detours.php?fn=2',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
type: "POST",
dataType: "json",
success: function(thiz){return function(data,status){
if(status=='success')
{
var features = (new ol.format.GeoJSON()).readFeatures(data, {dataProjection: 'EPSG:4326',featureProjection: 'EPSG:3857'});
for(i=0;i<features.length;i++)
{
features[i].setStyle(new ol.style.Style({
fill: new ol.style.Fill({color: 'rgba(0, 255, 0, 0.5)'}),
stroke: new ol.style.Stroke({color: 'rgba(0, 100, 0, 0.7)', width: 2}),
text: new ol.style.Text({
font: 'bold 12px helvetica,sans-serif',
//text: userData.percent+" %",
fill: new ol.style.Fill({color: 'black'}),
stroke: new ol.style.Stroke({color: 'white', width: 1}),
offsetX: 0,
offsetY: 0
})
}));
thiz.feature=features[i]; //Должен быть один объект в объекте
thiz.feature.userData=thiz; //ссылка на родителя
g_vectorSourceDetours.addFeature(thiz.feature);
//Если в режиме редактирования точек то отображаем эти точки
if(thiz.shP)
enableEditPoints(thiz.feature);
}
}else
{
alert(status);
}
}}(this)
});
}
};

View File

@ -0,0 +1,200 @@
/**
*
*/
//Список событий
class TEvents
{
constructor(map){
this.events = []; //Список событий
}
filtering()
{
var date;
var date_s,date_e;
date_s=document.getElementById("filter_X1_date_start_e").value;
date = new Date(date_s.replace(/-/g, "/"));
date_s=date.getTime()/1000;
if(isNaN(date_s)) date_s='';
date_e=document.getElementById("filter_X1_date_end_e").value;
date = new Date(date_e.replace(/-/g, "/"));
date_e=date.getTime()/1000;
if(isNaN(date_e)) date_e='';
var data = {
active: document.getElementById("active_e").value, //Установленна либо снята пломба
cnumber: document.getElementById("cnumber_e").value, //Гос. номер
tnumber: document.getElementById("tnumber_e").value, //Номер ТД
type: document.getElementById("type_e").value,
date_start: date_s,
date_end: date_e
};
var req=createRequestObject();
req.onreadystatechange = function(thiz)
{
return function(){
if(req.readyState === 4){
var data=null;
try {
data = JSON.parse(req.responseText);
} catch (e) {
alert(e.message);
return;
}
if(data!=null)
{
if(data.errorMessage !== undefined && data.errorMessage!='')
{
alert(data.errorMessage);
return;
}
thiz.events = [];
//Приходит JSON уже в объектах
features = [];
for(i=0;i<data.length;i++)
{
var feature=null;
var lon=parseFloat(data[i].lon);
var lat=parseFloat(data[i].lat);
if(!isNaN(lat) && !isNaN(lon))
{
feature = new ol.Feature({geometry: new ol.geom.Point(ol.proj.transform([lon,lat], 'EPSG:4326','EPSG:3857')),name: data[i].name,icon_name: data[i].icon_name});
feature.setStyle(createFatypeStyleEvent(feature,false));
feature.userType="TEvent";
//feature.userName='terrain';
feature.userID=data[i].id;
features.push(feature);
}
var obj = new TEvent();
obj.feature=feature;
obj.id=data[i].id;
obj.name=data[i].name;
obj.sensor_name=data[i].sensor_name;
obj.lon=parseFloat(data[i].lon);
obj.lat=parseFloat(data[i].lat);
obj.value=data[i].value;
obj.date=data[i].date;
//alert('obj.name = '+obj.name);
/*obj.declaration=data[i].declaration;
obj.icon_name=data[i].icon_name;
obj.lon=parseFloat(data[i].lon);
obj.lat=parseFloat(data[i].lat);
obj.alt=parseFloat(data[i].alt);
obj.utime=parseInt(data[i].utime);
obj.date=data[i].date;
obj.bat=parseFloat(data[i].bat);
obj.bat_date=data[i].bat_date;
obj.tros=parseFloat(data[i].tros);
obj.tros_date=data[i].tros_date;
obj.box=parseFloat(data[i].box);
obj.box_date=data[i].box_date;*/
thiz.events.push(obj);
}
g_vectorSource.clear(false);
g_vectorSource.addFeatures(features);
thiz.fillRezDiv();
}
};
}(this);
}
req.setRequestHeader("Content-type", "text/plain");
req.send(JSON.stringify(data));
req.open("POST", '/transit/events.php', true);
}
//Заполнить результатом выборки DIV в виде таблицы
fillRezDiv()
{
//alert('fillRezDiv');
var div=document.getElementById("div_tbl_e");
delChild(div);
div.innerHTML='<table id="thetable_e" border="0" style="width:100%;" class="SShow"><thead><tr style="background-color: rgb(218, 218, 218);"><th style="width: 1%;">Гос. номер</th><th style="width: 1%;">Тип события</th><th style="width: 1%;">Значение</th><th style="width: 1%;">Дата</th></tr></thead><tbody></tbody></table>';
var theTable = document.getElementById('thetable_e');
for(i=0;i<this.events.length;i++)
{
var tr = document.createElement('tr');
let bgColor='';
if (i%2==0) bgColor='var(--row-color-1)'; else bgColor='var(--row-color-2)';
tr.style.backgroundColor=bgColor;
tr.onmouseover=function(){this.style.backgroundColor='var(--btn-color2)';};
tr.onmouseout=function(val1,val2){return function(){val1.style.backgroundColor=val2;}}(tr,bgColor);
tr.id='cell_e_'+this.events[i].id;
tr.style.cursor='pointer';
var td;
td = document.createElement('td');
td.innerHTML=this.events[i].name;
tr.appendChild(td);
td = document.createElement('td');
td.innerHTML=this.events[i].sensor_name;
tr.appendChild(td);
td = document.createElement('td');
td.innerHTML=this.events[i].value;
tr.appendChild(td);
td = document.createElement('td');
//ts.style.whiteSpace='nowrap';
td.innerHTML=this.events[i].date;
tr.appendChild(td);
theTable.tBodies[0].appendChild(tr);
//При щелчке на ячейку перемещаем карту на точку
var cell=document.getElementById("cell_e_"+this.events[i].id);
cell.onclick=function(object){
return function(){
alert('lon='+object.lon);
if(!isNaN(parseFloat(object.lon)))
{
g_map.getView().setCenter(ol.proj.transform([object.lon,object.lat], 'EPSG:4326','EPSG:3857'));
if(g_map.getView().getZoom()<9)
g_map.getView().setZoom(9);
}
}
}(this.events[i]);
//При щелчке по иконке календаря отображаем календарь выбора
//setCalendar("filter_date_route_start_"+this.events[i].id,"filter_date_route_start_trigger_"+this.events[i].id,-2);
//setCalendar("filter_date_route_end_"+this.events[i].id,"filter_date_route_end_trigger_"+this.events[i].id);
}
//Количество элементов в дереве
var divCnt = document.getElementById("count_e");
delChild(divCnt);
divCnt.appendChild(document.createTextNode(this.events.length));
}
}
//Событие из списка
class TEvent
{
constructor(map){
}
}

View File

@ -0,0 +1,510 @@
//Объезды
class TGeofences //Current user with role name and access
{
constructor(map){
this.geofences = [];
}
//Получаем список объектов
//Фильтруем объекты для заполнения в таблицу
filtering()
{
showProgressBar(document.getElementById('id5_geofences'));
let data = {
geofence_type_id: document.getElementById("geofence_type_id_id0").value,
name: document.getElementById("filter_name_geofences").value
};
let req=createRequestObject();
req.onreadystatechange = function(thiz)
{
return function(){
if(req.readyState === 4){
var data=null;
try {
data = JSON.parse(req.responseText);
} catch (e) {
alert(e.message);
return;
}
if(data!=null)
{
if(data.errorMessage !== undefined && data.errorMessage!='')
{
alert2(trt('Error'),data.errorMessage);
return;
}
thiz.clear();
//Приходит JSON уже в объектах
//let features = [];
for(i=0;i<data.length;i++)
{
var obj = new TGeofence(thiz);
obj.id=data[i].id;
obj.name=data[i].name;
obj.count=data[i].count;
obj.geofence_type_name=data[i].geofence_type_name;
obj.lon=parseFloat(data[i].lon);
obj.lat=parseFloat(data[i].lat);
thiz.geofences.push(obj);
}
thiz.fillRezDiv();
}
hideProgressBar(document.getElementById('id5_geofences'));
};
}
}(this);
req.open("POST", '/monitoring/pscripts/geofences.php?fn=1', true);
req.setRequestHeader("Content-type", "text/plain");
req.send(JSON.stringify(data));
/*
var data = {
name: "",
type: ""
};
$.ajax({
url: '/monitoring/pscripts/geofences.php',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
type: "POST",
dataType: "json",
success: function(thiz){return function(data,status){
if(status=='success')
{
thiz.geofences = []; //Удаляю старые объекты
g_vectorSourceGeofences.clear(); //Удаляю все отображения
for(i=0;i<data.length;i++)
{
var obj = new TRoute();
obj.id=data[i].id;
obj.name=data[i].name;
obj.count=data[i].count;
thiz.geofences.push(obj);
}
thiz.fillRezDiv();
}else
{
alert(status);
}
}}(this)
});
*/
}
//Заполнить результатом выборки DIV в виде таблицы
fillRezDiv()
{
var div=document.getElementById("id5_geofences");
delChild(div);
div.innerHTML='<table id="thetable_geofences" border="0" style="width:100%;" class="SShow"><thead><tr style="background-color: rgb(218, 218, 218);"><th></th><th id="cell_ch_D" style="width:1%;text-decoration:underline;cursor: pointer;">'+trt('View')+'.</th><th style="width: 90%;">'+trt('Geofence_name')+'</th><th style="width: 1%;">'+trt('Points')+'</th></tr></thead><tbody></tbody></table>';
var theTable = document.getElementById('thetable_geofences');
let type_name='';
for(i=0;i<this.geofences.length;i++)
{
if(type_name!=this.geofences[i].geofence_type_name) //Если новая группа
{
type_name=this.geofences[i].geofence_type_name;
if(type_name=='') type_name=trt('Group');
let tr = document.createElement('tr');
let bgColor='';
if (i%2==0) bgColor='var(--row-color-1)'; else bgColor='var(--row-color-2)';
tr.style.backgroundColor=bgColor;
let td = document.createElement('td');
td.innerHTML=type_name;
td.colSpan=6;
//td.style.cssText="text-align: center;";
tr.appendChild(td);
theTable.tBodies[0].appendChild(tr);
}
let tr = document.createElement('tr');
let bgColor='';
if (i%2==0) bgColor='var(--row-color-1)'; else bgColor='var(--row-color-2)';
tr.style.backgroundColor=bgColor;
tr.onmouseover=function(){this.style.backgroundColor='var(--btn-color2)';};
tr.onmouseout=function(val1,val2){return function(){val1.style.backgroundColor=val2;}}(tr,bgColor);
let td;
td = document.createElement('td');
td.style.cssText="width:24px;text-align:center;vertical-align:top;";
td.innerHTML='<img id="geofences_down_btn_'+this.geofences[i].id+'" src="/resources/images/right.png" alt="" style="cursor: pointer;">';
tr.appendChild(td);
td = document.createElement('td');
td.style.cssText="text-align: center;";
td.innerHTML='<input id="geofences_ch_'+this.geofences[i].id+'" type="checkbox"/>';
tr.appendChild(td);
td = document.createElement('td');
td.style.cursor='pointer';
td.innerHTML=this.geofences[i].name;
td.onclick=function(detour){
return function(){
detour.goToCenter();
}
}(this.geofences[i]);
tr.appendChild(td);
/*td = document.createElement('td');
td.style.cssText='cursor:pointer;text-align:right;';
td.innerHTML=this.geofences[i].date_start;
td.onclick=function(detour){
return function(){
detour.goToCenter();
}
}(this.geofences[i]);
tr.appendChild(td);
td = document.createElement('td');
td.style.cssText='cursor:pointer;text-align:right;';
td.innerHTML=this.geofences[i].date_end;
td.onclick=function(detour){
return function(){
detour.goToCenter();
}
}(this.geofences[i]);
tr.appendChild(td);*/
td = document.createElement('td');
td.style.cssText='cursor:pointer;text-align:right;';
td.innerHTML=this.geofences[i].count;
td.onclick=function(detour){
return function(){
detour.goToCenter();
}
}(this.geofences[i]);
tr.appendChild(td);
theTable.tBodies[0].appendChild(tr);
//Формирую раскрывающийся список
var tr = document.createElement('tr');
tr.id=this.geofences[i].id;
tr.style.cssText="background-color:var(--back-color-3);display:none";
td = document.createElement('td');
td.colSpan=4;
let html='<table style="width:100%;"><tr><td style="width:100%;border: 0;">';
if(this.geofences[i].geofence_type_name!=null)
html+='<b>Тип геозоны'+trt('')+'</b>: '+this.geofences[i].geofence_type_name+'<br>';
html+='</td><td valign="top" style="border: 0;"><img id="detour_del_'+this.geofences[i].id+'" src="/resources/images/del24.png" alt="'+trt('Delete')+'" title="'+trt('Delete')+'" style="cursor:pointer;"></td><td valign="top" style="border: 0;"><img id="detour_edit_'+this.geofences[i].id+'" src="/resources/images/edit24.png" alt="'+trt('Edit')+'" title="'+trt('Edit')+'" style="cursor:pointer;"></td></tr></table>';
td.innerHTML=html;
tr.appendChild(td);
theTable.tBodies[0].appendChild(tr);
var cell=document.getElementById("geofences_ch_"+this.geofences[i].id);
cell.onclick=function(route){
return function(){
var chb=document.getElementById("geofences_ch_"+route.id);
route.setVisibility(chb.checked);
}
}(this.geofences[i]);
//Кнопка разсрыть список
var btn=document.getElementById('geofences_down_btn_'+this.geofences[i].id);
btn.onclick=function(tr,thiz,id){ return function(){
var btn=document.getElementById('geofences_down_btn_'+id);
if(btn.src.indexOf("right.png")!=-1)
{
btn.src = '/resources/images/down.png';
tr.style.display = 'table-row';
}else if(btn.src.indexOf("down.png")!=-1)
{
btn.src = '/resources/images/right.png';
tr.style.display = 'none';
}
}; }(tr,this,this.geofences[i].id);
/*
//При щелчке по иконке календаря отображаем календарь выбора
//setCalendar("filter_date_route_start_"+this.geofences[i].id,"filter_date_route_start_trigger_"+this.geofences[i].id,-2);
//setCalendar("filter_date_route_end_"+this.geofences[i].id,"filter_date_route_end_trigger_"+this.geofences[i].id);
this.geofences[i].getGeoJSON();
*/
//Кнопка удалить
btn=document.getElementById('detour_del_'+this.geofences[i].id)
btn.onclick=function(thiz,id){ return function(){ thiz.deleteDetour({id:id}); }; }(this,this.geofences[i].id);
//Кнопка редактировать
btn=document.getElementById('detour_edit_'+this.geofences[i].id)
btn.onclick=function(thiz,id){ return function(){ thiz.editDetour({id:id}); }; }(this,this.geofences[i].id);
}
//Количество элементов в дереве
var divCnt = document.getElementById("count_geofences");
delChild(divCnt);
divCnt.appendChild(document.createTextNode(this.geofences.length));
//По нажатию на заголовок инвертируем чекбуксы
divCnt = document.getElementById("cell_ch_D");
divCnt.onclick=function(thiz){
return function(){
thiz.hide();
}
}(this);
}
createDetour()
{
//В настройках передаю центр карты
let center=ol.proj.transform(g_map.getView().getCenter(), 'EPSG:3857','EPSG:4326');
let eRec = new EdtRec("");
eRec.eRecNa("Geofences",-1,'<type n="Geofences"><properties><prop n="name"><![CDATA['+document.getElementById("filter_name_geofences").value+']]></prop><prop n="lat"><![CDATA['+center[1]+']]></prop><prop n="lon"><![CDATA['+center[0]+']]></prop></properties></type>');
eRec.win.onClose=function(thiz){ return function(){ thiz.filtering();};}(this);
}
//Удалить объезд
deleteDetour(settings)
{
if (typeof settings === 'string' || settings instanceof String)
{
try {
settings = JSON.parse(settings);
} catch (e) {
alert(e.message);
return;
}
}
if (confirm(trt("Do_you_really_want_to_delete_the_record")+'?')) {
var req=createRequestObject();
req.onreadystatechange = function(thiz)
{
return function(){
if(req.readyState === 4){
var data=null;
try {
data = JSON.parse(req.responseText);
} catch (e) {
alert(e.message);
return;
}
if(data!=null)
{
if(data.errorMessage !== undefined && data.errorMessage!='')
{
alert(data.errorMessage);
thiz.win.hideProgressBar();
}else
{
}
}
//Фильтрую список заново
thiz.filtering();
}
};
}(this);
req.open("POST", '/monitoring/pscripts/geofences.php?fn=3', true);
req.setRequestHeader("Content-type", "text/plain");
req.send(JSON.stringify(settings));
this.filtering();
}
return true;
}
editDetour(settings)
{
if (typeof settings === 'string' || settings instanceof String)
{
try {
settings = JSON.parse(settings);
} catch (e) {
alert(e.message);
return;
}
}
var detour=this.getDetourByID(settings.id);
let eRec = new EdtRec("");
eRec.eRecNa("Geofences",settings.id);
eRec.win.onClose=function(thiz,detour){ return function(){
detour.showPoints(false);
//thiz.filtering();
};}(this,detour);
if(detour!=null)
{
detour.showPoints(true);
detour.setVisibility(true);
}
}
//Вернуть объект TDetour по идентификатору
getDetourByID(id)
{
for(var i=0;i<this.geofences.length;i++)
{
if(this.geofences[i].id==id)
return this.geofences[i];
}
return null;
}
clear()
{
//Удаляю геометриию
for(var i=0;i<this.geofences.length;i++)
{
this.geofences[i].setVisibility(false);
}
this.geofences = [];
}
//Инвертировать видимость маршрутов
hide()
{
for(var i=0;i<this.geofences.length;i++)
{
this.geofences[i].setVisibility(!this.geofences[i].getVisibility());
}
}
}
class TGeofence
{
constructor(geofences){
this.id='';
this.feature=null; //Объект который отображается на карте
this.shP=false; //Показывать ли точки для редактирования
this.geofences=geofences;
this.visible=false; //По умолчанию всё видим
}
getVisibility()
{
return this.visible;
}
//Отобразить объект на карте
setVisibility(val)
{
var chb=document.getElementById("geofences_ch_"+this.id);
if(val)
{
if(!chb.checked) chb.checked=true;
if(this.feature==null)
{
this.getGeoJSON(); //Подгружаем объект с сервера
}else
{
//Проверяю чтобы заново не добавить
var exists=false;
var features=g_vectorSourceGeofences.getFeatures();
for(var i=0;i<features.length;i++)
{
if(features[i]==this.feature)
{
exists=true;
break;
}
}
if(!exists)
g_vectorSourceGeofences.addFeature(this.feature);
}
}else{
if(chb!=null && chb.checked) chb.checked=false;
if(this.feature!=null)
{
g_vectorSourceGeofences.removeFeature(this.feature);
this.showPoints(false);
}
}
this.visible=val;
}
goToCenter()
{
var point=ol.proj.transform([this.lon, this.lat], 'EPSG:4326','EPSG:3857');
g_map.getView().setCenter(point);
if(g_map.getView().getZoom()<9)
g_map.getView().setZoom(9);
}
//Отобразить точки для редактирования
showPoints(val)
{
//alert("showPoints="+val);
this.shP=val;
if(this.shP)
enableEditPoints(this.feature);
else
disableEditPoints(this.feature);
return true;
}
//Запросить гео данные для построения объекта на карте
getGeoJSON()
{
if(this.feature!=null) return;
var data = {
id: this.id
};
$.ajax({
url: '/monitoring/pscripts/geofences.php?fn=2',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
type: "POST",
dataType: "json",
success: function(thiz){return function(data,status){
if(status=='success')
{
var features = (new ol.format.GeoJSON()).readFeatures(data, {dataProjection: 'EPSG:4326',featureProjection: 'EPSG:3857'});
for(i=0;i<features.length;i++)
{
features[i].setStyle(new ol.style.Style({
fill: new ol.style.Fill({color: 'rgba(0, 255, 0, 0.5)'}),
stroke: new ol.style.Stroke({color: 'rgba(0, 100, 0, 0.7)', width: 2}),
text: new ol.style.Text({
font: 'bold 12px helvetica,sans-serif',
//text: userData.percent+" %",
fill: new ol.style.Fill({color: 'black'}),
stroke: new ol.style.Stroke({color: 'white', width: 1}),
offsetX: 0,
offsetY: 0
})
}));
thiz.feature=features[i]; //Должен быть один объект в объекте
thiz.feature.userData=thiz; //ссылка на родителя
g_vectorSourceGeofences.addFeature(thiz.feature);
//Если в режиме редактирования точек то отображаем эти точки
if(thiz.shP)
enableEditPoints(thiz.feature);
}
}else
{
alert(status);
}
}}(this)
});
}
};

View File

@ -0,0 +1,332 @@
//Класс для отображения и обработки сообщения пользователя
class TUserMessage
{
constructor(parent){
this.id=null;
this.parent = parent;
this.win = null;
}
//Отметить сообщение как обработанное
MarkAsProcessed(id)
{
var description=document.getElementById("msg_desc").value;
var data = {
id: id,
description: description
};
$.ajax({
url: '/monitoring/pscripts/messages.php?fn=5',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
type: "POST",
dataType: "json",
success: function(thiz){return function(data,status){
if(status=='success')
{
if(data.errorCode=='0')
{
//alert(trt('Saved')+'!');
thiz.win.Close();
//Обновляю список
thiz.parent.Filtering();
}else
{
alert(trt('Error')+': "'+data.errorMessage);
thiz.win.hideProgressBar();
}
}else
{
alert(status);
thiz.win.hideProgressBar();
}
}}(this)
});
this.win.showProgressBar();
}
//Загрузить сообщение в окно
ShowMessage(id)
{
if(this.win!=null) this.win.Close();
this.win = new TWin();
this.win.setParent(this.parent.win);
this.win.BuildGUI(10,10);
this.win.setCaption(trt('Message'));
this.win.setSize("600px","400px");
this.win.setCenter();
this.win.hide(false);
this.win.showProgressBar();
//Запрашиваю данные для отображения в окне
var data = {
id: id
};
var req=createRequestObject();
req.onreadystatechange = function(thiz)
{
return function(){
if(req.readyState === 4){
thiz.win.hideProgressBar(); //Всё "OK" скрываю "Progress bar"
var data=null;
try {
data = JSON.parse(req.responseText);
} catch (e) {
alert(e.message);
}
if(data!=null)
{
//Отображаю окошко с необработанными сообщениями
var html='<table class="SShow" style="width:100%;height:100%; background-color: #3a3a3a;">';
html+='<thead><tr><th style="width:30%;">'+trt('Name')+'</th><th style="width:70%;">'+trt('Value')+'</th></tr></thead>';
html+='<tr><td style="padding:2px;font-weight:bold;vertical-align:top;">'+trt('Theme')+'</td><td style="padding: 2px;vertical-align:top;">'+trt(data.subject)+'</td>';
html+='<tr style="height:100%;"><td style="font-weight:bold;padding:2px;vertical-align:top;">'+trt('Content')+'</td><td style="padding: 2px;vertical-align:top;">'+data.text+'</td></tr>';
if(data.action_name!='' && data.action_name!=null)
{
html+='<tr"><td style="padding:2px;vertical-align:top;">'+trt('Action')+'</td><td style="padding: 2px;vertical-align:top;"><button type="button" class="button-secondary" id="create_msg_a" style="width:100%;">'+trt(data.action_name)+'</button></td></tr>';
}
html+='<tr style="height:100%;"><td style="padding:2px;vertical-align:top;">'+trt('Additional_Information')+' ('+trt('Action_taken')+')'+'</td><td style="padding: 2px;vertical-align:top;"><textarea id="msg_desc" style="width:100%;height:100px;"></textarea></td></tr>';
html+='<tr><td style="padding: 2px;text-align:right;" colspan="2"><button class="button-secondary" onclick="g_UserMessage.MarkAsProcessed('+data.id+');">'+trt('Mark_as_processed')+'</button></td></tr>';
html+='</table>';
thiz.win.setContent(html);
//Обработчик события нажатия на кнопку действия
var btn = document.getElementById('create_msg_a');
if(btn!=null)
{
btn.onclick=function(name,settings){ return function(){
if(name=='Create_trip')
g_trips.createTrip(settings);
else if(name=='Edit_trip')
g_trips.editTrip(settings);
else
alert('Unknown action "'+name+'"!');
}; }(data.action_name,data.action_settings);
}
}
}
};
}(this);
req.open("POST", '/monitoring/pscripts/messages.php?fn=4', true);
req.setRequestHeader("Content-type", "text/plain");
req.send(JSON.stringify(data));
}
}
class TUserMessages
{
consctuctor(){
this.win = null;
}
//this.win.addResizeListener(function(obj){return function(){obj.updateSize();}}(this));
//Update dimensions of the elements (the main table in absolute coordinates).
updateSize()
{
var dv1=document.getElementById("tblMsgContainer");
var dv2=document.getElementById("tblMsgSContainer");
if(dv1!=null && dv2!=null)
{
dv1.style.width = dv2.offsetWidth+"px";
dv1.style.height = dv2.offsetHeight+"px";
}
}
//Отобразить окно с сообщениями пользователя
ShowMessages()
{
if(this.win!=null) this.win.Close();
this.win=new TWin();
this.win.BuildGUI(10,10);
this.win.setCaption(trt('User_messages'));
this.win.setSize("1000px","500px");
this.win.hide(false);
var content = '';
content+='<table style="width:100%; height:100%;"><tr><td>';
content+='<table style="width:100%; border: 1px solid rgb(99, 99, 99); table-layout: auto; margin-bottom: 10px;">';
content+='<caption></caption>';
content+='<thead></thead>';
content+='<tbody>';
content+=' <tr><td style="padding: 1px; white-space: nowrap;">'+trt('Company')+'</td><td style="padding: 1px; width: 100%;"><select id="sCompany_3" style="width: 100%;"></select></td></tr>';
content+=' <tr><td style="padding: 1px; white-space: nowrap;">'+trt('Status')+'</td><td style="padding: 1px; width: 100%;"><select id="sEvents_3" style="width: 100%;"><option value="1">'+trt('Processed')+'</option><option selected="selected" value="0">'+trt('Unprocessed')+'</option></select></td></tr>';
content+=' <tr><td style="padding: 1px;"></td><td style="padding: 1px; text-align:right;"><input class="button-secondary" type="button" value="Фильтровать" id="btnfilter_3"></td></tr>';
content+='</tbody>';
content+='</table>';
//Контент
content+='</td></tr><tr><td style="width:100%; height:100%;">';
content+='<div id="tblMsgSContainer" style="width:100%; height:100%;" bgcolor="green">';
content+='<div id="tblMsgContainer" style="position: absolute; overflow: scroll; width: 400px; height: 300px;">';
content+='</div>';
content+='</div>';
content+='</td></tr></table>';
this.win.setContent(content);
this.win.setCenter();
this.win.addResizeListener(function(thiz){return function(){thiz.updateSize();}}(this));
//Кнопочка фильтровать
var obj = document.getElementById("btnfilter_3");
obj.onclick = function(thiz){ return function(){ thiz.Filtering(); };}(this);
//Запрашиваю данные для заполнения выпадающего списка компаний
this.Filtering();
//Запрашиваю данные для заполнения компании
$.ajax({
url: "/monitoring/pscripts/user.php?fn=10",
type: "POST",
success: function(response) {
let b = document.getElementById("sCompany_3");
b.innerHTML += response;
}
});
}
//Запросить данные для отображения в фильтре
Filtering()
{
var data = {
state: ''
};
var req=createRequestObject();
req.onreadystatechange = function(thiz)
{
return function(){
if(req.readyState === 4){
var data=null;
try {
data = JSON.parse(req.responseText);
} catch (e) {
alert(e.message);
}
if(data!=null)
{
if(data.errorMessage !== undefined && data.errorMessage!='')
{
alert(data.errorMessage);
thiz.win.hideProgressBar();
return;
}
//Отображаю окошко с необработанными сообщениями
var html='<table class="SShow">';
html+='<thead><tr style="background-color: rgb(218, 218, 218);"><th>Тема</th><th>Содержание</th></tr></thead>';
for(i=0;i<data.length;i++)
{
let bgColor='';
if (i%2==0) bgColor='var(--row-color-1)'; else bgColor='var(--row-color-2)';
html+='<tr onclick="g_UserMessage.ShowMessage('+data[i].id+');" onmouseover="this.style.backgroundColor=\'var(--btn-color2)\';" onmouseout="this.style.backgroundColor=\''+bgColor+'\';" style="cursor: pointer; background-color:'+bgColor+';">';
//html+='<td>'+data[i].id+'</td>';
html+='<td>'+data[i].subject+'</td>';
html+='<td>'+data[i].text+'</td>';
html+='</tr>';
/*var userMessage = new TUserMessage();
userMessage.id=data[i].id;
thiz.messages.push(userMessage);*/
}
html+='</table>';
var cont=document.getElementById("tblMsgContainer");
cont.innerHTML = html;
}
thiz.win.hideProgressBar();
}
};
}(this);
req.open( "GET", '/monitoring/pscripts/messages.php?fn=3&status='+document.getElementById("sEvents_3").value, true );
req.send( null );
this.win.showProgressBar();
}
}
var g_UserMessages = new TUserMessages();
var g_UserMessage = new TUserMessage(g_UserMessages);
//Функция для переодическогой проверки количество сообщений требующих обработки а также кол-во сообщений для текущего пользователя
function getAllMessagesCount()
{
var data = {
test: ''
};
$.ajax({
url: '/monitoring/pscripts/messages.php?fn=1',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
type: "POST",
dataType: "json",
success: function(thiz){return function(data,status){
if(status=='success')
{
//Отображаю окошко с количеством необработанных сообщений
if(g_winCntMsg==null || g_winCntMsg.closed==true)
{
g_winCntMsg=new TWin();
g_winCntMsg.BuildGUI(20,60);
g_winCntMsg.setCaption(trt('Messages'));
//this.win.setContent(str);
g_winCntMsg.setSize("130px","120px");
//g_winCntMsg.setCenter();
//g_winCntMsg.shadow=true;
g_winCntMsg.hide(false);
}
//g_winCntMsg.setLeftTop(20,60);
g_winCntMsg.hide(false);
if(g_count!=parseInt(data.count))
{
beep();
g_count = parseInt(data.count);
}
var mCNTUser = parseInt(data.user);
var content = '';
content+=trt("Unassigned")+":<br>";
if(g_count>0){
content+="<button class=\"button-secondary\" id=\"takeMessage\" style=\"width:100%;height:50px;font-size:24pt;font-weight:bold;color:red;\" onclick=\"takeMessage();\"><blink class=\"blink\">"+g_count+"</blink></button>";
}else{
content+="<button class=\"button-secondary\" id=\"takeMessage\" style=\"width:100%;height:50px;font-size:24pt;font-weight:bold;\" onclick=\"takeMessage();\">"+g_count+"</button>";
}
content+=trt("Designated")+":<br>";
if(mCNTUser>0){
content+="<button class=\"button-secondary\" style=\"width:100%;height:50px;font-size:24pt;font-weight:bold;color:red;\" onclick=\"g_UserMessages.ShowMessages();\"><blink class=\"blink\">"+mCNTUser+"</blink></button>";
}else{
content+="<button class=\"button-secondary\" style=\"width:100%;height:50px;font-size:24pt;font-weight:bold;\" onclick=\"g_UserMessages.ShowMessages();\">0</button>";
}
g_winCntMsg.setContent(content);
}else
{
alert(status);
}
}}(this)
});
}
//Запрашиваем каждые 5 секунд
var timerId = setInterval(function() {
getAllMessagesCount();
}, 5000);

View File

@ -0,0 +1,850 @@
//Список автомобилей
class TObjects
{
constructor(map)
{
this.objects = [];
this.map=map;
//Запускаю таймер для обновления объектов раз в 10 секунд
setInterval(function(thiz){ return function(){thiz.updateData();}; }(this), 10000);
//Запускаю функцию для перемещения объектов по прогнозному маршруту
setInterval(function(thiz){ return function(){thiz.updateForecastLonLat();};}(this), 500);
}
//Фильтруем объекты для заполнения в таблицу
filtering()
{
showProgressBar(document.getElementById('div_tbl_monitoring'));
let company_id=document.getElementById("company_id_m");
if(company_id==null)
{
company_id=g_user.company_id;
}else
{
company_id=company_id.value;
}
let data = {
company_id: company_id,
cnumber: document.getElementById("cnumber_m").value
};
$.ajax({
url: '/monitoring/pscripts/objects.php',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
type: "POST",
dataType: "json",
success: function(thiz){return function(data,status){
if(status=='success')
{
thiz.objects = []; //Удаляю старые объекты
//Приходит JSON уже в объектах
let features = [];
for(let i=0;i<data.length;i++)
{
let feature=null;
let lon=parseFloat(data[i].lon);
let lat=parseFloat(data[i].lat);
if(!isNaN(lat) && !isNaN(lon))
{
let point = new ol.geom.Point(ol.proj.transform([lon,lat], 'EPSG:4326','EPSG:3857'));
feature = new ol.Feature({geometry: point,name: data[i].name,icon_name: data[i].icon_name});
feature.setStyle(createFatypeStyleDel(feature,false));
feature.userType="TObject";
feature.userID=data[i].id;
features.push(feature);
}
var obj = new TObject();
obj.feature=feature;
obj.id=data[i].id;
obj.seq=data[i].seq;
obj.active=data[i].active; //Активная или нет перевозка
obj.name=data[i].name;
obj.terminal_name=data[i].terminal_name;
obj.declaration=data[i].declaration;
obj.icon_name=data[i].icon_name;
obj.lon=parseFloat(data[i].lon);
obj.lat=parseFloat(data[i].lat);
obj.alt=parseFloat(data[i].alt);
obj.utime=parseInt(data[i].utime);
obj.speed=data[i].speed;
obj.date=data[i].date;
obj.geofences=data[i].geofences;
obj.bat=parseFloat(data[i].bat);
obj.bat_date=data[i].bat_date;
obj.tros=parseFloat(data[i].tros);
obj.tros_date=data[i].tros_date;
obj.box=parseFloat(data[i].box);
obj.box_date=data[i].box_date;
obj.sensors=data[i].sensors;
//alert("obj.box = "+obj.box+" obj.box_date = "+obj.box_date);
thiz.objects.push(obj);
}
g_vectorSource.clear(false);
g_vectorSource.addFeatures(features);
thiz.fillRezDiv();
}else
{
alert(status);
}
hideProgressBar(document.getElementById('div_tbl_monitoring'));
}}(this)
});
}
//Заполнить результатом выборки DIV в виде таблицы
fillRezDiv()
{
let div=document.getElementById("div_tbl_monitoring");
delChild(div);
div.innerHTML='<table id="thetable" border="0" style="width:100%;" class="SShow"><thead><tr style="background-color: rgb(218, 218, 218);"><th style="width:24px;"></th><th id="object_ch_M" style="width:36px;text-decoration:underline;cursor: pointer;">'+trt('View')+'.</th><th></th><th>'+trt('Object_of_observation')+'</th><th style="width:70px;">'+trt('Speed')+'</th><th style="width:75px;white-space:nowrap;" valign="middle"><img src="/resources/images/clock.png" alt="">'+trt('Date')+'</th></tr></thead><tbody></tbody></table>';
var theTable = document.getElementById('thetable');
for(i=0;i<this.objects.length;i++)
{
let tr = document.createElement('tr');
let bgColor='';
if (i%2==0) bgColor='var(--row-color-1)'; else bgColor='var(--row-color-2)';
tr.style.backgroundColor=bgColor;
tr.onmouseover=function(){this.style.backgroundColor='var(--btn-color2)';};
tr.onmouseout=function(val1,val2){return function(){val1.style.backgroundColor=val2;}}(tr,bgColor);
let td;
td = document.createElement('td');
td.style.cssText="width:24px;text-align:center;vertical-align:top;";
td.innerHTML='<img id="object_down_btn_'+this.objects[i].id+'" src="/resources/images/right.png" alt="" style="cursor: pointer;">';
tr.appendChild(td);
td = document.createElement('td');
td.style.cssText="text-align: center;";
td.innerHTML='<input id="object_ch_'+this.objects[i].uid+'" type="checkbox" checked/>';
tr.appendChild(td);
td = document.createElement('td');
td.style.cssText="text-align: center; width:30px;";
td.innerHTML='<img src="../resources/data/icons/'+this.objects[i].icon_name+'" alt="">';
tr.appendChild(td);
td = document.createElement('td');
td.style.cursor='pointer';
td.innerHTML=this.objects[i].name;
td.onclick=function(object){return function(){object.goToCenter();}}(this.objects[i]);
tr.appendChild(td);
td = document.createElement('td');
td.style.cssText="white-space:nowrap;";
td.style.cursor='pointer';
if(this.objects[i].speed!=null)
td.innerHTML=this.objects[i].speed+' '+trt('km_h');
td.onclick=function(object){return function(){object.goToCenter();}}(this.objects[i]);
tr.appendChild(td);
td = document.createElement('td');
td.id='date_'+this.objects[i].uid;
td.style.cursor='pointer';
td.innerHTML=this.objects[i].date;
td.onclick=function(object){return function(){object.goToCenter();}}(this.objects[i]);
tr.appendChild(td);
/*td = document.createElement('td');
var tros='-';
if(!isNaN(this.objects[i].tros))
tros=this.objects[i].tros +' '+ trt('Flag');
var tros_date='-';
if (typeof this.objects[i].tros_date != 'undefined')
tros_date=this.objects[i].tros_date;
var bat='-';
if(!isNaN(this.objects[i].bat)) bat= this.objects[i].bat+'%';
var bat_date='-';
if (typeof this.objects[i].bat_date != 'undefined')
bat_date=this.objects[i].bat_date;
var box='-';
if(!isNaN(this.objects[i].box))
box=this.objects[i].box +' '+ trt('Flag');
var box_date='-';
if (typeof this.objects[i].box_date != 'undefined')
box_date=this.objects[i].box_date;
td.innerHTML='<table border="0" style="width:100%;">\
<tr id="cell_'+this.objects[i].id+'" style="cursor: pointer;"><td style="width:30px;"></td><td></td><td style="width:20px;"><img src="/resources/images/clock.png" alt=""></td><td style="width:145px;"></td></tr>\
<tr style="background-color: #ffffff;"><td colspan="4" id="cell_data_'+this.objects[i].id+'" style="display: none;">\
<table border="0" style="width:100%;">\
<tr><td style="width:30px;"> </td><td style="border-bottom: 1px solid #7a7a7a;" colspan="4">\
<table>\
<tr>\
<td style="padding: 1px; width: 100%;">\
<table style="width: 100%;" border="0">\
<tr>\
<td style="width: 10px; padding: 1px; white-space: nowrap;">Маршрут, </td>\
<td style="width: 10px; padding: 1px;">c</td>\
<td style="width: 40%; padding: 1px;">\
<table style="width: 100%; table-layout: fixed; border-spacing: 0px; border-collapse: collapse;" border="0">\
<tr>\
<td style="width: 100%;"><input style="width: 100%;" name="date_start" value="" id="filter_date_route_start_'+this.objects[i].id+'" type="text"></td>\
<td style="width: 25px;"><img id="filter_date_route_start_trigger_'+this.objects[i].id+'" src="../resources/images/datepicker.jpg" style="margin-left: 1px; cursor: pointer;"></td>\
</tr>\
</table>\
</td>\
<td style="width: 10px; padding: 1px; white-space: nowrap;" width="1%">по</td>\
<td style="width: 40%; padding: 1px;">\
<table style="width: 100%; table-layout: fixed; border-spacing: 0px; border-collapse: collapse;" border="0">\
<tr>\
<td style="width: 100%;"><input style="width: 100%;" name="date_end" value="" id="filter_date_route_end_'+this.objects[i].id+'" type="text"></td>\
<td style="width: 25px;"><img id="filter_date_route_end_trigger_'+this.objects[i].id+'" src="../resources/images/datepicker.jpg" style="cursor: pointer; margin-left: 1px;"></td>\
</tr>\
</table>\
</td>\
</tr>\
</table>\
</td>\
</tr>\
<tr>\
<td style="padding: 1px; width: 100%;">\
<table style="width: 100%;" border="0">\
<tr>\
<td style="padding: 1px; white-space: nowrap;text-align:left;"><button onclick="g_objects.getObjectByID('+this.objects[i].id+').showDetailedInformation();">'+trt('Detailed_information')+'</button></td><td><td style="padding: 1px; white-space: nowrap;text-align:right;" width="1%" colspan="3"><button onclick="g_objects.getObjectByID('+this.objects[i].id+').getObjectTrack();">Отобразить маршрут</button><button onclick="g_objects.getObjectByID('+this.objects[i].id+').hideObjectTrack();">Скрыть</button></td>\
</tr>\
</table>\
</td>\
</tr>\
</table>\
</td></tr>\
</table>\
</td></tr></table>';
tr.appendChild(td);*/
theTable.tBodies[0].appendChild(tr);
//Формирую раскрывающийся список
tr = document.createElement('tr');
tr.id=this.objects[i].id;
tr.style.cssText="background-color:var(--back-color-3);display:none";
td = document.createElement('td');
td.colSpan=6;
let html='';
html+='<b>'+trt('Geofence_groups')+':</b> <img id="object_edit4_'+this.objects[i].uid+'" src="/resources/images/edit16.png" alt="'+trt('Edit')+'" title="'+trt('Edit')+'" style="cursor:pointer;"> '+this.objects[i].geofences+'<br>';
html+=' <table border="0" style="width:100%; border:none;">\
<tr><td style="width:30px;border:none;"> </td><td style="width: 50%;border:none;border-bottom: 1px solid #7a7a7a;">'+trt('Terminal')+'</td><td colspan="4" style="border:none;border-bottom: 1px solid #7a7a7a;">'+this.objects[i].terminal_name+'</td></tr>';
for(let j=0;j<this.objects[i].sensors.length;j++)
{
html+='<tr><td style="width:30px;border:none;"> </td><td style="width: 50%;border:none;border-bottom: 1px solid #7a7a7a;">'+trt(this.objects[i].sensors[j].name)+'</td><td id="svalue_'+this.objects[i].sensors[j].id+'_'+this.objects[i].uid+'" style="border:none;border-bottom: 1px solid #7a7a7a;">'+this.objects[i].sensors[j].value+'</td><td>'+this.objects[i].sensors[j].type_name+'</td><td style="width:20px;border:none;border-bottom: 1px solid #7a7a7a;"><img src="/resources/images/clock.png" alt=""></td><td id="sdate_'+this.objects[i].sensors[j].id+'_'+this.objects[i].uid+'" style="width:145px;border:none;border-bottom: 1px solid #7a7a7a;">'+this.objects[i].sensors[j].date+'</td></tr>';
}
html+='\
<tr style="width: 100%;"><td style="border:none; text-align: right; width: 100%;" colspan="6">\
<table>\
<tr>\
<td style="padding: 1px; width: 100%; border:none;">\
<table style="width: 100%;" border="0">\
<tr>\
<td style="width: 10px; padding: 1px; white-space: nowrap; border:none;">'+trt('Route')+', </td>\
<td style="width: 10px; padding: 1px;border:none;">c</td>\
<td style="width: 40%; padding: 1px;border:none;">\
<table style="width: 100%; table-layout: fixed; border-spacing: 0px; border-collapse: collapse;" border="0">\
<tr>\
<td style="width: 100%;border:none;"><input style="width: 100%;" name="date_start" value="" id="filter_date_route_start_'+this.objects[i].id+'" type="text"></td>\
<td style="width: 25px;border:none;"><img id="filter_date_route_start_trigger_'+this.objects[i].id+'" src="../resources/images/datepicker.jpg" style="margin-left: 1px; cursor: pointer;"></td>\
</tr>\
</table>\
</td>\
<td style="width: 10px; padding: 1px; white-space: nowrap;border:none;" width="1%">по</td>\
<td style="width: 40%; padding: 1px;border:none;">\
<table style="width: 100%; table-layout: fixed; border-spacing: 0px; border-collapse: collapse;" border="0">\
<tr>\
<td style="width: 100%;border:none;"><input style="width: 100%;" name="date_end" value="" id="filter_date_route_end_'+this.objects[i].id+'" type="text"></td>\
<td style="width: 25px;border:none;"><img id="filter_date_route_end_trigger_'+this.objects[i].id+'" src="../resources/images/datepicker.jpg" style="cursor: pointer; margin-left: 1px;"></td>\
</tr>\
</table>\
</td>\
</tr>\
</table>\
</td>\
</tr>\
<tr>\
<td style="padding: 1px; width: 100%;border:none;">\
<table style="width: 100%;" border="0">\
<tr>\
<td style="padding: 1px; white-space: nowrap;text-align:left;border:none;"><button class="button-secondary" onclick="g_objects.getObjectByID('+this.objects[i].id+').showDetailedInformation();">'+trt('Detailed_information')+'</button></td><td style="padding: 1px; white-space: nowrap;text-align:right;border:none;" width="1%" colspan="3"><button class="button-secondary" onclick="g_objects.getObjectByID('+this.objects[i].id+').getObjectTrack();">'+trt('Show_route')+'</button><button class="button-secondary" onclick="g_objects.getObjectByID('+this.objects[i].id+').hideObjectTrack();">'+trt('Hide')+'</button></td>\
</tr>\
</table>\
</td>\
</tr>\
</table>\
</td></tr>\
</table>';
td.innerHTML=html;
tr.appendChild(td);
theTable.tBodies[0].appendChild(tr);
//Кнопка редактировать грепп геозон объекта
btn=document.getElementById('object_edit4_'+this.objects[i].uid)
btn.onclick=function(thiz,id){ return function(){
var settings='<type n="ObjectsGeofences"><objects-list><filter><column n="object_id"><![CDATA['+id+']]></column></filter></objects-list></type>';
myFunction('ObjectsGeofences',settings);
}; }(this,this.objects[i].id);
//Чекбукс скрыть показать
var cell=document.getElementById("object_ch_"+this.objects[i].uid);
cell.onclick=function(object){
return function(){
var chb=document.getElementById("object_ch_"+object.uid);
object.setVisibility(chb.checked);
}
}(this.objects[i]);
//Кнопка разсрыть список
var btn=document.getElementById('object_down_btn_'+this.objects[i].id);
btn.onclick=function(tr,thiz,id){ return function(){
var btn=document.getElementById('object_down_btn_'+id);
if(btn.src.indexOf("right.png")!=-1)
{
btn.src = '/resources/images/down.png';
tr.style.display = 'table-row';
}else if(btn.src.indexOf("down.png")!=-1)
{
btn.src = '/resources/images/right.png';
tr.style.display = 'none';
}
};
}(tr,this,this.objects[i].id);
/*
//При щелчке на ячейку открываем содержимое и перемещаем карту на точку
var cell=document.getElementById("cell_"+this.objects[i].id);
cell.onclick=function(object){
return function(){
var cell=document.getElementById("cell_data_"+object.id);
if(cell.style.display=="none")
{
cell.style.display="table-cell";
}else{
cell.style.display="none";
}
//Пытаемся переместиться на точку на карте
if(!isNaN(parseFloat(object.lon)))
{
g_map.getView().setCenter(ol.proj.transform([object.lon,object.lat], 'EPSG:4326','EPSG:3857'));
if(g_map.getView().getZoom()<9)
g_map.getView().setZoom(9);
}
}
}(this.objects[i]);
*/
//При щелчке по иконке календаря отображаем календарь выбора
setCalendar("filter_date_route_start_"+this.objects[i].id,"filter_date_route_start_trigger_"+this.objects[i].id,-2);
setCalendar("filter_date_route_end_"+this.objects[i].id,"filter_date_route_end_trigger_"+this.objects[i].id);
}
//Количество элементов в дереве
var divCnt = document.getElementById("count_m");
delChild(divCnt);
divCnt.appendChild(document.createTextNode(this.objects.length));
//По нажатию на заголовок инвертируем чекбуксы
divCnt = document.getElementById("object_ch_M");
divCnt.onclick=function(thiz){
return function(){
thiz.hide();
}
}(this);
}
getObjectByID(id)
{
var obj=null;
for(var i=0;i<this.objects.length;i++)
{
if(this.objects[i].id==id)
{
obj = this.objects[i];
}
}
return obj;
}
//Обновляю дату и коордионаты для выбраного списка (вызывается раз в 10 секунд)
updateData()
{
//console.log("updateData len="+this.objects.length);
if(this.objects.length==0) return true;
//Пересылаю список идентификаторов для которых хотим получить обновления
var data = [];
for(i=0;i<this.objects.length;i++)
{
data.push(parseInt(this.objects[i].id));
}
$.ajax({
url: '/monitoring/pscripts/objects.php?fn=1',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
type: "POST",
dataType: "json",
success: function(thiz){return function(data,status){
if(status=='success')
{
//console.log("data1 = "+JSON.stringify(data));
//Перебираю элементы и обновляю соответствующие поля
for(var i=0;i<data.length;i++)
{
//console.log("data[i].id = "+data[i].id);
//console.log("data[i].date = "+data[i].date);
var obj=thiz.getObjectByID(data[i].id);
if(obj!=null)
{
obj.date=data[i].date;
obj.setLonLat(data[i].lon,data[i].lat);
for(let j=0;j<data[i].sensors.length;j++)
{
let sns=obj.getSensorByID(data[i].sensors[j].id);
if(sns!=null)
{
sns.value=data[i].sensors[j].value;
sns.date=data[i].sensors[j].date;
}
}
obj.updateGUI();
}
}
}else
{
alert(status);
}
}}(this)
});
}
//Инвертировать видимость маршрутов
hide()
{
for(var i=0;i<this.objects.length;i++)
{
this.objects[i].setVisibility(!this.objects[i].getVisibility());
}
}
}
//Конкретный автомобиль (объект, установка)
class TObject
{
constructor(){
this.uid=getUID(); //Уникальный идентификатор
this.active=1; //1 - пломба активная, 0 - пломба не активная
this.name=''; //Гос номер автомобиля
this.id=0; //Идентификатор записи (установки)
this.lon=0; //Долгота
this.lat=0; //Широта
this.alt=0; //Высота в метрах
this.icon_name="testicon";
this.sensors=null;
//Трос
//Аккумулятор
//Датчик вскрытия
this.feature=null; //Объект который отображается на карте
this.visible=true; //По умолчанию всё видим
}
getVisibility()
{
return this.visible;
}
//Отобразить объект на карте
setVisibility(val)
{
var chb=document.getElementById("object_ch_"+this.uid);
if(val)
{
if(!chb.checked) chb.checked=true;
if(this.feature==null)
{
//this.getGeoJSON(); //Подгружаем объект с сервера
}else
{
//Проверяю чтобы заново не добавить
var exists=false;
var features=g_vectorSource.getFeatures();
for(var i=0;i<features.length;i++)
{
if(features[i]==this.feature)
{
exists=true;
break;
}
}
if(!exists)
g_vectorSource.addFeature(this.feature);
}
}else{
if(chb!=null && chb.checked) chb.checked=false;
if(this.feature!=null)
{
g_vectorSource.removeFeature(this.feature);
//this.showPoints(false);
}
}
this.visible=val;
}
//Запрашиваем трек автомобиля (объект, установка)
getObjectTrack()
{
var dStart=new Date(document.getElementById("filter_date_route_start_"+this.id).value).getTime() / 1000;
var dEnd=new Date(document.getElementById("filter_date_route_end_"+this.id).value).getTime() / 1000;
if(isNaN(dStart)) dStart='';
if(isNaN(dEnd)) dEnd='';
//alert('dStart = '+dStart+' dEnd = ' + dEnd);
var data = {
object_id: this.id, //Идентификатор объекта
date_start: dStart, //Начало выборки UNIX время
date_end: dEnd //Конец выборки UNIX время
};
var req=createRequestObject();
req.onreadystatechange = function(thiz)
{
return function(){
if(req.readyState === 4){
var data=null;
try {
data = JSON.parse(req.responseText);
} catch (e) {
alert(e.message);
}
if(data!=null)
{
//alert('data.length = '+data.length);
if(data.length>=2) //Если количество точек >2
{
//Создаю массив точек
var points=[];
for(i=0;i<data.length;i++)
{
var point=[parseFloat(data[i].lon),parseFloat(data[i].lat)];
point = ol.proj.transform(point, 'EPSG:4326', 'EPSG:3857');
points.push(point);
}
var line = new ol.geom.LineString(points)
let featureL = new ol.Feature({
geometry: line
});
featureL.userID=thiz.id;
var style=new ol.style.Style(
{
fill: new ol.style.Fill({ color: '#6363fc', weight: 4 }),
stroke: new ol.style.Stroke({ color: '#6363fc', width: 3 })
});
featureL.setStyle(style);
g_vectorSource.addFeature(featureL);
//Создаю точки для отображения подробной информации
for(let i=0;i<data.length;i++)
{
var lon=parseFloat(data[i].lon);
var lat=parseFloat(data[i].lat);
if(!isNaN(lat) && !isNaN(lon))
{
let feature = new ol.Feature({geometry: new ol.geom.Point(ol.proj.transform([parseFloat(data[i].lon),parseFloat(data[i].lat)], 'EPSG:4326','EPSG:3857'))});
feature.userID=thiz.id;
let style = new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 0.5],
anchorXUnits: 'fraction',
anchorYUnits: 'fraction',
src: '../resources/images/point.png'
}))
});
feature.setStyle(style);
feature.userType='TTrackPoint';
feature.userHTML='<b>'+trt('Date')+'</b>: '+(new Date(data[i].udate*1000))+'<br>';
feature.userHTML+='<b>'+trt('Latitude')+'</b>: '+data[i].lat+' <b>'+trt('Longitude')+'</b>: '+data[i].lon+'<br>';
feature.userHTML+='<b>'+trt('Speed')+'</b>: '+data[i].speed+' '+trt('km_h')+" (GPS: "+data[i].velocity+trt('km_h')+')<br>';
g_vectorSource.addFeature(feature);
}
}
var pointS=featureL.getGeometry().getCoordinates()[0]; //Коордионаты первой точки в треке
var pointE=featureL.getGeometry().getCoordinates()[featureL.getGeometry().getCoordinates().length-1]; //Координаты последней точки
//Также создаю иконки старта трека и окончания трека
let featureS = new ol.Feature({geometry: new ol.geom.Point(pointS)});
featureS.userID=thiz.id;
featureS.setStyle(new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 37],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: '../resources/images/istart.png'
}))
}));
g_vectorSource.addFeature(featureS);
//Также создаю иконку окончания трека
let featureE = new ol.Feature({geometry: new ol.geom.Point(pointE)});
featureE.userID=thiz.id;
featureE.setStyle(new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 37],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: '../resources/images/istop.png'
}))
}));
g_vectorSource.addFeature(featureE);
//Перемещаемся на первую точку маршрута
g_map.getView().setCenter(pointS);
if(g_map.getView().getZoom()<9)
g_map.getView().setZoom(9);
}else
{
thiz.hideObjectTrack(); //Пытаемся спрятать если 0 точек
}
//Востанавливаю курсор
hideProgressBarIco();
}
}
};
}(this);
req.open("POST", '/monitoring/pscripts/track.php', true);
req.setRequestHeader("Content-type", "text/plain");
req.send(JSON.stringify(data));
//Курсор ожидание со стрелочкой
showProgressBarIco();
}
hideObjectTrack()
{
let delList = [];
let features=g_vectorSource.getFeatures();
for(let i=0;i<features.length;i++)
{
if(features[i].userID==this.id)
{
delList.push(features[i]);
}
}
for(let i=0;i<delList.length;i++)
{
g_vectorSource.removeFeature(delList[i]);
}
}
goToCenter()
{
//Пытаемся переместиться на точку на карте
if(!isNaN(parseFloat(this.lon)))
{
g_map.getView().setCenter(ol.proj.transform([this.lon,this.lat], 'EPSG:4326','EPSG:3857'));
if(g_map.getView().getZoom()<9)
g_map.getView().setZoom(9);
}
}
//Отобразить окно с детальной информацией о установке
showDetailedInformation()
{
//Запрашиваем информацию о объекте и отображаем в отдельном всплывающем окне
if(m_winPP!=null) m_winPP.Close();
m_winPP=new TWin();
m_winPP.BuildGUI(pageX-100,pageY-100);
m_winPP.setSize(500,100);
m_winPP.setCaption(this.name);
m_winPP.showProgressBar();
m_winPP.setCenter();
m_winPP.setContent('<table style="width:100%;height:100%;"><tr><td id="winPP_m"></td></tr><tr><td style="padding-top:5px;"></td></tr></table>');
//<button id="winPP_mm">Деактивировать ЭЗПУ</button>
/*var obj=document.getElementById("winPP_mm");
if(this.active==1)
{
obj.onclick = function(thiz){ return function(){ thiz.deactivation(); }; }(this);
}else
{
obj.style.display="none";
}*/
//alert('/monitoring/pscripts/object.php?object_id='+this.id);
$.ajax({
url: '/monitoring/pscripts/object.php?object_id='+this.id,
type: "POST",
dataType: "text",
success: function(thiz){return function(data,status){
if(status=='success')
{
m_winPP.hideProgressBar();
//m_winPP.setContent(data);
var obj=document.getElementById("winPP_m");
if(obj!=null)
{
obj.innerHTML=data;
}
m_winPP.setCenter();
}else
{
alert(status);
}
}}(this)
});
}
//Обновить графические элементы (дата если она отображается пользователю)
updateGUI()
{
var obj=document.getElementById('date_'+this.uid);
if(obj!=null){
obj.innerHTML=this.date;
}
if(this.sensors!=null)
{
for(let i=0;i<this.sensors.length;i++)
{
let obj=document.getElementById('svalue_'+this.sensors[i].id+'_'+this.uid);
if(obj!=null) obj.innerHTML=this.sensors[i].value;
obj=document.getElementById('sdate_'+this.sensors[i].id+'_'+this.uid);
if(obj!=null) obj.innerHTML=this.sensors[i].date;
}
}
}
//Переместить точку автомобиля в прогнозную точку
goToForecast(){
//if(this.name=='VIRTUAL') {
//Отдаляем последнюю точку ещё дальше
if (this.time != 0 && this.time_p != 0 && this.time != this.time_p && this.lon_p != this.lon && this.lat_p != this.lat) { //Чтобы не поделить на 0
//console.log('Object = ' + this.id+') '+this.name + ' предпоследний = ' + this.time + ' последний = ' + this.time_p);
let p = ((new Date()).getTime() - this.time) / (this.time - this.time_p);
p=p/1.2; //замедление 80%
//console.log('p = ' + p); //Процент от 0 до 1
if (p <= 1) {
let lat_c=this.lat+(this.lat-this.lat_p);
let lon_c=this.lon+(this.lon-this.lon_p);
this.lat_f = this.lat * (1 - p) + lat_c * p;
this.lon_f = this.lon * (1 - p) + lon_c * p;
//console.log('p = ' + p+' this.lat_f = '+this.lat_f+' this.lon_f = '+this.lon_f); //Процент от 0 до 1
this.setMarkerPosition(this.lon_f, this.lat_f);
//console.log('p = ' + p); //Процент от 0 до 1
}
}
//}
}
//Обновить коордионаты и иконку на карте
setLonLat(lon,lat)
{
lon = parseFloat(lon); //Долгота
lat = parseFloat(lat); //Широта
//Сохраняю предыдущее значение
if(this.time!=this.time_p){
this.time_p=this.time;
this.lon_p=this.lon;
this.lat_p=this.lat;
}
this.time=(new Date()).getTime(); //Текущее время для прогноза
this.lon=lon; //Долгота
this.lat=lat; //Широта
this.setMarkerPosition(lon,lat);
}
//Задать позицию маркера
setMarkerPosition(lon,lat){
if(!isNaN(lat) && !isNaN(lon))
{
let point = new ol.geom.Point(ol.proj.transform([lon,lat], 'EPSG:4326','EPSG:3857'));
if(this.feature==null)
{
let features = [];
this.feature = new ol.Feature({geometry: point,name: this.name,icon_name: this.icon_name});
this.feature.setStyle(createFatypeStyleDel(this.feature,false));
this.feature.userType="TObject";
//feature.userName='terrain';
this.feature.userID=this.id;
features.push(this.feature);
g_vectorSource.addFeatures(features);
}
this.feature.set('geometry', point);
}
}
getSensorByID(id)
{
let result=null;
if(this.sensors!=null)
{
for(let i=0;i<this.sensors.length;i++)
{
if(this.sensors[i].id==id)
{
result=this.sensors[i];
break;
}
}
}
return result;
}
}

View File

@ -0,0 +1,856 @@
class TRoutes
{
constructor(map)
{
this.routes = []; //Список маршрутов
}
//Получаем список объектов
//Фильтруем объекты для заполнения в таблицу
filtering()
{
showProgressBar(document.getElementById('div_tbl_e'));
var data = {
name: "",
type: ""
};
$.ajax({
url: '/monitoring/pscripts/routes.php',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
type: "POST",
dataType: "json",
success: function(thiz){return function(data,status){
if(status=='success')
{
thiz.routes = []; //Удаляю старые объекты
g_vectorSourceRoute.clear(); //Удаляю все отображения
for(i=0;i<data.length;i++)
{
var obj = new TRoute();
obj.id=data[i].id;
obj.name=data[i].name;
obj.station=data[i].station;
obj.carriers=data[i].carriers;
obj.count=data[i].count;
obj.length=data[i].length;
obj.lon=parseFloat(data[i].lon);
obj.lat=parseFloat(data[i].lat);
obj.schedules=data[i].schedules;
obj.checkpoints = [];
for(var j=0;j<data[i].checkpoints.length;j++)
{
var chp = new TCheckPoint();
Object.assign(chp,data[i].checkpoints[j]); //Копирую все свойства в новый объект
obj.checkpoints.push(chp);
}
thiz.routes.push(obj);
}
thiz.fillRezDiv();
}else
{
alert(status);
}
hideProgressBar(document.getElementById('div_tbl_e'));
}}(this)
});
}
//Заполнить результатом выборки DIV в виде таблицы
fillRezDiv()
{
var div=document.getElementById("div_tbl_e");
delChild(div);
div.innerHTML='<table id="thetable_e" border="0" style="width:100%;" class="SShow"><thead><tr style="background-color: rgb(218, 218, 218);"><th></th><th id="route_ch_M" style="width:1%;text-decoration:underline;cursor: pointer;">'+trt('View')+'.</th><th style="width: 90%;">'+trt('Route_name')+'</th><th style="width: 1%;">'+trt('Points')+'</th><th style="width: 1%;">'+trt('Length')+'</th></tr></thead><tbody></tbody></table>';
var theTable = document.getElementById('thetable_e');
for(i=0;i<this.routes.length;i++)
{
let tr = document.createElement('tr');
let bgColor='';
if (i%2==0) bgColor='var(--row-color-1)'; else bgColor='var(--row-color-2)';
tr.style.backgroundColor=bgColor;
tr.onmouseover=function(){this.style.backgroundColor='var(--btn-color2)';};
tr.onmouseout=function(val1,val2){return function(){val1.style.backgroundColor=val2;}}(tr,bgColor);
tr.id='cell_e_'+this.routes[i].id;
var td;
td = document.createElement('td');
td.style.cssText="width:24px;text-align:center;vertical-align:top;";
td.innerHTML='<img id="routes_down_btn_'+this.routes[i].id+'" src="/resources/images/right.png" alt="" style="cursor: pointer;">';
tr.appendChild(td);
td = document.createElement('td');
td.style.cssText="text-align: center;";
td.innerHTML='<input id="route_ch_'+this.routes[i].id+'" type="checkbox"/>';
tr.appendChild(td);
td = document.createElement('td');
td.style.cursor='pointer';
td.innerHTML=this.routes[i].name;
td.onclick=function(route){
return function(){
route.goToStart();
}
}(this.routes[i]);
tr.appendChild(td);
td = document.createElement('td');
td.style.cssText='cursor:pointer;text-align:right;';
td.innerHTML=this.routes[i].count;
td.onclick=function(route){
return function(){
route.goToStart();
}
}(this.routes[i]);
tr.appendChild(td);
td = document.createElement('td');
td.style.cssText='cursor:pointer;white-space:nowrap;text-align:right;';
td.innerHTML=this.routes[i].length+' '+trt('km');
td.onclick=function(route){
return function(){
route.goToStart();
}
}(this.routes[i]);
tr.appendChild(td);
/*td = document.createElement('td');
td.innerHTML=this.routes[i].value;
tr.appendChild(td);*/
/*td = document.createElement('td');
td.innerHTML=this.routes[i].date;
tr.appendChild(td);*/
theTable.tBodies[0].appendChild(tr);
//Формирую раскрывающийся список
tr = document.createElement('tr');
tr.id=this.routes[i].id;
tr.style.cssText="background-color:var(--back-color-3);display:none";
td = document.createElement('td');
td.colSpan=6;
var html='<table style="width:100%;"><tr><td style="width:100%;border: 0;">';
html+='<b>'+trt('Bus_station')+':</b> <img id="route_edit2_'+this.routes[i].id+'" src="/resources/images/edit16.png" alt="'+trt('Edit')+'" title="'+trt('Edit')+'" style="cursor:pointer;"> '+this.routes[i].station+'<br>';
html+='<b>'+trt('Carrier')+':</b> <img id="route_edit3_'+this.routes[i].id+'" src="/resources/images/edit16.png" alt="'+trt('Edit')+'" title="'+trt('Edit')+'" style="cursor:pointer;"> '+this.routes[i].carriers+'<br>';
html+='<b>'+trt('Schedule')+':</b> <img id="route_edit4_'+this.routes[i].id+'" src="/resources/images/edit16.png" alt="'+trt('Edit')+'" title="'+trt('Edit')+'" style="cursor:pointer;"><br>';
for(var j=0;j<this.routes[i].schedules.length;j++)
{
html+='<span style="padding-left:1em">'+this.routes[i].schedules[j].direction+': '+this.routes[i].schedules[j].time+' '+this.routes[i].schedules[j].carrier+'</span><br>';
}
html+='<b>Контрольные точки:</b> <img id="route_edit5_'+this.routes[i].id+'" src="/resources/images/rplus16.png" alt="'+trt('Create')+'" title="'+trt('Create')+'" style="cursor:pointer;"> <img id="route_edit6_'+this.routes[i].id+'" src="/resources/images/edit16.png" alt="'+trt('Edit')+'" title="'+trt('Edit')+'" style="cursor:pointer;"><br>';
for(var j=0;j<this.routes[i].checkpoints.length;j++)
{
html+='<span style="padding-left:1em"><input id="route_ch_c_'+this.routes[i].checkpoints[j].id+'" type="checkbox"/> <div id="route_ch_cd_'+this.routes[i].checkpoints[j].uid+'" style="display:inline;cursor:pointer;">'+this.routes[i].checkpoints[j].direction+': '+this.routes[i].checkpoints[j].time+' '+this.routes[i].checkpoints[j].name+'</div> <img id="route_edit_cp1_'+this.routes[i].checkpoints[j].id+'" src="/resources/images/edit16.png" alt="'+trt('Edit')+'" title="'+trt('Edit')+'" style="cursor:pointer;"> <img id="route_edit_cp2_'+this.routes[i].checkpoints[j].id+'" src="/resources/images/rdel16.png" alt="'+trt('Delete')+'" title="'+trt('Delete')+'" style="cursor:pointer;"></span><br>';
}
html+='</td><td valign="top" style="border: 0;"><img id="route_rev_'+this.routes[i].id+'" src="/resources/images/rev24.png" alt="'+trt('Swap')+' A B" title="'+trt('Swap')+' A B" style="cursor:pointer;"></td><td valign="top" style="border: 0;"><img id="route_edit_'+this.routes[i].id+'" src="/resources/images/edit24.png" alt="'+trt('Edit')+'" title="'+trt('Edit')+'" style="cursor:pointer;"></td><td valign="top" style="border: 0;"><img id="route_del_'+this.routes[i].id+'" src="/resources/images/del24.png" alt="'+trt('Delete')+'" title="'+trt('Delete')+'" style="cursor:pointer;"></td></tr></table>';
td.innerHTML=html;
tr.appendChild(td);
theTable.tBodies[0].appendChild(tr);
//При щелчке на ячейку перемещаем карту на точку
/*var cell=document.getElementById("cell_e_"+this.routes[i].id);
cell.onclick=function(object){
return function(){
object.getGeoJSON();
}
}(this.routes[i]);*/
var cell=document.getElementById("route_ch_"+this.routes[i].id);
cell.onclick=function(route){
return function(){
var chb=document.getElementById("route_ch_"+route.id);
route.setVisibility(chb.checked);
}
}(this.routes[i]);
//Кнопка разсрыть список
var btn=document.getElementById('routes_down_btn_'+this.routes[i].id);
btn.onclick=function(tr,thiz,id){ return function(){
var btn=document.getElementById('routes_down_btn_'+id);
if(btn.src.indexOf("right.png")!=-1)
{
btn.src = '/resources/images/down.png';
tr.style.display = 'table-row';
}else if(btn.src.indexOf("down.png")!=-1)
{
btn.src = '/resources/images/right.png';
tr.style.display = 'none';
}
};
}(tr,this,this.routes[i].id);
//Кнопка поменять местами начальную и конечную точку
btn=document.getElementById('route_rev_'+this.routes[i].id)
btn.onclick=function(thiz,id){ return function(){ thiz.swapPoints({id:id}); }; }(this,this.routes[i].id);
//Кнопка редактировать
btn=document.getElementById('route_edit_'+this.routes[i].id)
btn.onclick=function(thiz,id){ return function(){ thiz.editRoute({id:id}); }; }(this,this.routes[i].id);
//Кнопка удалить
btn=document.getElementById('route_del_'+this.routes[i].id)
btn.onclick=function(thiz,id){ return function(){ thiz.deleteRoute({id:id}); }; }(this,this.routes[i].id);
//Кнопка редактировать "Автовокзал", "Перевозчик"
var eBtn=function(thiz,id){ return function(){
var settings='<type n="RoutesCompanies"><objects-list><filter><column n="route_id"><![CDATA['+id+']]></column></filter></objects-list></type>';
myFunction('RoutesCompanies',settings);
}; }(this,this.routes[i].id);
btn=document.getElementById('route_edit2_'+this.routes[i].id)
btn.onclick=eBtn;
btn=document.getElementById('route_edit3_'+this.routes[i].id)
btn.onclick=eBtn;
//Кнопка редактировать расписание рейса
btn=document.getElementById('route_edit4_'+this.routes[i].id)
btn.onclick=function(thiz,id){ return function(){
var settings='<type n="TripsSchedules"><objects-list><filter><column n="route_id"><![CDATA['+id+']]></column></filter></objects-list></type>';
myFunction('TripsSchedules',settings);
}; }(this,this.routes[i].id);
//Кнопка создать контрольную точку
btn=document.getElementById('route_edit5_'+this.routes[i].id)
btn.onclick=function(thiz,id){ return function(){
thiz.createCheckPoint(id);
}; }(this,this.routes[i].id);
//Кнопка редактировать контрольные точки (табличка)
btn=document.getElementById('route_edit6_'+this.routes[i].id)
btn.onclick=function(thiz,id){ return function(){
var settings='<type n="RoutesCheckpoints"><objects-list><filter><column n="route_id"><![CDATA['+id+']]></column></filter></objects-list></type>';
myFunction('RoutesCheckpoints',settings);
}; }(this,this.routes[i].id);
//Кнопки редактировать контрольные точки
for(var j=0;j<this.routes[i].checkpoints.length;j++)
{
//Чекбукс видимости контрольной точки
var bnt=document.getElementById("route_ch_c_"+this.routes[i].checkpoints[j].id);
bnt.onclick=function(checkPoint){
return function(){
var chb=document.getElementById("route_ch_c_"+checkPoint.id);
checkPoint.setVisibility(chb.checked);
}
}(this.routes[i].checkpoints[j]);
//Центрировать на контрольной точке
btn=document.getElementById('route_ch_cd_'+this.routes[i].checkpoints[j].uid);
btn.onclick=function(checkpoint){ return function(){ checkpoint.goToCenter(); }; }(this.routes[i].checkpoints[j]);
//Кнопка редактировать
btn=document.getElementById('route_edit_cp1_'+this.routes[i].checkpoints[j].id);
btn.onclick=function(thiz,id){ return function(){ thiz.editCheckPoint({id:id}); }; }(this,this.routes[i].checkpoints[j].id);
//Кнопка удалить контрольную точку
btn=document.getElementById('route_edit_cp2_'+this.routes[i].checkpoints[j].id);
btn.onclick=function(thiz,id){ return function(){ thiz.deleteControlPoint({id:id}); }; }(this,this.routes[i].checkpoints[j].id);
}
}
//Количество элементов в дереве
var divCnt = document.getElementById("count_e");
delChild(divCnt);
divCnt.appendChild(document.createTextNode(this.routes.length));
//По нажатию на заголовок инвертируем чекбуксы
divCnt = document.getElementById("route_ch_M");
divCnt.onclick=function(thiz){
return function(){
thiz.hide();
}
}(this);
}
//Поменять местами начальную и конечную точки
swapPoints(settings)
{
if (typeof settings === 'string' || settings instanceof String)
{
try {
settings = JSON.parse(settings);
} catch (e) {
alert(e.message);
return;
}
}
if (confirm(trt("Do_you_really_want_to_swap_the_points")+'?')) {
}
}
createRoute()
{
//В настройках передаю центр карты
let center=ol.proj.transform(g_map.getView().getCenter(), 'EPSG:3857','EPSG:4326');
let eRec = new EdtRec("");
eRec.eRecNa("Routes",-1,'<type n="Routes"><properties><prop n="name"><![CDATA['+document.getElementById("cnumber_e").value+']]></prop><prop n="lat"><![CDATA['+center[1]+']]></prop><prop n="lon"><![CDATA['+center[0]+']]></prop></properties></type>');
eRec.win.onClose=function(thiz){ return function(){ thiz.filtering();};}(this);
}
createCheckPoint(id)
{
//В настройках передаю центр карты
let center=ol.proj.transform(g_map.getView().getCenter(), 'EPSG:3857','EPSG:4326');
let eRec = new EdtRec("");
eRec.eRecNa("RoutesCheckpoints",-1,'<type n="RoutesCheckpoints"><properties><prop n="route_id"><![CDATA['+id+']]></prop><prop n="name"><![CDATA['+document.getElementById("cnumber_e").value+']]></prop><prop n="lat"><![CDATA['+center[1]+']]></prop><prop n="lon"><![CDATA['+center[0]+']]></prop></properties></type>');
eRec.win.onClose=function(thiz){ return function(){ thiz.filtering();};}(this);
}
//Удалить маршрут
deleteRoute(settings)
{
if (typeof settings === 'string' || settings instanceof String)
{
try {
settings = JSON.parse(settings);
} catch (e) {
alert(e.message);
return;
}
}
if (confirm(trt("Do_you_really_want_to_delete_the_record")+'?')) {
var req=createRequestObject();
req.onreadystatechange = function(thiz)
{
return function(){
if(req.readyState === 4){
var data=null;
try {
data = JSON.parse(req.responseText);
} catch (e) {
alert(e.message);
return;
}
if(data!=null)
{
if(data.errorMessage !== undefined && data.errorMessage!='')
{
alert(data.errorMessage);
thiz.win.hideProgressBar();
}else
{
}
}
//Фильтрую список заново
thiz.filtering();
}
};
}(this);
req.open("POST", '/monitoring/pscripts/routes.php?fn=3', true);
req.setRequestHeader("Content-type", "text/plain");
req.send(JSON.stringify(settings));
this.filtering();
}
return true;
}
//Удалить маршрут
deleteControlPoint(settings)
{
if (typeof settings === 'string' || settings instanceof String)
{
try {
settings = JSON.parse(settings);
} catch (e) {
alert(e.message);
return;
}
}
if (confirm(trt("Do_you_really_want_to_delete_the_record")+'?')) {
alert(settings.id);
/*var req=createRequestObject();
req.onreadystatechange = function(thiz)
{
return function(){
if(req.readyState === 4){
var data=null;
try {
data = JSON.parse(req.responseText);
} catch (e) {
alert(e.message);
return;
}
if(data!=null)
{
if(data.errorMessage !== undefined && data.errorMessage!='')
{
alert(data.errorMessage);
thiz.win.hideProgressBar();
}else
{
}
}
//Фильтрую список заново
thiz.filtering();
}
};
}(this);
req.open("POST", '/monitoring/pscripts/routes.php?fn=3', true);
req.setRequestHeader("Content-type", "text/plain");
req.send(JSON.stringify(settings));
this.filtering();*/
}
return true;
}
editRoute(settings)
{
if (typeof settings === 'string' || settings instanceof String)
{
try {
settings = JSON.parse(settings);
} catch (e) {
alert(e.message);
return;
}
}
let route=this.getRouteByID(settings.id);
let eRec = new EdtRec("");
eRec.eRecNa("Routes",settings.id);
eRec.win.onClose=function(thiz,route){ return function(){
route.showPoints(false);
//thiz.filtering();
};}(this,route);
if(route!=null)
{
route.showPoints(true);
route.setVisibility(true);
}
}
editCheckPoint(settings)
{
if (typeof settings === 'string' || settings instanceof String)
{
try {
settings = JSON.parse(settings);
} catch (e) {
alert(e.message);
return;
}
}
let checkPoint=this.getCheckPointByID(settings.id);
let eRec = new EdtRec("");
eRec.eRecNa("RoutesCheckpoints",settings.id);
eRec.win.onClose=function(thiz,checkPoint){ return function(){
checkPoint.showPoints(false);
};}(this,checkPoint);
//alert("checkPoint = "+checkPoint+" id = "+settings.id);
if(checkPoint!=null)
{
checkPoint.showPoints(true);
checkPoint.setVisibility(true);
}
}
//Вернуть объект TRoute по идентификатору
getRouteByID(id)
{
for(var i=0;i<this.routes.length;i++)
{
if(this.routes[i].id==id)
return this.routes[i];
}
return null;
}
//Вернуть объект TCheckPoint по идентификатору
getCheckPointByID(id)
{
for(var i=0;i<this.routes.length;i++)
{
for(var j=0;j<this.routes[i].checkpoints.length;j++)
{
if(this.routes[i].checkpoints[j].id==id)
return this.routes[i].checkpoints[j];
}
}
return null;
}
//Инвертировать видимость маршрутов
hide()
{
for(var i=0;i<this.routes.length;i++)
{
this.routes[i].setVisibility(!this.routes[i].getVisibility());
}
}
}
class TRoute
{
constructor(){
this.uid=getUID(); //Уникальный идентификатор
this.id='';
this.feature=null; //Объект который отображается на карте
this.featureA=null; //Начало маршрута
this.featureB=null; //Конец маршрута
this.shP=false; //Показывать ли точки для редактирования
this.visible=false; //По умолчанию всё видим
}
getVisibility()
{
return this.visible;
}
setVisibility(val)
{
var chb=document.getElementById("route_ch_"+this.id);
if(val)
{
if(!chb.checked) chb.checked=true;
if(this.feature==null)
{
this.getGeoJSON(); //Подгружаем объект с сервера
}else
{
//Проверяю чтобы заново не добавить
var exists=false;
var features=g_vectorSourceRoute.getFeatures();
for(var i=0;i<features.length;i++)
{
if(features[i]==this.feature)
{
exists=true;
break;
}
}
if(!exists)
{
g_vectorSourceRoute.addFeature(this.feature);
g_vectorSourceRoute.addFeature(this.featureA); //Начало маршрута
g_vectorSourceRoute.addFeature(this.featureB); //Конец маршрута
}
}
}else{
if(chb!=null && chb.checked) chb.checked=false;
if(this.feature!=null)
{
g_vectorSourceRoute.removeFeature(this.feature);
this.showPoints(false);
}
if(this.featureA!=null) g_vectorSourceRoute.removeFeature(this.featureA); //Начало маршрута
if(this.featureB!=null) g_vectorSourceRoute.removeFeature(this.featureB); //Конец маршрута
}
this.visible=val;
//Также присваваю видимость для контрольных точек
for(var i=0;i<this.checkpoints.length;i++)
{
this.checkpoints[i].setVisibility(val);
}
}
goToStart()
{
if(this.feature!=null)
{
var coord = this.feature.getGeometry().getCoordinates();
if(coord.length>0)
{
var point = coord[0];
if(point!=null)
{
g_map.getView().setCenter(point);
if(g_map.getView().getZoom()<9)
g_map.getView().setZoom(9);
}
}
}else
{
if(!isNaN(parseFloat(this.lon)))
{
var point = ol.proj.transform([this.lon,this.lat], 'EPSG:4326','EPSG:3857');
if(point!=null)
{
g_map.getView().setCenter(point);
if(g_map.getView().getZoom()<9)
g_map.getView().setZoom(9);
}
}
}
}
//Отобразить точки для редактирования
showPoints(val)
{
this.shP=val;
if(this.shP)
enableEditPoints(this.feature);
else
disableEditPoints(this.feature);
return true;
}
//Запросить гео данные для построения маршрута на карте
getGeoJSON()
{
if(this.feature!=null) return;
var data = {
id: this.id
};
$.ajax({
url: '/monitoring/pscripts/routes.php?fn=1',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
type: "POST",
dataType: "json",
success: function(thiz){return function(data,status){
if(status=='success')
{
var dataC;
var featuresC;
var vectorSourceC;
dataC = data;//JSON.parse('{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type": "LineString","coordinates": [[34.32128906249999,54.67383096593114],[45.3955078125,54.44449176335762],[52.7783203125,52.61639023304539],[62.13867187499999,49.095452162534826],[76.1572265625,43.45291889355465]]}}]}');
vectorSourceC = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(dataC,{featureProjection: 'EPSG:3857'})
});
featuresC = vectorSourceC.getFeatures();
var point=null; //Коордионаты первой точки в маршруте
for(i=0;i<featuresC.length;i++)
{
featuresC[i].setStyle(new ol.style.Style({
fill: new ol.style.Fill({color: 'rgba(255, 0, 76, 0.3)'}),
stroke: new ol.style.Stroke({color: 'rgba(255, 0, 0, 0.7)', width: 4}),
text: new ol.style.Text({
font: 'bold 12px helvetica,sans-serif',
//text: userData.percent+" %",
fill: new ol.style.Fill({color: 'black'}),
stroke: new ol.style.Stroke({color: 'white', width: 1}),
offsetX: 0,
offsetY: 0
})
}));
thiz.feature=featuresC[i]; //Должен быть один массив в объекте
thiz.feature.userData=thiz; //Ссылка на TRoute
g_vectorSourceRoute.addFeature(featuresC[i]);
}
var pointS=thiz.feature.getGeometry().getCoordinates()[0]; //Коордионаты первой точки в треке
var pointE=thiz.feature.getGeometry().getCoordinates()[thiz.feature.getGeometry().getCoordinates().length-1]; //Координаты последней точки
//Обозначаю начальную точку маршрута как A
thiz.featureA = new ol.Feature({geometry: new ol.geom.Point(pointS)});
thiz.featureA.setStyle(new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 24],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: '../resources/images/icons/19.png'
}))
}));
g_vectorSourceRoute.addFeature(thiz.featureA);
//Обозначаю конечную точку маршрутат как B
thiz.featureB = new ol.Feature({geometry: new ol.geom.Point(pointE)});
thiz.featureB.setStyle(new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 24],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: '../resources/images/icons/20.png'
}))
}));
g_vectorSourceRoute.addFeature(thiz.featureB);
//Если в режиме редактирования точек то отображаем эти точки
if(thiz.shP)
enableEditPoints(thiz.feature);
}else
{
alert(status);
}
}}(this)
});
}
};
//У каждого маршрута должно быть по крайней мере 2 контрольные точки
class TCheckPoint
{
constructor(){
this.uid=getUID(); //Уникальный идентификатор
this.id='';
this.feature=null; //Объект который отображается на карте
this.shP=false; //Показывать ли точки для редактирования
this.visible=false; //По умолчанию всё видим
}
getVisibility()
{
return this.visible;
}
setVisibility(val)
{
var chb=document.getElementById("route_ch_c_"+this.id);
if(val)
{
if(!chb.checked) chb.checked=true;
if(this.feature==null)
{
this.getGeoJSON(); //Подгружаем объект с сервера
}else
{
//Проверяю чтобы заново не добавить
var exists=false;
var features=g_vectorSourceRoute.getFeatures();
for(var i=0;i<features.length;i++)
{
if(features[i]==this.feature)
{
exists=true;
break;
}
}
if(!exists)
g_vectorSourceRoute.addFeature(this.feature);
}
}else{
if(chb!=null && chb.checked) chb.checked=false;
if(this.feature!=null)
{
//Проверяем есть ли Feature а если есть то удаляем
var exists=false;
var features=g_vectorSourceRoute.getFeatures();
for(var i=0;i<features.length;i++)
{
if(features[i]==this.feature)
{
exists=true;
break;
}
}
if(exists)
{
g_vectorSourceRoute.removeFeature(this.feature);
this.showPoints(false);
}
}
}
this.visible=val;
}
//Отобразить точки для редактирования
showPoints(val)
{
//alert("showPoints="+val);
this.shP=val;
if(this.shP)
enableEditPoints(this.feature);
else
disableEditPoints(this.feature);
return true;
}
goToCenter()
{
var point=ol.proj.transform([parseFloat(this.lon), parseFloat(this.lat)], 'EPSG:4326','EPSG:3857');
g_map.getView().setCenter(point);
if(g_map.getView().getZoom()<9)
g_map.getView().setZoom(9);
}
//Запросить гео данные для построения объекта на карте
getGeoJSON()
{
if(this.feature!=null) return;
var data = {
id: this.id
};
$.ajax({
url: '/monitoring/pscripts/routes.php?fn=2',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
type: "POST",
dataType: "json",
success: function(thiz){return function(data,status){
if(status=='success')
{
var features = (new ol.format.GeoJSON()).readFeatures(data, {dataProjection: 'EPSG:4326',featureProjection: 'EPSG:3857'});
for(i=0;i<features.length;i++)
{
features[i].setStyle(new ol.style.Style({
fill: new ol.style.Fill({color: 'rgba(0, 255, 0, 0.5)'}),
stroke: new ol.style.Stroke({color: 'rgba(0, 100, 0, 0.7)', width: 2}),
text: new ol.style.Text({
font: 'bold 12px helvetica,sans-serif',
//text: userData.percent+" %",
fill: new ol.style.Fill({color: 'black'}),
stroke: new ol.style.Stroke({color: 'white', width: 1}),
offsetX: 0,
offsetY: 0
})
}));
thiz.feature=features[i]; //Должен быть один объект в объекте
thiz.feature.userData=thiz; //ссылка на родителя
g_vectorSourceRoute.addFeature(thiz.feature);
//Если в режиме редактирования точек то отображаем эти точки
if(thiz.shP)
enableEditPoints(thiz.feature);
}
}else
{
alert(status);
}
}}(this)
});
}
}

View File

@ -0,0 +1,475 @@
class TTrips
{
constructor(map){
//this.m_id=null; //id редактируемой записи
this.trips = []; //Список маршрутов
this.win=null;
this.iframe = createIFrame('trip_file_i', '/monitoring/pscripts/trips.php?fn=4', document.body, false); //Фрейм для закачки файла на сервер
}
//Открывается новое окно для создания нового рейса
// settings - объект(или строка) с настройками для создания маршрута
createTrip(settings)
{
if(this.win!=null && !this.win.closed) return; //Несколько одновременно нельзя создавать
if (typeof settings === 'string' || settings instanceof String)
{
try {
settings = JSON.parse(settings);
} catch (e) {
alert(e.message);
return;
}
}
this.win=new TWin();
this.win.pth='../metadata/dbms/form/';
this.win.BuildGUI(10,40)
this.win.getCaption().appendChild(document.createTextNode(trt("Creation_of_trip")));
//Как подгрузится содержимое выполниться данная функция для настройки по средством JS
var func=function(thiz)
{
return function()
{
setCalendar('trip_date_start','trip_date_start_s');
//кнопка выбора файла
var btn=document.getElementById('e_trip_btn_select_file');
var doc=getIframeDocument(thiz.iframe)
var inp=document.getElementById('trip_file_name');
btn.onclick=function(doc){return function(){doc.forms["form"].elements["file"].click()}}(doc);
doc.forms["form"].elements["file"].onchange = function(inp) {return function(){inp.value=this.files[0].name;/*this.value;*/};}(inp);
/*if(BeforeFirst(doc.body.innerHTML,'=')=='ok')
{
var fName=BeforeFirst(AfterFirst(doc.body.innerHTML,'='),"\n");
inp.value=BeforeLast(inp.value,'.')+'_'+fName;
if(inp.value!='')
{ thiz.sendData();
}
}*/
//Кнопка скачать файл
//Кнопка удаления файла
var btn=document.getElementById('trip_btn_delete_file');
btn.onclick=function(inp,ifr){return function(){ inp.value=''; getIframeDocument(ifr).forms["form"].reset(); }}(inp,thiz.iframe)
thiz.win.setCenter();
}
};
this.win.load("/monitoring/pscripts/trips.php?fn=2",settings,func(this));
this.win.setSize("750px","200px");
//win.setCenter();
this.win.obj=this;
//this.win.Hide(false)
this.win.setCenter();
}
editTrip(settings)
{
if(this.win!=null && !this.win.closed) //Несколько одновременно нельзя редактировать
{
alert(trt('Trip_is_already_being_edited')+'!');
return;
}
if (typeof settings === 'string' || settings instanceof String)
{
try {
settings = JSON.parse(settings);
} catch (e) {
alert(e.message);
return;
}
}
this.win=new TWin();
this.win.pth='../metadata/dbms/form/';
this.win.BuildGUI(10,40)
this.win.getCaption().appendChild(document.createTextNode(trt("Editing_of_trip")));
//Как подгрузится содержимое выполниться данная функция для настройки по средством JS
var func=function(thiz)
{
return function()
{
setCalendar('trip_date_start','trip_date_start_s');
//кнопка выбора файла
var btn=document.getElementById('e_trip_btn_select_file');
var doc=getIframeDocument(thiz.iframe)
var inp=document.getElementById('trip_file_name');
btn.onclick=function(doc){return function(){doc.forms["form"].elements["file"].click()}}(doc);
//Настраиваю форму
doc.forms["form"].elements["file"].onchange = function(inp) {return function(){inp.value=this.files[0].name;/*this.value;*/};}(inp);
thiz.iframe.onload=function(inp,obj){return function()
{ doc=getIframeDocument(this)
if(BeforeFirst(doc.body.innerHTML,'=')=='ok')
{
inp.value=BeforeFirst(AfterFirst(doc.body.innerHTML,'='),"\n")
if(inp.value!='') obj.sendData()
}
}}(inp,thiz);
//Кнопка скачать файл
var btn=document.getElementById('e_trip_btn_download_file');
btn.onclick=function(name){return function(){ window.open('/monitoring/pscripts/trips.php?fn=5&fname='+name, '_blank'); }}(document.getElementById('e_trip_file_name').value)
//Кнопка удаления файла
var btn=document.getElementById('e_trip_btn_delete_file');
btn.onclick=function(inp,ifr){return function(){ inp.value=''; getIframeDocument(ifr).forms["form"].reset(); }}(inp,thiz.iframe)
thiz.win.setCenter();
}
};
this.win.load("/monitoring/pscripts/trips.php?fn=2",settings,func(this));
this.win.setSize("750px","200px");
//win.setCenter();
this.win.obj=this;
//this.win.Hide(false)
this.win.setCenter();
}
//Удалить маршрут
deleteTrip(settings)
{
if (typeof settings === 'string' || settings instanceof String)
{
try {
settings = JSON.parse(settings);
} catch (e) {
alert(e.message);
return;
}
}
if (confirm(trt("Do_you_really_want_to_delete_the_record")+'?')) {
var req=createRequestObject();
req.onreadystatechange = function(thiz)
{
return function(){
if(req.readyState === 4){
var data=null;
try {
data = JSON.parse(req.responseText);
} catch (e) {
alert(e.message);
return;
}
if(data!=null)
{
if(data.errorMessage !== undefined && data.errorMessage!='')
{
alert(data.errorMessage);
thiz.win.hideProgressBar();
}else
{
}
}
//Фильтрую список заново
thiz.filtering();
}
};
}(this);
req.open("POST", '/monitoring/pscripts/trips.php?fn=1', true);
req.setRequestHeader("Content-type", "text/plain");
req.send(JSON.stringify(settings));
this.filtering();
}
return true;
}
saveTrip()
{
//Отправляю файлик дожидаюсь загрузки потом отправляю данные
this.win.showProgressBar();
var doc=getIframeDocument(this.iframe);
if(doc.forms["form"].elements["file"].value!='') //Отправляем файла
{
doc.forms["form"].submit();
}else //Отправляем без файла
{
this.sendData();
}
}
sendData()
{
//Считываю значения с полей и отправляю на сервер
var json='{';
if(document.getElementById('e_trip_id').value=='') json+='"id":null,';
else json+='"id":'+document.getElementById('e_trip_id').value+',';
if(document.getElementById('e_trip_type_id').value=='') json+='"trip_type_id":null,';
else json+='"trip_type_id":'+document.getElementById('e_trip_type_id').value+',';
if(document.getElementById('e_trip_route_id').value=='') json+='"route_id":null,';
else json+='"route_id":'+document.getElementById('e_trip_route_id').value+',';
if(document.getElementById('e_trip_direction').value=='') json+='"direction":null,';
else json+='"direction":'+document.getElementById('e_trip_direction').value+',';
if(document.getElementById('e_trip_carrier_id').value=='') json+='"carrier_id":null,';
else json+='"carrier_id":'+document.getElementById('e_trip_carrier_id').value+',';
if(document.getElementById('e_trip_object_id').value=='') json+='"object_id":null,';
else json+='"object_id":'+document.getElementById('e_trip_object_id').value+',';
if(document.getElementById('e_trip_date_start').value=='') json+='"date_start":null,';
else json+='"date_start":"'+document.getElementById('e_trip_date_start').value+'",';
if(document.getElementById('e_trip_passenger').value=='') json+='"passenger":null,';
else json+='"passenger":"'+document.getElementById('e_trip_passenger').value+'",';
if(document.getElementById('e_trip_file_name').value=='') json+='"file_name":null,';
else json+='"file_name":"'+document.getElementById('e_trip_file_name').value+'",';
if(document.getElementById('e_trip_description').value=='') json+='"description":null';
else json+='"description":"'+document.getElementById('e_trip_description').value+'"';
json+='}';
var req=createRequestObject();
req.onreadystatechange = function(thiz)
{
return function(){
if(req.readyState === 4){
var data=null;
try {
data = JSON.parse(req.responseText);
} catch (e) {
alert(e.message);
return;
}
if(data!=null)
{
if(data.errorMessage !== undefined && data.errorMessage!='')
{
alert(data.errorMessage);
thiz.win.hideProgressBar();
}else
{
thiz.win.Close();
}
}
//Фильтрую список заново
thiz.filtering();
}
};
}(this);
req.open("POST", '/monitoring/pscripts/trips.php?fn=3', true);
req.setRequestHeader("Content-type", "text/plain");
//alert(json);
req.send(json);
}
//Фильтруем объекты для заполнения в таблицу
filtering()
{
showProgressBar(document.getElementById('div_tbl_trips'));
//Выбираем рейсы текущей компании (если админ то все)
var data = {
company_id: document.getElementById('trip_company_id').value,
carrier_id: document.getElementById('trip_carrier_id').value,
route_id: document.getElementById('trip_route_id').value,
status: document.getElementById("trip_status").value
};
var req=createRequestObject();
req.onreadystatechange = function(thiz)
{
return function(){
if(req.readyState === 4){
var data=null;
try {
data = JSON.parse(req.responseText);
} catch (e) {
alert(e.message);
return;
}
if(data!=null)
{
thiz.trips = []; //Удаляю старые объекты
for(i=0;i<data.length;i++)
{
var obj = new TTrip();
obj.id=data[i].id;
obj.trip_type_name=data[i].trip_type_name;
obj.name=data[i].name;
obj.company_name=data[i].company_name;
obj.carrier_name=data[i].carrier_name;
obj.object_name=data[i].object_name;
obj.object_places=data[i].object_places;
obj.direction=data[i].direction;
obj.date_start=data[i].date_start;
obj.date_end=data[i].date_end;
obj.passenger=data[i].passenger;
obj.description=data[i].description;
obj.real_checkpoints=data[i].real_checkpoints;
obj.plan_checkpoints=data[i].plan_checkpoints;
thiz.trips.push(obj);
}
thiz.fillRezDiv(); //Обновляю отображение элементов
}
hideProgressBar(document.getElementById('div_tbl_trips'));
}
};
}(this);
req.open("POST", '/monitoring/pscripts/trips.php?fn=0', true);
req.setRequestHeader("Content-type", "text/plain");
req.send(JSON.stringify(data));
}
//Заполнить результатом выборки DIV в виде таблицы
fillRezDiv()
{
var div=document.getElementById("div_tbl_trips");
delChild(div);
div.innerHTML='<table id="thetable_trips" class="SShow"><thead><tr><th> </th><th title="">Дата/время отправления ('+trt('plan')+')</th><th title="">Дата/время прибытия ('+trt('plan')+')</th><th>'+trt('Route')+'</th><th title="">'+trt('Direction')+'</th><th title="">Автовокзал</th><th title="">Перевозчик</th><th title="">Автобус</th><th title=""></th></tr></thead><tbody></tbody></table>';
var theTable = document.getElementById('thetable_trips');
for(i=0;i<this.trips.length;i++)
{
let tr = document.createElement('tr');
let bgColor='';
if (i%2==0) bgColor='var(--row-color-1)'; else bgColor='var(--row-color-2)';
tr.style.backgroundColor=bgColor;
tr.onmouseover=function(){this.style.backgroundColor='var(--btn-color2)';};
tr.onmouseout=function(val1,val2){return function(){val1.style.backgroundColor=val2;}}(tr,bgColor);
var td=null;
td = document.createElement('td');
td.style.cssText="width:24px;text-align:center;vertical-align:top;";
td.innerHTML='<img id="trip_down_btn_'+this.trips[i].id+'" src="/resources/images/right.png" alt="" style="cursor: pointer;">';
tr.appendChild(td);
td = document.createElement('td');
td.innerHTML=this.trips[i].date_start;
tr.appendChild(td);
td = document.createElement('td');
td.innerHTML=this.trips[i].date_end;
tr.appendChild(td);
td = document.createElement('td');
td.innerHTML=this.trips[i].name;
tr.appendChild(td);
td = document.createElement('td');
if(this.trips[i].direction) td.innerHTML=trt('Direct'); else td.innerHTML=trt('Back');
tr.appendChild(td);
td = document.createElement('td');
td.innerHTML=this.trips[i].company_name;
tr.appendChild(td);
td = document.createElement('td');
td.innerHTML=this.trips[i].carrier_name;
tr.appendChild(td);
td = document.createElement('td');
if(this.trips[i].object_name!=null)
td.appendChild(document.createTextNode(this.trips[i].object_name));
tr.appendChild(td);
/*td = document.createElement('td');
td.style.cssText="vertical-align:top;";
td.innerHTML='<img id="trip_edit_'+this.trips[i].id+'" src="/resources/images/edit24.png" alt="'+trt('Edit')+'" style="cursor:pointer;">';
tr.appendChild(td);*/
theTable.tBodies[0].appendChild(tr);
//Формирую раскрывающийся список
tr = document.createElement('tr');
tr.id=this.trips[i].id;
tr.style.cssText="background-color:var(--back-color-3);display:none";
td = document.createElement('td');
td.colSpan=8;
var html='<table style="width:100%;"><tr><td style="width:100%;border: 0;">';
if(this.trips[i].trip_type_name!=null)
html+='<b>'+trt('Trip_type')+'</b>: '+this.trips[i].trip_type_name+'<br>';
if(this.trips[i].passenger!=null)
{
html+='<b>'+trt('Passengers')+'</b>: '+this.trips[i].passenger;
if(this.trips[i].passenger!=null) html+=' из '+this.trips[i].object_places;
html+='<br>';
}
if(this.trips[i].description!=null)
html+='<b>'+trt('Additional_Information')+'</b>: '+this.trips[i].description+'<br>';
if(this.trips[i].real_checkpoints!=null)
html+='<b>'+'Пройдено контрольных точек'+'</b>: '+this.trips[i].real_checkpoints+' из '+this.trips[i].plan_checkpoints+'<br>';
html+='</td><td valign="top" style="border: 0;"><img id="trip_del_'+this.trips[i].id+'" src="/resources/images/del24.png" alt="'+trt('Delete')+'" title="'+trt('Delete')+'" style="cursor:pointer;"></td><td valign="top" style="border: 0;"><img id="trip_edit_'+this.trips[i].id+'" src="/resources/images/edit24.png" alt="'+trt('Edit')+'" title="'+trt('Edit')+'" style="cursor:pointer;"></td></tr></table>';
td.innerHTML=html;
tr.appendChild(td);
theTable.tBodies[0].appendChild(tr);
//Кнопка разсрыть список
var btn=document.getElementById('trip_down_btn_'+this.trips[i].id);
btn.onclick=function(tr,thiz,id){ return function(){
var btn=document.getElementById('trip_down_btn_'+id);
if(btn.src.indexOf("right.png")!=-1)
{
btn.src = '/resources/images/down.png';
//alert('Показать = '+tr+' = '+tr.style.display);
tr.style.display = 'table-row';
}else if(btn.src.indexOf("down.png")!=-1)
{
btn.src = '/resources/images/right.png';
//alert('Скрыть = '+tr+' = '+tr.style.display);
tr.style.display = 'none';
}
}; }(tr,this,this.trips[i].id);
//Кнопка редактировать
var btn=document.getElementById('trip_edit_'+this.trips[i].id)
btn.onclick=function(thiz,id){ return function(){ thiz.editTrip({id:id}); }; }(this,this.trips[i].id);
//Кнопка удалить
btn=document.getElementById('trip_del_'+this.trips[i].id)
btn.onclick=function(thiz,id){ return function(){ thiz.deleteTrip({id:id}); }; }(this,this.trips[i].id);
}
//Количество элементов в дереве
var divCnt = document.getElementById("count_trips");
delChild(divCnt);
divCnt.appendChild(document.createTextNode(this.trips.length));
}
}
class TTrip
{
constrictor(){
this.id=null;
}
}

View File

@ -0,0 +1,600 @@
class TUser //Current user with role name and access
{
constructor() {
//this.name="TUser"; //User name
this.company_id = null;
this.win = null;
this.access = {}; //Associative array
this.onUpdate = null; //Listener update access array
this.timezone = ""; // +06:00:00 временая зона текущего пользователя
this.checkSession();
}
loadAccess() {
let xs = '<?xml version="1.0" encoding="utf-8"?>\n\
<metadata fn="4">\n\
<type n="SysAccessList" pp="-1">\n\
<objects-list><filter></filter></objects-list>\n\
</type>\n\
</metadata>';
var request = new TRequest(this);
if (request.callServer(ScriptName, xs)) {
//m_winPP.showProgressBar();
}
}
applyReq(req, fn, node) {
if (fn == -1) {
alert2(trt("Alert"),findFirstNode(node, '#cdata-section').nodeValue);
} else if (fn == 4) {
var nodeType = findFirstNode(node, "type");
if (nodeType != null) {
if (nodeType.getAttribute("n") == "_ChangePassword") {
if (findFirstNode(node, '#cdata-section').nodeValue == 't') {
alert2(trt("Alert"),trt('Password_changed_successfully'));
//this.win.hideProgressBar();
this.win.Close();
this.win = null;
} else {
alert2(trt("Alert"),trt('Failed_to_change_password') + '\n' + trt('Check_the_entered_data'));
this.win.hideProgressBar();
}
} else {
this.updateAccess(node);
}
}
} else if (fn == 7) {
var nCmd = findFirstNode(node, "cmd");
if (nCmd != null) {
if (findFirstNode(nCmd, '#cdata-section').nodeValue == "1") //Logout
{
location.reload();
} else if (findFirstNode(nCmd, '#cdata-section').nodeValue == "2") //Check if user not logged
{
if (findNode(node, '#cdata-section').nodeValue == "0") //if not logged
{
this.showLoginForm();
} else {
this.name = getCdataValue(findNode(node, 'name'));
this.company_id = getCdataValue(findNode(node, 'company_id'));
//alert2(trt("Alert"),'this.company_id = '+this.company_id);
configGUIbyAccessLevel();
//var shadow=document.getElementById("shadow");
//if(shadow.parentNode!=null) shadow.parentNode.removeChild(shadow);
g_trips.filtering();
g_geofences.filtering();
g_objects.filtering();
g_routes.filtering();
g_detours.filtering();
}
} else if (findFirstNode(nCmd, '#cdata-section').nodeValue == "3") //Login
{
if (findNode(node, '#cdata-section').nodeValue == "0") //if not logged
{
alert2(trt("Alert"),trt('Invalid_username_and_or_password'));
} else {
location.reload();
}
} else if (findFirstNode(nCmd, '#cdata-section').nodeValue == "4") //Register
{
if (findNode(node, '#cdata-section').nodeValue == "1") //if register
{
alert2(trt("Alert"),trt('New_user_is_registered') + '\n' + trt('The_password_has_been_sent_to_you_by_Email'));
location.reload();
}
}
}
} else {
alert2(trt("Alert"),"Unknown function! fn=\"" + fn + "\"");
}
if (this.win != null) this.win.hideProgressBar();
}
updateAccess(node) {
this.access = {};
var nodeType = findFirstNode(node, "type");
var nodeRecord = nodeType.firstChild;
while (nodeRecord != null) {
if (nodeRecord.nodeName == "record") {
var key = '';
var val = '';
i = 0; //column number
var cdataNode = nodeRecord.firstChild;
while (cdataNode != null) {
if (cdataNode.nodeName == "#cdata-section") {
if (i == 0) key = cdataNode.nodeValue;
if (i == 1) val = cdataNode.nodeValue;
i++;
}
cdataNode = cdataNode.nextSibling;
}
if (val == 'f' || val == 0 || val == 'false') val = false;
else if (val = 't' || val == 1 || val == 'true') val = true;
else val = null;
this.access[key] = val;
}
nodeRecord = nodeRecord.nextSibling;
}
if (this.onUpdate != null) this.onUpdate(this);
return true;
}
getAccess(name) {
var rez = this.access[name];
if (rez === undefined) {
alert2(trt("Alert"),'Access key "' + name + '" not found!');
return false;
}
if (rez != true) return false;
return rez;
};
changePassword() {
this.win = new TWin();
this.win.BuildGUI(10, 10);
this.win.setCaption(trt('Change_password'));
let str = '<div style="width: 100%; height: 100%; padding: 3px; text-align: left;">\n\
<table border="0" cellpadding="0" cellspacing="0" style="width: 100%; height: 100%;">\n\
<tbody>\n\
<tr><td>\n\
<table border="0" style="width: 100%; height: 100%;">\n\
<tr>\n\
<td style="padding: 2px; width: 30%; white-space: nowrap"><b>' + trt('Login') + ' (email):</b></td>\n\
<td style="padding: 2px;"><input type="text" maxlength="50" style="width: 100%; padding: 2px; display: inline;" id="id_ch_login" name="login"><br></td>\n\
</tr>\n\
<tr>\n\
<td style="padding: 2px;"><b>' + trt('Old_password') + ':</b></td>\n\
<td style="padding: 2px;"><input type="password" maxlength="33" style="width: 100%; padding: 2px; display: inline;" id="id_ch_oldpassword" name="password"><br></td>\n\
</tr>\n\
<tr>\n\
<td style="padding: 2px;"><b>' + trt('New_password') + ':</b></td>\n\
<td style="padding: 2px;"><input type="password" maxlength="33" style="width: 100%; padding: 2px; display: inline;" id="id_ch_newpassword" name="password"><br></td>\n\
</tr>\n\
<tr>\n\
<td style="padding: 2px;"><b>' + trt('Repeat_password') + ':</b></td>\n\
<td style="padding: 2px;"><input type="password" maxlength="33" style="width: 100%; padding: 2px; display: inline;" id="id_ch_newrpassword" name="password"><br></td>\n\
</tr>\n\
<tr><td colspan="2" style="text-align: right;"><input class="button-secondary" id="id_change_pass" type="button" style="display: inline;" value="' + trt('Apply') + '"><input class="button-secondary" id="exit_pass_' + this.win.uid + '" type="button" style="display: inline;" value="' + trt('Cancel') + '"></td></tr>\n\
</table>\n\
</td></tr>\n\
</tbody>\n\
</table>\n\
</div>';
this.win.setContent(str);
this.win.setSize("500px", "180px");
this.win.setCenter();
this.win.shadow = true;
this.win.hide(false);
document.getElementById('id_change_pass').onclick = function (thiz) {
return function () {
let data = {
email: document.getElementById('id_ch_login').value,
password: document.getElementById('id_ch_oldpassword').value,
new_password: document.getElementById('id_ch_newpassword').value,
repeat_new_password: document.getElementById('id_ch_newrpassword').value
};
if (data.email == '') {
document.getElementById('id_ch_login').select();
alert2(trt("Alert"),trt('Not_filled_Email_address'));
return;
}
if (!isEmail(data.email)) {
alert2(trt("Alert"),sprintf(trt('The_s_is_not_Email'), data.email));
return;
}
if (data.new_password != data.repeat_new_password) {
alert2(trt("Alert"),trt('Passwords_did_not_match'));
return;
}
thiz.win.showProgressBar();
$.ajax({
url: "/monitoring/pscripts/user.php?fn=3",
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(data),
success: function (win) {
return function (response, status) {
if (status == 'success') {
if (response.errorCode == '0') {
alert2(trt("Alert"),trt('Password_changed_successfully'));
} else {
alert2(trt("Alert"),response.errorMessage);
}
} else {
alert2(trt("Alert"),status);
}
win.hideProgressBar();
}
}(thiz.win)
});
};
}(this);
document.getElementById('exit_pass_' + this.win.uid).onclick = function (win) {
return function () {
win.Close();
};
}(this.win);
}
//logout current user
Logout() {
let xs = '<?xml version="1.0" encoding="utf-8"?><metadata fn="7"><cmd><![CDATA[1]]></cmd></metadata>';
var request = new TRequest(this);
if (request.callServer(ScriptName, xs)) {
//m_winPP.showProgressBar();
}
}
//Display login and registration form
showLoginForm() {
if (this.win == null || this.win.closed) {
this.win = new TWin(true);
this.win.disableClosing = true;
this.win.BuildGUI(10, 10);
this.win.setCaption(trt('Authorization') + ' / ' + trt('Registration'));
this.win.setSize("350px", "150px");
/*let str='<div style="width: 100%; height: 100%; padding: 3px; text-align: left;">\n\
<table border="0" cellpadding="0" cellspacing="0" style="width: 100%; height: 100%;">\n\
<tbody>\n\
<tr><td>\n\
<table border="0" style="width: 100%; height: 100%;">\n\
<tr>\n\
<td style="padding: 2px; width: 30%; white-space: nowrap"><b>'+trt('Login')+' (email):</b></td>\n\
<td style="padding: 2px;"><input type="text" maxlength="50" style="width: 100%; padding: 2px; display: inline;" id="login0" name="login"><br></td>\n\
</tr>\n\
<tr>\n\
<td style="padding: 2px;"><b>'+trt('Password')+':</b></td>\n\
<td style="padding: 2px;"><input type="password" maxlength="33" style="width: 100%; padding: 2px; display: inline;" id="password0" name="password"><br></td>\n\
</tr>\n\
<tr>\n\
<td style="padding: 2px;" colspan="2"><table cellspacing="0" cellpadding="0" border="0" style="width: 100%;"><tr><td><!--label for="save0" style="white-space: nowrap;"><input id="save0" type="checkbox" style="display: inline;" checked/>&nbsp;'+trt('Remember')+'&nbsp;(--><a href="#" onclick="showRestoreForm();">'+trt('Password_recovery')+'</a><!--)</label>--></td></tr></table></td>\n\
</tr>\n\
<tr><td colspan="2" style="text-align: right;"><input class="button-secondary" id="'+this.win.uid+'_login" type="button" style="display: inline;" value="'+trt('Log_in')+'"></td></tr>\n\
</table>\n\
</td></tr>\n\
</tbody>\n\
</table>\n\
</div>';
this.win.setContent(str);*/
let str;
var tab = new tcTabs(document.getElementById('TWin_Co_' + this.win.tWinId));
tb = tab.addTab({caption: trt('Authorization')});
str = '<div style="width: 100%; height: 100%; padding: 3px; text-align: left;">\n\
<table border="0" cellpadding="0" cellspacing="0" style="width: 100%; height: 100%;">\n\
<tbody>\n\
<tr><td>\n\
<table border="0" style="width: 100%; height: 100%;">\n\
<tr>\n\
<td style="padding: 2px; width: 30%; white-space: nowrap"><b>' + trt('Login') + ' (' + trt('E_mail') + '):</b></td>\n\
<td style="padding: 2px;"><input type="text" maxlength="50" style="width: 100%; padding: 2px; display: inline;" id="login0" name="login"><br></td>\n\
</tr>\n\
<tr>\n\
<td style="padding: 2px;"><b>' + trt('Password') + ':</b></td>\n\
<td style="padding: 2px;"><input type="password" maxlength="33" style="width: 100%; padding: 2px; display: inline;" id="password0" name="password"><br></td>\n\
</tr>\n\
<tr>\n\
<td style="padding: 2px;" colspan="2"><table cellspacing="0" cellpadding="0" border="0" style="width: 100%;"><tr><td><label for="save0" style="white-space: nowrap;"><input id="save0" type="checkbox" style="display: inline;" checked/>&nbsp;' + trt('Remember') + '&nbsp;</label>(<a href="#" id="' + this.win.uid + '_restore">' + trt('Forgot_your_password') + '</a>)</td></tr></table></td>\n\
</tr>\n\
<tr><td colspan="2" style="text-align: right;"><input class="button-secondary" id="' + this.win.uid + '_login" type="button" style="display: inline;" value="' + trt('Log_in') + '"></td></tr>\n\
</table>\n\
</td></tr>\n\
</tbody>\n\
</table>\n\
</div>';
tb.setConText(str);
tb.setSel();
tb = tab.addTab({caption: trt('Registration')});
str = '<div style="width: 100%; height: 100%; padding: 3px; text-align: left;">\n\
<form action="./?path=f1;0;" id="create_order_form" method="post" name="create_order_form">\n\
<input type="hidden" name="fn" value="2">\n\
<table border="0" cellpadding="0" cellspacing="0" style="width: 100%; height: 100%;">\n\
<tbody>\n\
<tr><td style="padding: 2px;">' + trt('Surname') + '</td><td style="padding: 2px;"><input type="text" maxlength="50" style="width: 100%; display: inline;" id="' + this.win.uid + '_lastname" value=""></td></tr>\n\
<tr><td style="padding: 2px;"><strong>' + trt('Name') + ' *</strong></td><td style="padding: 2px;"><input type="text" maxlength="50" style="width: 100%; display: inline;" id="' + this.win.uid + '_firstname" value=""></td></tr>\n\
<tr><td style="padding: 2px;">' + trt('Company') + ' </td><td style="padding: 2px;"><input type="text" maxlength="255" style="width: 100%; display: inline;" id="' + this.win.uid + '_company" value=""></td></tr>\n\
<tr><td style="padding: 2px;">' + trt('Position') + ' </td><td style="padding: 2px;"><input type="text" maxlength="255" style="width: 100%; display: inline;" id="' + this.win.uid + '_position" value=""></td></tr>\n\
<tr><td style="padding: 2px;">' + trt('Phone') + ' </td><td style="padding: 2px;"><input type="text" maxlength="50" style="width: 100%; display: inline;" id="' + this.win.uid + '_phone" value=""></td></tr>\n\
<tr><td style="padding: 2px;"><strong>' + trt('E_mail') + ' *</strong></td><td style="padding: 2px;"><input type="text" maxlength="50" style="width: 100%; display: inline;" id="' + this.win.uid + '_email" value=""></td></tr>\n\
<tr><td colspan="2" style="padding: 2px;"><b>' + trt('Enter_the_numbers_from_the_image') + ' *</b></td></tr>\n\
<tr><td style="padding: 2px;"><img id="l_img" src="/resources/metadata/include/captcha.php?id=1" alt="' + trt('Security_Code') + '" /></td><td style="padding: 2px;"><input type="text" maxlength="5" style="width: 100%; display: inline;" id="' + this.win.uid + '_captcha" name="captcha"><br><a href="#" style="white-space: nowrap" onclick="document.getElementById(\'l_img\').src = \'/resources/metadata/include/captcha.php?id=2&time=' + (new Date()).getTime() + '\'">&#x21bb; ' + trt('Another_picture') + '</a></td></tr>\n\
<tr><td colspan="2" style="text-align: right;"><input class="button-secondary" id="' + this.win.uid + '_registration" type="button" style="display: inline;" value="' + trt('Registration') + '"></td></tr>\n\
</tbody>\n\
</table>\n\
</form>\n\
</div>';
tb.setConText(str);
//tb.setSel()
//Center the window and display the shadow
this.win.setCenter();
this.win.shadow = true;
this.win.hide(false);
//Clicking on the button login
var obj = null;
obj = document.getElementById(this.win.uid + '_login');
if (obj !== null) {
obj.onclick = function (thiz) {
return function () {
let login=document.getElementById('login0').value;
let password=document.getElementById('password0').value;
if(login==''){ alert2(trt("Alert"),trt('Please_fill_in_the_login_field')); return; }
if(password==''){ alert2(trt("Alert"),trt('Please_fill_in_the_password_field')); return; }
let xs = '<?xml version="1.0" encoding="utf-8"?>\
<metadata fn="7">\
<cmd><![CDATA[3]]></cmd>\n\
<login><![CDATA[' + login + ']]></login>\
<password><![CDATA[' + password + ']]></password>\
</metadata>';
let request = new TRequest(thiz);
if (request.callServer(ScriptName, xs)) {
thiz.win.showProgressBar();
}
};
}(this);
}
//Щелчёк по нажатию Enter
obj = document.getElementById('password0');
if (obj != null) {
obj.onkeypress = function (thiz) {
return function (e) {
if (e.keyCode == 13) {
let xs = '<?xml version="1.0" encoding="utf-8"?>\
<metadata fn="7">\
<cmd><![CDATA[3]]></cmd>\n\
<login><![CDATA[' + document.getElementById('login0').value + ']]></login>\
<password><![CDATA[' + document.getElementById('password0').value + ']]></password>\
</metadata>';
let request = new TRequest(thiz);
if (request.callServer(ScriptName, xs)) {
thiz.win.showProgressBar();
}
}
};
}(this);
}
//Регистрация нового пользователя и компании
obj = document.getElementById(this.win.uid + '_registration');
if (obj !== null) {
obj.onclick = function (thiz) {
return function () {
//showProgressBar(document.getElementById('TWin_Co_'+thiz.win.tWinId),thiz.win.uid);
let data = {
lastname: document.getElementById(thiz.win.uid + '_lastname').value,
firstname: document.getElementById(thiz.win.uid + '_firstname').value,
company: document.getElementById(thiz.win.uid + '_company').value,
position: document.getElementById(thiz.win.uid + '_position').value,
phone: document.getElementById(thiz.win.uid + '_phone').value,
email: document.getElementById(thiz.win.uid + '_email').value,
captcha: document.getElementById(thiz.win.uid + '_captcha').value
};
//Check for completeness of the fields
if (data.firstname == '') {
document.getElementById(thiz.win.uid + '_firstname').select();
alert2(trt("Alert"),sprintf(trt('The_s_field_is_empty'), trt('Name')));
return;
}
if (data.email == '') {
document.getElementById(thiz.win.uid + '_email').select();
alert2(trt("Alert"),sprintf(trt('The_s_field_is_empty'), trt('Email')));
return;
}
if (!isEmail(data.email)) {
document.getElementById(thiz.win.uid + '_email').select();
alert2(trt("Alert"),trt('Please_enter_a_valid_email_address'));
return;
}
thiz.win.showProgressBar();
$.ajax({
url: "/monitoring/pscripts/user.php?fn=1",
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(data),
success: function (win) {
return function (response, status) {
if (status == 'success') {
if (response.errorCode == '0') {
alert2(trt("Alert"),trt('New_user_is_registered') + '\n' + trt('The_password_has_been_sent_to_you_by_Email'));
} else {
alert2(trt("Alert"),response.errorMessage);
}
} else {
alert2(trt("Alert"),status);
}
win.hideProgressBar();
}
}(thiz.win)
});
};
}(this);
}
obj = document.getElementById(this.win.uid + '_restore');
if (obj !== null) {
obj.onclick = function (thiz) {
return function () {
thiz.showRestoreForm();
};
}(this);
}
}
/*
log.bind(this, 'Hello world')
let user = {
firstName: "Вася"
};
function func() {
alert2(trt("Alert"),this.firstName);
}
let funcUser = func.bind(user);
funcUser(); // Вася
*/
/*var field1=document.getElementById("lang_1");
if(field1!=null)
{
field1.value=getURLParam("lng");
}
var field2=document.getElementById("lang_2");
if(field2!=null)
{
field2.value=getURLParam("lng");
}*/
}
//Display password recovery form
showRestoreForm() {
let win = new TWin(true);
win.BuildGUI(10, 10);
win.setCaption(trt("Password_recovery"));
let str = '<div id="TWin_DT_' + win.tWinId + '" style="width: 100%; height: 100%; padding: 4px; text-align: left;">\n\
<table border="0" cellpadding="0" cellspacing="0" style="width: 100%; height: 100%; padding: 0px;">\n\
<tr>\n\
<td style="padding: 2px; white-space: nowrap"><b>' + trt('Login') + ' (E-mail):</b></td>\n\
<td style="padding: 2px;"><input type="text" maxlength="40" style="width: 100%; display: inline;" id="' + win.uid + '_email" name="login"></td>\n\
</tr>\n\
<tr>\n\
<td colspan="2" style="padding: 2px;"><b>' + trt('Enter_the_numbers_from_the_image') + ' *</b></td>\n\
</tr>\n\
<tr>\n\
<td style="width: 10px; padding: 2px;"><img id="r_img" src="/resources/metadata/include/captcha.php?id=2" alt="' + trt('Security_Code') + '" /></td>\n\
<td style="padding: 2px;"><input type="text" maxlength="5" style="width: 100%; display: inline;" id="' + win.uid + '_captcha" name="captcha"><br><a href="#" style="white-space: nowrap" onclick="document.getElementById(\'r_img\').src = \'/resources/metadata/include/captcha.php?id=2&time=\'+(new Date()).getTime()">&#x21bb; ' + trt('Another_picture') + '</a></td>\n\
</tr>\n\
<tr><td colspan="2" style="text-align: right; padding: 2px;"><input class="button-secondary" id="' + win.uid + '_restore" type="button" style="display: inline;" value="' + trt('Restore') + '"></td></tr>\n\
</table>\n\
</td></tr>\n\
</div>';
document.getElementById('TWin_Co_' + win.tWinId).innerHTML = str;
win.setSize("300px", "170px");
//Центрируем окно и отображаем тень
if (win.tbl.offsetHeight > win.div.offsetHeight) win.div.style.height = win.tbl.offsetHeight + "px";
if (win.tbl.offsetWidth > win.div.offsetWidth) win.div.style.width = win.tbl.offsetWidth + "px";
win.setCenter();
win.shadow = true;
win.hide(false);
//Click on restore button
var obj = null;
obj = document.getElementById(win.uid + '_restore');
if (obj != null) {
obj.onclick = function (win) {
return function () {
let data = {
email: document.getElementById(win.uid + '_email').value,
captcha: document.getElementById(win.uid + '_captcha').value
};
if (data.email == '') {
document.getElementById(win.uid + '_email').select();
alert2(trt("Alert"),trt('Not_filled_Email_address'));
return;
}
if (!isEmail(data.email)) {
document.getElementById(win.uid + '_email').select();
alert2(trt("Alert"),trt('Please_enter_a_valid_email_address'));
return;
}
win.showProgressBar();
$.ajax({
url: "/monitoring/pscripts/user.php?fn=2",
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(data),
success: function (win) {
return function (response, status) {
if (status == 'success') {
if (response.errorCode == '0') {
alert2(trt("Alert"),trt('A_new_password_has_been_sent_to_your_email') + '.');
} else {
alert2(trt("Alert"),response.errorMessage);
}
} else {
alert2(trt("Alert"),status);
}
win.hideProgressBar();
}
}(win)
});
};
}(win);
}
}
//Check whether the already authorized (+ attempt to log in through "hash").
isLogined() {
let xs = '<?xml version="1.0" encoding="utf-8"?><metadata fn="7"><cmd><![CDATA[2]]></cmd></metadata>';
//var xs='{"fn":7,"cmd":2}';
let request = new TRequest(this);
if (request.callServer(ScriptName, xs)) {
//m_winPP.showProgressBar();
}
};
//Checking the session without its extension, if it is completed, we display the authorization window.
checkSession() {
let jqxhr = $.getJSON('./session.php', {}, function (thiz) {
return function (data) {
if (data.result == 'ERROR') {
thiz.showLoginForm();
}
divsh.style.display = 'none';
};
}(this));
jqxhr.fail(function () {
divsh.style.display = 'block';
});
setTimeout(function (thiz) {
return function () {
thiz.checkSession();
};
}(this), 10000);
}
}