var m_pagethis = "phien_quanlytinhtien.ls";
var m_active_service_id = 0;
var m_payment_method = 0;//0-cash, 1: bank, 2: credit card, 3: mix
var m_param_viewfilter_status = 0;//0-all, 1-free, 2:using
var m_param_viewfilter_type = 0;//4-takeaway
var m_param_viewfilter_group = 0;
var m_param_viewfilter_objcategory = -1;
var m_params = new Map();



//

var ds_objgroup = [
    { name: "group_id", head: "", visible: 0 },
    { name: "group_name", head: "Tên nhóm bàn/phòng", visible: 1, type: "text", required: 1, width: "70%" },
    { name: "show_order", head: "Thứ tự", visible: 1, type: "number", width: "30%" },
];

var ds_objsession = [
    { name: "id", head: "", visible: 0 },
    { name: "name", head: "", visible: 1, type: "text" },
    { name: "objcategory", head: "", visible: 0, type: "number" },
    { name: "statusremotecall", head: "", visible: 0, type: "number" },
    { name: "totalcost", head: "", visible: 0, type: "number" },
    { name: "invoiceid", head: "", visible: 0, type: "number" },
    { name: "seatcount", head: "", visible: 0, type: "number" },
    { name: "group", head: "", visible: 0, type: "number" },
];
var ds_objsessiondetails = [];
var gridObj = new GridViewEx(ds_obj, "gridObj");
gridObj.page_source = "kb_danhsachbanphong.ls";

var gridViewExGoodsCategory = new GridViewEx(ds_goods_categoryls, 'gridViewExGoodsCategory');
gridViewExGoodsCategory.page_source = "kb_nhomhang";
gridViewExGoodsCategory.page_title = itxt("nhomhang");

var gridViewExGoods = new GridViewEx(ds_goods, "gridViewExGoods");
gridViewExGoods.page_source = "kb_hang";
gridViewExGoods.page_title = itxt("kb_hang");

var gridObjGroup = new GridViewEx(ds_objgroup, "gridObjGroup", "kb_nhombanphong");
var gvRemoteCall = new GridViewEx(ds_goodscallqueue, "gvRemoteCall");

//RES_OBJ_CATEGORY_RES,RES_OBJ_CATEGORY_KARA,RES_OBJ_CATEGORY_HOTEL,
//RES_OBJ_CATEGORY_SPA,RES_OBJ_CATEGORY_TICKET,RES_OBJ_CATEGORY_TAKEAWAY
//obj:id,name,objcategory,typeid,totalcost,invoiceid,seatcount,group
//obj_details:invoiceid,totalcost,costfixed,costhourly,costmix,
//5 discountfoods,discountdrink,discountgoods,discountservice,invoicediscount,
//10 extracharge,vat,invoicemoneydiscount,
//13 contactid,contactname,contactaddress,phone,datebirth (13->17)
//goods: goods_id,unit_id,goods_name,unit,stock,export_price,image_name{,id}
//goods_service:id,goodsid,unitid,name,unit_price,unit,quantity,objcategory,from,hourly,minutelimit,iscombo,to,idmixmain,ismix,realname
//sync function
async function sessionLoadParams() {
    async function promised_fetch() {
        var url = "?page=" + m_pagethis + "&action=param&pagesub=load&loadtime=" + g_map_listloadtime.get("store");
        var dataString = "";
        return new Promise((resolve, reject) => {
            $.ajax({
                url: url,
                data: dataString,
                type: "GET",
                timeout: 10000,
                success: (data) => {
                    resolve(data);
                },
                error: (response) => {
                    reject(response);
                }
            })
        })
    }
    var data = await promised_fetch();
    if (!isDataOk(data)) {
        showMsg([itxt("loi")]);
        return false;
    }

    var rows = getDataOk(data).split(g_split_row);
    for (var i = 0; i < rows.length; i++) {
        var vals = rows[i].split(g_split_val);
        if (vals.length == 2)
            m_params.set(vals[0], vals[1]);
    }
    var session_viewfilter = m_params.get("session_viewfilter");

    if (session_viewfilter.length == 2) {
        m_param_viewfilter_status = parseNumberVn(session_viewfilter.substr(0, 1));
        m_param_viewfilter_type = parseNumberVn(session_viewfilter.substr(-1));
    }
    return true;
}
function sessionSaveParams() {
    var params = "session_viewfilter" + g_split_val + m_param_viewfilter_status + m_param_viewfilter_type;
    var url = "?page=" + m_pagethis + "&action=param&pagesub=save&params=" + params + "&loadtime=" + g_map_listloadtime.get("store");
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)], itxt("ghilocdanhsach"));
                return;
            }
            data = getDataOk(data);
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}
function showListObj_Group(iddivshow) {
    if (g_list_objgroup.length > 0) {
        var html = "";
        for (var i = 0; i < g_list_objgroup.length; i++) {

            var item = g_list_objgroup[i];
            html += "<div class='btn_mainheader square'" +
                " onclick='showListObj(-1,\"\",0,\"idobjlist\",0," + item.id + ")' " +
                " ondrop=\"phienobj_drop(event," + item.id + ")\" ondragover=\"phienobj_allowDrop(event)\"" +
                "style='display: inline-block;'>" + item.name + "</div>";
        }
        setInnerById(iddivshow, html);
        return;
    }
}

//***UI_RENDER */
//objlistdata: list cua cac obj data lsDataToObj
function updateObjData(objlistdata) {
    var arobj = objlistdata.split(g_split_row);
    for (var i = 0; i < arobj.length; i++) {
        var objnew = lsDataToObj(arobj[i]);
        var objindex = getObjIndexFromId(objnew.id);
        if ((objindex >= 0) && (objindex < g_ls_objlist.length)) {
            g_ls_objlist[objindex].invoicels.invoiceid = objnew.invoicels.invoiceid;
            g_ls_objlist[objindex].invoicels.invoiceno = objnew.invoicels.invoiceno;
            g_ls_objlist[objindex].invoicels.totalcost = objnew.invoicels.totalcost;
            g_ls_objlist[objindex].gs_order = objnew.gs_order;
            uiUpdateObjInList(g_ls_objlist[objindex]);

        } else {
            showMsg(itxt("khongdungbanphong"));
        }

    }

}

