var m_refresh_busy = false;
var m_obj_id = 0;
var m_pagethis = "phienbb";

//store_id,store_name,store_code,store_address,comment,is_main
var gvRemoteCall = new GridViewEx(ds_goodscallqueue, "gvRemoteCall");
var gvGoodsInvoice = new GridViewEx(ds_goodscallqueue, "gvGoodsInvoice");

initOneTime();

function initOneTime() {
    //check xem da khoi tao chua
    var page_initflag = document.getElementById("page_initflag");
    if (page_initflag != null) {
        if (page_initflag.value.length > 0)
            return;
        page_initflag.value = "1";
    }
    showList(0);

    uiUpdateSelectFoodsDrink();
    loadObjList();
    g_event_param = { type: "rd", fn: "eventRDHandle" };
}
async function loadObjList() {
    if (g_ls_objlist.length < 1) {
        if (await getSyncListObj() == false)
            return;
        if (g_ls_objlist.length < 1)
            return;
    }
}
//showType:0-confirm, 1:delivered
//id-obj_id-obj_name-goods_name-quantity-unit-unit_price-hourinday_add-right
function showListItem(data, iddivshow, showType) {

    var rows = data.split(g_split_row);
    if (rows.length < 1) setInnerById(iddivshow, "");
    var strOut = "";
    for (var i = 0; i < rows.length; i++) {
        var vals = rows[i].split(g_split_val);
        if (vals.length == 9) {
            var idrow = gvGoodsInvoice.getRowId(vals[0]);
            var style = "";
            strOut += "<div class='list_item' style='margin-bottom:1px;padding:4px;overflow:auto;' id='" + idrow + "'>";
            if (showType == 0) {
                strOut += "<div style='float:right;'>";
                strOut += "<a class='btn_mainheader circle confirm' onclick='setConfirm(" + vals[0] + ",1)' title='" + itxt("dongy") + "'></a>";
                if (!g_viewmode) {
                    strOut += "<br>";
                    style = "margin-top:8px";
                } else {
                    style = "margin-left:8px";
                }
                strOut += "<a class='btn_mainheader circle deny' style='" + style + "' onclick='setConfirm(" + vals[0] + ",0)' title='" + itxt("tuchoi") + "'></a>";
                strOut += "</div>";
            } else {
                strOut += "<div style='float:right;'>";
                strOut += "<a class='btn_mainheader circle delivered' style='float:right;' onclick='setDone(" + vals[0] + ")' title='" + itxt("xacnhandagiao") + "'></a>";
                if (!g_viewmode) {
                    strOut += "<br>";
                    style = "margin-top:8px";
                } else {
                    style = "margin-left:8px";
                }
                strOut += "<a class='btn_mainheader circle none' style='" + style + "' onclick='' title=''></a>";
                strOut += "</div>";

            }

            strOut += "<b>" + vals[3] + "</b><br>";
            strOut += "<span class='subinfo'>" + vals[4] + "*" + vals[5] + "</span>";
            strOut += "<br><span class='subinfo'><b>" + vals[2] + "</b></span><span class='highlight_hour'>" + vals[7] + "</span>";
            strOut += "</div>";
        }
    }
    if (showType == 0)
        setInnerById("idunconfirmedcount", rows.length);
    else
        setInnerById("idconfirmedcount", rows.length);

    setInnerById(iddivshow, strOut);
}
function eventRDHandle(data) {

    if (data.length == 0) return;
    //event_id-log_type-obj_id-log_src_id
    var vals = data.split(g_split_val);
    if (vals.length != 4) return;

    CEventAlert.start_event_id = parseInt(vals[0]);
    var log_type = parseInt(vals[1]);
    var obj_id = parseInt(vals[2]);
    var log_src_id = parseInt(vals[3]);

    if (log_type == 5) {//finish
        showListWaitConfirm(obj_id);
        showListWaitDelivered(obj_id);
    }
    else if ((log_type >= 10) && (log_type <= 16)) {
        showListWaitConfirm(obj_id);
    } else if ((log_type >= 6) && (log_type <= 9)) {
        showListWaitDelivered();
        if (log_type == 6) {
            showListWaitConfirm(obj_id);
        }
    }
    playNotify();
}

async function showListWaitConfirm(obj_id) {
    m_obj_id = obj_id;
    var url = "?page=" + m_pagethis + "&pagesub=ordered&obj_id=" + obj_id + "&food_drink=" + g_food_drink;
    var dataWCF = await getSync(url);
    if (isDataOk(dataWCF)) showListItem(getDataOk(dataWCF), "div_goods_remote_call", 0);
}
async function showListWaitDelivered(obj_id) {
    m_obj_id = obj_id;
    url = "?page=" + m_pagethis + "&pagesub=hangchogiao&obj_id=" + obj_id + "&food_drink=" + g_food_drink;
    var dataUCF = await getSync(url);

    if (isDataOk(dataUCF)) showListItem(getDataOk(dataUCF), "div_goods_invoice", 1);

}
async function showList(obj_id) {
    hideModal();
    await showListWaitConfirm(obj_id);
    await showListWaitDelivered(obj_id);

}
function setRemove(id) {
    setConfirm(id, 0);
}
function setDone(id) {
    showWaitModal();
    var url = "?page=" + m_pagethis + "&pagesub=dagiao&id=" + id;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            var idrow = document.getElementById(gvGoodsInvoice.getRowId(id));
            if (idrow != null)
                idrow.outerHTML = "";
            hideModalBlock();
        },
        error: function () {
            showModal(itxt("thatbai"));
        }
    });
    return false;
}
//val: 1 dongy, 0: tu choi
function setConfirm(id, val) {

    showWaitModal();
    var url = '?page=' + m_pagethis + '&pagesub=orderconfirm&id=' + id + '&val=' + val;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showModal([itxt("thatbai"), getDataFail(data)]);
                return;
            }
            var idrow = document.getElementById(gvRemoteCall.getRowId(id));
            if (idrow != null)
                idrow.outerHTML = "";
            m_refresh_busy = true;
            if (val == 1) {
                showListWaitDelivered(0);
            }
            m_refresh_busy = false;
            hideModalBlock();

        },
        error: function () {
            showModal(itxt("thatbai"));
        }
    });
    return false;
}

