var m_pagethis = "phienrm";
var m_cart = new Array();
g_phien_invoice = new CInvoiceLS("xb", 0, "g_phien_invoice", "taiban");
initOneTime();
function initOneTime() {
    //check xem da khoi tao chua
    var page_initflag = document.getElementById("page_initflag");
    if (page_initflag != null) {
        if (page_initflag.value.length > 0)
            return;
        page_initflag.value = "1";
    }
    getListGoodsCategory();

    g_event_param = { type: "rm", fn: "eventRMHandle" };

    g_phien_invoice.page_source = m_pagethis;
    g_phien_invoice.viewmode_goodsselectcategory = g_phien_viewmode_selectgoodscategory;
    g_phien_invoice.fnCallbackOnCartChange = "onChangeCart";
    g_phien_invoice.fnCallbackOnInvoiceChange = "onChangeInvoice";
    g_phien_invoices.set("taiban", g_phien_invoice);
    g_phien_invoice.obj_id = g_phien_obj.id;
    g_phien_obj.invoicels = g_phien_invoice;

    showInvoice();
    showOrdered();

    //sau khi hien thi phieu xuat va hang dat
    //thi coi nhu xu ly het event thoi diem nay
    //event_id se la moi nhat

    strout = "<div style='-moz-box-sizing:border-box;box-sizing:border-box;width:100%;padding:10px;text-align:center;font-weight:bold'> \
				<p>Để chọn món nhập vào <span style='color:#0000FF;font-size:12pt'>menu/tìm món</span></p> \
				Vào <span style='color:#0000FF;font-size:12pt'>giỏ hàng</span> để xem lại món đã chọn và gửi lệnh đặt món</div>";

    showObj_HeaderCaption();
    setTitleById("idrmcallpayment", itxt("yeucauthanhtoan"));
    setTitleById("idrmcallpaywaiter", itxt("goinhanvienphucvu"));
    setPlaceholderById("idgoodsname", itxt("timmon"));
    //if(!isVisiable('idgoodslistselect'))
    //    showGoods(0,'','idgoodslistselect');
    g_initiated_complete = true;
    CEventAlert.start_event_id = 0;
    setInnerById("idvlangtongphaithu", itxt("tong"));
    setInnerById("idvlanggopthanhtoan", itxt("gopthanhtoan"));
    //setInnerById("idgoodslistselect",strout);
    //eleShowHide("idgoodslistselect",true);
}
function onChangeCart() {
    var strCart = "";
    if (g_phien_invoice.cart_count > 0)
        strCart = g_phien_invoice.cart_count + " " + itxt("s_mons") + " - " + formatNumber(g_phien_invoice.cart_sum);
    else
        strCart = itxt("giohang");
    setInnerById("idcart", strCart);
    if (g_phien_invoice.cart_count == 0) eleShowHide("idgoodslistselect", false);
    showOrdered();
}
function onChangeInvoice() {

}
async function eventRMHandle(data) {

    if (data.length == 0) return;
    //id-log_type
    var vals = data.split(g_split_val);
    if (vals.length != 2) return;
    CEventAlert.start_event_id = parseInt(vals[0]);
    var log_type = parseInt(vals[1]);
    if ((log_type >= 0) && (log_type <= 5)) {
        //them - ket thuc
        if (log_type == 5) {
            showInvoiceClear();
        } else {
            showInvoice();
            uiUpdate();
        }

    } else if ((log_type >= 6) && (log_type <= 9)) {
        showInvoice();
        showOrdered();
    } else if ((log_type >= 10) && (log_type <= 16)) {
        showOrdered();
    }
    //goods pause
    else if (log_type == 16) {

    }
    //call pay - call pay cancel
    else if ((log_type >= 17) && (log_type <= 18)) {

    }//call waiter
    else if (log_type == 19) {

    }
    playNotify();
}