function showListObjDlgSelect_GetSelectedIds() {
    var listId = "";
    var container = document.querySelector('#iddivcardselectobjall');

    //var checkboxesAll = container.querySelectorAll('input[type="checkbox"]');
    var checkBoxesSelected = container.querySelectorAll('input[type="checkbox"]:checked');
    if (isEmpty(checkBoxesSelected)) {
        alert("EMPTY"); return "";
    }
    if (checkBoxesSelected.length < 1) return "";
    for (var i = 0; i < checkBoxesSelected.length; i++) {
        var idnum = getId_ObjList_Check_NumberPart(checkBoxesSelected[i].id);
        if (idnum > 0) {
            if (listId != "") listId += ",";
            listId += idnum;
        }
    }
    return listId;
}
function showListObjDlgSelect_List_Add(objlist) {
    if (isEmpty(objlist)) {
        objlist = showListObjDlgSelect_GetSelectedIds();
    }
    if (isEmpty(objlist)) return;
    g_phien_invoice.cartSubmit(objlist);
    if (g_phien_viewmode == "list") {
        show("list");
    }
}
//nObjStatus: 1
async function showListObjDlgSelect(fnCallBackName, viewfilter_status, objcategory = -1, bmultiselect = true, strDlgTitle = "", arObjIdExclude) {
    var strOut = await showListObj(objcategory, "", 0, null, viewfilter_status, null, bmultiselect, fnCallBackName, arObjIdExclude);
    if (strOut.length == 0) {
        showMsg(itxt("khongcobanphongphuhop"));
        return;
    };
    strOut = "<div id='iddivcardselectobjall'>" + strOut + "</div>";
    strOut += "<div style='width:100%;height:auto;clear: both;'>";
    strOut += "<div class=\"btndlg cancel\" style=\"width:50%;height:36px;text-align:center;float:left\" title=\"\" onclick=\"dlgRemove();\">" + itxt("boqua") + "</div>";
    strOut += "<div class=\"btndlg ok\" style=\"width:50%;height:36px;text-align:center;float:right\" title=\"\" onclick=\"eval(" + fnCallBackName + ")(showListObjDlgSelect_GetSelectedIds());dlgRemove();\">" + itxt("cmd_apdung") + "</div>";
    strOut += "</div>";
    if (isEmpty(strDlgTitle)) {
        strDlgTitle = itxt("chonmothaynhieubanphong");
    }
    dlgShow(strOut, strDlgTitle);
    return false;
}
//hang chua trong cart cho toi khi ghi
function showInvoice() {

    g_phien_obj = null;
    g_phien_invoice.fnCallbackOnCartChange = "onChangeCart";
    g_phien_invoice.fnCallbackOnInvoiceChange = "onChangeInvoice";
    //idviewheader_invoice_caption
    show_HeaderCaption();
    //invoice goods list
    g_phien_invoice.iddivshow_goods_list = "idobjgoodslist";
    g_phien_invoice.invoiceShowGoods();

    if ((g_phien_invoice.getInvoiceGoodsCount() < 1) && (g_phien_invoice.cart_count < 1)) {
        g_phien_invoice.showSelect_Goods(0, '', "idgoodslistselect");
    }
    if (g_phien_invoice.invoiceid > 0) {
        eleEnable("idbuttoninvoiceprint", true);
        eleEnable("idbuttoninvoicenew", true);
        eleEnable("idbuttoninvoicesave");
    } else {
        eleEnable("idbuttoninvoiceprint");
        eleEnable("idbuttoninvoicenew");
        eleEnable("idbuttoninvoicesave", true);
    }
    show_ContactTradeUser();
}
async function showListObj(objcategory = -1, objname = "", selected_obj_id = 0, iddivshow, status, group_id, bmultiselect, fnCallBackNameOnClickObj, arrayObjIdExclude) {
    if (g_ls_objlist.length < 1) {
        if (await getSyncListObj() == false)
            return;
        if (g_ls_objlist.length < 1)
            return;
    }
    if (objcategory == -1) objcategory = m_param_viewfilter_type - 1;
    if (status == -1) status = m_param_viewfilter_status;
    if (isEmpty(group_id) || (group_id == -1))
        group_id = m_param_viewfilter_group;
    else
        m_param_viewfilter_group = group_id;
    if (!isEmpty(arrayObjIdExclude)) {
        if (isString(arrayObjIdExclude)) {
            arrayObjIdExclude = arrayObjIdExclude.split(",");
        }
    }
    //id,name,objcategory,statusremotecall,receivable,invoiceid,seatcount,group
    var objwidth = "20%";
    var wratio = $(window).width / 200;
    if (wratio != 0)
        objwidth = 100 / wratio + "%";
    if ($(window).width() < 600) {
        objwidth = "50%";
        var idmainobjlist = document.getElementById("idmainobjlist");
        if (idmainobjlist != null)
            idmainobjlist.style.width = "100%";
        var idmaincallgoods = document.getElementById("idmaincallgoods");
        if (idmaincallgoods != null)
            idmaincallgoods.style.width = "100%";
    }
    var strout = "";
    var strobj = ""; var strobjclass = ""; var strtotalcost = "";
    if (!isEmpty(objname)) {
        objname = objname.toLowerCase();
    }
    var item = g_ls_objlist[0];

    for (i = 0; i < g_ls_objlist.length; i++) {
        if ((!isEmpty(group_id)) && (group_id > 0)) {
            if (g_ls_objlist[i].group != group_id)
                continue;
        }
        if (objname.length > 0) {

            var name = g_ls_objlist[i].name.toLowerCase();
            if (name.indexOf(objname) < 0) {
                continue;
            }
        }
        if (objcategory >= 0) {
            if (g_ls_objlist[i].objcategory != objcategory)
                continue;
        }

        if (!isEmpty(status)) {
            if ((status == 1) && (g_ls_objlist[i].invoiceid > 0))
                continue;
            if ((status == 2) && (g_ls_objlist[i].invoiceid <= 0)) {
                continue;
            }

        }
        if (!isEmpty(arrayObjIdExclude)) {
            if (Array.isArray(arrayObjIdExclude)) {
                if (arrayObjIdExclude.includes(String(g_ls_objlist[i].id)))
                    continue;
            }
        }
        var item = g_ls_objlist[i];
        strobjclass = lsGetObjInListClass(item);
        var receivable = item.invoicels.getReceivableShow();
        var iddivobj = getId_ObjList_Div(item.id);
        var iddivobjmr = getId_ObjList_Div_MustRec(item.id);
        var iddivobjinfo = getId_ObjList_Div_Info(item.id);
        var onclick = "";
        var itemnameshow = item.name;



        //invoiceid la so phieu dang mo, chua ket thuc
        if (!isEmpty(fnCallBackNameOnClickObj)) {
            onclick = " onclick=\"dlgRemove();eval(" + fnCallBackNameOnClickObj + ")(" + item.id + ")\"";
        }
        else {
            onclick = " onclick=\"javascript:showObj(" + item.id + ")\"";
        }
        //obj_wrapper
        strobj = "<div id=\"" + iddivobj + "\" class=\"obj_wrapper\" style=\"width:" + objwidth + "\" draggable=\"true\" ondragstart=\"phienobj_drag(event," + item.id + ")\">";
        strobj += "<div class=\"" + strobjclass + "\" id=\"" + iddivobjinfo + "\">";
        strobj += "<div style='float:left;flex:100;cursor: pointer;'" + onclick + ">";
        strobj += "<div class='obj_up'>" + itemnameshow + "</div>";
        //seatcount
        if (item.seatcount > 0) {
            strobj += "<div class='obj_down'>";
            strobj += "<span class='objseatcount'>" + item.seatcount + "</span>";
            strobj += "<span style='float:center;margin-right:20px' id=\"" + iddivobjmr + "\">" + receivable + "</span>";
            strobj += "</div>";
        } else {
            strobj += "<div class='obj_down' id=\"" + iddivobjmr + "\">" + receivable + "</div>";
        }
        strobj += "</div>";
        if (bmultiselect == true)
            strobj += "<label class=\"objswitch\" style=\"float:right;margin:0px;padding:0px;\"><input type=\"checkbox\" id=\"" + getId_ObjList_Check(item.id) + "\"><span class=\"objslider\"></span></label>";

        strobj += "</div>";
        strobj += "</div>";

        strout += strobj;
    }
    if (!isEmpty(iddivshow)) {
        setInnerById(iddivshow, strout);
        //button
        if ((m_param_viewfilter_type != 0) || (m_param_viewfilter_status != 0)) {
            var idcmdlist_filter = document.getElementById("idcmdlist_filter");
            if (!isEmpty(idcmdlist_filter)) {
                idcmdlist_filter.style.backgroundImage = "url(imgs/bt_filter_on.png)";
                idcmdlist_filter.style.backgroundColor = "green";
            }

        }
        else {
            var idcmdlist_filter = document.getElementById("idcmdlist_filter");
            if (!isEmpty(idcmdlist_filter)) {
                idcmdlist_filter.style.backgroundImage = "url(imgs/bt_filter.png)";
                idcmdlist_filter.style.backgroundColor = "";
            }

        }
        if (g_ls_objlist.length < 30) eleShowHide("idcmdlist_searchobj");

        m_param_viewfilter_objcategory = objcategory;
    }

    else
        return strout;
}
//******************************************************************************************************************/
//swap: 1->1
//merge: 1/multi->1
//copy: 1->1/multi
function onClickCmdObjDo(target_objidlist, cmd, objidlist) {
    if (isEmpty(objidlist)) {
        if (g_phien_obj === null) return;
        objidlist = String(g_phien_obj.id);
    }
    if (target_objidlist.length < 1) {
        showMsg(itxt("khongxacdinhbanphong"));
        return;
    }
    showWaitModal();
    html = "";
    var url = "?page=" + m_pagethis + "&action=" + cmd + "&objidlist=" + objidlist + "&objidlisttarget=" + target_objidlist;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            hideModalBlock();
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            //invoiceid,totalcost,costfixed,costhourly,costmix,
            //5 discountfoods,discountdrink,discountgoods,discountservice,invoicediscount,extracharge,vat,invoicemoneydiscount,
            //13 contactid,contactname,contactaddress,phone,datebirth (13->17)
            //[{id,name,objcategory,statusremotecall,totalcost,invoiceid,seatcount}]
            //1-1
            if (cmd == "doicho") {
                var objindexfrom = getObjIndexFromId(objidlist);
                var objindexto = getObjIndexFromId(target_objidlist);

                var f = g_ls_objlist[objindexfrom];
                var t = g_ls_objlist[objindexto];

                t.invoicels.invoiceid = f.invoicels.invoiceid;
                clearObj(f, true);

                showObj(target_objidlist);
            }//1/multi->1
            else if (cmd == "gop") {
                //objlistid se gop vao target_objidlist
                var objindexto = getObjIndexFromId(target_objidlist);
                var t = g_ls_objlist[objindexto];
                if (isEmpty(t.costmix)) t.costmix = 0;

                var arFrom = objidlist.split(",");
                for (var i = 0; i < arFrom.length; i++) {
                    var objindexfrom = getObjIndexFromId(arFrom[i]);
                    var f = g_ls_objlist[objindexfrom];
                    t.invoicels.costmix += f.invoicels.totalcost;
                    clearObj(f, false);
                    uiUpdateObjInList(f);
                }
                uiUpdateObjInList(t);
                showObj(target_objidlist);
            }//1->1/multi					
            else if (cmd == "copy") {   //target_objidlist se copy sang objidlist
                //thong tin tra ve: [{obj_id,invoice_id,totalcost}]
                var objindexsrc = getObjIndexFromId(target_objidlist);
                var srcobj = g_ls_objlist[objindexsrc];
                var arDes = objidlist.split(",");
                var arDesObjInfo = getDataOk(data).split(g_split_row);
                for (var i = 0; i < arDesObjInfo.length; i++) {
                    var vals = arDesObjInfo[i].split(g_split_val);
                    if (vals.length == 3) {
                        var objindexdes = getObjIndexFromId(vals[0]);
                        var objdes = g_ls_objlist[objindexdes];
                        objdes.invoicels.totalcost = vals[2];
                        objdes.invoicels.invoiceid = vals[1];
                        uiUpdateObjInList(objdes);
                        if (!isEmpty(g_phien_obj)) {
                            if (objdes.id == g_phien_obj.id) {
                                showObj(g_phien_obj.id);
                            }
                        }
                    }
                    else {
                        showMsg(itxt("loidulieu"));
                        return;
                    }
                }
            }
            hideModalBlock();

        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });

}
function clearObj(f, bupdateviewobjdetails) {
    f.invoicels.clear();
    f.gs_order = 0;
    g_map_carts.set(f.id, null);
    if (bupdateviewobjdetails == true) {
        showObj_Clear(f);
    }
}
function onClickCmdObjDoGop(objid) {
    onClickCmdObjDo(String(objid), "gop");
}
function onClickCmdObjDoCopy(objid) {
    onClickCmdObjDo(String(objid), "copy");
}
function onClickCmdObjDoDoiCho(objid) {
    onClickCmdObjDo(String(objid), "doicho");
}
function onClickCartSubmit() {
    if (g_phien_invoice.cart_count < 1) {
        showMsg(itxt("giohangrong"), "", 500);
        return;
    }
    if (!isEmpty(g_phien_obj)) {
        g_phien_invoice.cartSubmit();
    } else {
        showListObjDlgSelect("showListObjDlgSelect_List_Add", 2);
    }
}
function onClickCart() {
    if (g_phien_viewmode == "obj") {
        if (!g_phien_obj.invoicels.canedit) return;
    } else if (g_phien_viewmode == "invoice") {
        if (!g_phien_invoice.canedit) return;
    }
    eleShowHide("idgoodslistselect");
    eleShowHide("idcart", 1);
    if (g_phien_viewmode == "invoice") {
        showInvoice();
    } else if (g_phien_viewmode == "list") {
        g_phien_invoice.cartShow("idcart", true);
    } else if (g_phien_viewmode == "obj") {
        eleShowHide("idgoodslistselect");
        g_phien_invoice.cartShow("idcart");
    } else {
        showMsg(itxt("khongxacdinhchedohienthi"));
    }
}

function onClickCmdObj(cmd) {
    if (isEmpty(g_phien_obj)) return;

    if (cmd == "gop") {
        if (g_phien_obj.invoicels.invoiceid <= 0) return;
        showListObjDlgSelect('onClickCmdObjDoGop', 2, -1, false, "[" + g_phien_obj.name + "] " + g_char_rightarrow + " " + itxt("gopvao") + "..");
    }
    else if (cmd == "copy") {
        if (g_phien_obj.invoicels.invoiceid > 0) return;
        showListObjDlgSelect('onClickCmdObjDoCopy', 2, g_phien_obj.objcategory, false);

    }
    else if (cmd == "doicho") {
        if (g_phien_obj.invoicels.invoiceid <= 0) return;
        showListObjDlgSelect('onClickCmdObjDoDoiCho', 1, g_phien_obj.objcategory, false);
    }
}
function onClickAddNewGoodsCategory(vals) {
    //showEditForm(id,extrafieldvalue=null,iddivshowitem="",rowdata=null,updategridview=1,fnCallBackNewRecordData)
    gridViewExGoodsCategory.editfrom_header = itxt("themnhomhang");
    if (isEmpty(vals))
        gridViewExGoodsCategory.showEditForm(0, null, "", null, 1, "onClickAddNewGoodsCategory");
    else {
        g_list_goodscategory.push({ "id": vals[0], "name": vals[1] });
    }
}
function onClickAddNewGoods() {
    if (g_list_goodscategory.length < 1) {
        showMsg(itxt("chuakhaibaonhomhang"));
        return;
    }
    gridViewExGoods.editfrom_header = itxt("themmathang");
    gridViewExGoods.showEditForm(0);
}
function onClickAddNewObjGroup(vals) {
    if (isEmpty(vals)) {
        gridObjGroup.editfrom_header = itxt("themnhombanphong");
        gridObjGroup.showEditForm(0, null, "", null, 1, "onClickAddNewObjGroup");
    } else {
        g_list_objgroup.push({ "id": vals[0], "name": vals[1] });
    }

}
function onClickGoodsLoadLocal() {
    if (!isEmpty(g_phien_obj))
        g_phien_obj.invoicels.invoice_GoodsLoadLocal();

}
async function onClickAddNewObj(vals) {
    if (isEmpty(vals)) {
        if (g_list_objcategory.length < 1) {
            await getSyncListObjCategory();
        }
        if (g_list_objtype.length < 1) {
            await getSyncListObjType();
        }
        if (g_list_objgroup.length < 1) {
            await getSyncListObjGroup();
        }
        gridObj.editfrom_header = itxt("thembanphong");
        gridObj.showEditForm(0, null, null, null, null, "onClickAddNewObj");
    } else {
        var obj = { "id": vals[0], "objcategory": vals[1], "name": vals[2], "typeid": parseNumberVn(vals[4]), "totalcost": 0, "invoiceid": 0, "seatcount": 0, "group": 7 };
        g_ls_objlist[g_ls_objlist.length] = obj;
        show("list");
        await showListObj(obj.objcategory, "", 0, "idobjlist", 0, 0, false, "");
    }
}
function lsGSOrderAddFromCart(cart) {
    var idshow = document.getElementById("idgoodscallqueue");
    if (isEmpty(idshow)) {
        alert("idgoodscallqueue not found!")
        return;
    }
    var param = "";
    cart.forEach((value, key) => {
        if (value.quantity != 0) {
            param += value.goods_id;
            param += value.unit_id;
            param += value.quantity;
            param += value.unit_price;
            param += value.note;

        }

    }
    );
}
//val_confirm:0-cancel,1-accept
async function lsGSOrderConfirm(log_src_id, obj_id, val_confirm) {
    var url = "?page=" + m_pagethis + "&pagesub=orderconfirm&&id=" + log_src_id + "&val=" + val_confirm;
    var data = await getSync(url);
    if (!isDataOk(data)) {
        showMsg([itxt("loi"), getDataFail(data)]);
        return;
    }

    lsGSOrderRemove(log_src_id);
    var obj = getObjFromId(obj_id);
    //view obj details
    if (!isEmpty(obj)) {
        //accept
        if (val_confirm == 1) {
            //uiUpdateObjInList(obj);
            showObjRefresh(obj);
        }
    }
}

