var offset = 0;
var page = 1;
var limit = 100;
var load = true;
var sendRequest = true;
var newRequest = true;
var sort_column = "";
var sort_type = "";

$(document).ready(function(){
    
    loadMoreData();
    //alert(segment1)
});

function resetForm() {
    document.getElementById("filter_form").reset();

    $(".shape-box").each(function(){
        $(this).removeClass("active");
    });
    $(".btn-box").each(function(){
        $(this).removeClass("active");
    });

    priceSliderReset();
    caratSliderReset();
}
function submitForm() {
    $("#add_data").html("");
    /*load = true;
    sendRequest = true;
    newRequest = true;
    scrollPos = 0;
    offset = 0;
    page = 1;
    limit = 100;
    sort_column = "";
    sort_type = "";
    defaultSort();*/
    loadMoreData();
}
function sortData(column,type) {
    $("#add_data").html("");
    load = true;
    sendRequest = true;
    newRequest = true;
    scrollPos = 0;
    offset = 0;
    page = 1;
    limit = 50;
    sort_column = column;
    sort_type = type;
    loadMoreData();
}

function validateInput(event) {
    var keycode = event.keyCode
    if(keycode != 46 && (keycode < 48 || keycode > 57)) {
        event.preventDefault();
    }  
}
function validateInputValue(id,index,text) {
    var from_val = $("#"+id+"_from").val();
    var to_val = $("#"+id+"_to").val();
    
    if(parseFloat(from_val) > parseFloat(to_val))  {
        notify('error','From '+text+' can not be greater than To '+text+' ');
        $("#"+id+"_to").val(from_val);
    }
}

let jsonBody = {};

const pushFilterIn = function (key, field = key) {
    const arr = [];
    $.each($("input[name='"+field+"[]']:checked"), function(){            
        arr.push($(this).val());
    });
    if(!arr.length) {
        return;
    }
    jsonBody[key] = arr.toString();
}
const pushFilterBtw = function(key, field = key) {
    const str_from = $("input[name='"+field+"_from']").val();
    let str_to = $("input[name='"+field+"_to']").val();

    if(!str_from && !str_to) {
        return;
    }

    if(field == 'carat') {
        str_to = (str_to == '6+') ? '100' : str_to;
    } else if(field == 'price') {
        str_to = (str_to == '1000000+') ? '10000000' : str_to;        
    }

    if(str_from.trim()!="" && str_to.trim()!="") {
        if(parseFloat(str_from) <= parseFloat(str_to)) {
            jsonBody[key] = str_from+"-"+str_to;
        }
    }
}

function getForm() {
    //var value_form = $('#form').serialize();

    const stock = $("input[name='stock']").val();
    jsonBody = {
        stock,
        type: segment3,
        page,
        limit,        
        sort_column,
        sort_type
    };

}

$(function () {
    $("#checkAll").click(function () {
        if ($("#checkAll").is(':checked')) {
            $(".tr_checkbox").prop("checked", true);
        } else {
            $(".tr_checkbox").prop("checked", false);
        }
    });
}); 

const checkEmpty = (val) => {
    return (val != null) ? val : '';
}

const checkDisc = (val) => {
    return (val > 0) ? '+' + val : val;
}

const pagination = (totalItems) => {
    let linkHtml = '';
    let totalPages = Math.ceil(totalItems / limit);

    if(page > 1) {
        linkHtml += `<a href="javascript:void(0)" onclick="onPaging(${page - 1})">Prev</a>`;        
    }
    for (let i = 1; i <= totalPages; i++) {
        if(i <= page + 2 && i > page - 3) {
            let activeClass = (page == i) ? 'active' : '';
            linkHtml += `<a href="javascript:void(0)" class="${activeClass}" onclick="onPaging(${i})">${i}</a>`;
        }
    }
    if(page < totalPages) {
        linkHtml += `<a href="javascript:void(0)" onclick="onPaging(${page + 1})">Next</a>`;        
    }
    document.getElementById('pagination').innerHTML = linkHtml;
}
const onPaging = (inPage) => {
    page = +inPage;

    loadMoreData();
}

