/*CALL_FUNCTION_BY_STRING_NAME AND PASS ARRAY PARAMETERS
    const fnCallBackParamArray = ['p0', 'p1', 'p2'];
    window[fnCallBackName].apply(this, fnCallBackParamArray);
*/
/*GLOBAL_APP_DATA*/
var g_event_param = null;//{type,fncallback}
var g_list_bankbin = [];//{bin,name}
var g_list_goodscategory = [];//{id,name,code,category_discount_default,web_in_level,[res_doan,res_douong]}
var g_list_services = [];//{id,objcategory,name,unit,price,hourly,minutelimit,iscombo}						
var g_list_bankaccount = [];//[{id,code,name,bank,owner}]
var g_list_store = [];//[{id,name}]
var g_list_employee = [];//[{id,name,mobile,comment}]
var g_list_objcategory = [];//[{id,name}]
var g_list_objtype = [];//[{id,name}]
var g_list_objgroup = [];//[{id,name}]
var g_list_usergroup = [];//[{code,name}]
const g_list_contacttype = [{ "id": 1, "name": "Khách hàng" }, { "id": 2, "name": "Nhà cung cấp" }, { "id": 3, "name": "Cả hai" }];
const g_list_gender = [{ "id": 1, "name": "Nam" }, { "id": 2, "name": "Nữ" }, { "id": 3, "name": "Chưa xác định" }];
const g_list_reason = [{ "id": "XB", "name": "Xuất bán" }, { "id": "NM", "name": "Nhập mua" }, { "id": "TN", "name": "Thu nợ" }, { "id": "CN", "name": "Trả nợ" }];
var g_list_resinvoicesource = [];//id,name,charge
var g_map_listloadtime = new Map();
var g_bankaccountdata = "";//{id,code,name,bank,owner}
var g_refreshinterval = 1000;
var g_invoicePrintType = new Map();//lq,l,b - k5880 a4 a5
//LS
var g_ls_gsorderqueue = [];//danh sach hang/dich vu duoc dat dang cho xac nhan/phuc vu
var g_ls_gsorderqueue_visible = true;//hien thi g_ls_gsorderqueue 
var g_ls_objlist = [];//[{id,name,objcategory,typeid,totalcost,invoiceid,seatcount}]
var g_map_invoices = new Map();//xb{invoice_id},nm{invoice_id}->cinvoicels
var g_phien_invoices = new Map();
var g_phien_invoice = null;//active cinvoicels
var g_phien_obj = null;//invoiceid,costtotal,costfixed,costhourly,costmix,
//5 discountfoods,discountdrink,discountgoods,discountservice,invoicediscount,vat,invoicemoneydiscount,
//12 contactid,contactname,contactaddress,phone,datebirth (12->16)
var g_phien_viewmode = "";//list,obj
var g_phien_viewmode_selectgoodscategory = 0;//0-horz bar, 1-vert bar
/*CART*/
var g_map_carts = new Map();//string -> array(CCartItem),all: all objs cart, obj_id -> obj cart, sa_x: shipaway 1/2/3.. cart, ta_x: takeaway 1/2/3.. cart
var g_cart_names = [];
var g_cart_active = "";
//goods
var g_goods_thumbnail_maxx = 120;
var g_goods_thumbnail_maxy = 120;
var g_goods_imageview_maxx = 200;
var g_goods_imageview_maxy = 200;
/*Scanner Camera*/
var g_scanner = null;
var g_scannerdeviceid = "";
//CLASS//
class CInvoiceInfo {
    constructor() {
        this.contact_id = 0;
        this.saleman_id = 0;
        this.deploymentmans = 0;
    }
}
class CCartItem {
    constructor(id, goods_id, unit_id, goods_name, unit, unit_price, quantity, idmixmain) {
        if (isEmpty(idmixmain)) idmixmain = "";
        this.id = id;
        this.goods_id = goods_id;
        this.unit_id = unit_id;
        this.goods_name = goods_name;
        this.goods_code = "";
        this.unit = unit;
        this.unit_price = unit_price;
        this.quantity = quantity;
        this.discount = 0;
        this.serial = "";
        this.warranty = null;
        this.color_name = "";
        this.template_id = null;
        this.parent_id = null;
        this.extra_id = null;
        this.quantity_max = null;
        this.note = "";
        this.idmixmain = idmixmain;
    }
}

//goods-service item (trong exim_export_invoice_details)
class CGSItem {
    //id,goodsid,unitid,name,price,unit,quantity,objcategory,from,hourly,minutelimit,iscombo,to,idmixmain,ismix,realname
    constructor(id, goods_id, unit_id, name, unit_price, unit, quantity, objcategory, from, hourly, minutelimit, iscombo, to, idmixmain, ismix, realname) {
        if (isEmpty(objcategory)) objcategory = 0;
        if (isEmpty(from)) from = "";
        if (isEmpty(hourly)) hourly = "";
        if (isEmpty(minutelimit)) minutelimit = 0;
        if (isEmpty(iscombo)) iscombo = "";
        if (isEmpty(to)) to = "";
        if (isEmpty(idmixmain)) idmixmain = 0;
        if (isEmpty(ismix)) ismix = "";

        this.id = id; this.goods_id = goods_id; this.unit_id = unit_id, this.name = name; this.unit_price = unit_price;
        this.unit = unit; this.quantity = quantity; this.objcategory = objcategory;
        this.from = from; this.hourly = hourly; this.minutelimit = minutelimit; this.iscombo = iscombo; this.to = to;
        this.idmixmain = idmixmain;
        this.ismix = ismix; this.realname = realname;
    }
}

class CObj {
    constructor(id, name, objcategory, typeid, totalcost, invoiceid, seatcount, group, gs_ordered) {
        this.id = id;
        this.name = name;
        this.objcategory = objcategory;
        this.typeid = typeid;
        this.totalcost = totalcost;
        this.invoiceid = invoiceid;
        this.seatcount = seatcount;
        this.group = group;
        //ex
        this.gs_ordered = gs_ordered;
    }

}

class CInvoiceLS {
    //instancename:outside name to call method
    //paymentdebit:0-cash,1-debit
    constructor(reason, invoiceid, instancename, key, resinvoicesource) {
        this.page_source = "";
        this.id = 0;
        this.reason = reason.toLowerCase();
        this.instancename = instancename;

        this.iddivshow_cart = null;

        this.iddvishow_invoice_contactname = null;
        this.iddivshow_invoice_header = null;
        this.iddivshow_goods_list = null;

        this.viewmode_selectgoodscategory = 0;

        this.cart = new Map();//idcombine goods_id unit_id -> ccartitem
        this.goods = new Map();
        this.services = new Map();
        //
        this.canedit = true;//mac dinh cho phep sua doi them bot..


        this.obj_id = null;
        this.invoiceid = parseNumberVn(invoiceid);
        this.invoiceno = null;
        this.invoicedate = null;



        this.vat = null;
        this.totalcost = null;
        this.invoicemoneydiscount = null;
        this.cart_count = null;
        this.cart_sum = null;

        this.contactid = null;
        this.contactname = null;
        this.contactaddress = null;
        this.contactphone = null;

        this.contactid_delivery = null;
        this.contactname_delivery = null;
        this.contactaddress_delivery = null;
        this.phone_delivery = null;

        this.resinvoicesource = null;//id
        this.resinvoicesourcename = null;
        this.resinvoicesourcecharge = null;

        this.paymentdebit = null;
        if (!isEmpty(resinvoicesource)) {
            for (var i = 0; i < g_list_resinvoicesource.length; i++) {
                if (g_list_resinvoicesource[i].id == resinvoicesource) {
                    this.resinvoicesourcename = g_list_resinvoicesource[i].name;
                    this.resinvoicesourcecharge = g_list_resinvoicesource[i].charge;
                    this.resinvoicesource = resinvoicesource;
                    this.paymentdebit = g_list_resinvoicesource[i].paymentdebit;
                    this.contactid = g_list_resinvoicesource[i].contactid;
                }
            }
        }
        var newid = 0;
        g_phien_invoices.forEach((value, key) => {
            if (value.id > newid) newid = value.id;
        }
        );
        newid = newid + 1;
        this.id = newid;
        if (!isEmpty(key))
            this.key = key;
        else
            this.key = this.reason + newid;

        this.fnCallbackOnInvoiceChange = null;
        this.fnCallbackOnCartChange = null;
        //fnCallbackOnInvoiceChange: call when goods add/remove/update
    }
    clear() {
        this.invoiceid = null;
        this.totalcost = null;
        this.costfixed = null;
        this.costhourly = null;
        this.costmix = null;

        this.invoiceno = "";


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

        this.contactid = null;
        this.contactname = null;
        this.contactaddress = null;
        this.phone = null;
        this.datebirth = null;

        this.tradeuserid = null;
        this.tradeusername = null;
        this.tradeusermobile = null;

        this.contactid_delivery = null;
        this.contactname_delivery = null;
        this.contactaddress_delivery = null;
        this.phone_delivery = null;

        this.statusremotecall = null;
        this.seatcount = null;
        this.userid = null;

        this.goods.clear();
        this.services.clear();

    }
    cartGetItem(goods_id, unit_id) {
        goods_id = parseNumberVn(goods_id);
        unit_id = parseNumberVn(unit_id);
        var item = null;
        this.cart.forEach((value, key) => {
            if ((value.goods_id == goods_id) && (value.unit_id == unit_id)) {
                item = value;
                return;
            }
        }
        );
        return item;
    }
    cartGetQuantity(goods_id, unit_id) {
        var count = 0;
        this.cart.forEach((value, key) => {
            //CCartItem
            if ((value.goods_id == goods_id) && (value.unit_id == unit_id)) {

                return value.quantity;

            }
            count = count + value.quantity;
        }
        );
        return 0;
    }
    cartSet(idcombine, quantity) {
        if (!this.canedit) return;

        quantity = parseNumberVn(quantity);

        var cartitem = this.cart.get(idcombine);
        if (isEmpty(cartitem)) return;
        cartitem.quantity = quantity;
        if (cartitem.quantity < 0)
            cartitem.quantity = 0;
        this.cartCalc();

        var idrow = document.getElementById(this.getIdCartRow(idcombine));
        if (!isEmpty(idrow)) idrow.outerHTML = this.cartShow_Row(cartitem);
        if (!isEmpty(this.fnCallbackOnCartChange)) eval(this.fnCallbackOnCartChange)();
    }
    //idmixmain
    cartAdd(goods_id, unit_id, quantity, goods_unit_price, idmixmain, goods_name, goods_unit) {
        if (!this.canedit) return;
        if (isEmpty(idmixmain)) idmixmain = "";

        //find quantity 
        var ccartitem = this.cartGetItem(goods_id, unit_id);

        //CCartItem exists
        if (!isEmpty(ccartitem)) {
            ccartitem.quantity += quantity;
            if (ccartitem.quantity < 0)
                ccartitem.quantity = 0;
            setValById(this.getIdCartQuantity(ccartitem.id), ccartitem.quantity);
            setValById(this.getIdSelectGoodsItemQuantity(ccartitem.id), ccartitem.quantity);
            this.cartCalc();
            //update ui
            var idrow = document.getElementById(this.getIdCartRow(ccartitem.id));
            if (!isEmpty(idrow)) idrow.outerHTML = this.cartShow_Row(ccartitem);

            if (!isEmpty(this.fnCallbackOnCartChange)) eval(this.fnCallbackOnCartChange)();
            return;
        }
        //neu cartitem
        if (isEmpty(this.cart_idstart)) {
            this.cart_idstart = 1;
        } else {
            this.cart_idstart += 1;
        }
        var idcombine = this.cart_idstart + genIdCombine(goods_id, unit_id);

        if (isEmpty(idmixmain)) {
            var idgettext = genIdCombine(goods_id, unit_id);
            var goods_name = getInnerById(this.getIdShowGoodsName(idgettext));
            var goods_unit = getInnerById(this.getIdShowGoodsUnit(idgettext));
            var goods_unit_price = getInnerById(this.getIdShowGoodsUnitPrice(idgettext));
        }
        //k-1000
        if (goods_unit_price.substr(goods_unit_price.length - 1, 1) == "k") {
            goods_unit_price = goods_unit_price.substr(0, goods_unit_price.length - 1) + "000";
        }
        goods_unit_price = parseNumberVn(goods_unit_price);

        //goods_id,unit_id,goods_name,unit,unit_price,quantity
        ccartitem = new CCartItem(idcombine, goods_id, unit_id, goods_name, goods_unit, goods_unit_price, quantity);
        if (!isEmpty(idmixmain))
            ccartitem.idmixmain = idmixmain;
        else
            ccartitem.idmixmain = "";

        setValById(this.getIdCartQuantity(idcombine), ccartitem.quantity);
        setValById(this.getIdSelectGoodsItemQuantity(idcombine), ccartitem.quantity);

        this.cart.set(idcombine, ccartitem);
        this.cartCalc();

        //update ui
        var idrow = document.getElementById(this.getIdCartRow(idcombine));
        if (!isEmpty(idrow)) {
            idrow.outerHTML = this.cartShow_Row(ccartitem);
        }
        if (!isEmpty(this.fnCallbackOnCartChange)) {
            if (!isEmpty(idmixmain))
                eval(this.fnCallbackOnCartChange)(0, 2);
            else
                eval(this.fnCallbackOnCartChange)();
        }
    }
    cartAddG(goods_id, unit_id, quantity) {
        if (!this.canedit) return;
        this.cartAdd(goods_id, unit_id, quantity);
    }
    cartCalc() {
        if (isEmpty(this.cart)) return 0;
        this.cart_count = 0;
        this.cart_sum = 0;
        this.cart.forEach((value, key) => {
            this.cart_count += value.quantity;
            this.cart_sum += ((value.quantity) * (value.unit_price));
        }
        );
    }