function invoiceNew(resinvoicesource) {

    if (isEmpty(resinvoicesource) && (g_list_resinvoicesource.length > 0)) {
        var menu = "";

        menu += "<a href='javascript:void(0)' onclick='hideModal();invoiceNew(0)' class='menu_popup_item'>Mang đi</a>";
        for (var i = 0; i < g_list_resinvoicesource.length; i++) {
            menu += "<a href='javascript:void(0)' onclick='hideModal();invoiceNew(" + g_list_resinvoicesource[i].id + ")' class='menu_popup_item'>" + g_list_resinvoicesource[i].name + "</a>";
        }
        showModal(menu, "Chọn nguồn đơn hàng");
        return;
    }
    var invoice = new CInvoiceLS("XB", 0, "g_phien_invoice", "", resinvoicesource);//key rong, tu tinh key
    invoice.invoicedate = getCurDateTime();
    g_phien_invoices.set(invoice.key, invoice);
    g_phien_invoice = invoice;
    show("invoice");
}
function invoiceChangeSource(key) {
    var invoice = g_phien_invoices.get(key);
    if (invoice == null) {
        showMsg(itxt("khongtimthayhoadon"), itxt("quanlytinhtien"), 1000);
        return;
    }
    hideModal();
    //g_phien_invoices.delete(key);
}
function invoiceRemove(key) {
    hideModal();
    var invoice = g_phien_invoices.get(key);
    if (invoice == null) {
        showMsg(itxt("khongtimthayhoadon"), itxt("quanlytinhtien"), 1000);
        return;
    }
    g_phien_invoices.delete(key);
    if (g_phien_invoice.key == key) {
        g_phien_invoice.clear();
        g_phien_invoice = null;
        show("list");
    }
    else {
        invoiceShowListPopup();
    }
}
function invoiceActive(key) {
    var invoice = g_phien_invoices.get(key);
    if (invoice == null) {
        showMsg(itxt("khongtimthayhoadon"), itxt("quanlytinhtien"), 1000);
        return;
    }
    g_phien_invoice = invoice;
    show("invoice");
}
//nParam==1: cart submit to queueu
async function onChangeCart(bHideCart, nParam) {
    if (g_phien_viewmode == "invoice") {
        show_HeaderCaption();
        if (nParam == 2)//cart add sub
        {
            showInvoice();
        }
        hideModal();

    } else if (g_phien_viewmode == "list") {
        if (bHideCart) {
            eleShowHide(g_phien_invoice.iddivshow_goods_select);
            show("list");
        } else {
            show_HeaderCaption();
        }

    } else if (g_phien_viewmode == "obj") {
        show_HeaderCaption();
    }
    else {
        showMsg(itxt("khongxacdinhchedohienthi"));
    }
    if (nParam == 1) {
        if (g_phien_viewmode == "obj") {
            eleShowHide(g_phien_invoice.iddivshow_goods_select);
            show(g_phien_viewmode);
            await lsGSOrderLoad(g_phien_obj, "lsGSOrderShow");
        } else {
            await lsGSOrderLoad(null, "lsGSOrderShow");
        }
    }
}
//param:1-change all invoice and list goods service
//      3-them hang tu gio hang che view goods cho nhieu ban/phong
//      4-change goods quantity
//      5-save complete
//obj_info: info of obj to update
function onChangeInvoice(param, obj_info) {

    if (!isEmpty(obj_info)) {
        var obj = getObjFromId(obj_info.id);
        if (!isEmpty(obj)) {
            obj.invoicels.invoiceid = obj_info.invoiceid;
            obj.invoicels.totalcost = obj_info.totalcost;
            uiUpdateObjInList(obj);
        }
        return;
    }

    if (param == 3) {
        show("list");
        return;
    }
    if (g_phien_viewmode == "invoice") {
        show_HeaderCaption();
        show_ContactTradeUser();
        if (g_phien_invoice.invoiceid > 0) {
            eleEnable("idbuttoninvoicenew", true);
            eleEnable("idbuttoninvoiceprint", true);
            eleEnable("idbuttoninvoicesave");

        } else {
            eleEnable("idbuttoninvoicenew");
            eleEnable("idbuttoninvoiceprint");
            eleEnable("idbuttoninvoicesave", true);

        }
        if (!g_phien_invoice.canedit) {
            setInnerById("idcartcount", "");
            if (g_phien_invoice.invoiceid > 0) g_phien_invoices.delete(g_phien_invoice.key);
        }
        setInnerById("idinvoicecount", g_phien_invoices.size - 1);

    } else if (g_phien_viewmode == "list") {

        show_HeaderCaption();

    } else if (g_phien_viewmode == "obj") {

        if (param == 1) {
            show("obj");
            showObj(g_phien_obj.id);
        } else if (param == 4) {
            showObj();
        }
        else {

            show_HeaderCaption();
            show_ContactTradeUser();
            uiUpdateObjInList(g_phien_obj);
            uiUpdateObjReceivables(g_phien_obj);
            if (!g_phien_invoice.canedit) {
                setInnerById("idcartcount", "");
            }
        }

    }
    else {
        showMsg(itxt("khongxacdinhchedohienthi"), itxt("quanlytinhtien"));
    }
    //invoice save complete
    if (param == 5) {

    }
}

function isCurObjInListId(listId) {
    if (isEmpty(g_phien_obj)) return false;
    if (isEmpty(listId)) return false;
    listId = String(listId);
    if (listId.length == 0) return false;
    var bcurobjinobjparam = false;
    var arobj = listId.split(",");

    for (var i = 0; i < arobj.length; i++) {
        if (arobj[i] == g_phien_obj.id) {
            bcurobjinobjparam = true;
            break;
        }
    }
    return bcurobjinobjparam;
}
function show_ContactTradeUser() {
    var cshow = "", dshow = "", tshow = "";

    if (!isEmpty(g_phien_invoice.contactid) && (g_phien_invoice.contactid > 0)) {
        var cshow = g_phien_invoice.contactname;
        if ((g_phien_invoice.contactaddress.length > 0) || (g_phien_invoice.phone.length > 0)) {
            cshow += "<br><div class='subinfo>";
            if (g_phien_invoice.contactaddress.length > 0) cshow += g_phien_invoice.contactaddress;
            if (g_phien_invoice.phone.length > 0) cshow += "  " + g_phien_invoice.phone;
            cshow += "</div>";
        }
        setInnerById("idmodedetailscontact", cshow);
        eleShowHide("idmodedetailscontact", 1);
    }

    if (!isEmpty(g_phien_invoice.tradeuserid) && (g_phien_invoice.tradeuserid > 0)) {

        for (i = 0; i < g_list_employee.length; i++) {

            if (g_list_employee[i].id == g_phien_invoice.tradeuserid) {
                tshow = g_list_employee[i].name;
                if (g_list_employee[i].mobile.length > 0) tshow += " (" + g_list_employee[i].mobile + ")";
            }
        }
        setInnerById("idmodedetailstradeuserid", tshow);
        eleShowHide("idmodedetailstradeuserid", 1);
    }
    if (g_phien_viewmode == "invoice") {
        if (!isEmpty(g_phien_invoice.contactid_delivery) > 0) {
            dshow = g_phien_invoice.contactname_delivery;
            if ((g_phien_invoice.contactaddress_delivery.length > 0) || (g_phien_invoice.phone_delivery.length > 0)) {
                dshow += "<br><div class='subinfo>";
                if (g_phien_invoice.contactaddress_delivery.length > 0) dshow += g_phien_invoice.contactaddress_delivery;
                if (g_phien_invoice.phone_delivery.length > 0) dshow += "  " + g_phien_invoice.phone_delivery;
                dshow += "</div>";
            }
        }
        if (dshow.length > 0)
            setInnerById("idmodedetailscontactdelivery", dshow);
        eleShowHide("idmodedetailscontactdelivery", 1);
    }

}
function show_HeaderCaption() {
    if (g_phien_viewmode == "invoice") {
        if (isEmpty(g_phien_invoice.invoiceno)) g_phien_invoice.invoiceno = "(" + itxt("donmoi") + ")";
        if (isEmpty(g_phien_invoice.invoicedate)) g_phien_invoice.invoicedate = getCurDateTime();
        if (isEmpty(g_phien_invoice.totalcost)) g_phien_invoice.totalcost = 0;

        var html = "";
        var totalcost = g_phien_invoice.cart_sum;
        if (g_phien_invoice.invoiceid > 0) totalcost = g_phien_invoice.totalcost;
        totalcost = totalcost - parseNumberVn(g_phien_invoice.invoicemoneydiscount);

        if (g_phien_invoice.resinvoicesourcename != null)
            html += g_phien_invoice.resinvoicesourcename + " - " + g_phien_invoice.invoiceno;
        else
            html += g_phien_invoice.invoiceno;

        html += "<div class='subinfo'>" + g_phien_invoice.invoicedate + " - " + formatNumber(totalcost) + "</div>";
        setInnerById("idviewheader_invoice_caption", html);
        setInnerById("idcartcount", g_phien_invoice.cart_count);
        setInnerById("idinvoicelist", g_phien_invoices.size - 1);

        var ttcshow = formatNumber(totalcost);
        if (isEmpty(ttcshow) || (ttcshow == "0") || ttcshow == 0) ttcshow = "";

        setInnerById("idobjmustrec", ttcshow);
        setInnerById("idmodedetailsobjpayment_val", ttcshow);
        setInnerById("idobjsum", ttcshow);
        setInnerById("idmixcost", "");

    } else if (g_phien_viewmode == "list") {
        setInnerById("idcartcount", g_phien_invoice.cart_count);
    } else if (g_phien_viewmode == "obj") {
        var nameshow = g_phien_obj.name;
        var subinfo = "";
        var i = 0;
        if (g_phien_invoice.services.size > 0) {
            var sts = g_phien_invoice.getInvoiceServiceCount();
            if (sts > 0)
                subinfo += sts + " " + itxt("dichvu");
        }
        if (g_phien_invoice.goods.size > 0) {
            var sts = g_phien_invoice.getInvoiceGoodsCount();
            if (sts > 0) {
                if (subinfo.length > 0) subinfo += " - ";
                subinfo += sts + " " + itxt("s_mons");
            }
        }
        if (g_phien_invoice.invoiceid > 0) {
            if (subinfo.length > 0) subinfo += " - ";
            subinfo += formatNumber(g_phien_invoice.totalcost);
        }
        if (subinfo.length > 0) nameshow = nameshow + "<br><div class='subinfo' style='float:left;color:#8800FF'>" + g_phien_invoice.invoiceno + ": " + subinfo + "</div>";
        setInnerById("idobjname", nameshow);

        setInnerById("idcartcount", g_phien_invoice.cart_count);

    } else {
        showMsg(itxt("khongxacdinhchedohienthi"));
    }
}
//tab: goods, list, obj, invoice
function show(tab) {
    if (isEmpty(tab)) tab = "list";

    eleShowHide("idcart");
    eleShowHide("idviewgoods_bottombar");
    eleShowHide("idviewobj_bottombar");

    //clear payment_details_display
    setNumById("iddiscountgoods", "");
    setNumById("iddiscountservice", "");
    setNumById("idinvoicediscount", "");
    setNumById("idobjservicecharge", "")
    setNumById("idobjvat", "");
    setValById("idobjinvoicemoneydiscount", "");
    setInnerById("iddebit", "");

    if (tab == "goods") {
        g_phien_invoice.showSelect_Goods(0, '', "idgoodslistselect");
        if (g_phien_viewmode != "obj") { showInvoice(); } else {
        }
        if (!isEmpty(g_phien_obj)) {
            setValById("idcartsubmit", itxt("them") + " [" + g_phien_obj.name + "]");
        } else {
            setValById("idcartsubmit", itxt("themvao") + "..");
        }

        eleShowHide("idviewgoods_bottombar", true);
    } else if (tab == 'list') {
        g_phien_viewmode = tab;
        g_phien_invoice = g_phien_invoices.get("phien");
        showListObj(-1, '', 0, "idobjlist", -1);
        setInnerById("idinvoicecount", g_phien_invoices.size - 1);
        show_HeaderCaption();
        lsGSOrderShow();
    } else if (tab == "obj") {

        g_phien_viewmode = tab;
        eleShowHide("idviewinvoice_bottombar");
        eleShowHide("idviewobj_bottombar", true);
        //hien thi giao dien chinh
        eleShowHide("idmodedetailsobj", 1);
        eleShowHide("idmodedetailsobjpayment", 1);
        eleShowHide("idmodedetailscontact");
        eleShowHide("idmodedetailscontactdelivery");
        eleShowHide("idmodedetailstradeuserid");
    } else if (tab == "invoice") {
        g_phien_viewmode = tab;
        eleShowHide("idobjservicelistwrap");
        eleShowHide("idobjmixlistwrap");
        eleShowHide("idmodedetailscontact", true);
        eleShowHide("idmodedetailscontactdelivery", true);
        eleShowHide("idmodedetailstradeuserid", true);
        eleShowHide("idviewinvoice_bottombar", true);
        eleShowHide("idviewobj_bottombar");
        eleShowHide("idobjgoodslistwrap", true);
        eleShowHide("idmodedetailsobjpayment", true);

        showInvoice();
    } else {
        alert("viewmode not detect");
        g_phien_viewmode = "list";
    }
    //if(isEmpty(g_phien_viewmode))g_phien_viewmode="list";

    eleShowHide("idgoodslistselect", (tab == "goods") ? true : false);
    eleShowHide("idviewlist", (tab == "list") ? true : false);
    eleShowHide("idviewobj", ((tab == "obj") || (tab == "invoice")) ? true : false);

    eleShowHide("idviewheader_goods", ((tab == "goods") && (g_phien_viewmode == "list") || (isEmpty(g_phien_viewmode))) ? true : false);
    eleShowHide("idviewheader_list", ((g_phien_viewmode == "list") && (tab == "list")) ? true : false);
    eleShowHide("idviewheader_obj", (g_phien_viewmode == "obj") ? true : false);
    eleShowHide("idviewheader_invoice", (g_phien_viewmode == "invoice") ? true : false);
}
function showObjMix(iddivshow) {
    var url = "?page=" + m_pagethis + "&action=getmerge&obj_id=" + g_phien_obj.id;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), data]);
                return;
            }
            data = getDataOk(data);
            gridMix.showGrid(data, iddivshow);
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}
//nap lai du lieu obj va cap nhat hien thi
async function showObjRefresh(obj) {
    var url = "?page=" + m_pagethis + "&action=phienobj&obj_id=" + obj.id;
    var data = await getSync(url);
    if (!isDataOk(data)) {
        showMsg([itxt("loi"), getDataFail(data)]);
        return false;
    }
    data = getDataOk(data);
    if (data.length < 1) return;

    var objret = lsDataToObj(data);
    obj.invoicels.invoiceid = objret.invoicels.invoiceid;
    obj.invoicels.invoiceno = objret.invoicels.invoiceno;
    obj.invoicels.totalcost = objret.invoicels.totalcost;
    obj.gs_order = objret.gs_order;

    if (isEmpty(obj)) {
        showMsg([itxt("loi"), data]);
        return false;
    }
    if (obj.invoicels.invoiceid == 0) clearObj(obj, false);

    if (g_phien_viewmode == "list") {
        uiUpdateObjInList(obj);
        //showListObj(m_param_viewfilter_objcategory,"",0,"idobjlist",m_param_viewfilter_status,m_param_viewfilter_group);    
    } else {
        if (!isEmpty(g_phien_obj)) {
            if (obj.id == g_phien_obj.id) showObj(obj.id);
        }
    }
    return true;
}

