jQuery(function ($) {
	const MAX_ITEM_COUNT = 5;

	var $wrapShow		= $('.js-phases-wrap-show');
	var $itemsShow		= $wrapShow.find('.js-phases-item');
	var $edit			= $wrapShow.find('.js-phases-edit');
	var $saveProgress	= $wrapShow.find('.js-phases-save');
	var $ok				= $wrapShow.find('.js-phases-ok');

	var $wrapEdit		= $('.js-phases-wrap-edit');
	var $itemsEdit		= $wrapEdit.find('.js-phases-item');
	var $add			= $wrapEdit.find('.js-phases-add');
	var $cancel			= $wrapEdit.find('.js-phases-cancel');
	var $savePhases		= $wrapEdit.find('.js-phases-save');

	var trackId = $wrapEdit.data('track-id');
  var orderId = $wrapEdit.data('order-id');
	
	function init() {
		$add.click(add);
		$edit.click(edit);
		$cancel.click(cancel);
		$saveProgress.click(saveProgress);
		$savePhases.click(savePhases);
		$wrapEdit.find('.js-phases-remove').click(remove);

		$wrapShow.closest('.report-message').find('.edit-link a').click(function () { $edit.closest('tr').show(); });

		$('.js-phases-wrap-show').on('click', '.loadbar.enable .progress-bar:not(.min-active-value)', progressBarClick);

		$('.js-phases-wrap-edit input').keyup(checkPhaseName);
		$('.js-phases-wrap-edit input').change(checkPhaseName);
	}
	
	function add() {
		var $new = $itemsEdit.filter(':hidden:first');

		if ($new.length) {
			$itemsEdit.find('.js-phases-remove').hide();

			$new.show().find('.js-phases-remove').show();

			$new.find('input').focus();

			if (!$itemsEdit.filter(':hidden').length) {
				$add.hide();
			}
		}
	}
	
	function edit() {
		$wrapShow.hide();
		$wrapEdit.show();

		// Отфильтровываем удаленные из документа элементы
		$itemsEdit = $itemsEdit.filter(function () {
			return $(this).closest('body').length;
		});
		$itemsShow = $itemsShow.filter(function () {
			return $(this).closest('body').length;
		});

		$itemsEdit.removeClass('error').hide()
			.find('input').val('').end()
			.find('.js-phases-remove').hide();

		$itemsShow.each(function (i, item) {
			var name = $(item).find('.js-phases-name').text();
			$itemsEdit.eq(i).show().find('input').val(name);
		});

		$itemsEdit.filter(':visible:last').find('.js-phases-remove').show();

		$add.toggle($itemsShow.length < MAX_ITEM_COUNT);
	}
	
	function cancel() {
		$wrapShow.show();
		$wrapEdit.hide();
	}
	
	function remove(e) {
		var $item = $(e.currentTarget).closest('.js-phases-item');
		$item.hide().find('input').val('');
		$itemsEdit.filter(':visible:last').find('.js-phases-remove').show();
		$add.show();
	}

	function savePhases() {
		var phases = [];
		var errors = false;

		$itemsEdit.removeClass('error').filter(':visible').each(function () {
			var $item = $(this);
			var val = $item.find('input').val();
			if (!val.length) {
				$item.addClass('error');
				errors = true;
				return;
			}
			phases.push(val);
		});

		if (errors) {
			return;
		}

		var params = {
			trackId: trackId,
      orderId: orderId,
			action: 'phases_save',
			phases: phases,
		};

		$savePhases.prop('disabled', true).addClass('disabled');

		$.post('/send_mk', params, function (response) {
			if (response.success) {
        location.assign('/order/' + orderId + '?scroll=1');
			} else {
				alert(response.error || 'Ошибка');
			}
		}, 'json').fail(function () {
			alert('Ошибка');
		}).always(function () {
			$savePhases.prop('disabled', false).removeClass('disabled');
		});
	}

	function saveProgress() {
		var phases = [];

		$itemsShow.each(function () {
			var progress = $(this).data('progress');
			phases.push(progress);
		});

		var params = {
      trackId: trackId,
      orderId: orderId,
			action: 'phases_save_progress',
			phases: phases,
		};

		$saveProgress.prop('disabled', true).addClass('disabled');
		$ok.stop(true, true).hide();

		$.post('/send_mk', params, function (response) {
			if (response.success) {
				$ok.show().delay(1000).fadeOut();
				 location.assign('/order/' + orderId + '?scroll=1');
			} else {
				alert(response.error || 'Ошибка');
        location.assign('/order/' + orderId + '?scroll=1');
      }
		}, 'json').fail(function () {
			alert('Ошибка');
		}).always(function () {
			$saveProgress.prop('disabled', false).removeClass('disabled');
		});
	}

	function progressBarClick() {
		var $bar = $(this);
		var $item = $bar.closest('.js-phases-item');
		var value = $bar.data('value');

		$item.find('.progress-bar').each(function () {
			var bar = $(this);
			if (bar.data('value') <= value) {
				bar.addClass('progress-bar-fill');
			} else {
				bar.removeClass('progress-bar-fill');
			}
		});

		$item.data('progress', value)
			.find('.current-percent-value').text(value);

		var $report = $item.closest('.new-report, .report-message');
		if ($report.length) {
			var index = $item.data('index');
			$report.find('[name="phase-' + index + '"]').val(value);
		}

		showCheckForm($bar);
	}

	function checkPhaseName(e) {
		var maxLength = 30;
		var $input = $(e.currentTarget);
		var value = $input.val();
		if (value.length >= maxLength) {
			value = value.substr(0, maxLength);
			$input.val(value);
		}
	}

	function showCheckForm($bar) {
		var track_id = $bar.data('track-id');
		var parentWrapper = $("#track-id-" + track_id);

		var showForm = true;
		parentWrapper.find('.js-phases-wrap-show .js-phases-item').each(function () {
			var $lastFilledBar = $(this).find('.progress-bar-fill:last');
			if ($lastFilledBar.data('value') < 100) {
				showForm = false;
				return false;
			}
		});

		if (showForm) {
			var cloneForm = $("#worker_check_form").clone();
			$("#track-form").find(".track-page-group-btn .green-btn").click();
			$("#track-form").find(".track-page-group-btn").hide();
			cloneForm.find(".sm-text-center").remove();
			cloneForm.find("#message_body2").attr("placeholder", "Отправьте выполненную работу на проверку");
			cloneForm.find("#message_body2").val(parentWrapper.find("#prd_report_message").val());
			cloneForm.removeClass("track-form-js");
			$('<input>').attr({
				type: 'hidden',
				value: (track_id) ? track_id : "new",
				name: 'inprogress_report'
			}).appendTo(cloneForm);
			cloneForm.show();
			parentWrapper.find(".append-form-wrapper").html(cloneForm);
			parentWrapper.find(".exist-form-wrapper").addClass('hide');
		} else {
			$("#track-form").find(".track-page-group-btn").show();
			parentWrapper.find(".append-form-wrapper").html("");
			parentWrapper.find(".exist-form-wrapper").removeClass('hide');
		}
	}

	init();
});