//hang da dat, chua xac nhan hoac tu choi phuc vu
async function showOrdered() {
    var iddivshow = "idgoodscallqueue";
    var idobjgoodscalllistwrap = document.getElementById("idobjgoodscalllistwrap");

    var data = await getSync('?page=' + m_pagethis + '&obj_id=' + g_phien_obj.id + '&pagesub=ordered');
    if (!isDataOk(data)) {
        idobjgoodscalllistwrap.style.display = "none";
        showMsg([itxt("loi"), getDataFail(data)]);
        return;
    }
    data = getDataOk(data);
    if (data.length < 1) {
        idobjgoodscalllistwrap.style.display = "none";;
        return;
    }
    var rows = data.split(g_split_row);
    if (rows.length < 1) setInnerById(iddivshow, "");
    var strOut = "";
    var btclass = "";
    var title = "";
    title = itxt("bogoimon");
    btclass = "btn_mainheader circle cancel";
    for (var i = 0; i < rows.length; i++) {
        var vals = rows[i].split(g_split_val);
        if (vals.length == 9) {
            var idrow = getIdEle(vals[0], "lwcf");
            var strclass = "list_item";
            if (vals[6] == "2") {
                strclass += " " + " deny";
            }
            strOut += "<div class='" + strclass + "' style='margin-bottom:1px;padding:4px' id='" + idrow + "'>";
            if (vals[6] != "2") {
                strOut += "<a class='" + btclass + "' style='float:right;' onclick='orderCancel(" + vals[0] + ")' title='" + title + "'></a>";
            }

            else
                strOut += "<div class='btn_mainheader circle' style='float:right;color:red;background:#EEEEEE'>" + itxt("het") + "</div>";
            strOut += "<span><b>" + vals[3] + "</b></span><br>";
            strOut += "<span class='highlight_hour'>" + vals[7] + "</span> - " + "<span class='subinfo'>" + vals[4] + "*" + vals[5] + "</span>";
            strOut += "</div>";
        }
    }
    if (rows.length > 0) {
        idobjgoodscalllistwrap.style.display = "block";
        idobjgoodscalllistwrap.margin = "0px 0px 8px 0px";
    } else {
        idobjgoodscalllistwrap.style.display = "none";
    }
    setInnerById(iddivshow, strOut);
}

async function callWaiter() {
    if (g_phien_obj.invoicels.invoicestatus == 2) {
        showModalBlock("<div style='padding:16px;margin:auto'>" + itxt("goinhanvienphucvu") + "..</div>");
        return;
    }
    showModalBlock("<div style='padding:16px;margin:auto'>" + itxt("goinhanvienphucvu") + "..</div>");

    var url = '?page=' + m_pagethis + '&obj_id=' + g_phien_obj.id + '&pagesub=callwaiter';
    var data = await getSync(url);
    if (!isDataOk(data)) {
        showMsg([itxt("loi"), getDataFail(data)]);
        return;
    }
    var idrmcallwaiter = document.getElementById("idrmcallwaiter");
    //idrmcallwaiter.classList="btn_mainheader circle callwaiter active";
    g_phien_obj.invoicels.invoicestatus = 2;
    showMsg(itxt("dagoinhanvien"), "Menu", 1000);

}