function showObj_Clear(obj) {
    setNumById("iddiscountgoods", "");
    setNumById("iddiscountservice", "");
    setNumById("idinvoicediscount", "");
    setNumById("idobjservicecharge", "");
    setNumById("idobjvat", "");
    setInnerById("idobjname", obj.name);
    setInnerById("idobjservicelist", "");
    setInnerById("idobjgoodslist", "");

    setInnerById("idmodedetailsobjpayment_val", "");
    setInnerById("idobjsum", "");
    setNumById("idobjinvoicemoneydiscount", "");
    setInnerById("idmixcost", "");
    setInnerById(getId_ObjList_Div_MustRec(obj.id), "");
    //setInnerById("idmodedetailscontact","");
    setNumById("iddebit", "");
    setInnerById("idcartcount", "");
    setInnerById("idsumservice", "");
    setInnerById("idsumgoods", "");

}
//nap va hien thi obj hoac nap lai va hien thi lai
async function showObj(obj_id) {
    if (g_phien_viewmode != "obj") {
        show("obj");
    }
    //reset trang thai goods
    var objtoshow = null;
    var objprev = g_phien_obj;

    if (!isEmpty(obj_id))//g_phien_obj hien tai, nap lai
    {
        var objindex = getObjIndexFromId(obj_id);
        if (objindex < 0)
            return;
        objtoshow = g_ls_objlist[objindex];
    }
    else
        objtoshow = g_phien_obj;

    g_phien_obj = objtoshow;

    showObj_Clear(g_phien_obj);

    if (isEmpty(g_phien_obj.invoicels)) {
        g_phien_invoice = g_phien_obj.invoicels;
        g_phien_invoice.iddivshow_cart_count = "idcartcount";
    } else {
        g_phien_invoice = g_phien_obj.invoicels;
    }
    g_phien_invoice.canedit = true;
    g_phien_invoice.page_source = m_pagethis;
    g_phien_invoice.fnCallbackOnCartChange = "onChangeCart";
    g_phien_invoice.fnCallbackOnInvoiceChange = "onChangeInvoice";

    g_phien_invoice.goods.clear();
    g_phien_invoice.services.clear();

    uiUpdateObjInList(objprev);
    uiUpdateObjInList(g_phien_obj);

    //clear
    //1. service list
    setInnerById("idobjservicelist", "");
    //2. goods list
    setInnerById("idobjgoodslist", "");
    //3. contact - employee



    var idobjservicelistwrap = document.getElementById("idobjservicelistwrap");
    if (g_phien_obj.invoicels.services.size > 0)
        idobjservicelistwrap.style.display = "block";
    else {
        if (g_phien_obj.objcategory != 0) {
            idobjservicelistwrap.style.display = "block";
        } else {
            idobjservicelistwrap.style.display = "none";

        }
    }
    lsGSOrderShow(g_phien_obj);

    if (g_phien_invoice.invoiceid > 0) {
        g_phien_invoice.invoiceLoad("showObjInvoiceDetails");//lay thong tin phieu, sau do lay thong tin chi tiet, sau do hien thi chi tiet
    }
    else {
        show_HeaderCaption();

        //gs_order: so hang/dich vu duoc goi
        //res-takeaway
        if ((g_phien_obj.objcategory == 0) || (g_phien_obj.objcategory == 4)) {

            //neu chua co goi dat hang thi hien thi bang chon lua hang
            if (g_phien_obj.gs_order > 0) {
                eleShowHide("idviewobj_bottombar");
                eleShowHide("idviewgoods_bottombar");
            } else {
                g_phien_invoice.showSelect_Goods(0, "", "idgoodslistselect");
                eleShowHide("idviewobj_bottombar");
                eleShowHide("idviewgoods_bottombar", true);
                setValById("idcartsubmit", itxt("themvao") + ": " + g_phien_obj.name);
            }

        }
        else {
            showSelect_Service(g_phien_obj.id);
        }
    }
}
//objlist la array: id+totalcost
function showObjFromData(freshdata) {
    if (freshdata.length < 1)
        return;
    var arinf = freshdata.split(g_split_row);
    var ncount = arinf.length;
    if (freshdata.length == 0) ncount = 0;
    var newval = "";
    for (i = 0; i < ncount; i++) {
        var arval = arinf[i].split(g_split_val);
        var idobj = getId_ObjList_Div_MustRec(arval[0]);
        var obj = document.getElementById(idobj);
        if (obj) {
            var curval = obj.innerHTML;
            newval = arval[1];
            if (newval == "0") newval = "";
            if (newval != curval) {
                if ((newval != "") || (curval != ""))
                    obj.innerHTML = newval;
            }
        }
        //trung voi obj hien tai
        if (g_phien_obj.id == arval[0]) {
            var idtotalmoney = document.getElementById("idtotalmoney");
            if (idtotalmoney)
                idtotalmoney.innerHTML = newval;
        }
    }

}

function showObjUpdateGoodsChange() {
    var url = "?page=" + m_pagethis + "&action=goodslist&obj_id=" + g_phien_obj.id;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            var rows = getDataOk(data).split(g_split_row);
            var start = 0;
            g_phien_obj.invoicels.parseServiceGoodsData(rows, start, 2);
            showObjInvoiceDetails();
            show_HeaderCaption();
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}
function showObjUpdateServiceChange() {
    var url = "?page=" + m_pagethis + "&action=servicelist&obj_id=" + g_phien_obj.id;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            var rows = getDataOk(data).split(g_split_row);
            var start = 0;
            g_phien_obj.invoicels.parseServiceGoodsData(rows, start, 1);
            showObjInvoiceDetails();
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}




function getObjIndexFromInvoiceId(invoiceid) {
    var i = 0;
    for (i = 0; i < g_ls_objlist.length; i++)
        if (g_ls_objlist[i].invoiceid == invoiceid)
            return i;
    return -1;
}
function getObjIndexFromId(id) {
    var i = 0;
    for (i = 0; i < g_ls_objlist.length; i++)
        if (g_ls_objlist[i].id == id)
            return i;
    return -1;
}
function updateCacheObjDetailsGoods(id, quantity, price) {
    var item = g_phien_obj.invoicels.goods.get(id);
    if (item != null) {
        item.quantity = quantity;
        item.unit_price = price;
    }
    else {
        showMsg(itxt("khongtimthayhangtrongphieu"));
    }
}
//tao cac id div
function getId_ObjList_Div(obj_id) {
    return "iddoil" + obj_id;
}
function getId_ObjList_Check(obj_id) {
    return "iddoil" + obj_id + "check";
}

function getId_ObjList_Check_NumberPart(idstring) {
    if (isEmpty(idstring)) return null;
    idstring = idstring.replace("iddoil", "");
    idstring = idstring.replace("check", "");
    return parseNumberVn(idstring);
}
function getId_ObjList_Div_MustRec(obj_id) {
    return getId_ObjList_Div(obj_id) + "mr";
}
function getId_ObjList_Div_Info(obj_id) {
    return "iddoil" + obj_id + "inf";
}
function getObjFromId(objid) {
    for (var i = 0; i < g_ls_objlist.length; i++) {
        if (g_ls_objlist[i].id == objid) return g_ls_objlist[i];
    }
    return null;
}

function s_ServiceSelectEmployeeRemove(id) {
    var url = "?page=" + m_pagethis + "&action=servicesetemployee&obj_id=" + g_phien_obj.id + "&employeeid=0&id=" + id;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (isDataFail(data)) {
                showMsg(itxt("loi"));
                return;
            }
            else if (isDataOk(data)) {
                var id = getDataOk(data);
                hideModalBlock();
                var item = g_phien_obj.invoicels.services.get(id);
                if (item != null) {
                    item.realname = "";
                    showObjDetails_Service();
                }
                else {
                    showMsg(itxt("khongtimthaydichvutrongphieu"));
                }
            }
            else
                showMsg(itxt("loi"));
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}
function s_ServiceSelectEmployeeDo(id, name, mobile, comment) {
    var url = "?page=" + m_pagethis + "&action=servicesetemployee&obj_id=" + g_phien_obj.id + "&employeeid=" + id + "&id=" + m_active_service_id;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            var idret = getDataOk(data);
            hideModalBlock();
            var item = g_phien_obj.invoicels.services.get(parseNumberVn(idret));
            if (item != null) {
                item.realname = name;
                showObjDetails_Service();
            } else {
                showMsg(itxt("khongtimthaydichvutrongphieu"));
            }

        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}
function s_ServiceSelectEmployee(id) {
    m_active_service_id = id;
    DlgSelect.showUser(0, 's_ServiceSelectEmployeeDo');
}
function s_ServiceChangeStartTime(hour, min, day, month, year) {
    if ((hour < 0) || (hour > 23) || (min < 0) || (min > 59)) {
        showMsg(itxt("giovaphutkhonghople"));
        return;
    }
    if ((day < 0) || (day > 31) || (month < 0) || (month > 12) || (year < 2000) || (year > 2100)) {
        showMsg(itxt("ngaythangnamkhonghople"));
        return;

    }
    var date = day + '-' + month + '-' + year;
    var url = "?page=" + m_pagethis + "&action=servicechangetime&obj_id=" + g_phien_obj.id + "&id=" + m_active_service_id + "&hour=" + hour + "&min=" + min + "&date=" + date;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (isDataFail(data)) {
                showMsg(itxt("loi"));
                return;
            }
            else if (isDataOk(data)) {
                var rows = getDataOk(data).split(g_split_row);
                var start = 0;
                var vals = rows[0].split(g_split_val);
                if (parseInvoiceData(g_phien_obj, vals))
                    start = 1;
                g_phien_obj.invoicels.parseServiceGoodsData(rows, start, 1);

                showObjInvoice();
                showObjInvoiceDetails();
                hideModalBlock();
            }
            else
                showMsg(itxt("loi"));
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
    hideModalBlock();
}
//id: details id
function s_ServiceChangeStartTimeDlg(id) {
    m_active_service_id = id;
    DlgSelect.showTimeSelect('s_ServiceChangeStartTime');
}