    cartRemove(idcombine) {

        if (!this.canedit) return;
        var cart = this.cart;
        if (isEmpty(cart)) return;
        var cartitem = this.cart.get(idcombine);
        if (isEmpty(cartitem)) return false;

        var idcombine = cartitem.id;
        this.cart.delete(idcombine);
        this.cartShow_RowRemove(idcombine);
        this.cartCalc();
        if (!isEmpty(this.fnCallbackOnCartChange)) eval(this.fnCallbackOnCartChange)();
    }
    cartRemoveAll() {
        if (!isEmpty(this.cart)) {
            this.cart.clear();
        }
        this.cart_count = 0;
        this.cart_sum = 0;
        this.cart_idstart = 1;

        setInnerById(this.iddivshow_cart, "");
        if (!isEmpty(this.fnCallbackOnCartChange)) eval(this.fnCallbackOnCartChange)();
    }
    //hidecartbutton: an nut khi trong phieu nhap mua/xuat ban
    cartShow(idcart, hidecartbutton) {
        this.iddivshow_cart = idcart;
        if (this.cart.size <= 0) {
            setInnerById(this.iddivshow_cart, "");
            showMsg(itxt("giohangrong"), "iShopmanX", 1000)
            return;
        }
        //eleShowHide(this.iddivshow_goods_select);
        //eleShowHide(this.iddivshow_cart,true);
        var i = 0;
        //mac dinh id=ta (take - away)
        var html = "";
        var ncount = 0;
        html += "<div>";
        this.cart.forEach((value, key) => {
            if ((value.goods_id > 0) && (value.quantity > 0) && (value.idmixmain == "")) {
                html += this.cartShow_Row(value);
                ncount++;
                this.cart.forEach((valuesub, keysub) => {
                    if (valuesub.idmixmain == value.id) {
                        html += this.cartShow_Row(valuesub);
                    }
                });
            }
        }
        );
        html += "</div>";
        if (isEmpty(hidecartbutton)) {
            html += "<input type='button' class='btndlg remove rb' style='width:50%;float:left' onclick='return " + this.instancename + ".cartRemoveAll();' value='" + itxt("xoahet") + "'>";
            if (!isEmpty(g_phien_obj)) {
                html += "<input type='button' class='btndlg default' style='width:50%;float:left' onclick='return " + this.instancename + ".cartSubmit();' value='" + g_char_rightarrow + " " + g_phien_obj.name + "'>";
            } else {
                html += "<input type='button' class='btndlg default' style='width:50%;float:left' onclick='return showListObjDlgSelect(\"showListObjDlgSelect_List_Add\",2);' value='" + itxt("chonbanphong") + "'>";
            }
            html = "<div class='phien_head'>" + itxt("giohang") + "</div>" + html;
        }
        setInnerById(this.iddivshow_cart, html);
        eleShowHide(this.iddivshow_cart, true);
    }

    //chi ap dung voi obj
    invoice_TradeUserAdd(id, name, mobile, comment) {
        if (!this.canedit) return;

        if (isEmpty(this.obj_id)) { showMsg(itxt("khongxacdinhbanphong")); return; }
        if (this.invoiceid <= 0) { showMsg(itxt("chuacohoadon")); return; }
        var url = "?page=" + this.page_source + "&action=settradeuser&obj_id=" + this.obj_id + "&tradeuser=" + id;
        var dataString = "";
        var outThis = this;
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    showMsg([itxt("loi"), getDataFail(data)]);
                    return;
                }