function clearInvoice(f, bupdateviewobjdetails) {
    f.invoiceid = null;
    f.totalcost = null;
    f.costfixed = null;
    f.costhourly = null;
    f.costmix = null;

    f.discountfoods = null;
    f.discountdrink = null;
    f.discountgoods = null;
    f.discountservice = null;
    f.invoicediscount = null;
    f.extracharge = null;
    f.invoicemoneydiscount = null;
    f.vat = null;

    f.contactid = null;
    f.contactname = "";
    f.contactaddress = "";
    f.phone = "";
    f.datebirth = "";
    f.statusremotecall = null;
    f.seatcount = null;
    f.userid = null;
    f.tradeuserid = null;
    f.invoicestatus = null;
    if (!isEmpty(g_phien_obj)) {
        if (f.id == g_phien_obj.id) {
            f.invoicels.goods.clear();
            f.invoicels.services.clear();
        }
    }
    if (bupdateviewobjdetails) {
        showObj_HeaderCaption();
        setInnerById("idsumservices", "");
        setInnerById("idlistservices", "");

        setInnerById("idsumgoods", "");
        setInnerById("idlistgoods", "");

        var idobjgoodslistwrap = document.getElementById("idobjgoodslistwrap");
        var idobjservicelistwrap = document.getElementById("idobjservicelistwrap");
        idobjgoodslistwrap.style.display = "none";
        idobjservicelistwrap.style.display = "none";
    }
}
async function callPayCancel() {
    showModalBlock(itxt("huyyeucauthanhtoan"));
    var url = '?page=' + m_pagethis + '&obj_id=' + g_phien_obj.id + '&pagesub=callpaycancel';
    var data = await getSync(url);
    if (!isDataOk(data)) {
        showMsg([itxt("loi"), getDataFail(data)]);
        return;
    }
    showModalBlock(itxt("dahuyyeucauthanhtoan"));
}
async function callPay() {
    if (g_phien_obj.invoicels.invoicestatus == 1) {
        showModal(itxt("bandagoithanhtoan"));
        return;
    }

    showModalBlock(itxt("yeucauthanhtoan"));
    var url = '?page=' + m_pagethis + '&obj_id=' + g_phien_obj.id + '&pagesub=callpay';
    var data = await getSync(url);
    if (!isDataOk(data)) {
        showMsg([itxt("loi"), getDataFail(data)]);
        return;
    }
    var idrmcallpay = document.getElementById("idrmcallpay");
    //idrmcallpay.classList="btn_mainheader circle callpayment active";
    g_phien_obj.invoicels.invoicestatus = 1;

    showMsg(itxt("dagoithanhtoan"), "Menu", 1000);
}
async function orderCancel(id) {
    if (parseNumberVn(id) <= 0) return;
    var data = await getSync('?page=' + m_pagethis + '&obj_id=' + g_phien_obj.id + '&pagesub=orderconfirm&id=' + id + '&val=0');
    if (!isDataOk(data)) {
        showMsg([itxt("loi"), getDataFail(data)]);
        return;
    }
    showOrdered();
}