function s_ServiceStopContinue(id, action) {
    var item = g_phien_obj.invoicels.services.get(id);
    if (item === null) return;
    //action=servicecontinue,servicestop
    if (action == "servicecontinue") {
        if (item.to === undefined) return;

        if (item.to == "") return;
    }
    if (action == "servicestop") {

        if (!isEmpty(item.to)) {
            if (item.to != "")
                return;
        }
    }

    showWaitModal();

    var url = "?page=" + m_pagethis + "&action=" + action + "&obj_id=" + g_phien_obj.id + "&id=" + id;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            hideModal();
            if (isDataFail(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            else if (isDataOk(data)) {
                var rows = getDataOk(data).split(g_split_row);
                var start = 0;
                var vals = rows[0].split(g_split_val);
                if (parseInvoiceData(g_phien_obj, vals))
                    start = 1;
                g_phien_obj.invoicels.parseServiceGoodsData(rows, start);

                showObjInvoice();
                showObjInvoiceDetails();
                hideModalBlock();
            }
            else
                showMsg(itxt("loi"));
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });

}
//type:0-goods, 1-service
function s_GoodsServiceRemove(id, type) {
    var url = "?page=" + m_pagethis + "&action=remove&obj_id=" + g_phien_obj.id + "&id=" + id + "&type=" + type;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            else {
                var rows = getDataOk(data).split(g_split_row);
                var start = 0;
                var vals = rows[0].split(g_split_val);
                if (parseInvoiceData(g_phien_obj, vals))
                    start = 1;
                g_phien_obj.invoicels.parseServiceGoodsData(rows, start);

                showObjInvoice();
                showObjInvoiceDetails();
                hideModalBlock();
            }

        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
    hideModalBlock();
}
function showObjDetails_Service_Details(id) {
    var url = "?page=" + m_pagethis + "&action=servicedetails&obj_id=" + g_phien_obj.id + "&id=" + id;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (isDataFail(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            else if (isDataOk(data)) {
                var rows = getDataOk(data).split(g_split_row);
                var html = "<div class='divtable'>";
                for (var i = 0; i < rows.length; i++) {
                    var vals = rows[i].split(g_split_val);
                    html += "<div class='divrow'>";
                    for (var j = 0; j < vals.length; j++)
                        html += "<div class='divcell'>" + vals[j] + "</div>";
                    html += "</div>";
                }
                html += "</div>";
                showMsg(html);
            }
            else
                showMsg(itxt("loi"));
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
    hideModalBlock();
}
//invoice_GoodsAdd(goods_id,unit_id,quantity,unit_price,details_id_parent)
function gsAddSub_OnGoodsSelect(param, id, goods_id, unit_id, goods_name, goods_code, unit_name, stock, export_price, color_name) {
    if (isEmpty(g_phien_obj)) return;
    if (!isEmpty(param))
        param = parseInt(param);
    else
        param = 0;
    goods_id = parseInt(goods_id);
    var bcancel = false;
    g_phien_obj.invoicels.goods.forEach((value, key) => {
        if (value.id == param) {
            if (value.goods_id == goods_id) {
                bcancel = true;
                return;
            }
        }
    });
    if (bcancel) {
        showMsg(itxt("khongthethemchinhhanglamhangphu"), "", 1000);
        return false;
    }
    g_phien_obj.invoicels.invoice_GoodsAdd(goods_id, unit_id, 1, export_price, param);
}
function gsAddSub(id) {
    DlgSelect.showGoods(1, "gsAddSub_OnGoodsSelect", id);
}
//invoice_GoodsAdd(goods_id,unit_id,quantity,unit_price,details_id_parent)
function gsCartAddSub_OnGoodsSelect(param, id, goods_id, unit_id, goods_name, goods_code, unit_name, stock, export_price, color_name) {
    if (isEmpty(g_phien_invoice)) return;
    showWaitModal();
    g_phien_invoice.cartAdd(goods_id, unit_id, 1, export_price, param, goods_name, unit_name);
}
function gsCartAddSub(id) {

    DlgSelect.showGoods(1, "gsCartAddSub_OnGoodsSelect", id);
}
function gsComment_OnOK(input_text, param) {
    if (isEmpty(g_phien_obj)) return;
    showWaitModal();
    g_phien_obj.invoicels.invoice_GoodsComment(param, input_text);
}
function gsComment(id) {
    DlgGetText(itxt("ghichu"), "gsComment_OnOK", id);
}
function gsPrintSticker(id) {
    gCallInterop("PRINTGOODSLABEL" + g_split_row + id);
}
function menuPopupItemGoods(id, idmixmain) {
    var menu = "";
    if (idmixmain <= 0) {
        menu += "<a href='javascript:void(0)' onclick='hideModal();gsAddSub(" + id + ")' class='menu_popup_item'>Thêm món phụ.." + "</a>";
    }
    menu += "<a href='javascript:void(0)' onclick='hideModal();gsComment(" + id + ")' class='menu_popup_item'>Ghi chú" + "</a>";
    if (idmixmain <= 0) {
        menu += "<a href='javascript:void(0)' onclick='hideModal();gsPrintSticker(" + id + ")' class='menu_popup_item'>In nhãn" + "</a>";
    }
    showModal(menu, "MENU");
}
function menuPopupItemGoodsCart(id, idmixmain) {
    var menu = "";
    if (idmixmain <= 0) {
        menu += "<a href='javascript:void(0)' onclick='hideModal();gsCartAddSub(\"" + id + "\")' class='menu_popup_item'>Thêm món phụ.." + "</a>";
    }
    menu += "<a href='javascript:void(0)' onclick='hideModal();gsCartComment(\"" + id + "\")' class='menu_popup_item'>Ghi chú" + "</a>";
    showModal(menu, "MENU-CART");
}
function menuPopupItemService(id) {
    var menu = "";
    menu += "<a href='javascript:void(0)' onclick='hideModal();s_ServiceSelectEmployee(" + id + ")' class='menu_popup_item'>Chọn nhân viên triển khai" + "</a>";
    menu += "<a href='javascript:void(0)' onclick='hideModal();s_ServiceSelectEmployeeRemove(" + id + ")' class='menu_popup_item'>Loại nhân viên triển khai" + "</a>";
    menu += "<a href='javascript:void(0)' onclick='hideModal();s_ServiceStopContinue(" + id + ",\"servicestop\")' class='menu_popup_item'>Dừng dịch vụ" + "</a>";
    menu += "<a href='javascript:void(0)' onclick='hideModal();s_ServiceStopContinue(" + id + ",\"servicecontinue\")' class='menu_popup_item'>Chạy tiếp dịch vụ" + "</a>";
    menu += "<a href='javascript:void(0)' onclick='hideModal();s_GoodsServiceRemove(" + id + ",1)' class='menu_popup_item'>Xóa dịch vụ" + "</a>";
    menu += "<a href='javascript:void(0)' onclick='hideModal();s_ServiceChangeStartTimeDlg(" + id + ")' class='menu_popup_item'>Đổi giờ bắt đầu" + "</a>";
    //hotel
    if (g_phien_obj.objcategory == 2)
        menu += "<a href='javascript:void(0)' onclick='hideModal();showObjDetails_Service_Details(" + id + ")' class='menu_popup_item'>Chi tiết về dịch vụ" + "</a>";

    showModal(menu, "MENU");
}
function showObjDetails_Service() {

    var subtotal = 0, totalcost = 0;
    //DANH SACH DICH VU

    var html = "<div class='divtable'>";
    g_phien_obj.invoicels.services.forEach((item, key) => {
        if (item.to != "")
            html += "<div class='divrow red' id='' onclick='menuPopupItemService(" + item.id + ")'>";
        else
            html += "<div class='divrow dgreen' id='' onclick='menuPopupItemService(" + item.id + ")'>";

        html += "<div class='divcell click' style='width:40%'><b>";
        html += item.name + "</b><br class='linebreak'><div class='subinfo'>" + formatNumber(item.unit_price) + "/" + item.unit + "</div>";
        html += "</div>";
        html += "<div class='divcell' style='text-align:right;width:35%'>";
        subtotal = (item.unit_price) * (item.quantity);
        totalcost += subtotal;
        html += item.from;
        if (item.to != "") html += "&#8594;" + item.to;
        html += " (<b>" + item.quantity + "</b>)";
        html += "<br class='linebreak'><b>" + formatNumber(subtotal) + "</b>";
        html += "</div>";
        html += "<div class='divcell' style='text-align:center;width:25%'>";
        html += item.realname;
        html += "</div>";
        html += "</div>";
    });
    html += "</div>";
    setInnerById("idobjservicelist", html);
    g_phien_obj.invoicels.costhourly = formatNumber(totalcost);
    setInnerById("idsumservice", formatNumber(totalcost));
    return totalcost;
}

function showObjDetails_Goods() {
    var idobjgoodslistwrap = document.getElementById("idobjgoodslistwrap");
    if (g_phien_obj.invoicels.goods.size > 0)
        idobjgoodslistwrap.style.display = "block";
    else
        idobjgoodslistwrap.style.display = "none";
    g_phien_obj.invoicels.iddivshow_goods_list = "idobjgoodslist";
    g_phien_obj.invoicels.invoice_ShowGoods();
}

function showObjInvoice() {
    setNumById("idobjinvoicemoneydiscount", g_phien_obj.invoicels.invoicemoneydiscount);
    setNumById("iddiscountgoods", g_phien_obj.invoicels.discountgoods);
    setNumById("iddiscountservice", g_phien_obj.invoicels.discountservice);
    setNumById("idinvoicediscount", g_phien_obj.invoicels.invoicediscount);
    setNumById("idobjservicecharge", g_phien_obj.invoicels.extracharge)
    setNumById("idobjvat", g_phien_obj.invoicels.vat);
    eleShowHide("idmodedetailsobjpayment", 1);

    show_HeaderCaption();
    show_ContactTradeUser();

    uiUpdateObjReceivables(g_phien_obj);
}
function showObjInvoiceDetails() {
    if (g_phien_obj === null)
        return;

    var curinvoiceid = g_phien_obj.invoicels.invoiceid;
    setNumById("iddiscountgoods", g_phien_obj.invoicels.discountgoods);
    setNumById("iddiscountservice", g_phien_obj.invoicels.discountservice);
    setNumById("idinvoicediscount", g_phien_obj.invoicels.invoicediscount);
    setNumById("idobjservicecharge", g_phien_obj.invoicels.extracharge);
    setNumById("idobjvat", g_phien_obj.invoicels.vat);
    setNumById("idobjinvoicemoneydiscount", g_phien_obj.invoicels.invoicemoneydiscount);


    var scost = showObjDetails_Service();
    var gcost = showObjDetails_Goods();
    //mix
    var idobjmixlistwrap = document.getElementById("idobjmixlistwrap");
    setInnerById("idsummix", g_phien_obj.invoicels.costmix);
    if (parseNumberVn(g_phien_obj.invoicels.costmix) > 0)
        idobjmixlistwrap.style.display = "block";
    else
        idobjmixlistwrap.style.display = "none";
}

function callPrintOnServer(printtype) {
    if (g_phien_obj.invoicels.invoiceid <= 0) {
        showMsg("Chưa có phiếu");
        return false;
    }
    var url = "?page=" + m_pagethis + "&action=goiin&obj_id=" + g_phien_obj.id + "&type=" + printtype;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }

            showModal("Đã gọi in trên máy chủ");
            hideModal();

        },
        error: function () {
            hideModal();

        }
    });
}
function callContactCardDo(inputbox) {
    hideModalBlock();
    if (inputbox === undefined) return; if (inputbox == null) return;
    var cardcode = inputbox.value;
    if (cardcode.length < 1)
        return false;
    var url = "?page=" + m_pagethis + "&action=contactcard&obj_id=" + g_phien_obj.id + "&cardcode=" + cardcode;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }

            var invoices = getDataOk(data).split(g_split_val);
            if (g_phien_obj.invoicels.parseInvoiceData(invoices)) show_ContactTradeUser();
            hideModal();

        },
        error: function () {
            showMsg(itxt("loi"));
            hideModal();
        }
    });
    hideModalBlock();

}
function callContactCard() {
    if (g_phien_obj.invoicels.invoiceid <= 0) {
        showMsg("Chưa có phiếu");
        return false;
    }
    DlgGetText("Nhập vào thẻ khách hàng", "callContactCardDo");
}
function callPaymentCustomerGive(val) {
    setValById("idpaymentcustomergive", formatNumber(val));
    setValById("idpaymentpayback", formatNumber(val - parseNumberVn(getInnerById("idpaymentmustreceive"))));
}