                outThis.tradeuserid = id;
                outThis.tradeusername = name;
                outThis.tradeusermobile = mobile;
                if (!isEmpty(outThis.fnCallbackOnInvoiceChange)) eval(outThis.fnCallbackOnInvoiceChange)();
            },
            error: function () {
                showMsg(itxt("loi"));
            }
        });
    }
    //chi ap dung voi obj
    invoice_ContactAddDelivery(id, name, address, phone) {
        if (!this.canedit) return;

        if (isEmpty(this.obj_id)) { showMsg(itxt("khongxacdinhbanphong")); return; }
        if (this.invoiceid <= 0) { showMsg(itxt("chuacohoadon")); return; }
        var url = "?page=" + this.page_source + "&action=contactdeliveryselect&obj_id=" + this.obj_id + "&contact_id=" + id;

        var dataString = "";
        var outThis = this;
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    showMsg([itxt("loi"), getDataFail(data)]);
                    return;
                }
                //thong tin tra ve la phieu vi ket qua du lieu phu thuoc doi tac - chiet khau giam gia..
                var invoices = getDataOk(data).split(g_split_val);
                //co the chua co phieu
                if (outThis.parseInvoiceData(invoices)) {
                    if (!isEmpty(outThis.fnCallbackOnInvoiceChange)) eval(outThis.fnCallbackOnInvoiceChange)();
                }
            },
            error: function () {
                showMsg(itxt("loi"));
            }
        });

    }

    //chi ap dung voi obj
    invoice_ContactAdd(id, name, address, phone) {
        if (!this.canedit) return;

        if (isEmpty(this.obj_id)) { showMsg(itxt("khongxacdinhbanphong")); return; }
        if (this.invoiceid <= 0) { showMsg(itxt("chuacohoadon")); return; }
        var url = "?page=" + this.page_source + "&action=contactselect&obj_id=" + this.obj_id + "&contact_id=" + id;
        var dataString = "";
        var outThis = this;
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    showMsg([itxt("loi"), getDataFail(data)]);
                    return;
                }
                //thong tin tra ve la phieu vi ket qua du lieu phu thuoc doi tac - chiet khau giam gia..
                var invoices = getDataOk(data).split(g_split_val);
                //co the chua co phieu
                if (outThis.parseInvoiceData(invoices)) {
                    if (!isEmpty(outThis.fnCallbackOnInvoiceChange)) eval(outThis.fnCallbackOnInvoiceChange)();
                }
            },
            error: function () {
                showMsg(itxt("loi"));
            }
        });

    }
    invoice_GoodsLoadLocal() {
        if (!this.canedit) return;
        showWaitModal();
        var url = "?page=" + this.page_source + "&action=goodsloadlocal&objlist=" + this.obj_id;
        var dataString = "";
        var outThis = this;
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    showMsg([itxt("thatbai"), getDataFail(data)]);
                    return;
                }
                //danh sach thong tin obj
                data = getDataOk(data);
                if (data.length < 1) {
                    showMsg(itxt("khongcodulieutrave"));
                    return;
                }
                var vals = data.split(g_split_val);
                if (vals.length < 4) {
                    showMsg(itxt("loi")); return;
                }
                if (parseNumberVn(vals[0]) <= 0) {
                    showMsg(itxt("loi")); return;
                }
                //gs_order: so loi goi hang/dich vu
                var obj = {
                    "id": parseNumberVn(vals[0]), "name": vals[1],
                    "objcategory": parseNumberVn(vals[2]), "typeid": vals[3],
                    "totalcost": parseNumberVn(vals[4]), "invoiceid": parseNumberVn(vals[5]),
                    "seatcount": parseNumberVn(vals[6]), "group": parseNumberVn(vals[7]),
                    "gs_order": parseNumberVn(vals[8]), "invoiceno": vals[9]
                };

                outThis.invoiceid = obj.id;
                if (!isEmpty(outThis.fnCallbackOnCartChange)) eval(outThis.fnCallbackOnCartChange)();
                if (!isEmpty(outThis.fnCallbackOnInvoiceChange)) eval(outThis.fnCallbackOnInvoiceChange)(1);
                showMsg(itxt("danaphang"), itxt("naphangdesan"), 1000);
            },
            error: function () {
                showMsg(itxt("loi"));

            }
        });
        return false;

    }
    invoice_GoodsComment(details_id, comment) {
        if (!this.canedit) return;

        var item = this.goods.get(parseInt(details_id));
        if (item == null) {
            showMsg(itxt("khongtimthayhangtrongphieu"), itxt("quanlytinhtien"), 1000);
            return;
        }
        item.comment = comment;

        showWaitModal(1, 1000);
        var url = "?page=" + this.page_source + "&action=goodscomment&obj_id=" + this.obj_id + "&id=" + details_id + "&comment=" + encodeURIComponent(comment);
        var dataString = "";
        var outThis = this;
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                hideModalBlock();
                if (!isDataOk(data)) {
                    showModalBlock(data);
                    return;
                }
                var okdata = getDataOk(data);
                hideModal();
                setOuterById(outThis.getIdShowGoodsRow(item.id), outThis.invoice_ShowGoods_Row(item));
                //setValById(outThis.getIdInvoiceQuantity(id),quantity);
                //setInnerById(outThis.getIdInvoiceSubtotal(id),formatNumber(item.quantity*item.unit_price));
                //if(!isEmpty(outThis.fnCallbackOnInvoiceChange))eval(outThis.fnCallbackOnInvoiceChange)();
            },
            error: function () {
                hideModalBlock();

            }
        });
    }
    //co the them goods chinh hoac goods sub vao goods da co
    invoice_GoodsAdd(goods_id, unit_id, quantity, unit_price, id_mixmain) {
        if (!this.canedit) return;
        var param = goods_id + g_split_val + unit_id + g_split_val + quantity + g_split_val + unit_price + g_split_val + "";
        var url = "?page=" + this.page_source + "&action=goodsadd&objlist=" + this.obj_id + "&id_mixmain=" + id_mixmain + "&param=" + param;

        var dataString = "";
        var outThis = this;
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    showMsg([itxt("loi"), getDataFail(data)]);
                    return;
                }
                var obj = lsDataToObj(getDataOk(data));
                g_phien_obj.invoicels.invoiceno = obj.invoicels.invoiceno;
                g_phien_obj.gs_order = obj.gs_order;
                if (g_phien_obj.invoicels.invoiceid <= 0) {
                    g_phien_obj.invoicels.invoiceid = obj.invoicels.invoiceid;
                    g_phien_obj.invoicels.totalcost = obj.invoicels.totalcost;
                } else {
                    g_phien_obj.invoicels.totalcost = obj.invoicels.totalcost;
                }
                if (!isEmpty(outThis.fnCallbackOnInvoiceChange)) eval(outThis.fnCallbackOnInvoiceChange)(1);
            },
            error: function () {
                showMsg(itxt("loi"));
            }
        });

    }
    invoice_GoodsRemove(id) {
        if (!this.canedit) return;
        id = parseInt(id);
        var ishavesub = false;
        this.goods.forEach((value, key) => {
            if (value.idmixmain == id) {

                ishavesub = true;
                return;
            }
        }
        );
        if (ishavesub) {
            showMsg(itxt("khongxoaduochangcomonphu"));
            return;
        }
        //type:0-goods, 1-service
        var type = 0;
        var url = "?page=" + this.page_source + "&action=remove&obj_id=" + this.obj_id + "&id=" + id + "&type=" + type;
        var dataString = "";
        var outThis = this;
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    showMsg([itxt("loi"), getDataFail(data)]);
                    return;
                }
                outThis.goods.delete(id);
                outThis.invoice_ShowGoods_RowRemove(id);

                var rows = getDataOk(data).split(g_split_row);
                var start = 0;
                var vals = rows[0].split(g_split_val);
                if (outThis.parseInvoiceData(vals))
                    start = 1;

                outThis.parseServiceGoodsData(rows, start);
                if (!isEmpty(outThis.fnCallbackOnInvoiceChange)) eval(outThis.fnCallbackOnInvoiceChange)();
            },
            error: function () {
                showMsg(itxt("loi"));
            }
        });
        hideModalBlock();

    }

    isGoodsHasMix(id) {
        var bhave = false;
        this.goods.forEach((value, key) => {
            if (value.idmixmain == id) {
                bhave = true;
                return;
            }
        }
        );
        return bhave;
    }

    invoice_GoodsSet(id, quantity) {
        if (!this.canedit) return;

        var item = this.goods.get(id);
        if (item == null) {
            showMsg(itxt("khongtimthayhangtrongphieu"), itxt("quanlytinhtien"), 1000);
            return;
        }
        if (quantity <= 0) {
            invoice_GoodsRemove(id);
            return;
        }

        var addquantity = quantity - item.quantity;
        var subtotaladjust = 0;
        subtotaladjust += parseNumberVn(addquantity) * parseNumberVn(item.unit_price);


        showWaitModal(1, 1000);
        var url = "?page=" + this.page_source + "&action=goodsaddquantity&obj_id=" + this.obj_id + "&id=" + id + "&quantity=" + addquantity;
        var dataString = "";
        var outThis = this;
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                hideModalBlock();
                if (!isDataOk(data)) {
                    showModalBlock(data);
                    return;
                }
                var okdata = getDataOk(data);
                outThis.totalcost = parseNumberVn(okdata);
                item.quantity = parseNumberVn(quantity);
                setValById(outThis.getIdInvoiceQuantity(id), quantity);
                setInnerById(outThis.getIdInvoiceSubtotal(id), formatNumber(item.quantity * item.unit_price));
                var param = null;
                //chi tang va hien thi lai cac hang to hop, khong phai hang chi co topping them vao
                if ((!isEmpty(item.ismix)) && (item.ismix != 0)) {
                    param = 4;
                }
                if (!isEmpty(outThis.fnCallbackOnInvoiceChange)) eval(outThis.fnCallbackOnInvoiceChange)(param);
            },
            error: function () {
                hideModalBlock();

            }
        });

    }
    invoiceLoad(fnCallBackOnOkName, fnCallBackOnFailName) {
        if (isEmpty(this.obj_id)) { showMsg(itxt("khongxacdinhbanphong")); return; }
        var url = "?page=" + this.page_source + "&action=getinvoice" + "&obj_id=" + this.obj_id;
        var dataString = "";
        var outThis = this;
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    showMsg([itxt("loi"), getDataFail(data)]);
                    if (!isEmpty(fnCallBackOnFailName)) eval(fnCallBackOnFailName)();
                    return;
                }
                //du lieu co the trong vi khong co phien
                var dataok = getDataOk(data);
                if (dataok.length <= 0)
                    return;
                var invoices = dataok.split(g_split_val);
                //co the chua co phieu
                if (outThis.parseInvoiceData(invoices)) {
                    if (outThis.invoiceid > 0)
                        outThis.invoiceLoad_Details(fnCallBackOnOkName, fnCallBackOnFailName);
                    if (!isEmpty(outThis.fnCallbackOnInvoiceChange)) eval(outThis.fnCallbackOnInvoiceChange)();

                }
                else {
                    if (!isEmpty(fnCallBackOnFailName)) eval(fnCallBackOnFailName)();
                    hideModal();
                }

            },
            error: function () {
                if (!isEmpty(fnCallBackOnFailName)) eval(fnCallBackOnFailName)();
                showMsg(itxt("loi"));
            }
        });

    }
    //lay danh sach hang va dich vu
    invoiceLoad_Details(fnCallBackOnOkName, fnCallBackOnFailName) {
        var url = "?page=" + this.page_source + "&action=getinvoicedetails&obj_id=" + this.obj_id;
        var dataString = "";
        var outThis = this;
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    showMsg([itxt("loi"), getDataFail(data)]);
                    if (!isEmpty(fnCallBackOnFailName)) eval(fnCallBackOnFailName)();
                    return;
                }
                var rows = getDataOk(data).split(g_split_row);
                if (rows < 1)//phieu chua co hang dich vu
                {
                    if (!isEmpty(fnCallBackOnFailName)) eval(fnCallBackOnFailName)();
                    return;
                }
                //danh sach hang dich vu
                //id,goodsid,name,price,unit,quantity,objcategory,from,hourly,minutelimit,iscombo,to
                if (!outThis.parseServiceGoodsData(rows, 0)) {
                    if (!isEmpty(fnCallBackOnFailName)) eval(fnCallBackOnFailName)();
                    return;
                }
                if (!isEmpty(fnCallBackOnOkName)) eval(fnCallBackOnOkName)();
            },
            error: function () {
                if (!isEmpty(fnCallBackOnFailName)) eval(fnCallBackOnFailName)();
                showMsg(itxt("loi"));
            }
        });

    }
    invoiceNew() {
        this.clear();
        this.cartRemoveAll(false);
        this.cartShow();
        this.invoiceid = 0;
        this.contactid = 0;
        this.contactname = null;
        this.contactaddress = null;
        this.contactphone = null;

        eleEnable("idbuttoninvoicenew");
        eleEnable("idbuttoninvoiceprint");
        eleEnable("idbuttoninvoicesave", true);
        //remove finished invoice
        g_phien_invoices.forEach((value, key) => {
            if (value.invoiceid > 0) g_phien_invoices.delete(key);
        }
        );

        this.canedit = true;
        if (!isEmpty(this.fnCallbackOnInvoiceChange)) eval(this.fnCallbackOnInvoiceChange)();

    }

    //show temp goods in cart
    invoiceShowGoods(bShowAdjustRemove = false) {
        var i = 0;
        //mac dinh id=ta (take - away)
        var html = "";
        var ncount = 0;
        html += "<div>";
        this.cart.forEach((value, key) => {
            if ((value.goods_id > 0) && (value.quantity > 0) && (value.idmixmain == "")) {
                html += this.cartShow_Row(value);
                ncount++;
                this.cart.forEach((valuesub, keysub) => {
                    if (valuesub.idmixmain == value.id) {
                        html += this.cartShow_Row(valuesub);
                    }
                });
            }
        }
        );

        html += "</div>";
        setInnerById(this.iddivshow_goods_list, html);
    }
    //method:0-cash,1-debit
    //print: 0,1 after save
    invoiceSave(method, print) {
        var cart = this.cart;
        var i = 0;
        if (isEmpty(cart)) {
            showMsg(itxt("khongcohang"), itxt("phieu"), 1000);
            return 0;
        }

        var param = "";
        this.cart.forEach((value, key) => {
            if ((value.goods_id > 0) && (value.quantity != 0) && isEmpty(value.idmixmain)) {
                if (param != "")
                    param += g_split_row;
                param += value.goods_id + g_split_val;
                param += value.unit_id + g_split_val;
                param += value.quantity + g_split_val;
                param += value.unit_price + g_split_val;
                param += value.note + g_split_val;
                param += value.id + g_split_val;
                param += value.idmixmain;

                this.cart.forEach((valuesub, keysub) => {
                    if (valuesub.idmixmain == value.id) {
                        param += g_split_row;
                        param += valuesub.goods_id + g_split_val;
                        param += valuesub.unit_id + g_split_val;
                        param += valuesub.quantity + g_split_val;
                        param += valuesub.unit_price + g_split_val;
                        param += valuesub.note + g_split_val;
                        param += valuesub.id + g_split_val;
                        param += valuesub.idmixmain;
                    }
                });
            }
        }
        );


        showWaitModal();
        if (isEmpty(this.page_source)) {
            //showMsg(itxt("chuaxacdinhtrangxuly"),itxt("ghiphieu"),1000);
            //return;
        }
        var page = "ls_phieunhapmua";

        if (this.reason == "xb") page = "ls_phieuxuatban";
        //ls_phieunhapmua,ls_phieuxuatban
        var url = "?page=" + page + "&pagesub=save&data=" + param + "&method=" + method + "&contactid=" + this.contactid + "&invoiceid=" + this.invoiceid +
            "&deliveryid=" + this.contactid_delivery + "&tradeuserid=" + this.tradeuserid + "&invoicediscount=" + this.invoicediscount +
            "&vat=" + this.vat + "&invoicemoneydiscount=" + this.invoicemoneydiscount + "&servicecharge=" + this.servicecharge
            + "&discountservice=" + this.discountservice + "&discountgoods=" + this.discountgoods +
            "&discountfoods=" + this.discountfoods + "&discountdrink=" + this.discountdrink + "&extracharge=" + this.extracharge +
            "&debit=" + this.debit + "&resinvoicesource=" + this.resinvoicesource + "&paymentdebit=" + this.paymentdebit;

        var dataString = "";
        var outThis = this;
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    showMsg([itxt("thatbai"), getDataFail(data)]);
                    return;
                }
                hideModalBlock();
                data = getDataOk(data);
                var vals = data.split(g_split_val);//invoiceid-invoiceno-totalcost

                if (vals.length == 3) {

                    outThis.invoiceid = parseNumberVn(vals[0]);
                    outThis.invoiceno = vals[1];
                    outThis.totalcost = parseNumberVn(vals[2]);
                    outThis.canedit = false;
                    showMsg(itxt("daghiphieu"), itxt("ghiphieu"), 1000);
                    if (!isEmpty(print) && print) {
                        invoicePrint(outThis.invoiceid);
                    }
                    callPrintInvoiceGoodsLabel(outThis.invoiceid);
                    if (!isEmpty(outThis.fnCallbackOnInvoiceChange)) eval(outThis.fnCallbackOnInvoiceChange)(5);
                }
                else {
                    showMsg(itxt("loi"));
                }
            },
            error: function () {
                showMsg(itxt("loi"));

            }
        });
        return false;
    }
    getIdCartRow(idcombine) {
        return "iddivcartrow" + idcombine;
    }
    getIdCartQuantity(idcombine) {
        return "iddivcartquantity" + idcombine;
    }
    getIdInvoiceRow(idcombine) {
        return "iddivinvoicerow" + idcombine;
    }
    getIdInvoiceQuantity(idcombine) {
        return "iddivinvoicequantity" + idcombine;
    }
    getIdInvoiceSubtotal(idcombine) {
        return "iddivinvoicesubtotal" + idcombine;
    }

    getIdShowGoodsRow(idcombine) {
        return "iddivgoodsrowselect" + idcombine;
    }
    getIdShowGoodsName(idcombine) {
        return "iddivgoodsnameselect" + idcombine;
    }
    getIdShowGoodsUnit(idcombine) {
        return "iddivgoodsunitselect" + idcombine;
    }
    getIdShowGoodsUnitPrice(idcombine) {
        return "iddivgoodsunitpriceselect" + idcombine;
    }
    getIdSelectGoodsItem(idcombine) {
        return "idgsirow" + idcombine;
    }
    getIdSelectGoodsItemCartButton(idcombine) {
        return "idgsirowcb" + idcombine;
    }
    getIdSelectGoodsItemQuantity(idcombine) {
        return "iddivgoodsquantityselect" + idcombine;
    }
    getInvoiceGoodsCount() {
        var count = 0;
        this.goods.forEach((value, key) => {
            count += value.quantity;
        }
        );
        return count;
    }
    getInvoiceServiceCount() {
        var count = 0;
        this.services.forEach((value, key) => {
            count += value.quantity;
        }
        );
        return count;
    }
    getReceivable() {
        //-parseNumberVn(this.invoicemoneydiscount)
        //totalcost da giam tru
        if (this.invoiceid > 0)
            return parseNumberVn(this.totalcost) + parseNumberVn(this.costmix);
        else
            return (this.cart_sum - parseNumberVn(this.invoicemoneydiscount));
    }
    getReceivableShow() {
        var receivable = parseNumberVn(this.totalcost) + parseNumberVn(this.costmix) - parseNumberVn(this.invoicemoneydiscount);
        var iteminvoiceshow = formatNumber(receivable);

        if (this.invoiceno != "") {
            //if(iteminvoiceshow!="")
            //iteminvoiceshow=this.invoiceno+ " - "+iteminvoiceshow;
            //else
            //iteminvoiceshow=this.invoiceno+ " - 0";
        }
        if (iteminvoiceshow == "0") return "";
        return iteminvoiceshow;
    }

    onClickSelectGoodsItem(goods_id, unit_id) {
        var idcombine = genIdCombine(goods_id, unit_id);
        var iddivitem = document.getElementById(this.getIdSelectGoodsItem(idcombine));
        iddivitem.classList = iddivitem.classList + " selected";
        var iddivitemcartbutton = document.getElementById(this.getIdSelectGoodsItemCartButton(idcombine));
        iddivitemcartbutton.style.display = "block";
        setValById(this.getIdSelectGoodsItemQuantity(idcombine), this.cartGetQuantity(goods_id, unit_id) + 1);
        this.cartAdd(goods_id, unit_id, 1);
    }
    parseInvoiceData(invoices) {
        if (invoices.length < 22) {
            showModalBlock(itxt("dulieukhongdung"));
            return false;
        }
        //invoiceid,totalcost,costfixed,costhourly,costmix,
        //5 discountfoods,discountdrink,discountgoods,discountservice,invoicediscount,extracharge,vat,invoicemoneydiscount,
        //13 contactid,contactname,contactaddress,phone,datebirth (13->17)
        //20 invoice_status,invoice_no

        this.invoiceid = parseNumberVn(invoices[0]);
        this.totalcost = parseNumberVn(invoices[1]);
        this.costfixed = parseNumberVn(invoices[2]);
        this.costhourly = parseNumberVn(invoices[3]);
        this.costmix = parseNumberVn(invoices[4]);

        this.discountfoods = parseNumberVn(invoices[5]);
        this.discountdrink = parseNumberVn(invoices[6]);
        this.discountgoods = parseNumberVn(invoices[7]);
        this.discountservice = parseNumberVn(invoices[8]);
        this.invoicediscount = parseNumberVn(invoices[9]);
        this.extracharge = parseNumberVn(invoices[10]);
        this.vat = invoices[11];
        this.invoicemoneydiscount = parseNumberVn(invoices[12]);

        this.contactid = invoices[13];
        this.contactname = invoices[14];
        this.contactaddress = invoices[15];
        this.phone = invoices[16];

        this.datebirth = invoices[17];
        this.userid = invoices[18];

        this.tradeuserid = invoices[19];
        this.tradeusername = "";
        this.tradeusermobile = "";

        this.invoicestatus = invoices[20];
        this.invoiceno = invoices[21];

        this.contactid_delivery = null;
        this.contactname_delivery = null;
        this.contactaddress_delivery = null;
        this.phone_delivery = null;

        return true;
    }

    //ndatatype: 0 - chua ca du lieu dich vu + hang, 1 - chi dich vu, 2 - chi hang
    parseServiceGoodsData(rows, start, ndatatype = 0) {
        if ((ndatatype == 0) || (ndatatype == 1)) this.services.clear();
        if ((ndatatype == 0) || (ndatatype == 2)) this.goods.clear();
        //danh sach hang dich vu
        //id,goodsid,unitid,name,price,unit,quantity,objcategory,from,hourly,minutelimit,iscombo,to,idmixmain,ismix,realname
        for (var i = start; i < rows.length; i++) {
            var vals = rows[i].split(g_split_val);

            if (vals.length != 17) {
                continue;
            }
            //id:export/import_invoice_details_id
            //var item={"id":vals[0],"goodsid":vals[1],"unitid":vals[2],"name":vals[3],"price":vals[4],"unit":vals[5],"quantity":vals[6],
            //"objcategory":vals[7],"from":vals[8],"hourly":vals[9],"minutelimit":vals[10],"iscombo":vals[11],"to":vals[12],"idmixmain":vals[13],"ismix":vals[14],"realname":vals[15]};

            var item = new CGSItem(parseNumberVn(vals[0]), parseNumberVn(vals[1]), parseNumberVn(vals[2]), vals[3],
                parseNumberVn(vals[4]), vals[5], parseNumberVn(vals[6]), vals[7], vals[8], vals[9], vals[10], vals[11], vals[12], parseNumberVn(vals[13]), vals[14], vals[15]);
            item.comment = vals[16];
            if (vals[7] != "") {

                this.services.set(parseNumberVn(vals[0]), item);
            }
            else
                this.goods.set(parseNumberVn(vals[0]), item);
        }

        return true;
    }

    invoiceSetContact(id, name, address, phone) {
        this.contactid = id;
        this.contactname = name;
        this.contactaddress = address;
        this.contactphone = phone;
    }
    invoiceSetDelivery(id, name, address, phone) {

    }
    invoiceSetTradeUserId(id, name, mobile, comment) {

    }
    //cart:CCartItem
    cartShow_Row(cartitem, bShowAdjustRemove = false) {

        var html = "", subclass = "";
        var idcombine = cartitem.id;
        var idcartrow = this.getIdCartRow(idcombine);
        var idcartquantity = this.getIdCartQuantity(idcombine);

        var name = "", subclass = "";
        if (cartitem.idmixmain != "") {
            subclass = " sub";
        }
        if (cartitem.ismix == "1") {
            name = "<b><u>" + cartitem.goods_name + "</u></b>";
        }
        else if (cartitem.idmixmain != "")
            name = " + " + cartitem.goods_name + "";
        else
            name = "<b>" + cartitem.goods_name + "</b>";

        html += "<div class='list_item" + subclass + "' style='border:none' id='" + idcartrow + "'>";
        html += "<div class='list_item title click' onclick='return menuPopupItemGoodsCart(\"" + idcombine + "\",\"" + cartitem.idmixmain + "\")'>";
        //html+="<a href='javascript:void(0)' class='goods_cmdremove' style='float:left;color:green' onclick='return menuPopupItemGoodsCart(\""+idcombine+"\",\""+cartitem.idmixmain+"\")'>"+g_char_menu+"</a>";
        html += "<a href='javascript:void(0)' class='goods_cmdremove' style='float:right' onclick='" + this.instancename + ".cartRemove(\"" + idcombine + "\");event.stopPropagation();'>" + g_char_x + "</a>";
        html += name;
        html += "</div>";

        html += "<div class='list_item_content'>";
        html += "<div style='width:35%;float:left;'>";
        html += formatNumber(cartitem.unit_price) + "/" + cartitem.unit;
        html += "</div>";
        html += "<div style='width:40%;float:left;text-align:center'>";
        html += "<input type=\"button\" class=\"btn_mainheader plusminus\" onclick=\"" + this.instancename + ".cartSet('" + idcombine + "'," + (cartitem.quantity - 1) + ");\" value=\"-\">";
        html += "<input type=\"text\"  class=\"phien_quantity\" onfocus=\"this.select()\" onchange=\"" + this.instancename + ".cartSet('" + idcombine + "',this.value)\" size=\"2\" name='quantity[" + idcombine + "]' id='" + idcartquantity + "' ";
        html += "value='" + formatNumber(cartitem.quantity) + "'>";
        html += "<input type=\"button\" class=\"btn_mainheader plusminus\" onclick=\"" + this.instancename + ".cartSet('" + idcombine + "'," + (cartitem.quantity + 1) + ");\" value=\"+\">";
        html += "</div>";
        html += "<div style='width:25%;float:left;text-align:right;font-weight:bold;'>";
        html += formatNumber((cartitem.unit_price) * (cartitem.quantity));
        html += "</div>";
        html += "</div>";
        html += "</div>";
        return html;
    }
    invoice_ShowGoods_RowRemove(id) {
        if (!this.canedit) return;

        var idrow = document.getElementById(this.getIdShowGoodsRow(id));
        if (!isEmpty(idrow)) idrow.outerHTML = "";
    }

    invoice_ShowGoods_Row(gsitem, bShowAdjustRemove = true) {

        var html = "";
        var idcombine = gsitem.id;
        var idquantity = this.getIdInvoiceQuantity(idcombine);
        var idsubtotal = this.getIdInvoiceSubtotal(idcombine);
        var name = "", subclass = "";
        if (gsitem.idmixmain > 0) {
            subclass = " sub";
        }
        if (gsitem.ismix == "1") {
            name = "<b><u>" + gsitem.name + "</u></b>";
        }
        else if (gsitem.idmixmain > 0)
            name = " + " + gsitem.name + "";
        else
            name = "<b>" + gsitem.name + "</b>";

        html += "<div class='list_item" + subclass + "' id='" + this.getIdShowGoodsRow(idcombine) + "'>";
        html += "<div class='list_item title click' onclick='return menuPopupItemGoods(" + gsitem.id + "," + gsitem.idmixmain + ")'>";
        html += name;
        if (bShowAdjustRemove)
            html += "<a href='javascript:void(0)' class='goods_cmdremove' style='float:right' onclick='event.stopPropagation();return " + this.instancename + ".invoice_GoodsRemove(" + gsitem.id + ")'>" + g_char_x + "</a>";
        if (gsitem.comment != "") {
            html += "<br><div class='subinfo'>" + gsitem.comment + "</div>";
        }
        html += "</div>";

        html += "<div class='list_item_content'>";
        html += "<div style='width:35%;float:left;'>";
        html += formatNumber(gsitem.unit_price) + "/" + gsitem.unit;
        html += "</div>";
        html += "<div style='width:40%;float:left;text-align:center'>";
        if (bShowAdjustRemove) {
            html += "<input type=\"button\" class=\"btn_mainheader plusminus\" onclick=\"" + this.instancename + ".invoice_GoodsSet(" + gsitem.id + ",parseNumberVn(getValById('" + idquantity + "'))-1);\" value=\"-\">";
            html += "<input type=\"text\"  class=\"phien_quantity\" onfocus=\"this.select()\" onchange=\"" + this.instancename + ".invoice_GoodsSet(" + gsitem.id + ",this.value)\" size=\"2\" name='quantity[" + idcombine + "]' id='" + idquantity + "' ";
            html += "value='" + formatNumber(gsitem.quantity) + "'>";
            html += "<input type=\"button\" class=\"btn_mainheader plusminus\" onclick=\"" + this.instancename + ".invoice_GoodsSet(" + gsitem.id + ",parseNumberVn(getValById('" + idquantity + "'))+1);\" value=\"+\">";
        } else {
            html += formatNumber(gsitem.quantity);
        }
        html += "</div>";
        html += "<div style='width:25%;float:left;text-align:right;font-weight:bold;' id='" + idsubtotal + "'>";
        html += formatNumber((gsitem.unit_price) * (gsitem.quantity));
        html += "</div>";
        html += "</div>";
        html += "</div>";
        return html;
    }
    invoice_ShowGoods(bShowAdjustRemove = true) {
        if (isEmpty(this.iddivshow_goods_list)) {
            //showMsg("div to show list goods unknown");
            return;
        }
        if (this.goods.size <= 0) {
            setInnerById(this.iddivshow_goods_list, "");
            return;
        }

        var i = 0;
        //mac dinh id=ta (take - away)
        var html = "";
        var ncount = 0;
        html += "<div>";
        this.goods.forEach((value, key) => {
            if ((value.goods_id > 0) && (value.quantity > 0) && (value.idmixmain <= 0)) {
                html += this.invoice_ShowGoods_Row(value, bShowAdjustRemove);
                ncount++;
                this.goods.forEach((valuesub, keysub) => {
                    if (valuesub.idmixmain == value.id) {
                        html += this.invoice_ShowGoods_Row(valuesub, bShowAdjustRemove);
                    }
                });
            }
        }
        );
        html += "</div>";
        setInnerById(this.iddivshow_goods_list, html);
    }

    cartShow_RowRemove(idcombine) {
        if (!this.canedit) return;
        var idrow = document.getElementById(this.getIdCartRow(idcombine));
        if (!isEmpty(idrow)) idrow.outerHTML = "";
    }
    //objlist: list obj id (1,2,3)
    cartSubmit(objlist) {
        if (isEmpty(objlist)) objlist = this.obj_id;

        if (objlist.length < 1) return;

        var param = "";
        this.cart.forEach((value, key) => {
            if (value.quantity != 0) {
                if (param != "")
                    param += g_split_row;
                param += value.goods_id + g_split_val;
                param += value.unit_id + g_split_val;
                param += value.quantity + g_split_val;
                param += value.unit_price + g_split_val;
                param += value.note;
            }

        }
        );

        var url = "?page=" + this.page_source + "&action=goodsadd&objlist=" + objlist + "&directinvoice=0&param=" + param;
        var dataString = "";
        var outThis = this;
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    showMsg([itxt("thatbai"), getDataFail(data)]);
                    return;
                }
                //danh sach thong tin obj
                data = getDataOk(data);

                if (data.length < 1) {
                    showMsg(itxt("khongcodulieutrave"));
                    return;
                }
                //neu chi la goi dat hang cua nhan vien, khach
                if (data == objlist) {
                    outThis.cartRemoveAll(false);
                    if (!isEmpty(outThis.fnCallbackOnCartChange)) eval(outThis.fnCallbackOnCartChange)(1, 1);//param1:hidecart,param2: show queue
                    showMsg(itxt("dagoihangchoxacnhan"), "", 1000);
                    return;
                }
                var objs = data.split(g_split_row);

                for (var i = 0; i < objs.length; i++) {
                    var vals = objs[i].split(g_split_val);
                    if (vals.length < 4) {
                        showMsg(itxt("loi")); return;
                    }
                    if (parseNumberVn(vals[0]) <= 0) {
                        showMsg(itxt("loi")); return;
                    }

                    outThis.cartRemoveAll(false);

                    //gs_order: so loi goi hang/dich vu
                    var obj = {
                        "id": parseNumberVn(vals[0]), "name": vals[1],
                        "objcategory": parseNumberVn(vals[2]), "typeid": vals[3],
                        "totalcost": parseNumberVn(vals[4]), "invoiceid": parseNumberVn(vals[5]),
                        "seatcount": parseNumberVn(vals[6]), "group": parseNumberVn(vals[7]),
                        "gs_order": parseNumberVn(vals[8]), "invoiceno": vals[9]
                    };

                    if (obj.id == outThis.obj_id) {
                        outThis.invoiceid = obj.id;

                        if (!isEmpty(outThis.fnCallbackOnCartChange)) eval(outThis.fnCallbackOnCartChange)();
                        if (!isEmpty(outThis.fnCallbackOnInvoiceChange)) eval(outThis.fnCallbackOnInvoiceChange)(1);
                    } else {
                        if (!isEmpty(outThis.fnCallbackOnCartChange)) eval(outThis.fnCallbackOnCartChange)();
                        if (!isEmpty(outThis.fnCallbackOnInvoiceChange)) eval(outThis.fnCallbackOnInvoiceChange)(2, obj);
                    }
                }
                if (objs.length > 2) {
                    if (!isEmpty(outThis.fnCallbackOnInvoiceChange)) eval(outThis.fnCallbackOnInvoiceChange)(3);
                }
                showMsg(itxt("dathemhang"), itxt("giohang"), 1000);
            },
            error: function () {
                showMsg(itxt("loi"));

            }
        });
        return false;
    }
    async showSelect_Goods(category_id, goodsname, iddivshow) {
        if (!this.canedit) return;

        this.iddivshow_goods_select = iddivshow;

        //xac dinh dang list hay obj
        if (isEmpty(category_id)) category_id = 0;
        if (isEmpty(goodsname)) goodsname = "";
        if (category_id > 0) goodsname = "";

        //showWaitModal();
        var invoice_type;
        if (this.reason == "xb") invoice_type = "phieuxuatban";
        else invoice_type = "phieunhapmua";
        //var url="?page=list&pagesub=goods&invoice_type="+invoice_type+"&category_id="+category_id+"&goods_name="+uriEncode(goodsname)+"&pagesize=1000";
        var url = "?page=list&pagesub=goods&invoice_type=&category_id=" + category_id + "&goods_name=" + uriEncode(goodsname) + "&pagesize=1000";
        var data = await getSync(url);
        if (!isDataOk(data)) {
            showMsg([itxt("loi"), getDataFail(data)]);
            return;
        }

        data = getDataOk(data);
        //hideModal();	
        //id,goods_id,unit_id,goods_name,unit,stock,export_price,image_name
        var argoods = data.split(g_split_row);
        var ncount = argoods.length;
        if (data.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;-moz-box-sizing:border-box;box-sizing:border-box;'>";
        for (var i = start; i < ncount; i++) {
            strrow = "";
            var arfields = argoods[i].split(g_split_val);
            var imgsrc = "";
            idcombine = arfields[0];
            var cartitem = this.cart.get(idcombine);
            var quantity = 0;
            if (cartitem != null) quantity = cartitem.quantity;
            if (arfields[11].length > 0)
                imgsrc = "/imgs/" + arfields[11];
            else
                imgsrc = "/imgs/foods.jpg";

            var style = "float:right;";
            if (quantity <= 0) style += "display:none;";

            //GOODS_ITEM_SELECT
            var rowstyle = "session_goodsselect_item";
            if (cartitem != null) {
                rowstyle += " selected";
            }
            var objwidth = "20%";
            var wratio = $(window).width / 200;
            if (wratio != 0)
                objwidth = 100 / wratio + "%";
            if ($(window).width() < 600)
                objwidth = "50%";
            //if(g_phien_viewmode_selectgoodscategory==0)rowstyle+=" half";
            var priceshow = arfields[7];
            if (g_showpricethousandask) {
                priceshow = parseNumberVn(priceshow) / 1000;
                priceshow += "k";
            }
            strrow = "<div class=\"obj_wrapper\" style=\"width:" + objwidth + "\">";
            strrow += "<div id='" + this.getIdSelectGoodsItem(idcombine) + "' class='" + rowstyle + "' onclick='return " + this.instancename + ".onClickSelectGoodsItem(" + arfields[1] + "," + arfields[2] + ")'>";
            strrow += "<div style='width:100%;text-align:left;float:left;'>";
            strrow += "<b><span id='" + this.getIdShowGoodsName(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;margin-top:4px'>";
            strrow += "<span id='" + this.getIdShowGoodsUnitPrice(idcombine) + "' class='subinfo' style='float:left;background-color:rgba(0, 0, 255, 0.1);padding:4px;border-radius:50%'>" + priceshow + "</span>";
            strrow += "<span id='" + this.getIdShowGoodsUnit(idcombine) + "' class='subinfo' style='float:right'>" + arfields[5] + "</span>";
            strrow += "</div>";
            strrow += "<div id='" + this.getIdSelectGoodsItemCartButton(idcombine) + "' style='" + style + "'>";
            strrow += "<input type=\"button\" class=\"btn_mainheader plusminus\" onclick=\"event.stopPropagation();setValChangeById('" + this.getIdSelectGoodsItemQuantity(idcombine) + "',-1,0);" + this.instancename + ".cartAdd(" + arfields[1] + "," + arfields[2] + ",-1);\" value=\"-\">";
            strrow += "<input type=\"text\"  class=\"phien_quantity\" onfocus=\"this.select()\" onclick=\"event.stopPropagation();\" onchange=\"event.stopPropagation();" + this.instancename + ".cartSet(" + arfields[1] + "," + arfields[2] + ",this.value)\" size=\"2\" id='" + this.getIdSelectGoodsItemQuantity(idcombine) + "' ";
            strrow += "value='" + formatNumber(quantity) + "'>";
            strrow += "<input type=\"button\" class=\"btn_mainheader plusminus\" onclick=\"event.stopPropagation();setValChangeById('" + this.getIdSelectGoodsItemQuantity(idcombine) + "',1);" + this.instancename + ".cartAdd(" + arfields[1] + "," + arfields[2] + ",1);\" value=\"+\">";
            strrow += "</div>";
            strrow += "</div>";
            strrow += "</div>";
            strrow += "</div>";
            //END_GOODS_ITEM_SELECT
            strout += strrow;
        }
        strout += "</div>";

        var strGuide = "";
        //strGuide="<div style='padding:5px'><b>Cách gọi hàng 01:</b> Nhấn nút 'G' để gọi ngay mặt hàng. Nhấn nút + - để chỉnh số lượng gọi ngay.<br><b>Cách gọi hàng 02:</b> nhấn nút + - chọn hàng vào giỏ hàng. Vào giỏ hàng và nhấn gọi hàng.</div>"

        strout = strout + strGuide;

        if (this.viewmode_selectgoodscategory == 0) {
            var catd = this.showSelect_GoodsCategoryList();

            strout = "<div class='session_goodsselect_cathorz'>" + catd + "</div>" +
                "<div class='session_goodsselect_goods'>" + strout + "</div>";
        } else {
            strout = "<div class='session_goodsselect_catvert'>" + this.showSelect_GoodsCategoryList() + "</div>" +
                "<div class='session_goodsselect_goods'>" + strout + "</div>";
        }

        if (!isEmpty(iddivshow)) {
            setInnerById(iddivshow, strout);
            eleShowHide(iddivshow, 1);
        }
    }
    showSelect_GoodsCategoryList() {
        if (g_list_goodscategory.length > 0) {
            var html = "";
            //horz bar
            if (g_phien_viewmode_selectgoodscategory == 0) {
                html += "<div class=\"session_goodsselect_cat_close\" style=\"float:left\" onclick=\";eleShowHide('" + this.iddivshow_goods_select + "');show('" + g_phien_viewmode + "');\" >" + g_char_x + "</div>";
                html += "<div class=\"session_goodsselect_cat_close\" style=\"float:right\" onclick='" + this.instancename + ".showSelect_GoodsCategoryListAllPopup(\"" + this.iddivshow_goods_select + "\")'>:::</div>";
                html += "<div class=\"session_goodsselect_cat_btngroup\">";
                for (var i = 0; i < g_list_goodscategory.length; i++) {
                    html += "<div class='session_goodsselect_cat_btn'";
                    html += " onclick='" + this.instancename + ".showSelect_Goods(" + g_list_goodscategory[i][0] + ",\"\",\"" + this.iddivshow_goods_select + "\")'>";
                    html += g_list_goodscategory[i][1] + "</div>";
                }
                html += "</div>";

            } else {
                html += "<div onclick=\"eleShowHide('" + this.iddivshow_goods_select + "');\" class=\"session_goodsselect_cat_close\" style=\"\"><span style=\"float:left\">" + g_char_x + " " + itxt("cmd_dong") + "</span></div>";
                for (var i = 0; i < g_list_goodscategory.length; i++) {
                    html += "<button class='session_goodsselect_cat_btn' ";
                    html += " onclick='" + this.instancename + ".showSelect_Goods(" + g_list_goodscategory[i][0] + ",\"\",\"" + this.iddivshow_goods_select + "\")'>";
                    html += g_list_goodscategory[i][1] + "</button>";
                }
                html += "<button class='session_goodsselect_cat_close' onclick='" + this.instancename + ".showSelect_GoodsCategoryListAllPopup(\"" + this.iddivshow_goods_select + "\")'>>></button>";

            }
            return html;
        }
        return "";
    }
    showSelect_GoodsCategoryListAllPopup() {
        var menu = "";
        menu += "<div class='menu_popup_group'>";
        for (var i = 0; i < g_list_goodscategory.length; i++) {
            menu += "<a class='menu_popup_item' href=\"javascript:void(0)\" onclick=\"hideModal();" + this.instancename + ".showSelect_Goods(" + g_list_goodscategory[i][0] + ",'','" + this.iddivshow_goods_select + "')\">" + g_list_goodscategory[i][1] + "</a>";
        }
        menu += "</div>";
        showModal(menu, itxt("chonnhomhang"));
    }
}
/*****************************************/
class CEventAlert {
    static getEventOccur() {
        //no callback or not loaded
        if ((g_event_param === null) || (isEmpty(g_userid) || (g_userid <= 0))) {
            setTimeout(CEventAlert.getEventOccur, 1000);
            return;
        }


        //chua xac dinh id dau tien de track
        //id dau tien duoc gui theo du lieu tai thoi diem thich hop: lay danh sach obj, lay thong tin invoice..
        if (isEmpty(CEventAlert.start_event_id)) {
            setTimeout(CEventAlert.getEventOccur, 1000);
            return;
        }
        //if(g_devmode)return;
        if (!g_initiated_complete) {
            setTimeout(CEventAlert.getEventOccur, 1000);
            return;

        }
        //eventRDHandle
        //eventPhienHandle
        //xac dinh xem dang load module nao se track event tuong ung
        var url = "?page=ht_sukien&mod=";
        if (g_event_param.type == "phien")
            url += "phien";
        else if (g_event_param.type == "rd")
            url += "rd";
        else if (g_event_param.type == "rm") {
            url += "rm";
            if (!isEmpty(g_phien_obj)) {
                url += "&obj_id=" + g_phien_obj.id;
            }
        }
        else
            return;

        if (CEventAlert.event_data == null) {
            CEventAlert.event_data = new Array;
        }
        url += "&id=" + CEventAlert.start_event_id + "&user_id=" + g_userid;

        var dataString = "";
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    //user not signed in
                    if (getDataFail(data) == -1) {

                    }
                    setTimeout(CEventAlert.getEventOccur, 1000);
                    return;
                }
                if (g_event_param.type == "phien") {
                    //var d=new Date();
                    //console.log(data+":"+url+" - "+d.getMinutes()+":"+d.getSeconds());
                }
                data = getDataOk(data);
                //data:"" -> no event, "0" -> no new event
                if (data == "") {

                } else if (data == "0") {

                }
                else {
                    if (g_event_param.type == "phien") {
                        eval(g_event_param.fn)(data);
                    }
                    else if (g_event_param.type == "rd") {
                        eval(g_event_param.fn)(data);
                    } else if (g_event_param.type == "rm") {
                        eval(g_event_param.fn)(data);
                    }
                }
                setTimeout(CEventAlert.getEventOccur, 1000);
            },
            error: function () {
                setTimeout(CEventAlert.getEventOccur, 1000);
            }
        });
    }


    static getEventName(nEventType) {
        if (nEventType == 0) return itxt("batdauphien");
        if (nEventType == 1) return itxt("capnhatphien");
        if (nEventType == 2) return itxt("doichophien");
        if (nEventType == 3) return itxt("xoaphien");
        if (nEventType == 4) return itxt("gopphien");
        if (nEventType == 5) return itxt("ketthucphien");
        if (nEventType == 6) return itxt("themhang");
        if (nEventType == 7) return itxt("capnhathang");
        if (nEventType == 8) return itxt("xoahang");
        if (nEventType == 9) return itxt("dungdichvu");
        if (nEventType == 10) return itxt("datgoihang");
        if (nEventType == 11) return itxt("huydatgoihang");
        if (nEventType == 12) return itxt("tuchoidathang");
        if (nEventType == 13) return itxt("quahanxulydatmon");
        if (nEventType == 14) return itxt("chapnhanmon");
        if (nEventType == 15) return itxt("giaomon");
        if (nEventType == 16) return itxt("tamdunghang");
        if (nEventType == 17) return itxt("goithanhtoan");
        if (nEventType == 18) return itxt("huygoithanhtoan");
        if (nEventType == 19) return itxt("goinhanvienphucvu");
        if (nEventType == 20) return itxt("yeucauin");
        return itxt("sukien");
    }
    static showEvent() {
        var menu = "";
        if (Array.isArray(CEventAlert.event_data)) {
            var nStart = CEventAlert.event_data.length - 1;
            menu += "<div class='divtable'>";

            for (i = nStart; i >= 0; i--) {
                var vals = CEventAlert.event_data[i].split(g_split_val);
                menu += "<div class='divrow'>";
                menu += "<div class='divcell'>";
                menu += "<span style='float:right;top:2px;color:rgb(8,97,242);font-size:8pt;font-weight:bold'>" + (vals[5]) + "</span>";
                menu += "<b>" + CEventAlert.getEventName(vals[3]) + "</b><br>";
                menu += vals[6];

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

            }
            menu += "</div>";

        }
        if (menu.length > 0)
            showModal(menu, itxt("thongbao"));
        //cap nhat xem lan cuoi
        CEventAlert.sendEventViewed()
    }
    static showEventDetails(id) {

    }
    static sendEventViewed() {
        var url = "?page=ht_sukien&viewed=1";
        var dataString = "";
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    showMsg([itxt("loi"), getDataFail(data)]);
                    return;
                }
                data = getDataOk(data);
                eleShowHide(g_id_alertcount, false);
            },
            error: function () {
                showMsg(itxt("loi"));
            }
        });
    }
}
defineStaticField(CEventAlert, "last_updated_time", null);
defineStaticField(CEventAlert, "event_data", null);
defineStaticField(CEventAlert, "check_interval", 10000);
CEventAlert.getEventOccur();