function showGoodsListCategory(iddivhide) {
    if (g_list_goodscategory.length > 0) {
        var html = "";
        html += "<div onclick=\"eleShowHide('" + iddivhide + "');\" class=\"session_goodsselect_cat_close\" style=\"\"><span id=\"idcart\" style=\"float:left\">" + g_char_leftarrow + " Đóng</span></div>";
        for (var i = 0; i < g_list_goodscategory.length; i++) {
            html += "<button class='session_goodsselect_cat_btn' ";
            html += " onclick='showGoods(" + g_list_goodscategory[i].id + ",\"\",\"" + iddivhide + "\")'>";
            html += g_list_goodscategory[i].name + "</button>";
        }
        //html+="<button class='session_goodsselect_cat_btn' onclick='showGoodsCategory()'>("+itxt("tatca")+")</button>";
        return html;
    }
}
function showCart(param) {
    var iddivshowobj = document.getElementById("idgoodslistselect");
    iddivshowobj.innerHTML = "";
    iddivshowobj.style.display = "block";
    g_phien_invoice.cartShow("idgoodslistselect");
}
function show(param) {

    var iddivshowobj = document.getElementById("idgoodslistselect");
    if (!isEmpty(iddivshowobj)) {
        if (param == "idgoodslistselect") {
            iddivshowobj.innerHTML = "";
            iddivshowobj.style.display = "block";
            g_phien_invoice.showSelect_Goods(0, getValById('idgoodslistselect_name'), 'idgoodslistselect');
        } else {
            setValById("idgoodslistselect_name", "");
            eleShowHide("idgoodslistselect", false);
        }
    }
}
async function showGoods(category_id, goodsname, iddivshow) {

    if (isEmpty(goodsname)) goodsname = "";
    var url = "?page=list&pagesub=goods&invoice_type=phieuxuatle&category_id=" + category_id + "&goods_name=" + uriEncode(goodsname) + "&pagesize=1000";

    var data = await getSync(url);
    if (!isDataOk(data)) return;
    g_phien_goods_list = getDataOk(data);
    //id,goods_id,unit_id,tenhang,mahang,dvt,ton,dongia,mausac,mausacid,kichthuoc,anh
    var argoods = g_phien_goods_list.split(g_split_row);
    var ncount = argoods.length;
    if (g_phien_goods_list.length == 0)
        ncount = 0;

    var start = 0, pagesize = 0, pageno = 0, pagecount = 0, arrheads;
    if (argoods[0].substr(0, g_sign_pageconfig.length) == g_sign_pageconfig) {
        var configs = argoods[0].split(g_split_val);
        start++;
        if (configs.length == 4) {
            pagesize = parseInt(configs[1]);
            pageno = parseInt(configs[2]);
            pagecount = parseInt(configs[3]);
        }
    }
    //arrheads la array chua tieu de cac cot, neu trong rong thi cot do khong hien thi
    if (argoods[start].substr(0, g_sign_columnconfig.length) == g_sign_columnconfig) {
        var datahead = argoods[start].substr(g_sign_columnconfig.length + g_split_val.length);
        arrheads = datahead.split(g_split_val);
        start++;
    }

    var strout = "";
    var strrow = "";
    var idcombine = "";
    strout += "<div style='width:100%;overflow:auto;padding-top:4px;padding-left:4px;-moz-box-sizing:border-box;box-sizing:border-box;'>";
    for (i = start; i < ncount; i++) {
        strrow = "";
        var arfields = argoods[i].split(g_split_val);
        var imgsrc = "";
        if (arfields[11].length > 0)
            imgsrc = "/imgs/" + arfields[11];
        else
            imgsrc = "/imgs/foods.jpg";
        idcombine = arfields[0];
        strrow += "<div id='tr" + idcombine + "' class='session_goodsselect_item'>";
        strrow += "<div style='width:100%;text-align:left;float:left;'>";
        strrow += "<b><span id='dividgoodsname" + idcombine + "' class='span-autocut'>" + arfields[3] + "</span></b>";
        strrow += "</div>";
        strrow += "<div style=\"width:100%;text-align:left;float:left;\">";
        strrow += "<div style='width:100%;text-align:left;height:20px'>";
        strrow += "<span id='dividgoodsunitprice" + idcombine + "' class='subinfo'>" + arfields[7] + "</span>";
        strrow += "/<span id='dividgoodsunit" + idcombine + "' class='subinfo'>" + arfields[5] + "</span>";
        strrow += "</div>";
        strrow += "<div style='width:100%;text-align:left;height:28px;clear:both;'>";
        strrow += "<div onclick='return cartAddAndSubmit(" + arfields[1] + "," + arfields[2] + ")' " +
            " class='btn_mainheader circle goodscall'><span style='float:left'>" + g_char_enter +
            "</span><span style='float:right;margin-right:4px' id='divgoodsindex" + idcombine + "' class='session_goodscall_count'></span></div>";
        strrow += "<input type=\"button\" onclick='return cartAdd(" + arfields[1] + "," + arfields[2] + ",-1)' class='btn_mainheader circle' style='float:left;margin-right:0px;width:25%;border-radius:50%' value='-'>";
        strrow += "<input type=\"button\" onclick='return cartAdd(" + arfields[1] + "," + arfields[2] + ",1)' class='btn_mainheader circle' style='float:left;margin-right:0px;width:25%;border-radius:50%' value='+'>";
        strrow += "</div>";
        strrow += "</div>";
        strrow += "</div>";
        strout += strrow;
    }
    strout += "</div>";
    var strGuide = "";
    strGuide = "<div style='padding:5px'><b>Cách gọi món 01:</b> Nhấn nút <b>'&#8626'</b> để gọi ngay 01 món. Mỗi lần nhấn là gọi 01 món<br><b>Cách gọi món 02:</b> nhấn nút + - chọn món vào giỏ hàng. Vào giỏ hàng và nhấn gọi món.</div>"

    var strCategoryList = showGoodsListCategory(iddivshow);

    strout = strout + strGuide;
    strout = "<div class='session_goodsselect_catvert'>" + strCategoryList + "</div><div class='session_goodsselect_goods'>" + strout + "</div>";
    var iddivshowobj = document.getElementById(iddivshow);
    if (!isEmpty(iddivshowobj)) {
        iddivshowobj.style.display = "block";
        iddivshowobj.innerHTML = strout;
    }
}