function uiUpdateSelectFoodsDrink() {
    var idselectfooddrink = document.getElementById("idselectfooddrink");
    if (g_food_drink == 1)
        idselectfooddrink.title = "(Đồ ăn)";
    else if (g_food_drink == 2)
        idselectfooddrink.title = "(Đồ uống)";
    else if (g_food_drink == 3)
        idselectfooddrink.title = "(Đồ khác)";
    else
        idselectfooddrink.title = "(Tất cả đồ)";
}
function selectFoodDrink(select) {
    m_refresh_busy = true;
    if (select != null) {
        g_food_drink = select;
        uiUpdateSelectFoodsDrink();
        showWaitModal();
        showList();
        m_refresh_busy = false;

        var url = '?page=rd&pagesub=setfoodsdrink&val=' + select;
        var dataString = "";
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                hideModal();
            },
            error: function () {
                showModal("Không ghi được chọn lựa đồ ăn/đồ uống");
            }
        });
    }
    else {
        var menu = "";
        menu += "<a href='javascript:void(0)' onclick='javascript:selectFoodDrink(0)' class='menu_popup_item'>Tất cả đồ</a>";
        menu += "<a href='javascript:void(0)' onclick='javascript:selectFoodDrink(1)' class='menu_popup_item'>Đồ ăn</a>";
        menu += "<a href='javascript:void(0)' onclick='javascript:selectFoodDrink(2)' class='menu_popup_item'>Đồ uống</a>";
        menu += "<a href='javascript:void(0)' onclick='javascript:selectFoodDrink(3)' class='menu_popup_item'>Đồ khác</a>";
        showModal(menu, "Chọn lựa đồ");
    }
}
//tao cac id div
function getIdDivObjInList(obj_id) {
    return "iddoil" + obj_id;
}
function getIdCheckObjInList(obj_id) {
    return "iddoil" + obj_id + "check";
}
function getIdCheckObjInList_NumberPart(idstring) {
    if (isEmpty(idstring)) return null;
    idstring = idstring.replace("iddoil", "");
    idstring = idstring.replace("check", "");
    return parseNumberVn(idstring);
}
function getIdDivObjInListMustRec(obj_id) {
    return getIdDivObjInList(obj_id) + "mr";
}
function getIdDivObjInListInfo(obj_id) {
    return "iddoil" + obj_id + "inf";
}

function showObjList(selected_obj_id, fnCallBackNameOnClickObj) {
    var bmultiselect = false;
    //alert($(window).width());
    //$(window).width();
    var objwidth = "20%";
    if ($(window).width() < 1000) {
        objwidth = "33%";
    }
    //obj_id,obj_name,obj_type,status_remotecall,totalcost,invoice_id,status_extra

    var nCount = g_ls_objlist.length;
    if (nCount < 1)
        return;
    var strout = "";
    var strobj = ""; var strobjclass = ""; var strtotalcost = "";

    for (i = 0; i < nCount; i++) {
        var item = g_ls_objlist[i];
        strobjclass = lsGetObjInListClass(item);
        var receivable = parseNumberVn(item.totalcost) + parseNumberVn(item.costmix);
        var iddivobj = getIdDivObjInList(item.id);
        var iddivobjmr = getIdDivObjInListMustRec(item.id);
        var iddivobjinfo = getIdDivObjInListInfo(item.id);
        var onclick = "";

        if (!isEmpty(fnCallBackNameOnClickObj)) {
            onclick = " onclick=\"dlgRemove();eval(" + fnCallBackNameOnClickObj + ")(" + item.id + ")\"";
        }
        else {
            onclick = " onclick=\"javascript:showList(" + item.id + ")\"";
        }

        strobj = "<div id=\"" + iddivobj + "\" class=\"obj_wrapper\" style=\"width:" + objwidth + "\">";
        strobj += "<div class=\"" + strobjclass + "\" id=\"" + iddivobjinfo + "\">";
        strobj += "<div style='float:left;flex:100;cursor: pointer;'" + onclick + ">";
        strobj += "<div class='obj_up'>" + item.name + "</div><div class='obj_down' id=\"" + iddivobjmr + "\">" + getNumberNZ(formatNumber(receivable)) + "</div>";
        strobj += "</div>";
        if (bmultiselect == true)
            strobj += "<label class=\"objswitch\" style=\"float:right;margin:0px;padding:0px;\"><input type=\"checkbox\" id=\"" + getIdCheckObjInList(item.id) + "\"><span class=\"objslider\"></span></label>";
        strobj += "</div>";
        strobj += "</div>";
        strout += strobj;
    }
    showModal(strout);
}