function callPaymentShowMethod(paymentdebit, iddivshow, subval) {
    var html = "";
    if (isEmpty(paymentdebit)) paymentdebit = 0;
    if (paymentdebit == 1)
        subval = -1;
    else if (isEmpty(subval))
        subval = 0;
    if (paymentdebit > 0)
        html += "<span onclick='m_payment_method=0;callPaymentShowMethod(1,\"idcallpaymentmethod\");' class='btn_mainheader " + strSelected(1, paymentdebit) + "' style='float:left;width:100%;margin-left:0px;margin-bottom:8px;'>" + itxt("ghino") + "</span>";
    html += "<span onclick='m_payment_method=0;callPaymentShowMethod(0,\"idcallpaymentmethod\",0);' class='btn_mainheader " + strSelected(0, subval) + "' style='float:left;width:20%;margin-left:0px'>" + itxt("tienmat") + "</span>";
    html += "<span onclick='m_payment_method=1;callPaymentShowMethod(0,\"idcallpaymentmethod\",1);' class='btn_mainheader " + strSelected(1, subval) + "' style='float:left;width:30%'>" + itxt("chuyenkhoan") + "</span>";
    html += "<span onclick='m_payment_method=2;callPaymentShowMethod(0,\"idcallpaymentmethod\",2);' class='btn_mainheader " + strSelected(2, subval) + "' style='float:left;width:20%'>" + itxt("the") + "</span>";
    html += "<span onclick='m_payment_method=3;callPaymentShowMethod(0,\"idcallpaymentmethod\",3);' class='btn_mainheader " + strSelected(3, subval) + "' style='float:right;width:20%;margin-right:0px'>" + itxt("kethop") + "</span>";
    if (!isEmpty(iddivshow)) {
        setInnerById(iddivshow, html);
    }
    else
        return html;
}
function callPaymentShowGuestMoney(cash) {
    var cashes = [1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000];
    var u500 = cash % 500000; var p500 = (cash - u500) / 500000;
    var u200 = u500 % 200000; var p200 = (u500 - u200) / 200000;
    var u100 = u200 % 100000; var p100 = (u200 - u100) / 100000;
    var u50 = u100 % 50000; var p50 = (u100 - u50) / 50000;
    var u20 = u50 % 20000; var p20 = (u50 - u20) / 20000;
    var u10 = u20 % 10000; var p10 = (u20 - u10) / 10000;
    var u5 = u10 % 5000; var p5 = (u10 - u5) / 5000;
    var u2 = u5 % 2000; var p2 = (u5 - u2) / 2000;
    var listM = [];
    var money1 = (p500 + 1) * 500000;
    var money2 = p500 * 500000 + (p200 + 1) * 200000;
    listM[0] = money1;
    listM[1] = money2;
    var money3 = p500 * 500000 + p200 * 200000 + (p100 + 1) * 100000;
    if (money3 != money2) listM[listM.length] = money3;
    var money4 = p500 * 500000 + p200 * 200000 + p100 * 100000 + (p50 + 1) * 50000;
    if (money4 != money3) listM[listM.length] = money4;
    var money5 = p500 * 500000 + p200 * 200000 + p100 * 100000 + p50 * 50000 + (p20 + 1) * 20000;
    listM[listM.length] = money5;
    var money6 = p500 * 500000 + p200 * 200000 + p100 * 100000 + p50 * 50000 + p20 * 20000 + (p10 + 1) * 10000;
    if (money6 != money5) listM[listM.length] = money6;
    var money7 = p500 * 500000 + p200 * 200000 + p100 * 100000 + p50 * 50000 + p20 * 20000 + p10 * 10000 + (p5 + 1) * 5000;
    if (money7 != money6) listM[listM.length] = money7;
    var html = "";
    for (var i = 0; i < listM.length; i++) {
        html += "<button class='btn_mainheader square' style='float:left;width:25%' value='' onclick=callPaymentCustomerGive(" + listM[i] + ")>" + formatNumber(listM[i]) + "</button>";
    }
    return html;
}
function callPayment() {
    var invoice;
    var dlgheader = "";
    if (g_phien_viewmode == "obj") {
        invoice = g_phien_obj.invoicels;
        if (invoice.invoiceid <= 0) {
            showMsg(itxt("chuacophieu"), "", 1000);
            return false;
        }
        dlgheader = g_phien_obj.name;
    } else if (g_phien_viewmode == "invoice") {
        invoice = g_phien_invoice;
        dlgheader = invoice.invoiceno;
    } else {
        showMsg(itxt("khongxacdinhtinhtien"), "", 1000);
        return;
    }
    var debit = parseNumberVn(getValById("iddebit"));
    if (debit != 0) {
        if ((invoice.contactid <= 0) || (invoice.contactname === "(Khách lẻ)") || (invoice.contactname == "(Kh&#225;ch l&#7867;)")) {
            showMsg(itxt("khongghinokhachle"));
            return false;
        }
    }

    var bank = getSelectText("bank_account_id");
    var cash = invoice.getReceivable();
    var html = "";
    //invoiceid,totalcost,costfixed,costhourly,costmix,
    //5 discountfoods,discountdrink,discountgoods,discountservice,invoicediscount,extracharge,vat,invoicemoneydiscount,
    //13 contactid,contactname,contactaddress,phone,datebirth (13->17)
    //var bank_select="<select id='bank_account_id'>"+showBankAccountInSelect(null,0)+"</select>";  
    html += "<div style='width:calc(100% - 8px);padding:8px 4px;overflow: auto;'>" + itxt("phaithu") + "<span style='float:right;font-size:14pt' id='idpaymentmustreceive'>" + formatNumber(cash) + "</span></div>";
    html += "<div style='width:calc(100% - 8px);border-top:4px solid #CCCCCC;padding:8px 4px;margin:4px 0px;overflow: auto;'>";
    html += "<div style='width:100%;margin-bottom:4px' >" + itxt("phuongthucthanhtoan") + "</div>";
    html += "<div id='idcallpaymentmethod'>" + callPaymentShowMethod(invoice.paymentdebit) + "</div>";
    html += "</div>";
    html += "<div style='width:calc(100% - 8px);padding:8px 4px;border-top:4px solid #CCCCCC;overflow: auto;'>";
    html += "<div class='widget_head'><span style='float:left;width:50%;' >" + itxt("khachdua") + "</span><input type='search' style='float:right;;width:50%;text-align:right;font-weight:bold;' id='idpaymentcustomergive'></div>";
    html += "<div class='widget_head'><span style='float:left;width:50%;'  >" + itxt("tralai") + "</span><input type='search' style='float:right;;width:50%;text-align:right;font-weight:bold;' id='idpaymentpayback'></div>";
    html += "</div>";
    //money guest
    html += "<div style='width:calc(100% - 8px);padding:8px 4px;height:48px' id='idmoneyguest' initvalue='" + getGuestPayment(cash) + "'>";
    html += callPaymentShowGuestMoney(cash);
    html += "</div>";
    html += "<div style='width:100% ;margin-top:8px 0px;overflow: auto;'>";
    html += "<input type='button' class='btndlg cancel' style='width:30%' value='" + itxt("cmd_boqua") + "' onclick='hideModalBlock();'>";
    html += "<input type='button' class='btndlg ok' style='width:35%' value='" + itxt("cmd_ghi") + "' onclick='callPaymentDo(null," + (cash - debit) + "," + debit + ",0)'>";
    html += "<input type='button' class='btndlg ok' style='width:35%' value='" + itxt("cmd_ghiin") + "' onclick='callPaymentDo(null," + (cash - debit) + "," + debit + ",1)'>";


    showModalBlock(html, itxt("thanhtoan") + ": " + dlgheader);
}