function loadMoreData(){ 

    getForm();    

    $.ajax({         
        url: BASE_URL+"admin/api-history/data",
        method: "POST",
        data: jsonBody,
        dataType: "json",
        success: function(data){
            let html = "";
            const details = data.records; 
            const total_records = data.total; 
            const details_length = details.length;

            pagination(total_records);

            for(let i=0; i < details_length; i++)
            {  

                html += `<tr>`;
                html += `<td></td>`;
                
                html += `<td>${checkEmpty(details[i].sku)}</td>`;
                html += `<td>${dateFormat(details[i].added_at)}</td>`;                

                html += `<td><button onclick="details('${details[i].sku}')" class="btn btn-info btn-sm"><i class="fa fa-book"></i> Details</button></td>`;
                
                html += `</tr>`;

            }


            if(newRequest) { 
                document.getElementById('total_records').innerHTML = total_records;
            }            
            //document.getElementById('add_data').insertAdjacentHTML('beforeend',html);
            document.getElementById('add_data').innerHTML = html;
            $("#list_div").show();
            $("#filter_div").hide();

            html = '';
            // offset = parseInt(offset)+parseInt(limit);
            // limit = 50;
            load = (total_records) ? true : false;

            if(!details_length) {
                if(newRequest) { 
                    $("#sticky-button").hide();
                    $("#list_section").hide();
                    $("#no_list_section").show();
                }
            } else {
                $("#sticky-button").show();
                $("#list_section").show();
                $("#no_list_section").hide();
            }
        },
        beforeSend: function () {            
            if(newRequest) {                
                $("#loading").show();
            }
        },
        complete: function () {
            $("#loading").hide();
        }
    });
}

const details = (sku) => {

    $.ajax({         
        url: BASE_URL+"admin/api-history/details",
        method: "GET",
        data: { sku },
        dataType: "json",
        success: function(data){
            let html = "";
            const details = data.records; 
            const json_data = JSON.parse(details[0].json_data); 
            const product = json_data.product; 
            const variants = product.variants[0]; 
            console.log(json_data)

            html += `<div class="row"><span class="title">Sku:</span> <span>${checkEmpty(details[0].sku)}</span></div>`;            
            html += `<div class="row"><span class="title">Title:</span> <span>${checkEmpty(product.title)}</span></div>`; 
            html += `<div class="row"><span class="title">Description:</span> <span>${checkEmpty(product.body_html)}</span></div>`;            
            html += `<div class="row"><span class="title">Handle:</span> <span>${checkEmpty(product.handle)}</span></div>`;            
            html += `<div class="row"><span class="title">Product type:</span> <span>${checkEmpty(product.product_type)}</span></div>`;            
            html += `<div class="row"><span class="title">Status:</span> <span>${checkEmpty(product.status)}</span></div>`;            

            html += `<div class="row"><span class="title">Barcode:</span> <span>${checkEmpty(variants.barcode)}</span></div>`;            
            html += `<div class="row"><span class="title">Price:</span> <span>${checkEmpty(variants.price)}</span></div>`;            
            html += `<div class="row"><span class="title">Compare at price:</span> <span>${checkEmpty(variants.compare_at_price)}</span></div>`;            
            html += `<div class="row"><span class="title">Cost:</span> <span>${checkEmpty(variants.cost)}</span></div>`;            
            html += `<div class="row"><span class="title">Inventory management:</span> <span>${checkEmpty(variants.inventory_management)}</span></div>`;            
            html += `<div class="row"><span class="title">Inventory policy:</span> <span>${checkEmpty(variants.inventory_policy)}</span></div>`;            
            html += `<div class="row"><span class="title">Requires shipping:</span> <span>${checkEmpty(variants.requires_shipping)}</span></div>`;            
            html += `<div class="row"><span class="title">Inventory quantity:</span> <span>${checkEmpty(variants.inventory_quantity)}</span></div>`;            
            html += `<div class="row"><span class="title">Taxable:</span> <span>${checkEmpty(variants.taxable)}</span></div>`;            
            

            document.getElementById('details_modal_body').innerHTML = html;
            html = '';
            
        },
        beforeSend: function () {     
            $("#loading").show();
        },
        complete: function () {
            $("#loading").hide();
        }
    });

    $("#details_modal").modal('show');

}

function print(html)
{
    //alert(html);
    var mywindow = window.open();
    mywindow.document.write('<html><head><title>print stone</title>');            
    mywindow.document.write('</head><body >');
    mywindow.document.write(html);
    mywindow.document.write('</body></html>');

    mywindow.print();
    mywindow.close();

    return true;
}

function open_windows(src)
{   
    window.open(src, "Diamond", "width=800, height=800");
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function exportList()
{
    var stock_arr = [];
    $.each($("input[name='check_stock[]']:checked"), function(){            
        stock_arr.push($(this).val());
    });
    var stock_str=stock_arr.toString();
    var stock_type = $("input[name='stock_type']").val();

    if(stock_str)
    {
        location.href=BASE_URL+'export-diamond?stock='+stock_str   
    }
    else
    {
        alertify.confirm(SITENAME, 'Do You Want To Download All Record ?', 
        function(){ 
          location.href=BASE_URL+'export-diamond?stock=&stock_type='+stock_type   
        }, 
        function(){  });                
    } 
}

