Skip to content

Instantly share code, notes, and snippets.

@pavelpower
Last active April 14, 2016 14:58
Show Gist options
  • Save pavelpower/5e880c53f98391951ce7c280927ba8c5 to your computer and use it in GitHub Desktop.
Save pavelpower/5e880c53f98391951ce7c280927ba8c5 to your computer and use it in GitHub Desktop.
updater lot in table for Artur
function Test () {
// cache table
var $table = $('#tbody-lots');
var INTERVAL_FOR_UPDATE_LOT = 1000;
var INTERVAL_FOR_GET_SERVER_TIME = 60 * 1000;
this.defaults = {
mode: 'member',
syncUrl: window.realEndTimeSyncUrl + '/' + window.auctionId,
syncLotsUrl: window.realLotEndTimeSyncUrl + '/' + window.auctionId,
durationMode: window.durationMode ? window.durationMode : 'none',
syncInterval: 60000,
processLotsSelector: "#lots-table tr[id]:not(.lot-disable)",
serverTimeSelector: "#server-clock",
remainingTimeSelector: "#auction-end-clock, .auction-end-clock ",
remainingTimeLotSelector: '#lot-end-clock-',
lotStatusSelector: '#lot-status-',
lotStatusActiveText: 'Аукцион по позиции продолжается',
lotStatusStopText: 'Аукцион по позиции завершен'
};
this._timerOfUpdateLot = null;
this._timerOfGetServerTime = null;
this.options = {};
this.init = function () {
Date.now = Date.now || function () { return +new Date; };
window.sc = this;
options = options || {};
this.options = $.extend(this.defaults, options);
if (this.options.mode == 'org') {
$('#bootstrap_alert').appendAlert(this.options.message + '<span class="auction-end-clock"></span>)', 'warning');
}
this.$serverTimeElement = $(this.options.serverTimeSelector);
this.$remainingTimeElement = $(this.options.remainingTimeSelector);
this.getServerTime();
this.initTimerGetServerTime();
this.updateServerAndRemainderTime();
if (this.options.durationMode == 'ProlongationByLots') {
this.disableLots();
}
};
this.stopTimerGetServerTime = function () {
clearTimeout(this._timerOfGetServerTime);
};
this.initTimerGetServerTime = function () {
var self = this;
this._timerOfGetServerTime = setTimeout(function () {
self.getServerTime();
self.initTimerGetServerTime();
}, INTERVAL_FOR_GET_SERVER_TIME);
};
this.stopTimerUpdateLot = function () {
clearTimeout(this._timerOfUpdateLot);
};
// рекурсивный вызов таймера обноления лотов в таблице
// TODO: это просто нужно обновлять время на секунду
this.updateServerAndRemainderTime = function () {
var self = this,
start = getTimestamp(),
timeout = INTERVAL_FOR_UPDATE_LOT;
var instance = function () {
var diff = (getTimestamp() - start - timeout);
var cnt = Math.floor(diff / timeout);
if (self.serverTime) {
self.serverTime.setSeconds(self.serverTime.getSeconds() + cnt + 1);
}
self.showServerTime();
if (self.$remainingTimeElement.length > 0) {
self.remainingTime = addSeconds(self.remainingTime, 0 - (cnt + 1));
// TODO вынести вызов нового запроса в событие завершения Аукциона
if (self.auctionIsEnd()) {
self.getServerTime();
}
self.showRemainingTime();
self.updateLots(remainingTime);
}
diff = diff - timeout * cnt;
start = getTimestamp() - diff;
self._timerOfUpdateLot = setTimeout(instance, (timeout - diff));
};
self._timerOfUpdateLot = setTimeout(instance, INTERVAL_FOR_UPDATE_LOT);
};
this.auctionIsEnd = function (remainingTime) {
var _remainingTime = remainingTime || this.remainingTime;
return _remainingTime.Hours == 0
&& _remainingTime.Minutes == 0
&& _remainingTime.Seconds == 0;
};
this.actionIsOn = function (remainingTime) {
var _remainingTime = remainingTime || this.remainingTime;
return _remainingTime.Hours >= 0
&& _remainingTime.Minutes >= 0
&& _remainingTime.Seconds >= 0
};
function getTimestamp () {
return new Date().getTime();
}
this.getServerTime = function () {
var self = this;
var beginGetDate = getTimestamp();
$.get(self.options.syncUrl + '?' + Date.now())
.done(function (response) {
var diffGetDate;
// response.endTimeSpan != 0; !=false; !=undefined
if ($.type(response) !== 'object' || !response.endTimeSpan) {
self.serverResponseFail();
return;
}
diffGetDate = Math.floor((getTimestamp() - beginGetDate) / 2);
self.remainingTime = addSeconds(response.endTimeSpan, Math.round(diffGetDate / 1000));
if (self.auctionIsEnd()) {
// TODO: remove this
window.console ? console.log("mast be off") : void (0);
self.timeIsOver();
return;
}
if (response.dateTime) {
self.serverTime = new Date(
response.dateTime.Year,
response.dateTime.Month - 1,
response.dateTime.Day,
response.dateTime.Hour,
response.dateTime.Minute,
response.dateTime.Second,
response.dateTime.Millisecond + diffGetDate
);
}
self.showServerTime();
self.showRemainingTime();
/**@d {по позициям} */
if (self.options.durationMode == 'ProlongationByLots') {
self.getLotsServerTime();
}
})
.fail(this.serverResponseFail.bind(this));
};
this.serverResponseFail = function () {
try {
if (this.$serverTimeElement) {
this.$serverTimeElement.text('-');
}
else {
$(this.options.serverTimeSelector).text('-');
}
if (this.$remainingTimeElement) {
this.$remainingTimeElement.text('-')
} else {
$('#auction-end-clock, .auction-end-clock').text('-');
}
this.stopTimerUpdateLot();
//TODO: дописать метод обновления таблицы
if (this.options.durationMode == 'ProlongationByLots') {
for (var lotId in this.lotTimeIntervalIds) {
$(this.options.remainingTimeLotSelector + lotId).text("-");
$(this.options.lotStatusSelector + lotId).removeClass('icon-pending').removeClass('icon-active');
}
}
} catch (e) { }
};
this.getLotsServerTime = function () {
var self = this;
$.get(this.options.syncLotsUrl + '?' + Date.now(), function (response) {
self.setStartTime();
self.setDataOfServerTime(response);
self.updateLots();
});
};
this.setStartTime = function () {
this._startTimeForRemenderTimer = getTimestamp();
};
this.setDataOfServerTime = function (data) {
this._dataOfServerTime = data;
};
/**
* Обновляет по View лотов данные
*/
this.updateLots = function (remainingTime) {
if (!this._dataOfServerTime) {
return;
}
var i = 0,
l = this._dataOfServerTime.lotsEndTime.length,
entry = this._dataOfServerTime.lotsEndTime,
lotId,
_remainingTime;
for (; i < l; i++) {
_remainingTime = entry[i].endTime;
lotId = entry[i].lotId;
this.showLotTime(lotId, remainingTime);
if (this.auctionIsEnd()) {
this.showLotTimeIsOver(lotId);
return;
} else {
this.showLotTimeIsNotOver(lotId);
}
}
};
/**
* Функция вычесляет сколько времени прошло с последнего получения данных для лотов
* и формирует время сколько еще осталось до закрытия.
* @param remainingTime {Time}
* @returns {Time} seconds отрицательная величина
*/
this.getSecondsAfterLastRequestOfLot = function (remainingTime) {
var start, timeout, diff, cnt;
// время последнего запроса лотов
start = this._startTimeForRemenderTimer;
timeout = INTERVAL_FOR_UPDATE_LOT;
// сколько прошло времени с последнего запроса лотов
diff = (getTimestamp() - start - timeout);
// количество тиков таймера со времени последнего запроса лотов
cnt = Math.floor(diff / timeout);
// расчет прошедших секунд с последнего запроса лотов
return addSeconds(remainingTime, 0 - (cnt + 1));
};
this.showLotTimeIsOver = function (lotId) {
var $el = $('#' + lotId),
$clockElement = $(this.options.remainingTimeLotSelector + lotId),
$lotStatus = $(this.options.lotStatusSelector + lotId);
$lotStatus.removeClass('icon-pending').addClass('icon-active');
$lotStatus.find('div.tolbody').html(this.options.lotStatusStopText);
$clockElement.text('00:00');
$el.addClass('lot-disable');
$el.find('input')
.val('')
.prop('disabled', true)
.css('background-color', '#c7ced7');
};
this.showLotTimeIsNotOver = function (lotId) {
var $el = $('#' + lotId),
$clockElement = $(this.options.remainingTimeLotSelector + lotId),
$lotStatus = $(this.options.lotStatusSelector + lotId);
if ($el.hasClass('lot-disable')) {
$lotStatus.addClass('icon-pending').removeClass('icon-active');
$el.removeClass('lot-disable');
$el.find('input')
.prop('disabled', false)
.css('background-color', '#fff');
}
$clockElement.text('00:00');
};
this.showLotTime = function (lotId, remainingTime) {
var $clockElement = $(this.options.remainingTimeLotSelector + lotId),
$lotStatus = $(this.options.lotStatusSelector + lotId);
if ($clockElement.length == 0) {
return;
}
remainingTime = this.getSecondsAfterLastRequestOfLot(remainingTime);
if (this.actionIsOn(remainingTime)) {
$clockElement.html(getClockString(remainingTime.Hours, remainingTime.Minutes, remainingTime.Seconds));
$lotStatus.addClass('icon-pending');
$lotStatus.find('div.tolbody')
.html(this.options.lotStatusActiveText);
}
};
this.showServerTime = function () {
if (!this.serverTime) {
return;
}
if (this.$serverTimeElement.length == 0) {
return false;
}
this.$serverTimeElement.html(
getClockString(this.serverTime.getHours(),
this.serverTime.getMinutes(),
this.serverTime.getSeconds())
);
};
this.showRemainingTime = function () {
if (this.remainingTime) {
return;
}
if (this.$remainingTimeElement.length == 0) {
return;
}
this.$remainingTimeElement.html(
getClockString(this.remainingTime.Hours,
this.remainingTime.Minutes,
this.remainingTime.Seconds)
);
};
this.disableLots = function () {
$table.find('input').prop('disabled', true);
$table.children('tr').addClass('lot-disable');
};
this.timeIsOver = function () {
this.$remainingTimeElement.text('-');
// global value
auctionIsFinished = true;
this.stopTimerGetServerTime();
this.stopTimerUpdateLot();
if (this.options.mode == 'member') {
/*var LA = new logUserActivities;
LA.pushAction.call(this, moment().format(), "4");*/
logUserActivities.buildLogObjectAndPushToList(moment().format(), '4');
new $.modal({
submitButtonText: 'Закрыть',
cancelButtonText: false,
header: false,
content: 'Аукцион завершён',
onSubmit: function () { location.reload(false); },
onCancel: function () { location.reload(false); }
}).show();
}
else if (this.options.mode == 'org') {
$('#bootstrap_alert').empty();
}
};
function getClockString(h, m, s) {
return getSmallClockString(h, m) + ':' + addZero(s);
}
function addZero(value) {
if (value >= 0 && value <= 9) return '0' + value;
return value;
}
function getSmallClockString(h, m) {
return addZero(h) + ':' + addZero(m);
}
function addSeconds(timeSpan, s) {
var ts = timeSpan.Hours * 3600;
ts += timeSpan.Minutes * 60;
ts += timeSpan.Seconds;
ts += s;
var h = ~~(ts / 3600);
ts = ts % 3600;
var m = ~~(ts / 60);
ts = ts % 60;
timeSpan.Hours = h;
timeSpan.Minutes = m;
timeSpan.Seconds = ts;
return timeSpan;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment