// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require tether
//= require bootstrap/js/popper.min
//= require bootstrap/js/bootstrap-material-design.min
//= require jquery_ujs
//= require turbolinks
//= require cable
//= require jquery-slimscroll/jquery.slimscroll.js
//= require node-waves/waves.js
//= require sweetalert/sweetalert.min.js
//= require BSBMaterial/turbolink_admin.js
//= require BSBMaterial/demo.js
//= require custom.js

$(document).on('turbolinks:load', function() {
	var oqs_id = "";

	if ($('.oqs_click').val()>0) {
	   $(".oqs_click").removeClass('oqs_active');
	         $(".queue_station").removeClass('queue_station_box');
	         $("#completed").addClass('hide');
	         $(".oqs_append").removeClass('hide');
	         $("#oqs_active").addClass('oqs_active');
	         $(".queue_station").addClass('queue_station_box');
	         // oqs_id = $(this).find(".oqs-id").text();
	          $("#oqs_active").attr('data-id',$('.oqs_click').val());
	         var url    = 'oqs/get_items/'+$('.oqs_click').val();

	         show_details(url,null);
	  }

	$(".nav-completed").on("click", function(){
       $("#completed").removeClass('hide')
       $(".oqs_append").addClass('hide')
    });

    $(".tables").on("click", function(){

 		active     = $(this).hasClass('selected-table');
 		if (active) {
	        $(this).removeClass('bg-blue');
	        $(this).addClass('green');
	        $(this).removeClass('selected-table');
	    }else{
	        $(this).removeClass('green');
	        $(this).addClass('bg-blue');
	        $(this).addClass('selected-table');
	    }
 		var list = document.getElementsByClassName('selected-table');
		var i;
		var table_id =[];
		for (i = 0; i < list.length; i++) {
		    table_id.push(list[i].value);
		}
		 console.log(table_id)
       	$('#table').val(table_id);

        oqs_id = $("#oqs_id").val();
        status = $("#status").val();

    	if (table_id.length>0){
    		var table = table_id
    	}else{
    		var table = null
    	}

    	if (oqs_id > 0 || status != "All" || table != null) {
    	   $(".oqs_click").removeClass('oqs_active');
	       $(".queue_station").removeClass('queue_station_box');
	       $("#completed").addClass('hide');
	       $(".oqs_append").removeClass('hide');
	       $("#oqs_active").addClass('oqs_active');
	       $(".queue_station").addClass('queue_station_box');
	       // oqs_id = $(this).find(".oqs-id").text();
	        $("#oqs_active").attr('data-id',oqs_id);
	       var url    = 'oqs/get_items/'+oqs_id;

	       show_details(url,table,status);
    	}else{
    		$("#completed").removeClass('hide')
            $(".oqs_append").addClass('hide')
    	}
    });

    // $(".oqs_click").on("click", function(){
    $(document).on('change', '.oqs_click', function(event){
    	oqs_id = $(this).val();
    	status = $("#status").val();
    	var table_id = $('#table_id').val();
    	if (table_id){
    		var table = table_id
    	}else{
    		var table = null
    	}

    	if (oqs_id > 0 || status != "All" || table_id != null) {
    	   $(".oqs_click").removeClass('oqs_active');
	       $(".queue_station").removeClass('queue_station_box');
	       $("#completed").addClass('hide');
	       $(".oqs_append").removeClass('hide');
	       $("#oqs_active").addClass('oqs_active');
	       $(".queue_station").addClass('queue_station_box');
	       // oqs_id = $(this).find(".oqs-id").text();
	        $("#oqs_active").attr('data-id',oqs_id);
	       var url    = 'oqs/get_items/'+oqs_id;

	       show_details(url,table,status);
    	}else{
    		$("#completed").removeClass('hide')
            $(".oqs_append").addClass('hide')
    	}
    }); //End Click

    // $(".status_click").on("click", function(){
    $(document).on('change', '.status_click', function(event){
    	oqs_id = $("#oqs_id").val();
    	status = $(this).val();
    	var table_id = $('#table_id').val();
    	if (table_id){
    		var table = table_id
    	}else{
    		var table = null
    	}

	   if (oqs_id > 0 || status != "All" || table != null) {
    	   $(".oqs_click").removeClass('oqs_active');
	       $(".queue_station").removeClass('queue_station_box');
	       $("#completed").addClass('hide');
	       $(".oqs_append").removeClass('hide');
	       $("#oqs_active").addClass('oqs_active');
	       $(".queue_station").addClass('queue_station_box');
	       // oqs_id = $(this).find(".oqs-id").text();
	        $("#oqs_active").attr('data-id',oqs_id);
	       var url    = 'oqs/get_items/'+oqs_id;

	       show_details(url,table,status);
    	}else{
    		$("#completed").removeClass('hide')
            $(".oqs_append").addClass('hide')
    	}

    }); //End Click

	function show_details(url,table_id,status){
		console.log(table_id)
	     var oqs_append = $('.oqs_append');
	     oqs_append.empty();
	     var filter = $('.filter').text();

	    //Start Ajax
	    $.ajax({
	      type: "GET",
	      url: url,
	      data: {'filter':filter,'table_id':table_id,'status':status},
	      dataType: "json",
	      success: function(data) {
	          for(var field in data) {
	            var price = parseFloat(data[field].price).toFixed(2);

	            if (data[field]["options"] == "[]" || data[field]["options"] == "") {
	             var options = "";
	            }else{
	             var options = data[field]["options"];
	            }

	            var date = new Date(data[field]["created_at"]);
	            // var show_date = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear() + ' ' +  date.getHours()+ ':' +  date.getMinutes();
	            var show_date =date.getHours()+ ':' +  date.getMinutes() +' '+(date.getHours() >= 12 ? 'PM' : 'AM');
	            var set_menu_items = data[field]["set_menu_items"];
	            var set_instance_items = "";
	            if(set_menu_items!=null){
	            	if(set_menu_items.length > 0){
						$.each(set_menu_items, function(k,val){
							set_instance_items += '<br><span class="font-12">'+val+'</span>';
						});
					}
	            }

	            var table_type = '';
            	if (data[field]["table_type"]!=null) {
            		table_type = data[field]["table_type"] +'-'+data[field]["zone"]
            	}else{
            		table_type = "No Table"

            	}
            	var delivery_status = ''
            	if (data[field]["delivery_status"] == true) {
				   delivery_status = "hidden"
				}

	            row ='<div class="card queue_station animated " data-order-no="'+data[field]["order_id"]+'">'
	                    +'<div class="card-block">'
	                         +'<div class="row">'
	                          +'<span class="col-md-4 order-zone-type font-13">'+table_type +'</span>'
	                           +'<span class="order-zone hidden font-14">'+ data[field]["zone"] +'</span>'
	                          +'<span class="col-md-8"><small class="float-right font-13">'+data[field]["order_id"]+'</small></span>'
	                         +'</div>'

	                         +'<p class="m-b--10">'
	                          +'<span class="order-item font-15">'+ data[field]["item_name"] +'- </span>'
	                          +'<span class="order-qty"> [x'+ data[field]["qty"] +'] </span>'
	                          +set_instance_items
	                         +'</p>'

	                        +'<p class="card-text item-options">'+ options +'</p>'

	                        +'<span class="card-text">'
	                          +'<span class="text-muted">Order at - '
	                            +'<span class="order-at">'+ show_date +'</span> <br>'

	                            +'Order By - <span class="order-by">'+ data[field]["item_order_by"] +'</span> '
	                            +'</span> '
	                        +'</span>'

	                        +'<p class="hidden order-customer">'+ data[field]["customer_name"] +'</p> '
	                        +'<p class="hidden assigned-order-item">'+ data[field]["assigned_order_item_id"] +'</p> '
	                    +'</div>'

	                    +'<div class="card-footer ">'
	                      +'<span class="'+delivery_status+'">'
	                        +'<button id="edit_'+ data[field]["assigned_order_item_id"] + '" data-no-turbolink="true" class="oqs-btn btn-warning order-item order-item-edit">EDIT</button>'
	                        +' <button id="assigned_queue_' + data[field]["assigned_order_item_id"] +'" class="oqs-btn btn-primary order-item order-complete">COMPLETE</button>'
	                      +'</span>'
	                    +'</div>'

	                +'</div>';

	              $('.oqs_append').append(row);
	          }
	       }
	    });
	    //end Ajax
	 }

	$(document).on('click', '.queue_station', function(event){
		$('#print_order_item').removeAttr("disabled","");
		$('#print_order_summary').removeAttr("disabled","");
		var orderNo = $(this).attr('data-order-no');
	    var orderZone=$(this).children().children().children('.order-zone').text().trim();
	    var orderZoneType=$(this).children().children().children('.order-zone-type').text().trim();
	    // var orderItem=$(this).children().children().children('.order-item').text();
	    var assigned_item_id = $(this).children().find(".assigned-order-item").text();
	    var orderQty = $(this).children().children().children('.order-qty').text();
	    var orderBy = $(this).children().children().children().children('.order-by').text();
	    var orderAt = $(this).children().children().children().children('.order-at').text();
	    var orderCustomer = $(this).children().children('.order-customer').text();
	    var order_status = $(this).children().children('.order-status').text();
	    $('.cus_name').removeClass('hidden');
	    $('#order-title').text("ORDER DETAILS - " + orderZoneType);
	    $('#order-by').text(orderBy);
	    $('#order-at').text(orderAt);
	    $('#order-customer').text(orderCustomer);
	    $('#order-from').text(orderZone);
	    // clear order items
		$("#oqs-order-details-table").children("tbody").empty();
	    // Call get_order_items() for Order Items by dining
	    $.ajax({
	    	type: 'GET',
	    	url: '/oqs/' + orderNo,
	    	data: { 'status' : order_status },
	    	success: function(res){
	    		// console.log(res);
	    		for (i = 0; i < res["items"].length; i++) {
	    			var data = JSON.stringify(res["items"][i]);
        			var parse_data = JSON.parse(data);
        			var assigned_order_items = [];
        			var assigned_order_item_id = '';
        			if(res["assigned_order_items"]!= undefined && res["assigned_order_items"]!=''){
        				assigned_order_items = JSON.parse(JSON.stringify(res["assigned_order_items"]));
        				$.each(assigned_order_items,function(key,value){
        					if(value[parse_data.order_items_id] != undefined){
        						assigned_order_item_id = value[parse_data.order_items_id];
        					}
        				});
        			}
        			// console.log(assigned_order_item_id);

        			var set_menu_items = parse_data.set_menu_items;
        			var set_instance_items = "";
        			if(set_menu_items!=null){
        				if(set_menu_items.length > 0){
	        				$.each(set_menu_items, function(k,val){
								set_instance_items += '<br><span class="font-12">'+val+'</span>';
							});
	        			}
        			}

        			if (oqs_id > 0){
        				if(assigned_order_item_id != ''){
        					var order_item_row = "<tr id='edit_"+assigned_order_item_id+"' class='order-item-edit'>" +
									                "<td class='order-items' style='width:80%; text-align:left'>" + parse_data.item_name + set_instance_items + "</td>" +
									                "<td class='order-qty' style='width:20%; text-align:right'>" + parse_data.qty + "</td>" +
		              						 	 "</tr>";
					 	}else{
					 		var order_item_row = "<tr>" +
									                "<td class='order-items' style='width:80%; text-align:left'>" + parse_data.item_name + set_instance_items + "</td>" +
									                "<td class='order-qty' style='width:20%; text-align:right'>" + parse_data.qty + "</td>" +
												"</tr>";
					 	}

				 	}else{
				 		var order_item_row = "<tr>" +
							                "<td class='order-items' style='width:80%; text-align:left'>" + parse_data.item_name + set_instance_items + "</td>" +
							                "<td class='order-qty' style='width:20%; text-align:right'>" + parse_data.qty + "</td>" +
              						 	 "</tr>";
				 	}

              		$("#oqs-order-details-table").children("tbody").append(order_item_row);
	    		}
	    	}
	    })

	    // $('#order-items').text(orderItem);
	    // $('#order-qty').text(orderQty);

	    $('.queue_station').removeClass('selected-item');
	    $(this).addClass('selected-item');
	});

	$(document).on('click', '.order-item-edit', function(event){
		var _self = $(this);	// To know in ajax return
	    var assigned_item_id=$(this).attr('id').substr(5);
	    window.location.href = '/oqs/'+ assigned_item_id  + "/edit/oqs";
	});

  	// complete for queue item

  	$(document).on('click', '.order-complete', function(event){
  		//e.preventDefault();
  		var _self = $(this);	// To know in ajax return
	    var assigned_item_id=$(this).attr('id').substr(15);
	    var params = { 'id':assigned_item_id };

	    // Call update_delivery_status() for changed delivery and move to delivery
	    $.ajax({
	      type: 'POST',
	      url: '/oqs/update_delivery',
	      data: params,
	      dataType: 'json',
	      success: function(data){
	      	for (i = 0; i < data.length; i++) {
	      		var queue_station = $('#assigned_queue_' + data[i]).parent().parent(".queue_station");
  			    var station = queue_station.parent().parent().attr('id');

		        // Remove a queue card from current station
		      	queue_station.remove();

		      	// Remove a queue card from current station
		      	queue_station.children('.card-footer').remove();

		      	// Add removed queue card from station to completed
		      	$("#completed").children('.card-columns').append(queue_station);

		      	// update queue item count in each station
		      	var station_count=parseInt($("#"+station+"_count").text()) - 1;
	      		$("#"+station+"_count").text(station_count);
	      	}

	      	// update queue item count in completed station
	      	$("#completed_count").text(parseInt($("#completed_count").text()) + data.length);

	      	swal({
		          title: "Information !",
		          text: 'Order has been successfully created',
		          confirmButtonColor: "green",
		          confirmButtonText: "Yes!",
		          closeOnConfirm: false,
		        }, function () {
		          if(table_type == "Table"){
		                  window.location.href = "/origami/table/" + table_id
		                }
		                else {
		                  window.location.href = "/origami/room/" + table_id
		                }
		        });
	      	// Page reload
	    	location.reload();
	      }
	    });
  	});

  	// Print Order Item
  	$(document).on('click', '#print_order_item', function(event){
  		$(this).attr("disabled","disabled");
  		var assigned_item_id = $('.selected-item').children('.card-block').children('.assigned-order-item').text();
  		var options = $('.selected-item').children('.card-block').find('.item-options').text();
  		var params = { 'options':options };
  		$.ajax({
			type: 'GET',
	     	url: '/oqs/print/print/'+assigned_item_id,
	     	data: params,
	     	success: function(result){
	     		 // For Server Print - from jade
	              if ($("#server_mode").val() == "cloud") {
	              	if(typeof code2lab != 'undefined'){
	                	code2lab.printFile(result.filepath.substr(6), result.printer_url);
	                }
	              }
	         location.reload();

	     	}
  		});

  	});

  	// Print Order Summary
  	// $('#print_order_summary').on('click',function(){
  	$(document).on('click', '#print_order_summary', function(event){
  		$(this).attr("disabled","disabled");
  		var orderNo = $('.selected-item').attr('data-order-no');
  		var table_name=$('.selected-item').children().children().children('.order-zone').text().trim();
  		var assigned_item_id=$('.selected-item').children('.card-block').children('.assigned-order-item').text();
  		var params = { 'table_name':table_name };
  		$.ajax({
			type: 'GET',
	     	url: '/oqs/print/print_order_summary/'+assigned_item_id,
	     	data: params,
	     	success: function(result){
	     		// For Server Print - from jade
	              if ($("#server_mode").val() == "cloud") {
	              	if(typeof code2lab != 'undefined'){
	                	code2lab.printFile(result.filepath.substr(6), result.printer_url);
	                }
	              }
	            location.reload();
	     	}
  		});
  	});
});