//current obj
function showObj_HeaderCaption() {
    var subinfo = "";
    var i = 0;

    if (g_phien_obj.invoicels.services.size > 0) {
        var sts = g_phien_obj.invoicels.getInvoiceServiceCount();
        if (sts > 0)
            subinfo += sts + " " + itxt("dichvu");

    }

    if (g_phien_obj.invoicels.goods.size > 0) {
        var sts = g_phien_obj.invoicels.getInvoiceGoodsCount();
        if (sts > 0) {
            if (subinfo.length > 0) subinfo += " - ";
            subinfo += sts + " " + itxt("s_mons");
        }
    }


    subinfo = "<div class='' style='float:left;color:#8800FF'>" + subinfo + "</div>";
    if (!isEmpty(g_phien_obj.invoicels.invoiceno))
        subinfo = itxt("tong") + " (" + itxt("sophieu") + ": " + g_phien_obj.invoicels.invoiceno + ")";
    else
        subinfo = itxt("tong");

    setInnerById("idvlangtongphaithu", subinfo);
}
function showInvoiceClear() {
    g_phien_obj.invoicels.clear();
    setInnerById("idobjgoodslist", "");
    setInnerById("idlistservices", "");

    setInnerById("idsumservices", "");
    setInnerById("idsumgoods", "");
    setInnerById("idmodedetailsobjpayment_val", "");
    setInnerById("idvlangtongphaithu", itxt("tong"));
    eleShowHide("idobjservicelistwrap");
    eleShowHide("idobjgoodslistwrap");
    eleShowHide("idmodedetailsobjpayment");
}
async function showInvoice() {
    var data = await getSync("?page=" + m_pagethis + "&obj_id=" + g_phien_obj.id + "&pagesub=invoice");
    if (!isDataOk(data)) return;
    data = getDataOk(data);
    //empty invoice - no invoice
    if (data.length == 0) {
        clearInvoice(g_phien_obj, true); return;
    }
    if (!parseInvoiceData(g_phien_obj, data.split(g_split_val))) return;
    //callpay
    if (g_phien_obj.invoicels.invoicestatus == 1) {
        var idrmcallpay = document.getElementById("idrmcallpay");
        if (idrmcallpay != null) {
            idrmcallpay.classList = "btn_mainheader circle callpayment active";
        }
    }
    //callwaiter
    else if (g_phien_obj.invoicels.invoicestatus == 2) {
        var idrmcallwaiter = document.getElementById("idrmcallwaiter");
        if (idrmcallwaiter != null) {
            idrmcallwaiter.classList = "btn_mainheader circle callwaiter active";
        }
    }
    if (g_phien_obj.invoicels.invoiceid != "0") {
        showInvoiceDetails();
        eleShowHide("idmodedetailsobjpayment", true);
    } else {
        eleShowHide("idmodedetailsobjpayment");
    }
    showObj_HeaderCaption();

    uiUpdate();
}
//ndatatype: 0 - chua ca du lieu dich vu + hang, 1 - chi dich vu, 2 - chi hang
//
function parseServiceGoodsData(rows, start, ndatatype = 0) {

    if ((ndatatype == 0) || (ndatatype == 1)) {
        g_phien_invoice.services.clear();
    }
    if ((ndatatype == 0) || (ndatatype == 2)) g_phien_invoice.goods.clear();

    g_phien_invoice.parseServiceGoodsData(rows, start, ndatatype);

    return true;
}