var m_temp_listidmerge = null;
function onClickCmdObjGopSelectDes(objid) {
    onClickCmdObjDo(String(objid), "gop", m_temp_listidmerge);
}
function onClickCmdObjGopSelectSrc(objid) {
    if (!isEmpty(objid))
        m_temp_listidmerge = String(objid);
    else
        m_temp_listidmerge = showListObjDlgSelect_GetSelectedIds();
    showListObjDlgSelect('onClickCmdObjGopSelectDes', 2, -1, false, itxt("chonbanphonggoptoi"), m_temp_listidmerge);
}
function callPaymentOnSelect(obj_id) {
    if (!isEmpty(obj_id))
        callPaymentDo(String(obj_id));
    else {
        var objidlist = showListObjDlgSelect_GetSelectedIds();
        if (isEmpty(objidlist)) return;
        callPaymentDo(objidlist);
    }

}
//print=0,1
function callPaymentDo(objlist, musrec, debit, print) {
    if (isEmpty(print)) print = 0;
    if (isEmpty(debit)) debit = 0;

    //che do phieu
    if (g_phien_viewmode == "invoice") {
        g_phien_invoice.invoiceSave(m_payment_method, print);
        return true;
    }

    if (isEmpty(objlist)) {
        if (!isEmpty(g_phien_obj)) {
            objlist = String(g_phien_obj.id);
        }
    }
    if (isEmpty(objlist)) {
        showMsg(itxt("khongxacdinhbanphong"));
        return;
    }
    if (isEmpty(debit)) debit = 0;

    var bCurObjInList = isCurObjInListId(objlist);

    showWaitModal();
    var bank_account_id = getValById("bank_account_id");
    var url = "?page=" + m_pagethis + "&action=thanhtoan&objlist=" + objlist + "&method=" + m_payment_method + "&bank_account_id=" + bank_account_id + "&debit=" + debit;

    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            var arObjId = objlist.split(",");
            for (var i = 0; i < arObjId.length; i++) {
                var obj = getObjFromId(arObjId[i]);
                if (!isEmpty(obj)) {
                    if (print > 0)
                        invoicePrint(obj.invoicels.invoiceid);
                    callPrintInvoiceGoodsLabel(obj.invoicels.invoiceid);

                    clearObj(obj);
                    uiUpdateObjInList(obj);
                    uiUpdateObjReceivables(obj);
                    lsGSOrderRemoveByObj(obj.id);
                }
                else {
                    showMsg(itxt("khongtimthaybanphong" + ": " + arObjId[i]));
                }
            }
            if (print < 1)
                hideModalBlock();

            show("list");
        },
        error: function () {
            hideModalBlock();
        }
    });
}
function callPrintInvoiceGoodsLabel(invoiceid) {

    if (isEmpty(invoiceid)) {
        if (isEmpty(g_phien_obj)) return;
        invoiceid = g_phien_obj.invoicels.invoiceid;
        if (invoiceid <= 0) return;
    }
    var url = "?page=" + m_pagethis + "&action=goodslabeled&invoice_id=" + invoiceid;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {

            if (!isDataOk(data)) {
                var datafail = getDataFail(data);
                if (datafail.length > 0)
                    showMsg([itxt("loi"), datafail]);
                return;
            }
            data = getDataOk(data);

            if (data.length > 0) {
                showMsg(itxt("innhan") + "..", "", 1000);

                gCallInterop("PRINTGOODSLABEL" + g_split_row + data);
            }
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}
//printpreview<>null: in tam tinh
function invoicePrint(invoiceid, printpreview, reason, goodscategorytype) {
    if (!isEmpty(reason)) reason = reason.toLowerCase();
    if (isEmpty(invoiceid)) {
        if (!isEmpty(g_phien_obj))
            invoiceid = g_phien_obj.invoicels.invoiceid;
        else if (!isEmpty(g_phien_invoice))
            invoiceid = g_phien_invoice.invoiceid;
    }

    if (invoiceid <= 0) {
        showMsg(itxt("chuacophieu"));
        return false;
    }
    var is_exportinvoice = true;
    if (reason == "nm") is_exportinvoice = false;
    printInvoice(is_exportinvoice, invoiceid, '80', 0, printpreview, goodscategorytype);
}
//include update goods
//return totalcost no mix
function callUpdateInvoice() {
    if (g_phien_obj.invoicels.invoiceid <= 0) {
        showMsg(itxt("chuacophieu"));
        return false;
    }
    if (!g_phien_obj.invoicels.canedit) return;

    var discount = getValById("idinvoicediscount");
    var vat = getValById("idobjvat");
    var invoicemoneydiscount = getValById("idobjinvoicemoneydiscount");
    var discountgoods = getValById("iddiscountgoods", g_phien_obj.invoicels.discountgoods);
    var discountservice = getValById("iddiscountservice", g_phien_obj.invoicels.discountservice);
    var servicecharge = getValById("idobjservicecharge");
    var url = "?page=" + m_pagethis + "&action=updateinvoice&obj_id=" + g_phien_obj.id + "&invoice_id="
        + g_phien_obj.invoicels.invoiceid + "&discount=" + discount + "&vat="
        + vat + "&invoice_money_discount=" + invoicemoneydiscount + "&servicecharge=" + servicecharge
        + "&discountservice=" + discountservice + "&discountgoods=" + discountgoods;

    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {

            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            g_phien_obj.invoicels.totalcost = parseNumberVn(getDataOk(data));

            g_phien_obj.invoicels.invoicemoneydiscount = parseNumberVn(invoicemoneydiscount);
            g_phien_obj.invoicels.extracharge = parseNumberVn(servicecharge);
            g_phien_obj.invoicels.invoicediscount = parseNumberVn(discount);
            g_phien_obj.invoicels.discountgoods = parseNumberVn(discountgoods);
            g_phien_obj.invoicels.discountservice = parseNumberVn(discountservice);
            g_phien_obj.invoicels.vat = parseNumberVn(vat);

            uiUpdateObjReceivables(g_phien_obj);
            show_HeaderCaption();
            showMsg(itxt("dacapnhatphieu"), "", 1500);
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}

//const fnCallBackParamArray = ['p0', 'p1', 'p2'];
//window[fnCallBackName].apply(this, fnCallBackParamArray);
//bo qua cac phieu da ghi co invoiceid>0
function invoiceShowListPopup() {
    if (g_phien_invoices.size < 2) {
        showMsg(itxt("khongcodonnao"), itxt("quanlytinhtien"), 1000);
        return;
    }
    var menu = "", textshow = "";
    menu += "<div class='menu_popup_group'>";
    g_phien_invoices.forEach((value, key) => {
        if (key != "phien") {
            textshow = "";
            var count = value.cart_count;
            var subtotal = value.cart_sum;
            if (value.invoiceid <= 0) {
                if (isEmpty(count)) count = 0;
                if (isEmpty(subtotal)) subtotal = 0;

                if (value.resinvoicesourcename != null)
                    textshow = value.resinvoicesourcename + " - ";
                textshow += value.invoiceno + "<br><div class='subinfo'>" + value.invoicedate + " - " + count + " " + itxt("mathang") + " - " + formatNumber(subtotal) + "</div>";

                menu += "<div class='menu_popup_item " + strSelected(g_phien_invoice, value) +
                    "' href=\"javascript:void(0)\" onclick=\"hideModal();invoiceActive('" + value.key + "')\">" +
                    "<span style='float:left;width:76%'>" + textshow + "</span>" +
                    "<button class='btnmenu' style='float:right;width:12%;color:blue;' onclick=\"event.stopPropagation();invoiceChangeSource('" + value.key + "')\"><-></button>" +
                    "<button class='btnmenu' style='float:right;width:12%;color:red;' onclick=\"event.stopPropagation();invoiceRemove('" + value.key + "')\">x</button>" +
                    "</div>";
            }
        }
    });
    //moi
    menu += "<a class='menu_popup_item' href=\"javascript:void(0)\" onclick=\"hideModal();invoiceNew()\">" + itxt("taodonmoi") + "</a>";

    menu += "</div>";
    showModal(menu, itxt("chondonhang"));
}

function onClickObjGroupSelect() {
    var menu = "";
    menu += "<div class='menu_popup_group'>";
    menu += "<a href='javascript:void(0)' onclick=\"hideModal();showListObj(-1,'',0,'idobjlist',0,0);\" class='btn_mainheader squarebig +" + strSelected(0, m_param_viewfilter_group) + "'>" + itxt("(tatcanhom)") + "</a>";
    for (var i = 0; i < g_list_objgroup.length; i++) {
        menu += "<a href='javascript:void(0)' onclick=\"hideModal();showListObj(-1,'',0,'idobjlist',0," + g_list_objgroup[i].id + ");\" class='btn_mainheader squarebig +" + strSelected(g_list_objgroup[i].id, m_param_viewfilter_group) + "'>" + g_list_objgroup[i].name + "</a>";
    }
    menu += "</div>";
    showModal(menu, itxt("chonnhombanphong"));
}
async function onDestroyThisInvoice() {
    showWaitModal(1);
    var url = "?page=" + m_pagethis + "&action=deleteinvoice&obj_id=" + g_phien_obj.id;
    var data = await getSync(url);
    if (!isDataOk(data)) {
        showMsg([itxt("loi"), getDataFail(data)]);
        return;
    }
    clearObj(g_phien_obj);
    uiUpdateObjInList(g_phien_obj);
    show("list");
    hideModalBlock();
}

function onSelectContact(id, name, address, phone) {
    if (!g_phien_invoice.canedit) return;

    if (isEmpty(id)) {
        DlgSelect.showContact(0, 'onSelectContact');
    }
    else {
        hideModal();
        if (g_phien_viewmode == "obj") {
            g_phien_invoice.invoice_ContactAdd(id, name, address, phone);
            //showObjInvoice();if(curinvoiceid<=0)showListObj();
        } else if (g_phien_viewmode == "invoice") {
            g_phien_invoice.contactid = id;
            g_phien_invoice.contactname = name;
            g_phien_invoice.contactaddress = address;
            g_phien_invoice.phone = phone;

        }
    }
    show_ContactTradeUser();
}

function onSelectTradeUser(id, name, mobile, comment) {
    if (!g_phien_invoice.canedit) return;

    //s_TradeUserIdAdd
    if (isEmpty(id)) {
        DlgSelect.showUser(0, 'onSelectTradeUser');
    } else {
        hideModal();
        if (g_phien_viewmode == "obj") {
            g_phien_invoice.invoice_TradeUserAdd(id, name, mobile, comment);
        }
        else if (g_phien_viewmode == "invoice") {
            g_phien_invoice.tradeuserid = id;
            g_phien_invoice.tradeusername = name;
            g_phien_invoice.tradeusermobile = mobile;
            show_ContactTradeUser();
        }
    }
}

function onSelectDelivery(id, name, address, phone) {
    if (!g_phien_invoice.canedit) return;

    if (isEmpty(id)) {
        DlgSelect.showContact(0, 'onSelectDelivery');
    } else {
        hideModal();
        if (g_phien_viewmode == "obj") {
            g_phien_invoice.invoice_ContactAddDelivery(id, name, address, phone);
        }
        else if (g_phien_viewmode == "invoice") {
            g_phien_invoice.contactid_delivery = id;
            g_phien_invoice.contactname_delivery = name;
            g_phien_invoice.contactaddress_delivery = address;
            g_phien_invoice.phone_delivery = phone;
            show_ContactTradeUser();

        }

    }
}

//chi event tao tu session khac (nguoi dung khac) va thuoc obj duoc phep quan ly duoc xu ly tai day
//id_event,obj_id,log_src,log_type,log_src_id,minute_away,val_string,is_current_session
function eventPhienHandle(data) {
    var rows = data.split(g_split_row);
    if (!Array.isArray(CEventAlert.event_data)) {
        CEventAlert.event_data = new Array;
    }
    var nremove = CEventAlert.event_data.length + rows.length - 9;
    var i = 0;
    for (i = 0; i < nremove; i++)CEventAlert.event_data.shift();
    for (i = 0; i < rows.length; i++) {
        var vals = rows[i].split(g_split_val);
        if (vals.length != 8) {
            errorAlert("dulieueventbiloi");
            continue;
        }
        var nIndex = getObjIndexFromId(vals[1]);
        var log_type = parseInt(vals[3]);
        var obj;
        if (nIndex >= 0) obj = g_ls_objlist[nIndex];

        if ((log_type >= 10) && (log_type <= 16))//khach goi hang
        {
            //14-order+accept
            if ((log_type != 10)) {
                lsGSOrderRemove(vals[4]);
            } else {
                lsGSOrderLoad(obj, "lsGSOrderShow");
                if ((log_type == 14) || (log_type == 15)) {
                    uiUpdateObjInList(obj);
                }
            }
        }
        if (!isEmpty(obj)) {
            if (log_type == 10) {
                obj.gs_order += 1;
            }
            else {
                obj.gs_order -= 1;
            }
            var iddivobjinfo = getId_ObjList_Div_Info(obj.id);
            iddivobjinfo = document.getElementById(iddivobjinfo);
            if (!isEmpty(iddivobjinfo)) {
                if (log_type == 10)
                    iddivobjinfo.className = iddivobjinfo.className + " ordered";
            }
            //cap nhat obj in list
            if ((log_type >= 0) && (log_type <= 5)) {
                showObjRefresh(obj);
                //finish: clear all order
                if (log_type == 5) lsGSOrderRemoveByObj(obj.id);
            } else if ((log_type >= 6) && (log_type <= 9)) {
                showObjRefresh(obj);
                uiUpdateObjInList(obj);
                if (log_type == 6) {//add co the tu accept
                    lsGSOrderRemove(vals[4]);
                }
            } else if (log_type == 14) {//accept
                uiUpdateObjInList(obj);
                showObjRefresh(obj);
            }
        }
        if (vals[2] == "ls") {

        }
        if ((vals[7] == true) || (vals[7] == "true")) {

        } else {
            //showObjRefresh(g_ls_objlist[nIndex]);
        }
        if (i == (rows.length - 1)) CEventAlert.start_event_id = vals[0];
        CEventAlert.event_data.push(rows[i]);
    }

    eleShowHide(g_id_alertcount, true);
    if (rows.length > 9)
        setInnerById(g_id_alertcount, "9+");
    else
        setInnerById(g_id_alertcount, rows.length);
    //event tao boi session hien tai
    playNotify();
}

//return: invoices + this service
function s_ServiceAdd(id, name, unit, price, servicetype, image) {
    if (g_phien_obj == null) { showMsg(itxt("loi")); return; }
    var curinvoiceid = g_phien_obj.invoicels.invoiceid;
    showWaitModal();
    var url = "?page=" + m_pagethis + "&action=serviceadd&obj_id=" + g_phien_obj.id + "&id=" + id;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            hideModal();
            if (!isDataOk(data)) {
                showMsg(itxt("khongthemduoc"));
                return;
            }
            //data:invoice+service
            var rows = getDataOk(data).split(g_split_row);
            var start = 0;
            var vals = rows[0].split(g_split_val);
            if (parseInvoiceData(g_phien_obj, vals))
                start = 1;
            g_phien_obj.invoicels.parseServiceGoodsData(rows, start, 1);
            showObjInvoice();
            showObjDetails_Service();
            uiUpdateObjInList(g_phien_obj);
        },
        error: function () {
            hideModal();

        }
    });

}

function uiUpdateObjReceivables(obj) {
    if (isEmpty(obj)) return;
    var invoice = obj.invoicels;
    var receivable = formatNumber(parseNumberVn(invoice.totalcost) + parseNumberVn(invoice.costmix));
    var recshow = invoice.getReceivableShow();

    if (isEmpty(recshow) || (recshow == "0") || recshow == 0) recshow = "";

    var iddivobjmr = getId_ObjList_Div_MustRec(obj.id);
    setInnerById(iddivobjmr, recshow);
    if (g_phien_viewmode == "obj") {
        if (obj.id == g_phien_obj.id) {
            setInnerById("idobjmustrec", receivable);
            setInnerById("idmodedetailsobjpayment_val", receivable);

            var ttcshow = formatNumber(invoice.totalcost);
            if (isEmpty(ttcshow) || (ttcshow == "0") || ttcshow == 0) ttcshow = "";
            setInnerById("idobjsum", ttcshow);
            var cmshow = invoice.costmix;
            if (isEmpty(cmshow) || (cmshow == "0") || cmshow == 0) cmshow = "";
            setInnerById("idmixcost", cmshow);
        }
    }

}

//co the khong co trong list do view mode & filter
function uiUpdateObjInList(obj) {
    if (isEmpty(obj)) return;
    var id = getId_ObjList_Div_Info(obj.id);
    id = document.getElementById(id);
    if (isEmpty(id)) {
        return;
    }
    var strclass = lsGetObjInListClass(obj);
    id.className = strclass;

    var iddivobjmr = getId_ObjList_Div_MustRec(obj.id);
    setInnerById(iddivobjmr, obj.invoicels.getReceivableShow());
}

function showSelect_Service(obj_id) {
    var url = "?page=list&pagesub=service&obj_id=" + obj_id;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            DlgSelect.showSimple(getDataOk(data), 's_ServiceAdd');


        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}