//html code: &#8593:up arrow,&#8595:down arrow,&#8594:right arrow,&#8592: left arrow,&#10003:checked
function getListObjGroup(fnCallBack, fnCallBackParamArray) {
    if (g_list_objgroup.length > 0) {
        if (fnCallBack !== undefined) execFn(fnCallBack, fnCallBackParamArray);
        return;
    }

    var url = "?page=list&pagesub=objgroup&loadtime=" + g_map_listloadtime.get("objgroup");
    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);

            for (var i = 0; i < rows.length; i++) {
                var vals = rows[i].split(g_split_val);
                if (vals.length == 3)
                    g_list_objgroup[g_list_objgroup.length] = { "id": vals[0], "name": vals[1] };
            }

            if (g_list_objgroup.length > 0) {
                if (fnCallBack !== undefined) {
                    execFn(fnCallBack, fnCallBackParamArray);
                }
            }
        },
        error: function () {

            showMsg(itxt("loi"));
        }
    });
}
function getListObjType(fnCallBack, fnCallBackParamArray) {
    if (g_list_objtype.length > 0) {
        if (fnCallBack !== undefined) fnCallBack.apply(this, fnCallBackParamArray);
        return;
    }
    var url = "?page=list&pagesub=objtype&loadtime=" + g_map_listloadtime.get("objtype");
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (isDataFail(data)) {
                showMsg(getDataFail(data));
                return;
            }
            data = getDataOk(data);
            var rows = 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)
                    g_list_objtype[g_list_objtype.length] = { "id": vals[0], "name": vals[1] };
            }

            if (g_list_objtype.length > 0) {
                if (fnCallBack !== undefined) fnCallBack.apply(this, fnCallBackParamArray);
            }
        },
        error: function () {

            showMsg(itxt("loi"));
        }
    });
}
async function getSyncListResInvoiceSource(fnCallBack, fnCallBackParamArray) {
    if (g_list_resinvoicesource.length > 0) {
        if (fnCallBack !== undefined) fnCallBack.apply(this, fnCallBackParamArray);
        return;
    }
    var url = "?page=list&pagesub=resinvoicesource&loadtime=" + g_map_listloadtime.get("resinvoicesource");
    var data = await getSync(url);
    if (isDataFail(data)) {
        showMsg(getDataFail(data));
        return;
    }
    data = getDataOk(data);
    var rows = data.split(g_split_row);

    for (var i = 0; i < rows.length; i++) {
        var vals = rows[i].split(g_split_val);
        if (vals.length == 5)
            g_list_resinvoicesource[g_list_resinvoicesource.length] = { "id": vals[0], "name": vals[1], "contactid": vals[2], "paymentdebit": vals[3], "charge": vals[4] };
    }

    if (g_list_resinvoicesource.length > 0) {
        if (fnCallBack !== undefined) fnCallBack.apply(this, fnCallBackParamArray);
    }
}
function executeFunctionByName(str, args) {
    var arr = str.split('.');
    var fn = window[arr[0]];

    for (var i = 1; i < arr.length; i++) { fn = fn[arr[i]]; }
    fn.apply(window, args);
}