async function showInvoiceDetails() {
    var url = "?page=" + m_pagethis + "&pagesub=getinvoicedetails&obj_id=" + g_phien_obj.id;
    var data = await getSync(url);
    if (!isDataOk(data)) return;
    if (!parseServiceGoodsData(getDataOk(data).split(g_split_row), 0)) return false;

    showInvoiceDetails_Service("idsumservices", "idlistservices");
    showInvoiceDetails_Goods("idsumgoods", "idlistgoods");
    setInnerById("idmodedetailsobjpayment_val", formatNumber(g_phien_invoice.costfixed));
}
function showInvoiceDetails_Goods(idsum, idlist) {
    var idobjgoodslistwrap = document.getElementById("idobjgoodslistwrap");
    if (g_phien_invoice.goods.size > 0) {
        idobjgoodslistwrap.style.display = "block";
        idobjgoodslistwrap.style.margin = "0px 0px 8px 0px";
    } else {
        idobjgoodslistwrap.style.display = "none";
    }

    g_phien_invoice.iddivshow_goods_list = "idobjgoodslist";
    g_phien_invoice.invoice_ShowGoods(false);
}
function showInvoiceDetails_Service(idsum, idlist) {
    var subtotal = 0, totalcost = 0;
    //DANH SACH DICH VU
    var html = "<div class='divtable'>";
    g_phien_invoice.services.forEach((item, key) => {
        if (item.to != "")
            html += "<div class='divrow red' id=''>";
        else
            html += "<div class='divrow dgreen' id=''>";

        html += "<div class='divcell' style='width:40%'><b>";
        html += item.name + "</b><br class='linebreak'><div class='subinfo'>" + (item.price + "/" + item.unit) + "</div>";
        html += "</div>";
        html += "<div class='divcell' style='text-align:right;width:30%'>";
        subtotal = parseNumberVn(item.price) * parseNumberVn(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:20%'>";
        html += item.realname;
        html += "</div>";
        html += "<div class='divcell padding0' style='width:10%'><input type='button' class='buttonincell' onclick='menuPopupItemService(" + item.id + ")' value='CMD'></div>"
        html += "</div>";
    });
    html += "</div>";
    setInnerById(idlist, html);
    g_phien_obj.invoicels.costhourly = formatNumber(totalcost);
    setInnerById(idsum, formatNumber(totalcost));

    var idobjservicelistwrap = document.getElementById("idobjservicelistwrap");
    if (g_phien_invoice.services.length > 0) {
        idobjservicelistwrap.style.display = "block";
        idobjservicelistwrap.style.margin = "0px 0px 8px 0px";
    } else {
        idobjservicelistwrap.style.display = "none";
    }
    return totalcost;
}
function uiUpdateGoodsListG() {
    var matches = [];
    var elems = document.getElementsByTagName("*");
    for (var i = 0; i < elems.length; i++) {
        if (elems[i].id.indexOf("divgoodsindex") == 0)
            setInnerById(elems[i].id, "G");
    }
}
function uiUpdate() {

    //eleShowHide("idgoodslistselect",g_phien_obj.statusremotecall!=1); 
    //eleEnable("idgoodsname",g_phien_obj.statusremotecall!=1);
    //eleEnable("idcart",g_phien_obj.statusremotecall!=1);

}
