!function () {
'use strict';
var posterApp = {
// todo определение фоормата даты можно вынести на бэк для контроля
initDatePickerr: function () {
[this._selector.inpDeparture, this._selector.inpArrival].forEach(i => {
if(!i.length) return
let date = i.val().trim() ? i.val() : new Date();
let startDate = null
if (window.location.href.includes("/ru/")) {
startDate = moment(date, this._data.formatDateClient, 'ru');
} else {
startDate = moment(date, this._data.formatDateClient, 'en');
}
if (!i.attr('hidden')) {
i.daterangepicker({
"autoapply": true,
"linkedCalendars": false,
"singleDatePicker": true,
"timePicker": false,
"timePicker24Hour": false,
"minDate": startDate,
"locale": changeLangForDateTimePicker(),
}, function (start, end, label) {
i.val(start.format('DD.MM.YYYY'));
});
}
i.off('mouseleave.i-disable').on('mouseleave.i-disable', e => {
i.attr('readonly', false);
i.blur();
})
i.off('mouseover.i-disable').on('mouseover.i-disable', e => {
i.attr('readonly', true);
})
i.off('focus.i-disable').on('focus.i-disable', e => {
i.blur()
})
});
},
changeCargoType: function () {
let inpTypeAvia = this._selector.typeItems.filter((d, i) => i.value === 'avia');
let inpTypePassenger = this._selector.cargoItems.filter((d, i) => i.value === 'passenger');
this._selector.cargoItems.off('change.i-disable').on('change.i-disable', (e) => {
this.handlerDisabled(e.target, inpTypeAvia, 'passenger')
})
// change other type
this.handlerDisabled(inpTypePassenger, inpTypeAvia, 'passenger')
},
handlerDisabled: function (el, el2, text) {
if ($(el).val() === text) {
$(el2).attr('disabled', true);
} else {
$(el2).attr('disabled', false);
}
},
changeTransportType: function () {
let inpTypePassenger = this._selector.cargoItems.filter((d, i) => i.value === 'passenger');
this._selector.typeItems.off('change.i-disable').on('change.i-disable', (e) => {
this.handlerDisabled(e.target, inpTypePassenger, 'avia');
})
},
createInpCoutryData: function (el, data) {
el.dataCoutry?.remove();
let template =
`
${data[2] || 'BY'}
`;
el.after(template);
el.dataCoutry = el.next('.poster__inp-country');
el.parent().addClass('is-set')
},
initHandlerItemsTowns: function (el) {
el.list.off('click.item').on('click.item', (e) => {
let target = $(e.target)
let item = target.hasClass('poster__towns-item') ? target : target.parents('.poster__towns-item')
let data = item.data('attrs')
if (!data.length) return
let [id, txt] = data;
this.createInpCoutryData(el, data);
let inpNames = {
id: 'from_city',
txt: 'from_address_point_txt',
}
if (el[0].name.match(/to/)) {
inpNames = {
id: 'to_city',
txt: 'to_address_point_txt',
}
}
const collection = this._selector.root[0].elements;
collection[inpNames.id].value = id;
collection[inpNames.txt].value = txt;
this.handlerShowList(el);
el.prevValue = el.val();
})
},
setDataTowns: function (data, inp) {
const newSearchlist = data.res_search_list;
inp.list.html(newSearchlist);
},
handlerPageOut: function () {
let observer = new MutationObserver((e) => {
for (let mutation of e) {
for (let node of mutation.addedNodes) {
if (!(node instanceof HTMLElement)) continue;
if (node.classList.contains('poster')) {
posterApp.init()
observer.disconnect();
}
}
}
});
observer.observe(this._selector.wrapper[0], {
childList: true,
subtree: false,
characterDataOldValue: false
});
},
handlerShowList: function (i, isHide) {
if (!isHide && i.list.text()) {
i.list.toggleClass('show')
} else {
i.list.removeClass('show')
}
},
getDataForm: function (isObj) {
let formData = new FormData(this._selector.root[0]);
if (isObj) return Object.fromEntries(formData)
return formData;
},
validForm: function () {
let elems = this._selector.root[0].elements
//todo пустые значения
elems.departure_DT.value = elems.departure_DT.value.trim()
if (!elems.departure_DT.value) {
elems.departure_DT.value = moment(new Date()).format(this._data.formatDate);
}
// console.log(elems.departure_DT.value.trim(), elems.departure_DT.value === '', elems.departure_DT.value, elems.departure_DT)
},
initSubmit: function () {
const _this = this;
this._selector.root.off('submit').on('submit', function (e) {
e.preventDefault();
_this.validForm();
let routeId = _this._selector.submitBtn.data('routeId');
var formData = _this.getDataForm();
let url = '/routes/create_or_change_route/'
if (routeId) {
url = '/routes/change_route/' + routeId + '/'
}
if (_this.getDataForm(true))
console.log(_this.getDataForm(true))
$.ajax({
headers: {"X-CSRFToken": $('input[name=csrfmiddlewaretoken]').val()},
url: url,
type: "POST",
cache: false,
processData: false,
contentType: false,
data: formData,
success: function (data) {
// return
let data_route_id = data.route_id
document.querySelector(".info_profile").innerHTML = data.html
let el_route = document.querySelector(`[data-number-of-route="${data_route_id}"]`);
if (routeId) {
el_route = document.querySelector(`[data-number-of-route="${routeId}"]`);
}
if (el_route) {
el_route.scrollIntoView({
behavior: "smooth",
block: 'start',
inline: 'start'
});
}
let currentUrl = window.location.pathname;
let newUrl = '';
if (currentUrl.includes('/create_route_for_customer')) {
newUrl = currentUrl.replace('/create_route_for_customer', '/my_routes');
} else if (currentUrl.includes('/create_route_for_mover')) {
newUrl = currentUrl.replace('/create_route_for_mover', '/my_routes');
}
window.history.replaceState(null, '', newUrl);
},
error: function (data, exception) {
console.log(data)
document.querySelector(".info_profile").innerHTML = data.responseJSON.html;
document.getElementById('departure_DT')?.scrollIntoView({
behavior: "smooth",
block: 'nearest',
inline: 'nearest'
});
}
});
});
},
getTowns: function (el) {
const _this = this;
let data = _this.getDataForm(true);
let getTownData = {
type_transport: data.type_transport,
search_str: el.val(),
ctrl_name: el.attr('name')
}
$.ajax({
headers: {"X-CSRFToken": $('input[name=csrfmiddlewaretoken]').val()},
url: '/reference_data/get_address_point/',
type: "POST",
cache: false,
processData: false,
contentType: false,
data: JSON.stringify(getTownData),
success: function (data) {
el.removeClass('loading');
const {res_search_list, unanswered_msgs_count} = data;
_this.setDataTowns(data, el)
_this.initHandlerItemsTowns(el)
_this.handlerShowList(el)
if (res_search_list.length) {
el.addClass('is-items')
el.parent().addClass('is-items')
el.list.addClass('is-items')
} else {
el.parent().removeClass('is-items')
el.removeClass('is-items')
el.list.removeClass('is-items')
}
console.log('fetch', data)
},
error: function (data) {
console.log('Error')
}
});
},
handlerSearchTown: function (e, i) {
this._cl('handlerSearchTown');
let el = i;
console.log('out', el.prevValue, el.val())
if (el.prevValue && el.val().length < el.prevValue.length) {
el.parent().removeClass('is-set')
el.next('.poster__inp-country').remove()
console.log(el, `${el[0].name.split('_')[0]}_city`, this._selector.root[0].elements[`${el[0].name.split('_')[0]}_city`])
this._selector.root[0].elements[`${el[0].name.split('_')[0]}_city`].value = ''
el.val('');
}
if (el.val().length > 2) {
console.log('in')
el.addClass('loading');
clearTimeout(el.timer)
el.timer = setTimeout(() => {
this.getTowns(el);
el.timer = null;
}, 500)
} else {
el.removeClass('loading');
}
el.prevValue = el.val();
},
initHandlerRoute: function () {
this._cl('initHandlerRoute');
const _this = this;
[this._selector.inpFrom, this._selector.inpTo].forEach(i => {
if (!i.length) return false
i.off('input.routes').on('input.routes', (e) => _this.handlerSearchTown(e, i));
i.parent().off('click.routes').on('click.routes', () => _this.handlerShowList(i));
i.parent().parent().off('mouseleave.routes').on('mouseleave.routes', () => _this.handlerShowList(i, true));
});
},
_cl: function (description, obj, debug) {
if (debug || this._data.debug) {
if (obj === undefined) {
console.log(description);
} else {
console.log(obj, description);
}
}
},
initData: function (root) {
window.posterApp = this;
this._data = {
debug: true,
formatDate: 'DD.MM.YYYY',
formatDateClient: window.location.href.includes("/ru/")
? "D MMMM YYYY г."
: "MMMM D, YYYY",
};
this._selector = {
root: root,
wrapper: $('.info_profile'),
inpFrom: root.find('#from'),
inpFromList: root.find('#from').parent().siblings('.poster__towns-list'),
inpTo: root.find('#to'),
inpToList: root.find('#to').parent().siblings('.poster__towns-list'),
cargoItems: root.find('.cargo__inp[name="cargo_type"]'),
typeItems: root.find('.cargo__inp[name="type_transport"]'),
inpDeparture: root.find('#departure_DT'),
inpArrival: root.find('#arrival_DT'),
submitBtn: root.find('button')
};
this._selector.inpFrom.list = this._selector.inpFromList
this._selector.inpFrom.date = this._selector.inpDeparture
this._selector.inpTo.list = this._selector.inpToList
this._selector.inpTo.date = this._selector.inpArrival
},
init: function () {
let root = $('#poster__form');
if (!root.length) return false
this.initData(root);
this._cl('posterApp init');
this._cl(this);
this.handlerPageOut();
this.initHandlerRoute();
this.initDatePickerr();
this.initSubmit();
this.changeCargoType();
this.changeTransportType();
},
};
$(function () {
posterApp.init();
});
}();