function getListGoodsCategory(fnCallBack, fnCallBackParamArray) {
    var url = "?page=list&pagesub=goods_category&loadtime=" + g_map_listloadtime.get("goods_category");

    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (isDataFail(data)) {
                showMsg(itxt("khongnapduocdanhmucnhomhang"));
                return;
            }
            //reset data
            g_list_goodscategory = [];
            data = getDataOk(data);

            var rows = data.split(g_split_row);
            var start = 0;
            if (rows.length < 1)
                return;
            if (isDataStartWith(rows[0], g_sign_columnconfig))
                start = 1;
            for (var i = start; i < rows.length; i++) {
                var vals = rows[i].split(g_split_val);
                if (vals.length >= 4)
                    g_list_goodscategory[g_list_goodscategory.length] = vals;
            }
            if (g_list_goodscategory.length > 0) {

                if (!isEmpty(fnCallBack)) {
                    if (isString(fnCallBack)) {
                        var fn = fnCallBack + "(" + arrayToStringAsList(fnCallBackParamArray) + ")";
                        eval(fn);
                    }
                    else {
                        fnCallBack.apply(this, (fnCallBackParamArray));
                    }

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


function getListObjCategory(fnCallBack, fnCallBackParamArray) {
    if (g_list_objcategory.length > 0) {
        if (fnCallBack !== undefined) execFn(fnCallBack, fnCallBackParamArray);
        return;
    }
    var url = "?page=list&pagesub=objcategory&loadtime=" + g_map_listloadtime.get("objcategory");
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {

            if (isDataFail(data)) {

                showMsg(getDataFail(data));
                return;
            }

            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)
                    g_list_objcategory[g_list_objcategory.length] = { "id": vals[0], "name": vals[1] };
            }
            if (g_list_objcategory.length > 0) {
                if (fnCallBack !== undefined) execFn(fnCallBack, fnCallBackParamArray);
            }
        },
        error: function () {

            showMsg(itxt("loi"));
        }
    });
}
//sync function
async function getSyncListStore() {
    async function promised_fetch() {
        var url = "?page=list&pagesub=store&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 (isDataFail(data)) {
        showMsg(getDataFail(data));
        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)
            g_list_store[g_list_store.length] = { "id": vals[0], "name": vals[1] };
    }
    return true;
}

async function getSync(url) {
    async function promised_fetch() {
        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();
    return data;
}
async function getSyncListBankBin() {
    if (g_list_bankbin.length > 0)
        return true;
    var url = "?page=list&pagesub=bankbin&loadtime=" + g_map_listloadtime.get("bankbin");
    var data = await getSync(url);
    if (isDataFail(data)) {
        showMsg(getDataFail(data));
        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 == 3)
            g_list_bankbin[g_list_bankbin.length] = { "id": vals[2], "name": vals[0], "shortname": vals[1] };//id-bin
    }
    return true;
}

async function getSyncListObjCategory() {
    if (g_list_objcategory.length > 0)
        return true;
    var url = "?page=list&pagesub=objcategory&loadtime=" + g_map_listloadtime.get("objcategory");
    var data = await getSync(url);
    if (isDataFail(data)) {
        showMsg(getDataFail(data));
        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)
            g_list_objcategory[g_list_objcategory.length] = { "id": vals[0], "name": vals[1] };
    }
    return true;
}
async function getSyncListEmployee() {
    if (g_list_employee.length > 0) return true;

    var url = "?page=list&pagesub=employee&loadtime=" + g_map_listloadtime.get("employee");
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg(getDataFail(data));
                return;
            }
            data = getDataOk(data);
            var rows = data.split(g_split_row);
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].substr(0, g_sign_pageconfig.length) == g_sign_pageconfig)
                    continue;
                if (rows[i].substr(0, g_sign_columnconfig.length) == g_sign_columnconfig)
                    continue;
                var vals = rows[i].split(g_split_val);
                if (vals.length == 4)
                    g_list_employee[g_list_employee.length] = { "id": vals[0], "name": vals[1], "mobile": vals[2], "comment": vals[3] };
            }
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}
//sync function
async function getSyncListObj() {
    var url = "?page=list&pagesub=phienlistobj";
    var data = await getSync(url);
    if (!isDataOk(data)) {
        showMsg([itxt("loi"), getDataFail(data)]);
        return false;
    }
    g_ls_objlist = [];
    data = getDataOk(data);
    if (data.isEmpty) return;
    var arobj = data.split(g_split_row);
    var nCount = arobj.length;
    if (nCount < 1)
        return true;

    //doi voi che do nhat nhieu obj, neu chua xac dinh start_event_id thi se xac dinh tai day
    if (isEmpty(CEventAlert.start_event_id)) {
        CEventAlert.start_event_id = parseInt(arobj[0]);
    }

    for (i = 1; i < nCount; i++) {
        var obj = lsDataToObj(arobj[i]);
        if (!isEmpty(obj)) g_ls_objlist.push(obj);
    }
    return true;
}