function lsGSOrderRemoveByObj(obj_id) {
    //xoa trong queu
    var i = 0;
    while (i < g_ls_gsorderqueue.length) {
        if (g_ls_gsorderqueue[i][1] == obj_id) {
            setOuterById(gvRemoteCall.getRowId(g_ls_gsorderqueue[i][0]), "");
            setOuterById(genIdRow(g_ls_gsorderqueue[i][0], "uordered"), "");
            g_ls_gsorderqueue.splice(i, 1);
        } else {
            i++;
        }

    }
}
function lsGSOrderRemove(log_src_id) {
    //xoa trong queu
    var nmax = g_ls_gsorderqueue.length - 1;
    for (var i = 0; i <= nmax; i++) {
        if (g_ls_gsorderqueue[i][0] == log_src_id) {
            g_ls_gsorderqueue.splice(i, 1);
            setOuterById(gvRemoteCall.getRowId(log_src_id), "");
            setOuterById(genIdRow(log_src_id, "uordered"), "");

            return;
        }
    }
}
//nap danh sach dat hang
async function lsGSOrderLoad(obj, fnCallBackName) {
    var obj_id = 0;
    if (!isEmpty(obj)) {
        obj_id = obj.id;
    }
    var id_from = 0;
    if (g_ls_gsorderqueue.length > 0) {
        id_from = g_ls_gsorderqueue[g_ls_gsorderqueue.length - 1][0];
    }
    //nap toan bo hang dat lien quan (quan ly - thu ngan - bep bar: tat ca, phuc vu: cac ban phong quan ly, tai ban: rieng ban do)
    var url = "?page=" + m_pagethis + "&pagesub=ordered&obj_id=" + obj_id + "&id_from=" + id_from;
    var data = await getSync(url);
    //them vao hang cho
    if (!isDataOk(data)) {
        showMsg([itxt("loi"), getDataFail(data)]);
    } else {
        if (getDataOk(data).length > 0) {
            var rows = getDataOk(data).split(g_split_row);
            if (rows.length < 1) return;
            for (var i = 0; i < rows.length; i++) {
                var vals = rows[i].split(g_split_val);
                if (vals.length == 9) g_ls_gsorderqueue.push(vals);
            }
            if (!isEmpty(fnCallBackName)) eval(fnCallBackName)();
        }
    }
}
//danh sach hang da goi cho xac nhan tu bep co phuc vu duoc hay khong
//log_src_id,obj_id...
function lsGSOrderShow(obj) {
    if (!g_ls_gsorderqueue_visible) {
        setInnerById("idgoodscallqueue", ""); return;
    }
    var idshow = document.getElementById("idgoodscallqueue");
    if (isEmpty(idshow)) {
        alert("idgoodscallqueue not found!")
        return;
    }

    if (g_ls_gsorderqueue.length < 1) {
        setInnerById("idgoodscallqueue", ""); return;
    }

    var strOut = "";
    var btclass = "";
    var title = "";
    btclass = "btn_mainheader circle cancel";
    title = itxt("huybogoihang");
    var end = g_ls_gsorderqueue.length - 1;
    var start = 0;
    if (!isEmpty(obj)) obj.gs_order = 0;
    for (var i = end; i >= start; i--) {
        var vals = g_ls_gsorderqueue[i];
        //neu hien thi doi tuong xac dinh
        if (!isEmpty(obj)) {
            if (obj.id == vals[1]) obj.gs_order++;
            if (obj.id != vals[1]) continue;
        }
        var idrow = gvRemoteCall.getRowId(vals[0]);
        strOut += "<div class='list_item' style='margin-bottom:1px;padding:4px;color:black;overflow:auto;' id='" + idrow + "'>";
        strOut += "<div style='float:right;'>";
        if (vals[8].length == 2) {
            if (vals[8].substr(0, 1) == "1") {
                strOut += "<a class='btn_mainheader circle confirm' onclick='lsGSOrderConfirm(" + vals[0] + "," + vals[1] + ",1)' title='" + itxt("dongy/xacnhan") + "'></a>";
                if (!g_viewmode) {
                    strOut += "<br>";
                }
            }
            if (vals[8].substr(1, 1) == "1") {
                var substyle = "";
                if (g_viewmode)
                    substyle = "style='margin-left:8px'";
                else
                    substyle = "style='margin-top:8px'";
                strOut += "<a class='btn_mainheader circle cancel' " + substyle + " onclick='lsGSOrderConfirm(" + vals[0] + "," + vals[1] + ",0)' title='" + itxt("tuchoi/huybo") + "'></a>";
            }
        }
        strOut += "</div>";
        strOut += "<b>" + vals[3] + "</b><br>";
        strOut += "<span class='subinfo'>" + vals[4] + "*" + vals[5] + " - <b>" + vals[2] + "</b> - " + vals[7] + "</span>";
        strOut += "</div>";
    }
    idshow.innerHTML = strOut;
}
//obj list
function menuPopupObjs() {
    var menu = "";
    menu += "<div class='menu_popup_group'>";
    menu += "<a href='javascript:void(0)' onclick=\"hideModal();showListObjDlgSelect('callPaymentOnSelect',2)\" class='menu_popup_item'>" + itxt("thanhtoan") + "..</a>";
    //showListObjDlgSelect('onClickCmdObjDoGop',2,-1,false,"["+g_phien_obj.name+"] "+g_char_rightarrow+" "+itxt("gopvao")+"..");
    menu += "<a href='javascript:void(0)' onclick=\"hideModal();showListObjDlgSelect('onClickCmdObjGopSelectSrc',2,-1,true,itxt(\'cacbanphongsegop\'))\" class='menu_popup_item'>" + itxt("gopbanphong") + "..</a>";
    menu += "<a href='javascript:void(0)' style='width:50%' onclick=\"hideModal();onClickAddNewGoodsCategory();\" class='menu_popup_item'>" + itxt("themnhomhang") + "</a>";
    menu += "<a href='javascript:void(0)' style='width:50%' onclick=\"hideModal();onClickAddNewGoods();\" class='menu_popup_item'>" + itxt("themmathang") + "</a>";

    menu += "<a href='javascript:void(0)' style='width:50%' onclick=\"hideModal();onClickAddNewObjGroup();\" class='menu_popup_item'>" + itxt("themnhombanphong") + "</a>";
    menu += "<a href='javascript:void(0)' style='width:50%' onclick=\"hideModal();onClickAddNewObj();\" class='menu_popup_item'>" + itxt("thembanphong") + "</a>";
    menu += "</div>";
    showModal(menu, itxt("tacvu"));
}
//current selected obj
function menuPopupObj() {
    if (isEmpty(g_phien_obj)) return;
    var nInvoiceId = parseInt(g_phien_obj.invoicels.invoiceid);
    var menu = "";
    menu += "<div class='menu_popup_group'>";
    menu += "<a class='menu_popup_item' href=\"javascript:void(0)\" onclick=\"hideModal();onClickGoodsLoadLocal()\">" + itxt("naphangdadesan") + "</a>";

    if (nInvoiceId > 0) {
        menu += "<a class='menu_popup_item w50' href=\"javascript:void(0)\" onclick=\"hideModal();onClickCmdObj('doicho')\">" + itxt("cmd_doicho") + "</a>";
        menu += "<a class='menu_popup_item w50' href=\"javascript:void(0)\" onclick=\"hideModal();onClickCmdObj('gop')\">" + itxt("cmd_gop") + "</a>";
        menu += "<a class='menu_popup_item remove' href=\"javascript:void(0)\" onclick=\"hideModal();onDestroyThisInvoice();\">" + itxt("cmd_huyphieu") + "</a>";

    } else {
        menu += "<a class='menu_popup_item' href=\"javascript:void(0)\" onclick=\"hideModal();onClickCmdObj('copy')\">" + itxt("cmd_saochep") + "</a>";
    }

    menu += "<a class='menu_popup_item w50' href=\"javascript:void(0)\" onclick=\"hideModal();callContactCard()\">" + itxt("thekhachang") + "</a>";
    menu += "<a class='menu_popup_item w50' href=\"javascript:void(0)\" onclick=\"hideModal();onSelectContact();\">" + itxt("cmd_chonkhach") + "</a>";
    menu += "<a class='menu_popup_item w50' href=\"javascript:void(0)\" onclick=\"hideModal();onSelectTradeUser();\">" + itxt("cmd_chonkinhdoanhtuvan") + "</a>";
    menu += "<a class='menu_popup_item w50' href=\"javascript:void(0)\" onclick=\"hideModal();shareInvoice(" + nInvoiceId + ")\">" + itxt("chiase..") + "</a>";
    //invoicePrint(invoiceid,printpreview,reason,goodscategorytype)
    menu += "<a class='menu_popup_item w50' href=\"javascript:void(0)\" onclick=\"hideModal();invoicePrint(null,1,'xb',1);\">" + itxt("cmd_indoan") + "</a>";
    menu += "<a class='menu_popup_item w50' href=\"javascript:void(0)\" onclick=\"hideModal();invoicePrint(null,1,'xb',2);\">" + itxt("cmd_indouong") + "</a>";
    menu += "<a class='menu_popup_item' href=\"javascript:void(0)\" onclick=\"hideModal();invoicePrint(null,1,'xb',3)\">" + itxt("cmd_indichvu") + "</a>";

    menu += "</div>";
    showModal(menu, itxt("tacvuphien"));
}
function menuPopupFilter(iddivshow) {
    if (isEmpty(iddivshow)) iddivshow = "idobjlist";

    var head = "<div class='menu_popup_group'>";
    head += "<a href=\"javascript:void(0)\" class=\"btn_mainheader squarebig " + strSelected(m_param_viewfilter_status, 0) + "\" style=\"background-image: url('/imgs/bt_filterno.png');\" title=\"trạng thái\" onclick=\"m_param_viewfilter_status=0;menuPopupFilter();\">" + itxt("(tatcakieu)") + "</a>";
    head += "<a href=\"javascript:void(0)\" class=\"btn_mainheader squarebig " + strSelected(m_param_viewfilter_status, 1) + "\" style=\"background-image: url('/imgs/bt_empty.png');\" title=\"Đang trống\" onclick=\"m_param_viewfilter_status=1;;menuPopupFilter();\">" + itxt("dangtrong") + "</a>";
    head += "<a href=\"javascript:void(0)\" class=\"btn_mainheader squarebig " + strSelected(m_param_viewfilter_status, 2) + "\" style=\"background-image: url('/imgs/bt_busy.ico');\" title=\"Đang sử dụng\" onclick=\"m_param_viewfilter_status=2;;menuPopupFilter();\">" + itxt("dangsudung") + "</a>";
    head += "</div>";
    //g_mods=[] duoc ghi tu server, luon co 01 takeaway;
    if (Array.isArray(g_mods) && (g_mods.length > 2)) {
        head += "<div class='menu_popup_group'>";
        head += "<a href=\"javascript:void(0)\" class=\"btn_mainheader squarebig " + strSelected(m_param_viewfilter_type, 0) + "\" style=\"background-image: url('/imgs/bt_filterno.png');\" title=\"loại bàn/phòng\" onclick=\"m_param_viewfilter_type=0;menuPopupFilter();\">" + itxt("(tatcaloai)") + "</a>";
        for (var i = 0; i < g_mods.length; i++) {
            var title = "";
            if (g_mods[i] == 0) title = itxt("nhahang");
            else if (g_mods[i] == 1) title = itxt("karaoke");
            else if (g_mods[i] == 2) title = itxt("khachsan");
            else if (g_mods[i] == 3) title = itxt("spa");
            else if (g_mods[i] == 4) title = itxt("mangdi");
            else continue;
            head += "<a href=\"javascript:void(0)\" class=\"btn_mainheader squarebig " + strSelected(m_param_viewfilter_type, (g_mods[i] + 1)) + "\" style=\"background-image: url('/imgs/obj_res.png');\" title=\"" + title + "\" onclick=\"m_param_viewfilter_type=" + (g_mods[i] + 1) + ";menuPopupFilter();\">" + title + "</a>";
        }
        head += "</div>";
    }

    head += "<div class='menu_popup_group'>";
    head += "<a href='javascript:void(0)' onclick=\"m_param_viewfilter_group=0;menuPopupFilter();\" class='btn_mainheader squarebig +" + strSelected(0, m_param_viewfilter_group) + "' style=\"background-image: url('/imgs/bt_filterno.png');\" >" + itxt("(tatcanhom)") + "</a>";
    for (var i = 0; i < g_list_objgroup.length; i++) {
        head += "<a href='javascript:void(0)' onclick=\"m_param_viewfilter_group=" + g_list_objgroup[i].id + ";menuPopupFilter();\" class='btn_mainheader squarebig +" + strSelected(g_list_objgroup[i].id, m_param_viewfilter_group) + "'>" + g_list_objgroup[i].name + "</a>";
    }
    head += "</div>";
    head += "<div style='width:100%;clear:both'>";
    head += "<div class=\"btndlg cancel\" style=\"width:50%;height:36px;\" title=\"\" onclick=\"hideModal();\">" + itxt("cmd_boqua") + "</div>";
    head += "<div class=\"btndlg ok\" style=\"width:50%;height:36px;\" title=\"\" onclick=\"hideModal();sessionSaveParams();showListObj(" + (m_param_viewfilter_type - 1) + ",'',0,'" + iddivshow + "'," + m_param_viewfilter_status + ");\">" + itxt("cmd_apdung") + "</div>";
    head += "</div>";
    showModal(head, itxt("locbanphong"));
}

function phienobj_drag(ev, obj_id) {

    ev.dataTransfer.setData("obj_id", obj_id);

    ev.dataTransfer.setData("text", ev.target.id);
}
function phienobj_allowDrop(ev) {
    ev.preventDefault();
}
function phienobj_drop(ev, target) {

    ev.preventDefault();
    var data = ev.dataTransfer.getData("obj_id");


    //ev.target.appendChild(document.getElementById(data));
}