$(document).ready(function() {
    checkSessionStat();
    get_total_status();
    check_stat_load();
    $("#search-input").val("");
    $("#region-select").val("");
    $(".multiple-region").select2({
        multiple: true,
    });
});
function check_stat_load(){
    var ship_stat = $("#ship-status").val();
    $("#trig-"+ship_stat).click();
}
$('#date-filter').daterangepicker({
    autoUpdateInput: false,
    locale: {
        cancelLabel: 'Clear'
    }
});
$('#date-filter').on('apply.daterangepicker', function(ev, picker) {
    $(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
    var start_date = picker.startDate.format('MM/DD/YYYY');
    var end_date = picker.endDate.format('MM/DD/YYYY');
    $("#start-date").val(start_date);
    $("#end-date").val(end_date);

    check_stat_load();
    detectFilter();
    get_total_status();
});
$('#date-filter').on('cancel.daterangepicker', function(ev, picker) {
    $(this).val('');
    $("#start-date").val("");
    $("#end-date").val("");
    check_stat_load();
    get_total_status();
});
$('#input-exdate').daterangepicker({
    autoUpdateInput: false,
    locale: {
        cancelLabel: 'Clear'
    }
});
$('#input-exdate').on('apply.daterangepicker', function(ev, picker) {
    $(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
    var start_date = picker.startDate.format('MM/DD/YYYY');
    var end_date = picker.endDate.format('MM/DD/YYYY');
    $("#start-exdate").val(start_date);
    $("#end-exdate").val(end_date);
});
$('#input-exdate').on('cancel.daterangepicker', function(ev, picker) {
    $(this).val('');
    $("#start-exdate").val("");
    $("#end-exdate").val("");
});
// $("#submit-export").click(function(){
//     get_export_data();
// });
function get_export_data(){
    win_loader('open');
    var exstatus = $("#input-exstatus").val();
    var exregion = $("#input-exregion").val();
    var start_date = $("#start-exdate").val();
    var end_date = $("#end-exdate").val(); 
    var redir_url = $("#export-url").val();

    var export_url = redir_url+"?status="+exstatus+"&region="+exregion+"&startDate="+start_date+"&endDate="+end_date;
    setTimeout( function(){ 
    window.open(export_url, '_blank');
    $("#input-exstatus").val("all");
    $("#input-exdate").val("");
    $("#input-exregion").val("all");
    $("#start-exdate").val("");
    $("#end-exdate").val("");
    win_loader('close');
    $('#modal-export').modal('hide');
    }, 1500 );
}
function delay(callback, ms) {
  var timer = 0;
  return function() {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      callback.apply(context, args);
    }, ms || 0);
  };
}
$('#search-input').keyup(delay(function (e) {
    detectFilter();
    var ship_stat = $("#ship-status").val();
    check_stat_load();
    get_total_status();
}, 500));
$('#region-select').on('change', function() {
    detectFilter();
    check_stat_load();
    get_total_status(); 
});
$('#sort-select').on('change', function() {
    detectFilter();
    check_stat_load();
    get_total_status(); 
});
$("#btn-clear").click(function(){
    clearFilter();
    detectFilter();
    get_total_status();
    $("#btn-clear").css("display","none");
});
function clearFilter(){
    $("#start-date").val("");
    $("#end-date").val("");
    $("#search-input").val("");
    $('#date-filter').val("");
    $('#region-select').val("");
    check_stat_load();
}
function detectFilter(){
    var start_date = $("#start-date").val();
    var end_date = $("#end-date").val();
    var search_key = $("#search-input").val();
    var region = $("#region-select").val();

    $("#btn-clear").css("display","none");
    if(start_date != ""){
        $("#btn-clear").css("display","inline-block");
    }
    if(end_date != ""){
        $("#btn-clear").css("display","inline-block");
    }
    if(search_key != ""){
        $("#btn-clear").css("display","inline-block");
    }
    if(region != ""){
        $("#btn-clear").css("display","inline-block");
    }

}
$('#date-filter').on('apply.daterangepicker', function(ev, picker) {
    $(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
    console.log(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
});

$('#date-filter').on('cancel.daterangepicker', function(ev, picker) {
    $(this).val('');
});
function OpenDetail(po_id){
    var redir_detail = $("#redir-detail").val();
    window.location.href = redir_detail+po_id+"/";
}
function checkSessionStat(){
    var status = sessionStorage.getItem("alert_status");
    var message = sessionStorage.getItem("alert_message");
    if(status == "success"){
        successAlert(message);
        sessionStorage.removeItem("alert_status");
        sessionStorage.removeItem("alert_message");
    } else if(status == "failed"){
        errorAlert(message);
        sessionStorage.removeItem("alert_status");
        sessionStorage.removeItem("alert_message");
    }
}
function openData(status){
    $("#ship-status").val(status);
    load_item(1,status);
}
function moreData(status){
    var cur_page = $("#tpage-"+status).val();
    var new_page = eval(cur_page) + eval(1);
    load_item(new_page,status);
}
function load_item(page,status){
    if(page != 1){
        $("#tloader-"+status).fadeIn();
    } else {
        $('#tlist-'+status).html("");
        $("#tloader-"+status).show();
    }
    get_item(page,status);
    $("#tpage-"+status).val(page);
}
function get_total_status(){
    var url = api_po_total;
    var acs_region = $("#acs-region").val();
    var session_id = $("#session-id").val();
    var search_key = $("#search-input").val();
    if(acs_region != 1){
    var region = $('#region-select').val();
    } else {
    var region = $('#region-admin').val();
    }
    var courier = $('#courier-select').val();

    var start_date = $("#start-date").val();
    var end_date = $("#end-date").val();
    var acsg_pic = $("#acsg-pic").val();
    
    var data = {
        user_id : session_id,
        keyword : search_key,
        region : region,
        start_date : start_date,
        end_date : end_date,
        acsg_pic : acsg_pic,
    }
    $.ajax({type: "POST",url: url,data : data, success:function(result){
        var total_open = result.total_open;
        var total_progress = result.total_progress;
        var total_prepared = result.total_prepared;
        var total_complete = result.total_complete;
        var total_cancel = result.total_cancel;

        $("#ltotal-open").text(total_open);
        $("#ltotal-progress").text(total_progress);
        $("#ltotal-prepared").text(total_prepared);
        $("#ltotal-complete").text(total_complete);
        $("#ltotal-cancel").text(total_cancel);

    }});
};
function get_item(page,status){
    var item_perpage = 30;//item perpage

    var url = api_po_list;
    var session_id = $("#session-id").val();
    var search_key = $("#search-input").val();
    var acs_region = $("#acs-region").val();

    var start_date = $("#start-date").val();
    var end_date = $("#end-date").val();

    if(acs_region != 1){
    var region = $('#region-select').val();
    } else {
    var region = $('#region-admin').val();
    }
    var courier = $('#courier-select').val();
    var sortby = $('#sort-select').val();
    var acsg_pic = $("#acsg-pic").val();
    
    var data = {
        user_id : session_id,
        item : item_perpage,
        status : status,
        region : region,
        keyword : search_key,
        start_date : start_date,
        end_date : end_date,
        sortby : sortby,
        acsg_pic : acsg_pic,
        page : page
    }
    $.ajax({type: "POST",url: url,data : data, success:function(result){
        $("#tpage-"+status).val(page);
        var total_data = result.total_data;
        var remaining = result.remaining;
        if(total_data > 0){
            var total_page = result.total_page;
            setTimeout(function() {
                var datas = result.data;
                $("#tloader-"+status).hide();
                if(page == 1){
                    $('#tlist-'+status).html("");
                }
                $('#tlist-'+status).append(show_data(datas, page, item_perpage));
                if(remaining < 1){
                    $("#tmore-"+status).hide();
                } else {
                    $("#tmore-"+status).show();
                }
            }, 100);
        } else {
            setTimeout(function() {
                emptyItem(status);
                $("#tmore-"+status).hide();
                $("#tloader-"+status).fadeOut();
            }, 100);
        }
    }});
};
function emptyItem(status){
    resultHTML = "<tr><td colspan='15' class='text-center'>There is no data right now.</td></tr>";
    $('#tlist-'+status).html(resultHTML);
}
function convertPaid(param){
    var result = "";

    if(param == 'not'){
        result = "<span class='label label-xs bg-red'>Not Paid</span>";
    } else {
        result = "<span class='label label-xs bg-green'>Paid</span>";
    }
    return result;
}  
function remove_mcheck(arr, what) {
    var found = arr.indexOf(what);

    while (found !== -1) {
        arr.splice(found, 1);
        found = arr.indexOf(what);
    }
}
function paidStat(param){
    var result = ""

    if(param == 'yes'){
        result = "<span class='label label-success label-xs'>Paid</span>"
    } else {
        result = "<span class='label label-warning label-xs'>Not Paid</span>"
    }

    return result;
}
function invoiceNull(param){
    var result = ""

    if(param != "" && param != null){
        result = param;
    } else {
        result = "-";
    }

    return result;
}
function show_data(datas,page,item_perpage){
    var resultHTML='';
    var ship_stat = $("#ship-status").val();//open, progress, prepared, complete or cancel
    var redir_detail = $("#redir-detail").val();
    var hide_amount = $("#acs-hide-amount").val();

    if(datas != null){
        var obj = datas;
        var num = 1;
        for(var i=0;i < obj.length;i++){
            var number = (page-1)*item_perpage+num;

            resultHTML += "<tr>";
            resultHTML += "<td class='text-center'>"+number+"</td>";
            resultHTML += "<td class='text-center'>";
            resultHTML += "<a href='"+redir_detail+obj[i].po_id+"/' class='btn btn-success btn-xs'><i class='fa fa-search'></i> Detail</a>";
            resultHTML += "</td>";
            resultHTML += "<td class='text-center'>"+obj[i].po_id+"</td>";
            resultHTML += "<td class='text-center'>"+obj[i].po_order_num+"</td>";
            resultHTML += "<td class='text-center'>"+obj[i].atpo_product+"</td>";
            resultHTML += "<td class='text-center'>"+obj[i].client_name+"</td>";
            resultHTML += "<td class='text-center'>"+obj[i].po_subclient+"</td>";
            resultHTML += "<td class='text-center'>"+obj[i].region_title+"</td>";
            resultHTML += "<td class='text-center'>"+obj[i].admin_name+"</td>";
            if(hide_amount != 1){
            resultHTML += "<td class='text-center'>"+formatRupiah(obj[i].po_total,'IDR ')+"</td>";
            }  
            if(obj[i].po_status == 'progress' || obj[i].po_status == 'complete'){
            resultHTML += "<td class='text-center'>"+invoiceNull(obj[i].po_invoice)+"</td>";
            }   
            if(obj[i].po_status == 'complete'){
            resultHTML += "<td class='text-center'>"+paidStat(obj[i].po_paid)+"</td>";
            }   
            if(obj[i].po_status == 'progress' || obj[i].po_status == 'complete'){
            if(obj[i].po_document == 'yes'){
            resultHTML += "<td class='text-center'><span class='label label-success'>READY</span></td>";
            } else {
            resultHTML += "<td class='text-center'><span class='label label-warning'>NOT READY</span></td>";
            }
            } else {
            resultHTML += "<td class='text-center'>"+dateFormat(obj[i].po_date, "dd mmmm yyyy")+"</td>";
            }
            resultHTML += "</tr>";

            num++;
        }
    }
    return resultHTML;
}