async function getSyncListObjType() {
    if (g_list_objtype.length > 0) {
        return true;
    }
    var url = "?page=list&pagesub=objtype&loadtime=" + g_map_listloadtime.get("objtype");
    var data = await getSync(url);
    if (isDataFail(data)) {
        showMsg(getDataFail(data));
        return false;
    }
    data = getDataOk(data);
    var rows = 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)
            g_list_objtype[g_list_objtype.length] = { "id": vals[0], "name": vals[1] };
    }
    return true;
}
async function getSyncListUserGroup() {
    if (g_list_usergroup.length > 0) return true;
    var url = "?page=list&pagesub=usergroup&loadtime=" + g_map_listloadtime.get("usergroup");
    var data = await getSync(url);
    if (!isDataOk(data)) {
        alert(data);
        showMsg([itxt("loi"), getDataFail(data)]);
        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)
            g_list_usergroup[g_list_usergroup.length] = { "id": vals[0], "name": vals[1] };
    }
    return true;
}
//html code: &#8593:up arrow,&#8595:down arrow,&#8594:right arrow,&#8592: left arrow,&#10003:checked
async function getSyncListObjGroup() {
    if (g_list_objgroup.length > 0) true;
    var url = "?page=list&pagesub=objgroup&loadtime=" + g_map_listloadtime.get("objgroup");
    var data = await getSync(url);
    if (!isDataOk(data)) {
        showMsg([itxt("loi"), getDataFail(data)]);
        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 == 3)
            g_list_objgroup[g_list_objgroup.length] = { "id": vals[0], "name": vals[1] };
    }
    return true;
}

async function getListGoodsSync(category_id = 0, goods_name = "", invoice_type = "phieuxuatle") {
    async function promised_fetch() {
        var url = "?page=list&pagesub=goods&invoice_type=" + invoice_type + "&category_id=" + category_id + "&goods_name=" + uriEncode(goods_name);
        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(getDataFail(data));
        return "";
    }
    return getDataOk(data);
}

function getListStore(fnCallBack, fnParam1, fnParam2, fnParam3, fnParam4, fnParam5) {
    if (g_list_store.length > 1) {
        if (fnCallBack !== undefined) fnCallBack(fnParam1, fnParam2, fnParam3, fnParam4, fnParam5);
        return;
    }
    var url = "?page=list&pagesub=store&loadtime=" + g_map_listloadtime.get("store");
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (isDataFail(data)) {
                showMsg(getDataFail(data));
                return;
            }

            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 == ds_store_c.length)
                    g_list_store[g_list_store.length] = { "id": vals[0], "name": vals[1] };
            }
            if (g_list_store.length > 0) {
                if (fnCallBack !== undefined) fnCallBack(fnParam1, fnParam2, fnParam3, fnParam4, fnParam5);
            }
        },
        error: function () {
            showMsg(itxt("loilaydulieu"));
        }
    });
}

function getListEmployee(fnCallBack, fnCallBackParamArray) {
    if (g_list_employee.length > 1) {
        if (fnCallBack !== undefined) fnCallBack.apply(this, fnCallBackParamArray);
        return;
    }
    var url = "?page=list&pagesub=employee&loadtime=" + g_map_listloadtime.get("employee");
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (isDataFail(data)) {
                showMsg(getDataFail(data));
                return;
            }
            data = getDataOk(data);
            var rows = data.split(g_split_row);
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].substr(0, g_sign_pageconfig.length) == g_sign_pageconfig)
                    continue;
                if (rows[i].substr(0, g_sign_columnconfig.length) == g_sign_columnconfig)
                    continue;
                var vals = rows[i].split(g_split_val);
                if (vals.length == 4)
                    g_list_employee[g_list_employee.length] = { "id": vals[0], "name": vals[1], "mobile": vals[2], "comment": vals[3] };
            }
            if (g_list_employee.length > 0) {
                if (fnCallBack !== undefined) fnCallBack.apply(this, fnCallBackParamArray);
            }
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}
function showGoodStockViewModeInSelect(idselect) {
    var ops = "";
    ops += "<option value='0'>" + itxt("(slton)") + "</option>";
    ops += "<option value='1' selected>" + itxt("<>0") + "</option>";
    ops += "<option value='2'>" + itxt(">0") + "</option>";
    ops += "<option value='3'>" + itxt("<0") + "</option>";
    setInnerById(idselect, ops);
}
function showNewsCategoryInSelect(idselect, selectedindex, showzero) {
    var url = "?page=list&pagesub=news_category&loadtime=" + g_map_listloadtime.get("news_category");
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            data = getDataOk(data);
            if (data.length < 1) return;
            var items = data.split(g_split_row);
            var ops = "";
            for (var i = 0; i < items.length; i++) {
                var vals = items[i].split(g_split_val);
                if ((selectedindex !== undefined) && (i === selectedindex))
                    ops += "<option value='" + vals[0] + "' selected>" + vals[1] + "</option>";
                else
                    ops += "<option value='" + vals[0] + "'>" + vals[1] + "</option>";
            }
            if (showzero !== undefined)
                ops = "<option value='0'>(" + itxt("nhomtin") + ")</option>" + ops;

            setInnerById(idselect, ops);
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}
function showGoodsCategoryInSelect(idselect, selectedindex, showzero) {
    if (g_list_goodscategory.length < 1) {
        getListGoodsCategory("showGoodsCategoryInSelect", [idselect, selectedindex, showzero]);
        return;
    }
    var ops = "", extra = "";
    for (var i = 0; i < g_list_goodscategory.length; i++) {
        extra = "";
        if (g_list_goodscategory[i][4] > 0) {
            for (var j = 0; j < g_list_goodscategory[i][4]; j++)
                extra += "&nbsp;&nbsp;&nbsp;";
        }
        if ((selectedindex !== undefined) && (i === selectedindex))
            ops += "<option  value='" + g_list_goodscategory[i][0] + "' selected>" + extra + g_list_goodscategory[i][1] + "</option>";
        else
            ops += "<option  value='" + g_list_goodscategory[i][0] + "'>" + extra + g_list_goodscategory[i][1] + "</option>";
    }
    if (showzero !== undefined)
        ops = "<option value='0'>(" + itxt("nhomhang") + ")</option>" + ops;

    setInnerById(idselect, ops);
}
function showEmployeeInSelect(selectname, selectedid, showzero) {
    if (g_list_employee.length < 1) {
        getListEmployee(showEmployeeInSelect, [selectname, selectedid, showzero]);
        return;
    }
    var ops = "";
    for (var i = 0; i < g_list_employee.length; i++) {
        if ((selectedid !== undefined) && (i === selectedid))
            ops += "<option value='" + g_list_employee[i].id + "' selected>" + g_list_employee[i].name + "</option>";
        else
            ops += "<option value='" + g_list_employee[i].id + "'>" + g_list_employee[i].name + "</option>";
    }
    if (showzero !== undefined)
        ops = "<option value=''>(nhân viên)</option>" + ops;

    setInnerById(selectname, ops);
}
function showGoodsMixTemplateInSelect(argmt, idselect, selectedIndex) {
    if (isEmpty(argmt)) {
        var url = "?page=list&pagesub=goods_mix_template";
        var dataString = "";
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    showMsg([itxt("loinapdanhsachmauthanhpham"), getDataFail(data)]);
                    return;
                }
                showGoodsMixTemplateInSelect(getDataOk(data), idselect, selectedIndex);
            },
            error: function () {
                showMsg(itxt("loinapdanhsachmauthanhpham"));
            }
        });
        return;
    }
    var gmts = argmt.split(g_split_row);
    if (gmts.length < 1) return;
    var ops = "";
    for (var i = 0; i < gmts.length; i++) {
        var vals = gmts[i].split(g_split_val);
        if (vals.length == 2) {
            ops += "<option value='" + vals[0] + "'>" + vals[1] + "</option>";
        }
    }
    if (selectedIndex < 0) ops = "<option value='0' selected>(" + itxt("maucombotohop") + ")</option>" + ops;
    setInnerById(idselect, ops);
}
//invoice_id, iddivshow
function showInvoiceDetails(iddivshow, invoice_id, is_exportinvoice) {
    if (isEmpty(iddivshow) || isEmpty(invoice_id)) {
        showMsg(itxt("loi"));
        return;
    }
    //neu da hien thi khong hien thi lai

    iddivshow = document.getElementById(iddivshow);
    if (iddivshow == null) return;
    if (iddivshow.innerHTML.length > 0) return;
    var page = "sophieuxuat";
    if (!is_exportinvoice) page = "sophieunhap";
    var url = "?page=" + page + "&action=details&invoice_id=" + invoice_id;

    var dataString = "";
    var strReason = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (isDataFail(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            var strOut = "";
            var strInvoiceSum = "";
            /*
            strInvoiceSum = "<div style='width:100%;'>";
            //contact-name
            strInvoiceSum += "<span style='float:left;width:35%;line-height:150%'>";
            strInvoiceSum += itxt("hd_giam") + ": " + gridViewEx.getDataFromIdAndColumnName(invoice_id, "invoice_discount") + "<br>";
            strInvoiceSum += itxt("hd_bot") + ": " + gridViewEx.getDataFromIdAndColumnName(invoice_id, "invoice_money_discount");
            strInvoiceSum += "</span>";
            strInvoiceSum += "<span style='float:left;width:30%;line-height:150%''>";
            strInvoiceSum += itxt("hd_vat") + ": " + gridViewEx.getDataFromIdAndColumnName(invoice_id, "vat") + "<br>";
            strInvoiceSum += itxt("hd_kethem") + ": " + gridViewEx.getDataFromIdAndColumnName(invoice_id, "deduction");
            strInvoiceSum += "</span>";

            strInvoiceSum += "<span style='float:right;width:35%;text-align:right;line-height:150%''>";
            strInvoiceSum += itxt("hd_tong") + ": <b>" + gridViewEx.getDataFromIdAndColumnName(invoice_id, "totalcost") + "</b><br>";
            strInvoiceSum += "<span style='color:red'>" + itxt("hd_no") + ": " + formatNumber(gridViewEx.getDataFromIdAndColumnName(invoice_id, "money_debit")) + "</span>";
            strInvoiceSum += "</span>";
            strInvoiceSum += "</div>";
            */
            var rows = getDataOk(data).split(g_split_row);

            strOut += "<div class=\"divtable\">";
            for (var i = 0; i < rows.length; i++) {
                var vals = rows[i].split(g_split_val);
                if (vals.length < 11) continue;
                var rowClass = "divrow";
                var rowId = "id_details" + vals[0] + "_" + vals[12] + "_" + vals[13];
                if (vals[9] > 0) rowClass += " mixed";
                if (vals[10] > 0) rowClass += " material";

                strOut += "<div id='" + rowId + "' class='" + rowClass + "' onclick=\"event.stopPropagation();javascript:menuGoods('" + vals[11] + "'," + vals[0] + "," + vals[12] + "," + vals[13] + "," + invoice_id + ")\">";
                strOut += "<div class='divcell click' style='width:100%;border-right:0px'>" + vals[1];
                strOut += " <span class='goods_color' id='" + vals[0] + "goodscolor'>" + vals[8] + "</span>";
                if (vals[6] != "")
                    strOut += " [" + vals[6] + "]";
                strOut += "<br>";
                strOut += "<span class='subinfo' style='float:right'>"
                if (((strReason != "NC") && (strReason != "XC"))) {
                    strOut += formatNumberZS(vals[3]) + "/" + formatNumberZS(vals[2]) + " * <b><span id='" + vals[0] + "quantity'>" + vals[4] + "</span></b> ";
                    if (vals[5] != 0) {
                        strOut += " - ";
                        strOut += vals[5] + "% ";
                    }
                    strOut += " = " + formatNumberZS(vals[7]);
                }
                strOut += "</span>";
                strOut += "</div>";
                //tren phieu xuat/nhap da loc hoa don do chinh nguoi dung nay
                strOut += "</div>";
            }
            strOut += "</div>";
            //strContactInfo
            strOut = strOut + "<br>" + strInvoiceSum;
            iddivshow.innerHTML = strOut;
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}
function showStoreInSelect(idselect, selectedindex, showemptyoption, fnCallBack, selectedVal) {
    if (g_list_store.length < 1) {
        getListStore(showStoreInSelect, idselect, selectedindex, showemptyoption, fnCallBack, selectedVal);
        return;
    }
    var ops = "", selected = "";
    for (var i = 0; i < g_list_store.length; i++) {
        if (i === selectedindex || selectedVal == g_list_store[i].id) {
            selected = "selected";
        } else {
            selected = "";
        }
        ops += "<option value='" + g_list_store[i].id + "' " + selected + ">" + g_list_store[i].name + "</option>";
    }

    if (showemptyoption == true) {
        ops = "<option value=''>(" + itxt("khohang") + ")</option>" + ops;
    }
    setInnerById(idselect, ops);
    if (!isEmpty(fnCallBack)) eval(fnCallBack)();
}
function showBankAccountInSelect(idselect, showzero, valselected) {
    if (g_bankaccountdata.length > 0) {
        var ret = "";
        if (showzero == 1)
            ret = DlgSelect.showDataToSelectBox(idselect, g_bankaccountdata, itxt("tienmat"), valselected);
        else
            ret = DlgSelect.showDataToSelectBox(idselect, g_bankaccountdata, " ", valselected);
        return ret;
    }
    var url = "?page=list&pagesub=bank";
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (isDataFail(data)) {
                showMsg([itxt("loinapdanhsachtaikhoan"), getDataFail(data)]);
                return;
            }
            else if (isDataOk(data)) {
                g_bankaccountdata = getDataOk(data);
                if (g_bankaccountdata.length > 0)
                    showBankAccountInSelect(idselect, showzero, valselected);
            }
            else {
                showMsg(itxt("loinapdanhsachtaikhoan"));
            }
        },
        error: function () {
            showMsg(itxt("loinapdanhsachtaikhoan"));
        }
    });
}
//fnCallBack: fnCallBackParamArray + store_id
async function showDlgStoreSelect(fnCallBack, fnCallBackParamArray) {
    if (g_list_store.length < 1) {
        if (await getSyncListStore() == false) {
            showMsg(itxt("loitruyxuatmaychu"));
        }
    }
    //item:id+name
    DlgSelect.showItemArray(g_list_store, fnCallBack, fnCallBackParamArray);
}

async function orderGoodsServiceRemove(page, obj_id, id) {
    if (parseNumberVn(id) <= 0) return;
    var data = await getSync('?page=' + page + '&obj_id=' + obj_id + '&pagesub=orderconfirm&id=' + id + '&val=0');
    if (!isDataOk(data)) {
        showMsg([itxt("loi"), getDataFail(data)]);
        return false;
    }
    return true;
}

//ls invoice
function parseInvoiceData(obj, invoices) {
    if (invoices.length < 22) {
        showModalBlock(itxt("dulieukhongdung"));
        return false;
    }
    if (isEmpty(obj.invoicels)) {
        showMsg(itxt("khongcophieu"));
        return;
    }
    obj.invoicels.parseInvoiceData(invoices);

    //neu ket qua co kem start_event_id va chua ghi nhan start_event_id
    if ((invoices.length == 23) && (isEmpty(CEventAlert.start_event_id))) {
        CEventAlert.start_event_id = parseNumberVn(invoices[22]);
    }
    return true;
}

function printTest(printer_id, papersize, charcode) {
    showMsg(itxt("inthu.."), itxt("inthu.."), 1000);
    gCallInterop("PRINT_T" + g_split_row + printer_id + g_split_row + papersize + g_split_row + charcode);
}
async function copyToClipboardImage(idele) {
    var el;
    if (isString(idele))
        el = document.querySelector("#" + idele);
    else
        el = idele;
    var canvas = await html2canvas(el);
    //document.getElementById('myModalContent').appendChild(canvas);
    canvas.toBlob(function (blob) {
        const item = new ClipboardItem({ "image/png": blob });
        navigator.clipboard.write([item]);
        showMsg(itxt("dacopyvaoclipboard"), "", 500);
    });
}
async function shareAsImage(idele) {
    var el;
    if (isString(idele))
        el = document.querySelector("#" + idele);
    else
        el = idele;
    var canvas = await html2canvas(el);
    //document.getElementById('myModalContent').appendChild(canvas);
    canvas.toBlob(function (blob) {
        const shareImage = async (title, text, blob) => {
            const data = {
                files: [
                    new File([blob], 'file.png', {
                        type: blob.type,
                    }),
                ],
                title: title,
                text: text,
            };
            try {
                if (!(navigator.canShare(data))) {
                    console.log("Can't share data.");
                }
                await navigator.share(data);
            } catch (err) {
                console.error(err.name, err.message);
            }
        };
        shareImage("iShopmanX", itxt("chitietcongno"), blob);
    });
}
function shareHTML(title, html) {
    //android:chrome,samsung
    //ios:safari (mobile&desktop)
    //windows:edge,chrome
    if (isEmpty(title)) title = itxt("chiasethongtin");
    if (navigator.share) {
        navigator.share({
            title: title,
            text: html,
            url: window.location.href
        })
            .then(() => console.log('Successful share'))
            .catch(error => console.log('Error sharing:', error));
    } else {
        console.log("share via local app");
        showMsg(title, itxt("chiase.."), 1000);
        gCallInterop("SHARE" + g_split_row + invoiceid);
    }
}
async function shareInvoice(invoiceid) {
    //android:chrome,samsung
    //ios:safari (mobile&desktop)
    //windows:edge,chrome

    if (navigator.share) {
        var url = "?page=ls_invoiceprintpreview&invoiceid=" + invoiceid;

        var data = await getSync(url);
        if (!isDataOk(data)) {
            showMsg([itxt("loi"), getDataFail(data)]);
            return;
        }
        data = getDataOk(data);

        navigator.share({
            title: itxt("hoadonbanhang"),
            text: data,
            url: window.location.href
        })
            .then(() => console.log('Successful share'))
            .catch(error => console.log('Error sharing:', error));
    } else {
        showMsg(itxt("chiasehoadon"), itxt("chiase.."), 1000);
        gCallInterop("SHARE" + g_split_row + invoiceid);
    }
}
async function playNotify() {
    var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZjuZR4AgAABYAAAABy1xcdQtxYBYYZdifkUDgzzXaXn98Z0oi9ILU5mBjFANmRwlVJ3/6jYDAmxaiDG3/6xjQQCCKkRb/6kg/wW+kSJ5//rLobkLSiKmqP/0ikJuDaSaSf/6JiLYLEYnW/+kXg1WRVJL/9EmQ1YZIsv/6Qzwy5qk7/+tEU0nkls3/zIUMPKNX/6yZLf+kFgAfgGyLFAUwY//uQZAUABcd5UiNPVXAAAApAAAAAE0VZQKw9ISAAACgAAAAAVQIygIElVrFkBS+Jhi+EAuu+lKAkYUEIsmEAEoMeDmCETMvfSHTGkF5RWH7kz/ESHWPAq/kcCRhqBtMdokPdM7vil7RG98A2sc7zO6ZvTdM7pmOUAZTnJW+NXxqmd41dqJ6mLTXxrPpnV8avaIf5SvL7pndPvPpndJR9Kuu8fePvuiuhorgWjp7Mf/PRjxcFCPDkW31srioCExivv9lcwKEaHsf/7ow2Fl1T/9RkXgEhYElAoCLFtMArxwivDJJ+bR1HTKJdlEoTELCIqgEwVGSQ+hIm0NbK8WXcTEI0UPoa2NbG4y2K00JEWbZavJXkYaqo9CRHS55FcZTjKEk3NKoCYUnSQ0rWxrZbFKbKIhOKPZe1cJKzZSaQrIyULHDZmV5K4xySsDRKWOruanGtjLJXFEmwaIbDLX0hIPBUQPVFVkQkDoUNfSoDgQGKPekoxeGzA4DUvnn4bxzcZrtJyipKfPNy5w+9lnXwgqsiyHNeSVpemw4bWb9psYeq//uQZBoABQt4yMVxYAIAAAkQoAAAHvYpL5m6AAgAACXDAAAAD59jblTirQe9upFsmZbpMudy7Lz1X1DYsxOOSWpfPqNX2WqktK0DMvuGwlbNj44TleLPQ+Gsfb+GOWOKJoIrWb3cIMeeON6lz2umTqMXV8Mj30yWPpjoSa9ujK8SyeJP5y5mOW1D6hvLepeveEAEDo0mgCRClOEgANv3B9a6fikgUSu/DmAMATrGx7nng5p5iimPNZsfQLYB2sDLIkzRKZOHGAaUyDcpFBSLG9MCQALgAIgQs2YunOszLSAyQYPVC2YdGGeHD2dTdJk1pAHGAWDjnkcLKFymS3RQZTInzySoBwMG0QueC3gMsCEYxUqlrcxK6k1LQQcsmyYeQPdC2YfuGPASCBkcVMQQqpVJshui1tkXQJQV0OXGAZMXSOEEBRirXbVRQW7ugq7IM7rPWSZyDlM3IuNEkxzCOJ0ny2ThNkyRai1b6ev//3dzNGzNb//4uAvHT5sURcZCFcuKLhOFs8mLAAEAt4UWAAIABAAAAAB4qbHo0tIjVkUU//uQZAwABfSFz3ZqQAAAAAngwAAAE1HjMp2qAAAAACZDgAAAD5UkTE1UgZEUExqYynN1qZvqIOREEFmBcJQkwdxiFtw0qEOkGYfRDifBui9MQg4QAHAqWtAWHoCxu1Yf4VfWLPIM2mHDFsbQEVGwyqQoQcwnfHeIkNt9YnkiaS1oizycqJrx4KOQjahZxWbcZgztj2c49nKmkId44S71j0c8eV9yDK6uPRzx5X18eDvjvQ6yKo9ZSS6l//8elePK/Lf//IInrOF/FvDoADYAGBMGb7FtErm5MXMlmPAJQVgWta7Zx2go+8xJ0UiCb8LHHdftWyLJE0QIAIsI+UbXu67dZMjmgDGCGl1H+vpF4NSDckSIkk7Vd+sxEhBQMRU8j/12UIRhzSaUdQ+rQU5kGeFxm+hb1oh6pWWmv3uvmReDl0UnvtapVaIzo1jZbf/pD6ElLqSX+rUmOQNpJFa/r+sa4e/pBlAABoAAAAA3CUgShLdGIxsY7AUABPRrgCABdDuQ5GC7DqPQCgbbJUAoRSUj+NIEig0YfyWUho1VBBBA//uQZB4ABZx5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");
    snd.play();

}
//printasimage:0 - print, 1-copy image to clipboard, 2-shareimage
function printHTML(htmlprint, printasimage) {
    var curpagekey = window_getKey(g_window_page, g_window_pageparam);
    var pobj = document.getElementById("window_" + curpagekey);
    var mobj = document.getElementById("iddropdownmenubar");
    mobj.style.display = "none";
    pobj.style.display = "none";
    var printDiv = document.createElement('div');
    printDiv.style.width = "1024px";
    printDiv.innerHTML = htmlprint;
    document.body.appendChild(printDiv);
    if (printasimage == 0) {
        window.print();
    } else if (printasimage == 1) {
        copyToClipboardImage(printDiv);
    } else {
        shareAsImage(printDiv);
    }

    mobj.style.display = "block";
    pobj.style.display = "block";
    printDiv.remove();
    /*
    var restorepage = $('body').html();
    var el = 'iddivprintcache';
    var idelement = document.getElementById(el);
    if (idelement == null) {
        var elemDiv = document.createElement('div');
        elemDiv.id = el;
        document.body.appendChild(elemDiv);
    }
    setInnerById(el, htmlprint);
    var printcontent = $('#' + el).clone();
    $('body').empty().html(printcontent);
    window.print();
    $('body').html(restorepage);
    */
}

async function printInvoiceThermal(invoiceid, printpreview, goodscategorytype) {
    if (isEmpty(goodscategorytype)) goodscategorytype = 0;
    if (isEmpty(printpreview)) printpreview = 0;
    showMsg("In..", itxt("inphieu"), 1000);
    if (isEmpty(printpreview)) printpreview = 0;
    gCallInterop("PRINT" + g_split_row + invoiceid + g_split_row + printpreview + g_split_row + goodscategorytype);
}
async function printInvoiceClientLocal(is_exportinvoice, invoice_id, size, printpreview) {
    //get invoice info
    showWaitModal();
    var url = "?page=printgetdata&pagesub=invoice&invoice_id=" + invoice_id;
    var data = await getSync(url);
    if (isDataFail(data)) {
        showMsg(getDataFail(data));
        return false;
    }
    data = getDataOk(data);
    //var invoice=JSON.parse(data);
    gCallInterop("PRINT" + g_split_row + data);
}

//check xem client in tai cho hay in tren server
function printInvoiceClientServer(is_exportinvoice, invoice_id, size, printpreview) {
    showWaitModal();
    var pagesub = "phieunhap";
    if (is_exportinvoice) pagesub = "phieuxuat";
    var url = "?page=printdirect&pagesub=" + pagesub + "&invoice_id=" + invoice_id + "&size=" + size + "&preview=" + printpreview;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (isDataOk(data)) {
                hideModalBlock();
            }
            else
                showMsg([itxt("loi"), getDataFail(data)])

        },
        error: function () {
            showModal(itxt("loi"));
        }
    });
}
function printReport(page_source, id, printasimage) {
    var url = "?page=printreport&pagesub=" + page_source + "&id=" + id;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (isDataOk(data)) {
                hideModalBlock();
                printHTML(getDataOk(data), printasimage);
            }
            else
                showMsg([itxt("loi"), getDataFail(data)])

        },
        error: function () {
            showModal(itxt("loi"));
        }
    });
}
function printInvoiceParseData(data, size, page_source) {
    var bIsK80 = (size.indexOf("80") >= 0) || (size.indexOf("58") >= 0);
    var argoods = data.split(g_split_row);
    if (argoods.length < 2) {
        alert(itxt("thatbai"));
        return;
    }
    var goods;
    var val;
    var html = argoods[0];//report template
    html = html.replace("{_COMPANY_LOGO_}", '<img border="0" src="data/logo.jpg" width="70" height="81">');
    //company:name,address,phone,email,website,taxcode,money_reader
    goods = argoods[1].split(g_split_val);

    html = html.replace("{_COMPANY_NAME_}", goods[0]);
    html = html.replace("{_COMPANY_ADDRESS_}", goods[1]);
    html = html.replace("{_COMPANY_PHONE_FAX_}", goods[2] + (goods[5].length > 0 ? " - " + goods[5] : ""));
    html = html.replace("{_COMPANY_MAIL_WEB_}", goods[3] + (goods[4].length > 0 ? " - " + goods[4] : ""));

    var money_reader = goods[6];
    //id,invoice_no,invoice_date,vat,invoice_money_discount,
    //total_cost,comment,money_debit,invoice_discount,store_id,
    //store_name,bank_account_id,bank_account_number,trade_user_id,trade_user_name
    //trade_user_phone,money_debit_old
    goods = argoods[2].split(g_split_val);
    var total_cost = 0;
    html = html.replace("{_INVOICE_HEADER_}", itxt(page_source).toUpperCase());//invoice_date
    if (goods.length == ds_invoice.length) {
        html = html.replace("{_INVOICE_NO_}", goods[1]);
        html = html.replace("{_STORE_NAME_}", goods[10]);

        html = html.replace("{_DAY_MONTH_YEAR_}", goods[2]);//invoice_date
        html = html.replace("{_TAX_}", goods[3]);//vat
        html = html.replace("{_INVOICE_DISCOUNT_}", goods[4]);//invoice_money_discount
        html = html.replace("{_INVOICE_DISCOUNT_PERCENT_}", goods[8]);//invoice_discount
        html = html.replace("{_INVOICE_COMMENT_}", goods[6]);//invoice_comment
        total_cost = goods[5];
    }
    var money_debit = goods[7];
    var money_payment = Number(total_cost) - Number(money_debit);
    var money_debit_now = 0;
    //html = html.replace("{}", goods[]);

    //id,name,phone (trade_user)
    val = "";
    if (!isEmpty(argoods[3])) {
        goods = argoods[3].split(g_split_val);
        if (goods.length == 3) {
            val = goods[1];
        }
    }
    html = html.replace("{_USER_REALNAME_}", val);


    //
    if (page_source == "phieuxuat")
        html = html.replace("{_CONTACT_LABEL_}", itxt("khachhang"));
    else
        html = html.replace("{_CONTACT_LABEL_}", itxt("nhacungcap"));

    //contact_id,contact_name,contact_address,phone,debit_now
    if (!isEmpty(argoods[4])) {
        goods = argoods[4].split(g_split_val);
        if (goods.length >= 4) {
            html = html.replace("{_CUSTOMER_NAME_}", goods[1]);
            html = html.replace("{_CUSTOMER_ADDRESS_}", goods[2]);
            html = html.replace("{_CUSTOMER_PHONE_}", goods[3]);
            money_debit_now = goods[4];
        }
    } else {
        money_debit_now = 0;
        html = html.replace("{_CUSTOMER_NAME_}", "");
        html = html.replace("{_CUSTOMER_ADDRESS_}", "");
        html = html.replace("{_CUSTOMER_PHONE_}", "");
    }

    html = html.replace("{_CONTACT_NAME_}", "");
    html = html.replace("{_TAX_CODE_}", "");
    html = html.replace("{_PAYMENT_METHOD_}", "");
    html = html.replace("{_BANK_ACCOUNT_}", "");

    //deploymentmans
    val = argoods[5];
    if (isEmpty(val)) val = "";
    goods = val.split(g_split_val);
    if ((goods.length >= 3) && (goods.length % 3 == 0)) {
        var i = 0;
        while (i < goods.length) {
            //g_pageobj['{_UID_}'].deploymentManAdd(goods[i], goods[i + 1], goods[i + 2]);
            i += 3;
        }
    }
    var rows = "", quantity_count = 0, goods_total = 0, subtotal = 0;
    var nColCount = 0;

    //header

    rows += "<tr>";
    if (bIsK80) {
        nColCount = 4;
        rows += "<td class='goods_head'>TT</td>";//name
        rows += "<td class='goods_head' >" + itxt("tenhang") + "</td>";//name
        rows += "<td class='goods_head' style='text-align:right'>" + itxt("sl") + "</td>";//quantity
        rows += "<td class='goods_head' style='text-align:right'>" + itxt("thanhtien") + "</td>";//subtotal
    } else {
        nColCount = 10;
        rows += "<td class='goods_head' style='width:45px;'>TT</td>";//name
        rows += "<td class='goods_head' >" + itxt("tenhang") + "</td>";//name
        rows += "<td class='goods_head'>" + itxt("dvt") + "</td>";//unit
        rows += "<td class='goods_head' style='text-align:right'>" + itxt("dongia") + "</td>";//price
        rows += "<td class='goods_head' style='text-align:right'>" + itxt("sl") + "</td>";//quantity
        rows += "<td class='goods_head' style='text-align:right'>" + itxt("ck") + "</td>";//discount
        rows += "<td class='goods_head'>" + itxt("serial") + "</td>";//serial
        rows += "<td class='goods_head' style='text-align:right'>" + itxt("baohanh") + "</td>";//waranty
        rows += "<td class='goods_head'>" + itxt("mausac") + "</td>";//color
        rows += "<td class='goods_head' style='text-align:right'>" + itxt("thanhtien") + "</td>";//subtotal
    }
    rows += "</tr>";
    for (var k = 6; k < argoods.length; k++) {
        goods = argoods[k].split(g_split_val);
        //goods_id,unit_id,unit,goods_name,unit_price,quantity,serial,warranty,discount,id_exim_invoice_details,color_name,template_id
        if (goods.length >= 13) {
            subtotal = parseNumber(goods[5]) * parseNumber(goods[4]) * (1 - parseNumber(goods[8] / 100));
            //trong 1 phieu co the 1 mat hang + 1 dvt xuat hien nhieu lan
            rows += "<tr>";
            if (bIsK80) {
                rows += "<td class='goods'>" + (k - 5) + "</td>";//index
                rows += "<td class='goods'>" + goods[3] + "</td>";//name
                rows += "<td class='goods' style='text-align:right'>" + goods[5] + "</td>";//quantity
                rows += "<td class='goods' style='text-align:right'>" + formatNumber(subtotal) + "</td>";//subtotal
            }
            else {
                rows += "<td class='goods'>" + (k - 5) + "</td>";//index
                rows += "<td class='goods'>" + goods[3] + "</td>";//name
                rows += "<td class='goods'>" + goods[2] + "</td>";//unit
                rows += "<td class='goods' style='text-align:right'>" + formatNumber(goods[4]) + "</td>";//price
                rows += "<td class='goods' style='text-align:right'>" + goods[5] + "</td>";//quantity
                rows += "<td class='goods' style='text-align:right'>" + goods[8] + "</td>";//discount
                rows += "<td class='goods'>" + goods[6] + "</td>";//serial
                rows += "<td class='goods' style='text-align:right'>" + goods[7] + "</td>";//waranty
                rows += "<td class='goods'>" + goods[10] + "</td>";//color
                rows += "<td class='goods' style='text-align:right'>" + formatNumber(subtotal) + "</td>";//subtotal

            }
            rows += "</tr>";
            quantity_count += parseNumberVn(goods[5]);
            goods_total += subtotal;
        }
    }
    html = html.replace("{_COLUMN_SPAN_READER_}", nColCount);
    html = html.replaceAll("{_COLUMN_SPAN_}", (nColCount - 1));

    html = html.replace("{_MONEY_READER_}", money_reader);

    html = html.replace("{_QUANTITY_COUNT_}", formatNumber(quantity_count));
    html = html.replace("{_SUM_}", formatNumber(goods_total));
    html = html.replace("{_SUM_WITH_VAT_}", formatNumber(total_cost));

    html = html.replace("{_LB_NOCU_}", itxt("nocu"));
    html = html.replace("{_LB_THANHTOAN_}", itxt("thanhtoan"));
    html = html.replace("{_LB_NOLAI_}", itxt("nolai"));
    html = html.replace("{_MONEY_PAYMENT_}", formatNumber(money_payment));
    html = html.replace("{_MONEY_DEBIT_OLD_}", formatNumber(money_debit_now - money_debit));
    html = html.replace("{_MONEY_DEBIT_}", formatNumber(money_debit_now));//invoice_debit

    html = html.replace("{_CHEN_THEM_GHI_CHU_}", "");
    html = html.replace("{_GOODS_LIST_}", rows);

    return html;
}
//printasimage: 0 - print normal, 1: copy image to clipboard, 2: share
function printInvoice(is_exportinvoice, invoice_id, size, printasimage, printpreview, goodscategorytype, printdirect) {
    if (isEmpty(size)) size = "a4";
    if (isEmpty(printasimage)) printasimage = 0;
    hideModal();
    if (!isEmpty(printdirect)) {
        if (isEmpty(goodscategorytype)) goodscategorytype = 0;
        if (isEmpty(printpreview)) printpreview = 0;
        //print on client
        if (isAppModeClient()) {
            gCallInterop("PRINTREQUEST" + g_split_row + is_exportinvoice + g_split_val + invoice_id + g_split_val + size + g_split_val + printpreview);
            return;
        }
    }
    var page_source = "";
    if (is_exportinvoice)
        page_source = "phieuxuat";
    else
        page_source = "phieunhap";
    var url = "?page=printpage&pagesub=" + page_source + "&id=" + invoice_id + "&size=" + size;
    var dataString = "";

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

            var html = printInvoiceParseData(data, size, page_source);
            printHTML(html, printasimage);
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });

}
function getGuestPayment(initvalue) {

}

//COMMON
function shPhieuGiaoHang(invoice_id, fnCallBackName, f) {
    if (!isEmpty(f)) {
        dlgRemove();
        var form = $(f);
        var url = form.attr('action');
        var dataString = form.serialize();

        jQuery.ajax({
            url: url,
            data: dataString,
            type: "POST",
            success: function (data) {
                if (isDataOk(data))
                    showMsg(itxt("daghi"), itxt("phieugiaohang"));
                else
                    showMsg([itxt("loi"), data]);
            },
            error: function () {

                showMsg(itxt("thatbai"), itxt("phieugiaohang"));
            }
        });
        return false;
    }
    if (invoice_id <= 0) {
        showMsg("khongxacdinhphieu");
        return false;
    }
    showWaitModal();
    var url = "?page=xuathang_phieugiaohang&invoice_id=" + invoice_id;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            hideModalBlock();
            if (isDataFail(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            } else {
                var rdatas = getDataOk(data).split(g_split_row);
                if (rdatas.length != 2) {
                    showMsg(itxt("dulieuloi"));
                    return;
                }
                var vals = rdatas[0].split(g_split_val);
                if (vals.length != 21) {
                    showMsg(itxt("dulieuloi"));
                    return;
                }
                var html = '<form  method="POST" action="?page=xuathang_phieugiaohang" onsubmit="return shPhieuGiaoHang(' + invoice_id + ',\'' + fnCallBackName + '\',this)">';
                html += rdatas[1];
                html += '</form>';

                dlgShow(html, itxt("phieugiaohang"));
                UiControl.selectInputContact("idreceiver", "receiver", itxt("nguoinhan"));
                UiControl.selectInputContact("idshipping_office", "shipping_office", itxt("trunggiannhan"));
                UiControl.selectInputContact("idshipper", "shipper", itxt("shipper"));
                UiControl.selectInputUsers("iduser", "user", itxt("nhanvien"));
                UiControl.inputWithClearButtonSetup();
                //idcontainer, idval, val_display, val_value
                UiControl.selectInput_Update("idreceiver", "receiver", vals[1], vals[0]);
                UiControl.selectInput_Update("idshipping_office", "shipping_office", vals[5], vals[4]);
                UiControl.selectInput_Update("idshipper", "shipper", vals[9], vals[8]);
                UiControl.selectInput_Update("iduser", "user", vals[13], vals[12]);
            }
        },
        error: function () {
            showModal(itxt("loi"));
        }
    });
}
//COMMON_END
//fnCallBack luon duoc truyen duoi dang String
//duoc goi voi doi so theo cau truc ds_goods
var gridDeclareGoodsHidden = null;
var gridDeclareContactHidden = null;
function kbThemHang(fnCallBack, updategridview = 1, init_goods_code = "") {
    if (g_list_goodscategory.length < 1) {
        getListGoodsCategory('kbThemHang', [fnCallBack, updategridview, init_goods_code]);
        return;
    }
    if (gridDeclareGoodsHidden === null) {
        gridDeclareGoodsHidden = new GridViewEx(ds_goods, 'gridDeclareGoodsHidden');
        gridDeclareGoodsHidden.page_source = 'kb_hang';
    }

    var idformgridedit = gridDeclareGoodsHidden.showEditForm(0, null, "", null, updategridview, fnCallBack);
    idformgridedit = document.getElementById(idformgridedit);
    if (idformgridedit) {
        if (idformgridedit.mahang) idformgridedit.mahang.value = init_goods_code;
    }
}
function kbThemNhomHang(fnCallBack, updategridview = 0) {
    if (gridDeclareGoodsHidden === null) {
        gridDeclareGoodsHidden = new GridViewEx(ds_goods_category, 'gridDeclareGoodsHidden');
        gridDeclareGoodsHidden.page_source = 'kb_nhomhang';
    }
    gridDeclareGoodsHidden.showEditForm(0, null, "", null, updategridview, fnCallBack);
}
//fnCallBack luon duoc truyen duoi dang String
//duoc goi voi doi so theo cau truc ds_contact
function kbThemDoiTac(fnCallBack) {
    if (gridDeclareContactHidden === null) {
        gridDeclareContactHidden = new GridViewEx(ds_contact, 'gridDeclareContactHidden');
        gridDeclareContactHidden.page_source = 'kb_danhmucdoitac';
    }
    gridDeclareContactHidden.showEditForm(0, null, "", null, 0, fnCallBack);
}

/**************/
function lsDataToObj(data) {

    var vals = data.split(g_split_val);
    if (vals.length < 4)
        return null;
    if (parseNumberVn(vals[0]) <= 0) {
        return null;
    }
    //gs_order: so loi goi hang/dich vu
    var obj = {
        "id": parseNumberVn(vals[0]), "name": vals[1],
        "objcategory": parseNumberVn(vals[2]), "typeid": vals[3],
        "seatcount": parseNumberVn(vals[6]), "group": parseNumberVn(vals[7]),
        "gs_order": parseNumberVn(vals[8]), "invoiceno": vals[9]
    };

    obj.invoicels = new CInvoiceLS("XB", parseNumberVn(vals[5]), "g_phien_invoice");
    obj.invoicels.obj_id = obj.id;
    obj.invoicels.totalcost = parseNumberVn(vals[4]);
    obj.invoicels.invoiceno = vals[9];
    return obj;
}
function lsGetObjInListClass(obj) {
    var strobjclass = "obj";
    if (obj.objcategory == 0)
        strobjclass += " obj_typeres";
    else if (obj.objcategory == 1)
        strobjclass += " obj_typekara";
    else if (obj.objcategory == 2)
        strobjclass += " obj_typehotel";
    else if (obj.objcategory == 3)
        strobjclass += " obj_typespa";
    else if (obj.objcategory == 4) {
        if (obj.typeid == 0)
            strobjclass += " obj_shipaway";
        else
            strobjclass += " obj_typetakeaway";
    }



    if (obj.invoicels.invoiceid > 0)
        strobjclass += " obj_inuse";
    if (obj.invoicels.totalcost != 0)
        strtotalcost = (obj.invoicels.totalcost);
    else
        strtotalcost = "";
    if (g_phien_obj != null) {
        if (g_phien_obj.id == obj.id) {
            strobjclass += " obj_selected";
        }
    }
    if (obj.gs_order > 0) {
        strobjclass += " ordered";
    }
    return strobjclass;
}

function mShowGoodsEximDetails(pageno, storeid, goodsid, unitid, type) {
    showWaitModal();
    var url = "?page=bc_hangtonkho&action=view&goodsid=" + goodsid + "&unitid=" + unitid +
        "&store_id=" + storeid + "&type=" + type + "&pageno=" + pageno;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            hideModal();
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            data = getDataOk(data);
            var gridViewExDetails = new GridViewEx(ds_goods_stock_exim, "gridViewExDetails");
            gridViewExDetails.bItemMultiRow = true;
            var html = gridViewExDetails.showGrid(data, null, "", "", "", "", "mShowGoodsEximDetails", [storeid, goodsid, unitid, type]);
            showModal(html, itxt("chitietmathang"));
        },
        error: function () {
            hideModal();
        }
    });
}

function gsTimHang() {
    var gsgoodsname = document.getElementById("gsgoodsname");
    var gsgoodscode = document.getElementById("gsgoodscode");
    var gsgoodsserial = document.getElementById("gsgoodsserial");
    if ((gsgoodsname.value.length == 0) && (gsgoodscode.value.length == 0) && (gsgoodsserial.value.length == 0)) {
        return 0;
    }
    var vgsgoodsname = uriEncode(gsgoodsname.value);
    var vgsgoodscode = uriEncode(gsgoodscode.value);
    var vgsgoodsserial = uriEncode(gsgoodsserial.value);
    window_menushow(myDropdownSearch);

    if (gsgoodsserial.value.length > 0)
        window_newtab('cc_timkiemchungtu', '', '&source=goods_serial&serial=' + vgsgoodsserial);
    else {
        window_newtab('bc_hangtonkho', '', '&goodsname=' + vgsgoodsname + "&goodscode=" + vgsgoodscode);
    }
    //clear
    gsgoodsname.value = "";
    gsgoodscode.value = "";
    gsgoodsserial.value = "";
}

function gsTimDoiTac() {
    gscontactname = document.getElementById("gscontactname");
    gscontactcode = document.getElementById("gscontactcode");
    gscontactaddress = document.getElementById("gscontactaddress");
    gscontactphone = document.getElementById("gscontactphone");
    vgscontactname = uriEncode(gscontactname.value);
    vgscontactcode = uriEncode(gscontactcode.value);
    vgscontactaddress = uriEncode(gscontactaddress.value);
    vgscontactphone = uriEncode(gscontactphone.value);
    if ((vgscontactname.length == 0) && (vgscontactcode.length == 0) && (vgscontactaddress.length == 0) && (vgscontactphone.length == 0)) {
        return 0;
    }
    window_menushow(myDropdownSearch);
    window_newtab('bc_doitacgiaodich', '', '&contactname=' +
        uriEncode(vgscontactname) + '&contactcode=' + uriEncode(vgscontactcode) + '&contactaddress=' +
        uriEncode(vgscontactaddress) + '&contactphone=' + uriEncode(vgscontactphone));
    //clear
    gscontactname.value = "";
    gscontactcode.value = "";
    gscontactaddress.value = "";
    gscontactphone.value = "";
}
