
var appVersion = "8.0";

/**
 * 配置项
 * @type {Object}
 */
var Config = {
    /**
     * default page size
     */
    DefaultPageSize: 15,
    /**
     * 餐台刷新时间，默认10秒
     */
    refreshTableTimeInterval: 10000,
    /**
     * 滑动模式切换的菜品数量限制
     */
    maxDishLength: 10,
    /**
     * 搜索菜品最多显示数量,
     */
    maxSearchDishDisplayLength: 6,
    /**
     * 关键业务超时时间, 默认60秒
     */
    importantBLTimeout: 60000,
    /**
     * 显示loading界面延时时间， 默认为800ms
     */
    showLoadingDelay: 800,
    /**
     * 请求告警耗时, 默认超过500ms的操作都会写到服务端
     */
    requestWarnTimeout: 500,
};

(function () {
    //polyfill
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function (searchString, position) {
            position = position || 0;
            return this.indexOf(searchString, position) === position;
        };
    }
    if (!String.prototype.endsWith) {
        String.prototype.endsWith = function (searchString, position) {
            var subjectString = this.toString();
            if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
                position = subjectString.length;
            }
            position -= searchString.length;
            var lastIndex = subjectString.indexOf(searchString, position);
            return lastIndex !== -1 && lastIndex === position;
        };
    }
    if (!Array.prototype.find) {
        /**
         * The find() method returns a value in the array,
         * if an element in the array satisfies the provided testing function.
         * Otherwise undefined is returned.
         * @param {Function} predicate function(item, index, array)
         */
        Array.prototype.find = function (predicate) {
            if (this === null) {
                throw new TypeError('Array.prototype.find called on null or undefined');
            }
            if (typeof predicate !== 'function') {
                throw new TypeError('predicate must be a function');
            }
            var list = Object(this);
            var length = list.length >>> 0;
            var thisArg = arguments[1];
            var value;

            for (var i = 0; i < length; i++) {
                value = list[i];
                if (predicate.call(thisArg, value, i, list)) {
                    return value;
                }
            }
            return undefined;
        };
    }
    if (!Array.prototype.findIndex) {
        Array.prototype.findIndex = function(predicate) {
            if (this === null) {
                throw new TypeError('Array.prototype.findIndex called on null or undefined');
            }
            if (typeof predicate !== 'function') {
                throw new TypeError('predicate must be a function');
            }
            var list = Object(this);
            var length = list.length >>> 0;
            var thisArg = arguments[1];
            var value;

            for (var i = 0; i < length; i++) {
                value = list[i];
                if (predicate.call(thisArg, value, i, list)) {
                    return i;
                }
            }
            return -1;
        };
    }

    if (!Array.isArray) {
        /**
         * The Array.isArray() method returns true if an object is an array, false if it is not.
         * @param {Object} arg
         */
        Array.isArray = function (arg) {
            return Object.prototype.toString.call(arg) === '[object Array]';
        };
    }

    /**
     * 格式化时间输出
     * @author meizz
     * @param {String} fmt 格式化字符串
     */
    Date.prototype.formatDate = function (fmt) {
        if (this == "Invalid Date") {
            return "";
        }
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "H+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        return fmt;
    };

    /**
     * yesterday
     */
    Date.prototype.yesterday = function () {
        var d = this;
        d.setDate(d.getDate() - 1);
        return d;
    };

    /**
     * tomorrow
     */
    Date.prototype.tomorrow = function () {
        var d = this;
        d.setDate(d.getDate() + 1);
        return d;
    };

    //Zepto extend

    /**
     * 格式化字符串，形如c#
     * $.formatStr("sdf{0},{1}, jkjkj", "a", "b");
     * @namespace $.formatStr
     * @returns {String} formatted string
     */
    $.formatStr = function () {
        var s = Array.prototype.shift.call(arguments);
        for (var i = 0; i < arguments.length; i++) {
            s = s.replace("{" + i + "}", arguments[i]);
        }
        return s;
    };

    /**
     * 将dom内的input类型在focus时选中, 会过滤掉readonly和有class=disabled的
     * @namespace $.selectOnFocus
     * @param page {HTMLElement} page dom
     */
    $.selectOnFocus = function (page) {
        $(page).find("input[type=text],input[type=search],input[type=number],input[type=email],input[type=url],input[type=password],input[type=tel]").on("focus", function () {
            if (this.readOnly) return;
            if ($(this).hasClass('disabled')) return;
            this.select();
        });
    };

    /**
     * deep clone an object
     * @namespace $.deepClone
     * @param {Object} obj clone object
     * @returns {Object} cloned object
     */
    $.deepClone = function _deepClone(obj) {
        var o, i, j;
        if (typeof (obj) != "object" || obj === null) return obj;
        if (obj instanceof (Array)) {
            o = [];
            i = 0;
            j = obj.length;
            for (; i < j; i++) {
                if (typeof (obj[i]) == "object" && obj[i] != null) {
                    o[i] = _deepClone(obj[i]);
                }
                else {
                    o[i] = obj[i];
                }
            }
        }
        else {
            o = {};
            for (i in obj) {
                if (typeof (obj[i]) == "object" && obj[i] != null) {
                    o[i] = _deepClone(obj[i]);
                }
                else {
                    o[i] = obj[i];
                }
            }
        }

        return o;
    };

})();
/**
 * Json返回数据
 */
var JsonResult = {
    Error: 0,
    OK: 1,
    NeedAuth: 2,
    NeedLogin: 3,
};
JsonResult[0] = "Error";
JsonResult[1] = "OK";
JsonResult[2] = "NeedAuth";
JsonResult[3] = "NeedLogin";

/*
输入类型限制
*/
var InputType = {
    Amount: 0,
    /*金额*/
    NegativeAmount: 1,
    /*可输负数的金额*/
    DishNum: 2,
    /*菜品数量*/
    Num0To100: 3,
    /*0到100的整数*/
    Num1To999: 4,
    /*1到999的整数*/
    MaxNum: 5,
    /*最大整数值99999999*/
    MaxInteger: 6,  /**可输入0的整数，最大数值99999999 */
};
InputType[0] = /^0$|^[1-9][0-9]{0,8}\.[0-9]{0,2}$|^0\.[0-9]{0,2}$|^[1-9][0-9]{0,8}$/  // /^0$|^[1-9][0-9]{0,8}\.[0-9]{0,2}$|^0\.[0-9]{0,2}$|^[1-9][0-9]{0,8}$/;
InputType[1] = /^0$|^[1-9][0-9]{0,7}\.[0-9]{0,2}$|^0\.[0-9]{0,2}$|^[1-9][0-9]{0,7}$|^\-$|^\-[1-9][0-9]{0,7}\.[0-9]{0,2}$|^\-0$|^\-0\.[0-9]{0,2}$|^\-[1-9][0-9]{0,7}$/  // /^[1-9][0-9]{0,7}\.[0-9]{0,2}$|^0$|^$|^0\.[0-9]{0,2}$|^[1-9][0-9]{0,7}$|^\-$|^\-[1-9][0-9]{0,7}\.[0-9]{0,2}$|^\-0$|^\-0\.[0-9]{0,2}$|^\-[1-9][0-9]{0,7}$/;
InputType[2] = /^[1-9][0-9]{0,2}\.[0-9]{0,3}$|^0$|^$|^[1-9][0-9]{0,2}$|^0\.[0-9]{0,3}$/;
InputType[3] = /^[1-9]\d$|^0$|^\d$|^100$|^$/;
InputType[4] = /^(?!0)\d{1,3}$/;
InputType[5] = /^(?!0)\d{1,8}$/;
InputType[6] = /^0$|^[1-9][0-9]{0,8}$/;

/**
 * 设备类型
 */
var DeviceType = {
    /**
     * 默认类型
     */
    Normal: 0,
    /**
     * 盒子设备
     */
    IboxPayDevice: 1,
    /**
     * 拉卡拉
     */
    LklPayDevice: 2,
    /**
     * 旺POS
     */
    WangPosPayDevice: 3,
    /**
     * 商米M1， 点菜宝
     */
    SunmiM1Device: 4,
    /**
     * 商米V1， 打印
     */
    SunmiV1Device: 5,

    /**
     * 商睿
     */
    ShangRunDevice: 6,

    /**
     * 联迪
     */ 
    LandicorpDevice: 7,

    /**
     * 阿里NFC设备
     */
    AlipayNfcPos: 8
};
DeviceType[0] = "3.0";
DeviceType[1] = "3.1";
DeviceType[2] = "3.2";
DeviceType[3] = "3.3";
DeviceType[4] = "3.4";
DeviceType[5] = "3.5";
DeviceType[6] = "3.6";
DeviceType[7] = "3.7";

/**
 * 餐台状态
 */
var TableStatus = {
    All: 0,
    Empty: 1, //空台
    Taken: 2, //  占用
    Reservation: 6, //预订
    Bill: 3, //预结
    CheckedOut: 4, //脏台
};
TableStatus[0] = "全部";
TableStatus[1] = "空台";
TableStatus[2] = "占用";
TableStatus[6] = "预订";
TableStatus[3] = "预结";
TableStatus[4] = "脏台";

/*
点菜菜品价格类型
*/
var OrderDishPriceType = {
    // 0-普通价格
    Normal: 0,
    // 1-会员价
    Member: 1,
    //2-特价
    Special: 2,
    // 3-手动改价
    Manual: 3,
    // 砍价
    CustomerManual: 4,
};


/*
订单菜品属性
*/
var OrderDishProperty = {
    //正常菜
    Normal: 1,

    //套餐子菜
    PackageDishChild: 2,

    //套餐主菜
    PackageDishMain: 5,

    //一品多吃主菜
    MultiDishMain: 3,

    //一品多吃子菜
    MultiDishChild: 4,
};

/*
茶类型
*/
var OrderDishTeaType = {
    //一般的菜
    Normal: 0,

    //茶
    Tea: 1,

    //小吃
    Snack: 2,
};

/*
称重菜结果
*/
var OrderDishConfirmWeighType = {
    //不需要称重
    NotNeedConfirmWeight: 1,

    //等待称重
    WaitConfirmWeigh: 2,

    //已称重
    HasConfirmWeigh: 3,
};


/*
是否免费菜品类型
*/
var IsFreeDishType = {
    //非免费
    None: 0,

    //赠送
    Present: 1,

    //票券兑换
    TicketExchange: 3,
};

/*
原因类型
*/
var ReasonType = {

    // 退菜
    ReturnDish: 1,

    // 赠送
    Present: 2,

    // 折扣
    Discount: 3,

    // 预订取消
    BookCancel: 4,

    // 反结账原因
    AntiPayment: 5,

    // 改价原因
    ChangePrice: 6,

    // 预订取消
    AntiDaySettlement: 7
};

/*
小票格式类型
*/
var PrtBillType = {
    //收银小票
    CashBill: 100,

    //外卖单
    SendBill: 150,

    //预结小票
    ReadyPayBill: 200,

    //总单
    TotalBill: 400,

    //分单
    SigleBill: 500,

    //标签小票
    TagBill: 550,

    //换台单
    SwapTableBill: 900,

    //整单起菜单
    CallUpAllBill: 920,

    //转菜单
    ChangeDishTableBill: 930,

    //台单
    TableBill: 999,

    //预订单
    BookOrderBill: 1100,

    //交班单
    SettlementShiftBill: 1200,

    //日汇总单
    DailySummaryBill: 1210,

    // 存酒单
    SaveWinesBill: 1301,

    // 取酒单
    FetchWinesBill: 1302
};

/*
订单属性
*/
var OrderPropertyType = {
    // 正常
    Normal: 1,

    //快餐
    Snack: 3,
};

/*
银行卡付款
*/
var BankPaymentType = {
    // 普通银行卡付款
    NormalPay: 0,
    // 盒子支付
    IBoxPay: 2,
    //拉卡拉支付
    Lakala: 3,
    //旺POS
    WangPos: 4,
};

/**
 * 移动POS支付结果
 */
var BankPayUsedPaymentType = {
    // 银行卡
    Bank: 1,
    // 微信
    WeiXin: 2,
    // 支付宝
    Alipay: 3,
    // 百度钱包
    Baidui: 4,
    // 京东钱包
    Jd: 5,
    // 易付宝支付
    Yfb: 6,
    // 现金
    Cash: 7,
    // 其它
    Other: 8,
};

/*
线上付款信息
*/
var PaymentFromOnlineType = {
    // 线下
    Offine: 0,
    // 线上自动导入的
    OnlineAuto: 1,
    // 线上手动导入的
    OnlineManual: 2
};

/*
第三方支付方式类型
*/
var ThirdPaymentType = {
    // 微信支付
    WXPay: 2,

    // 支付宝支付
    ZFBBarcodePay: 1,

    //美团
    MTPay: 3,

    //糯米
    NMPay: 4
};

var OnlinePayStatus = {
    //  1-已发起支付
    PayStart: 1,
    //  2-支付失败
    PayFail: 2,
    /// 3-支付成功
    PaySuccess: 3,
    ///  4-已撤销
    PayCancel: 4,
    /// 撤销异常
    CancelError: 5,
    /// 正在支付（确认）
    Paying: 6
};

/*订单状态*/
var DiningOrderStatus = {
    //未结账
    Take: 1,

    // 预结
    Bill: 2,

    // 已结束
    Over: 99,
};

/*
消息类型
*/
var ConsumptionMessageType = {
    // 支付
    Payment: 1,
    /// 服务
    Service: 2,
};

/**
 * 餐台操作类型
 */
var TableOperationType = {
    //点菜
    OrderDish: "OrderDish",
    //团体点菜
    OrderDishForGroup: "OrderDishForGroup",
    //整单起菜
    TakeAllDish: "TakeAllDish",
    //类别起菜
    TakeTypeDish: "TakeTypeDish",
    //详情
    OrderDetail: "OrderDetail",
    //称重
    WeightDish: "WeightDish",
    //打印台单
    PrintTableBill: "PrintTableBill",
    //预结
    PreBilledOrder: "PreBilledOrder",
    //结账
    Settle: "Settle",
    //修改台头
    ModifyTableHeader: "ModifyTableHeader",
    //撤销开台
    DeleteOrder: "DeleteOrder",
    // <li>换台</li>
    SwapTable: "SwapTable",
    // <li>加台</li>
    AddTableOrder: "AddTableOrder",
    //搭台
    CutTable: "CutTable",
    // <li>菜品转台</li>
    ChangeDishTable: "ChangeDishTable",
    // <li>收款记录</li>
    PayToOrderData: "PayToOrderData",
    // <li>催菜</li>
    PushFood: "PushFood"
};
TableOperationType[0] = "OrderDish";
TableOperationType[1] = "OrderDetail";
TableOperationType[2] = "TakeAllDish";
TableOperationType[3] = "TakeTypeDish";
TableOperationType[4] = "PrintTableBill";
TableOperationType[5] = "PreBilledOrder";
TableOperationType[6] = "Settle";
TableOperationType[7] = "OrderDishForGroup";
TableOperationType[8] = "WeightDish";
TableOperationType[9] = "ModifyTableHeader";
TableOperationType[10] = "DeleteOrder";
TableOperationType[11] = "SwapTable";
TableOperationType[12] = "AddTableOrder";
TableOperationType[13] = "CutTable";
TableOperationType[14] = "ChangeDishTable";
TableOperationType[15] = "PayToOrderData";
TableOperationType[16] = "PushFood";

/*
沽清类型
*/
var DishSaleOutType = {
    /// 绝对沽清
    SaleOut: 1,

    /// 数量沽清
    SaleOutWithNum: 2,
};

/*
 结账类型
*/
var SettleMode = {
    // 酒楼结账模式
    Restaurant: 1,

    // 快餐点菜结账模式
    SnackDining: 2,

    // 快餐送餐结账模式
    SnackSendDish: 3,
};

// 存酒状态，1－正常，2－已取完，3－已作废
var SaveWinesStorageStatusEnum = {
    1: '正常',
    2: '已取完',
    3: '已作废'
}

/**
 * 客户类型。0-未指定，1-粉丝，2-线下客户，3-会员
 * */
var UserTypeEnum = {
    0: '未指定',
    1: '粉丝',
    2: '线下客户',
    3: '会员'
}

/**
 *  厨房备注，0-无，1-已催菜 2-已起菜 4-叫起（支持位移运算，如2|4=6）
 * */
var KitchenRemarkEnum = {
    None: 0,  // 无
    QuickDish: 1,  // 催菜
    TakeOut: 2,  // 已起菜
    Called: 4,   // 叫起
}

/**
 * 支付类型
 * 1= 现金，  2=会员卡， 4=银行卡  8=挂账   16=免单  32=票券  64=订金
 * 128=第三方支付 （具体还要判断第三方支付类型ThirdPaymentType）
 * */
var PaymentPatternTypeEnum = {
    CashPayment: 1,  // 现金
    MemberCardPayment: 2,  // 会员卡
    BankCardPayment: 4,  // 银行卡
    CreditPayment: 8,  // 挂账
    FreePayment: 16,  // 免单
    TicketPayment: 32,  // 票券 （具体还要通过TicketPattern来区分票券类型：1=实物券，2=代金券，3=抵扣券，4=满减券，5=次卡券，6=抵扣券）
    DownPayment: 64,  // 订金
    ThirdPayment: 128   // 第三方支付 （ThirdPaymentType第三方支付类型：1=支付宝，2=微信，3=美团，4=糯米，8=美团代收，13=跨店会员支付，9=饿了么代收，100=优质双人餐）
}

/**
 * ThirdPaymentType第三方支付类型：1=支付宝，2=微信，3=美团，4=糯米，8=美团代收，12=云闪付，13=跨店会员支付，9=饿了么代收，100=优质双人餐
 * */
var ThirdPaymentTypeEnum = {
    Alipay: 1,   // 支付宝
    Weixin: 2,   // 微信
    Meituan: 3,  // 美团
    Nuomi: 4,   // 糯米
    MeituanDaishou: 8,   // 美团代收
    Eleme: 9,   // 饿了么代收
    CloudFlashPay: 12,   // 云闪付
    MultiShopMember: 13,  // 跨店会员支付
    DouyinTicket: 15,   // 抖音券
    DoublePeople: 100,  // 优质双人餐
}

//model definition
/**
 * mpos定义
 */
window.mpos = (function (app) {
    //localstorage keys
    var PreBilledOrderNumberKey = "__PreBilledOrderNumberKey__",
        PreBilledOrderIdKey = "__PreBilledOrderIdKey__",
        CashOrderNumberKey = "__CashOrderNumberKey__",
        TableBillIdKey = "__TableBillIdKey__",
        TableBillNumberKey = "__TableBillNumberKey__",
        BillHeadNumberKey = "__BillHeadNumberKey__",
        BillFootNumberKey = "__BillFootNumberKey__",
        PrintTotalBillKey = "__PrintTotalBillKey__",
        PrintSigleBillKey = "__PrintSigleBillKey__",
        SaveWinesPrintIdKey = "__SaveWinesPrintIdKey__",
        SaveWinesPrintNumberKey = "__SaveWinesPrintNumberKey__",
        FetchWinesPrintIdKey = "__FetchWinesPrintIdKey__",
        FetchWinesPrintNumberKey = "__FetchWinesPrintNumberKey__";

    var packageName = "com.paidui.mpos";
    //current request number
    var requestNumber = 0;
    var exitAppCallbacks = [];
    var showLoadingTimeout = null;
 
    var mpos = {
        version: "1.0.0",
        //baseURL，设置API地址
        baseUrl: "/PadApi/",
        //API地址，可以在此处添加， 也可以每个使用的地方添加
        api: {},
        //ajax 请求Header
        //Paidui-Header: DeviceId=88848756-19B4-4141-8E6D-52E554BA82C5;AppSign=MPOS;AppVersion=5.4.1;Package=com.paidui.MPOS;DeviceType=3.1
        //ajax: true
        headers: {
            "ajax": "true",
            "SessionID": genGUID(),
            "AppSign": "MPOS",
            "DeviceType": DeviceType[0],
            "DeviceId": createGuidDeviceId(), // "00:00:00:00:00:00",
            "IP": "127.0.0.1",
            "Paidui-Header": ""
        },
        /**
         * 设备信息
         */
        deviceConfig: {deviceType: DeviceType.Normal},
        /**
         * 是否使用原生的请求， 非同步请求有效， 即async = false时无效
         */
        useNativeAjax: false,
        /**
         * 生成GUID
         */
        genGUID: genGUID,
        /**
         * 调试模式
         */
        isDebug: (typeof DEBUG === "boolean" ? DEBUG : false),
        isDevice: false,
        /**
         * DEBUG模式下输出日志
         */
        log: function () {
            if (this.isDebug) {
                if (arguments.length === 1) {
                    console.log.call(console, arguments[0]);
                } else {
                    console.log.apply(console, Array.prototype.slice.call(arguments));
                }
            }
        },
        /**
         * 是否正在支付
         */
        isPaying: false,
        /**
         * 是否正在扫码
         */
        isScanning: false,
        /**
         * 初始化mpos, 在device ready之后，部分插件，只有在deviceReady之后才能获取
         */
        initialize: function (page) {
            var t = this;
            /**
             * 本地toast
             https://www.npmjs.com/package/cordova-plugin-x-toast
             Showing a Toast
             You have two choices to make when showing a Toast: where to show it and for how long.

             show(message, duration, position)
             duration: 'short', 'long'
             position: 'top', 'center', 'bottom'
             You can also use any of these convenience methods:

             showShortTop(message)
             showShortCenter(message)
             showShortBottom(message)
             showLongTop(message)
             showLongCenter(message)
             showLongBottom(message)

             Hiding a Toast
             In case you want to hide a Toast manually, call this:

             function hide() {
                  // this function takes an optional success callback, but you can do without just as well
                  window.plugins.toast.hide();
                }
             */
            t.toast = plugins.toast;

            /**
             * 本地存储
             https://www.npmjs.com/package/cordova-plugin-app-preferences

             function ok (value) {}
             function fail (error) {}

             var prefs = plugins.appPreferences;

             // cordova interface

             // store key => value pair
             prefs.store (ok, fail, 'key', 'value');

             // store key => value pair in dict (see notes)
             prefs.store (ok, fail, 'dict', 'key', 'value');

             // fetch value by key (value will be delivered through "ok" callback)
             prefs.fetch (ok, fail, 'key');

             // fetch value by key from dict (see notes)
             prefs.fetch (ok, fail, 'dict', 'key');

             // remove value by key
             prefs.remove (ok, fail, 'key');

             // show application preferences
             prefs.show (ok, fail);

             // instead of cordova interface you can use promise interface
             // you'll receive promise when you won't pass function reference
             // as first and second parameter

             // fetch the value for a key using promise
             prefs.fetch ('key').then (ok, fail);

             // support for iOS suites (untested)
             var suitePrefs = prefs.iosSuite ("suiteName");
             suitePrefs.fetch (...);
             suitePrefs.store (...);
             */
            t.appPreferences = plugins.appPreferences;

            /**
             * udp扫描
             mpos.udpScanner.scan(
             function(result) {
                        alert("We got a url\n" +
                            "ServerUrl: " + result.ServerUrl + "\n" +
                            "Cancelled: " + result.cancelled);
                    },
             function(error) {
                        alert("Scanning failed: " + error);
                    }
             );
             */
            t.udpScanner = cordova.plugins.UdpScanner;

            /**
             * 扫描二维码
             * @param {Function} [successCallback]
             * @param {Function} [errorCallback]
             */
            t.scanQR = function (successCallback, errorCallback) {
                mpos.isScanning = true;
                /** @namespace cordova.plugins.barcodeScanner */
                cordova.plugins.barcodeScanner.scan(successCallback, errorCallback);
            };

            /**
             * mpos.mposUtils.getIpMacAddress(successcallback, errorcallback);
             */
            t.mposUtils = cordova.plugins.MposUtils;
       
            //获取mac/sn/ip地址/deviceType，初始化ajax请求
            t.mposUtils.getDeviceConfig(function (result) {
                //alert(JSON.stringify(result));
                //清除跳转痕迹，返回键可以直接退出, 测试时可以注释掉，这样可以返回后刷新当前界面
                //noinspection JSUnresolvedVariable
                navigator.app.clearHistory();

                //处理后退键，用于page堆栈
                //navigator.app.overrideBackbutton(true);
                document.addEventListener('backbutton', onBackKeyDown, false);
                document.addEventListener('resume', onResume, false);
                document.addEventListener('pause', onPause, false);

                t.isDevice = true;


                if (result == null || typeof result != 'object')
                    return;
                mpos.log(JSON.stringify(result));
                mpos.deviceConfig = result;

                //generate ajax header & settings
                if (typeof result.sn == 'string' && result.sn.length > 0) {
                    mpos.headers.DeviceId = result.sn;
                } else if (typeof result.mac == 'string' && result.mac.length > 0) {
                    mpos.headers.DeviceId = result.mac;
                }
                // 判断DeviceId不存在情况下，设置guid的值作为DeviceId  wang.p  2024-06-06
                if(!mpos.headers.DeviceId ||  mpos.headers.DeviceId == '02:00:00:00:00:00' ||  
                    mpos.headers.DeviceId == '00:00:00:00:00:00') {
                    mpos.headers.DeviceId = createGuidDeviceId();
                }
                
                if (typeof result.ip == 'string' && result.ip.length > 0) {
                    mpos.headers.IP = result.ip
                }
                mpos.headers.DeviceType = DeviceType[result.deviceType] || DeviceType[0];

                generateHeaders();
                initAjaxSettings();

                //初始化支付设备
                mpos.deviceFactory.initialize(result);

            }, function (err) {
                debugger
                mpos.log("get device config error:" + err);
            });

            generateHeaders();
            initAjaxSettings();

            if (typeof page == "string")
                t.load(page);
        },
        /**
         * 添加退出App执行的函数，ajax采用同步请求，业务中需要重写该函数
         * @param {Function} callback
         */
        addExitAppCallback: function (callback) {
            if (typeof callback == 'function')
                exitAppCallbacks.push(callback);
        },
        exitApp: exitApp(),
        /**
         * toast 显示文本
         * @param {String} message
         */
        alert: function (message) {
            this.toast.showShortBottom(message);
        },
        /**
         * 显示loading
         */
        showLoading: function () {
            if (arguments[0] != false)
                requestNumber += 1;
            appendLoading().addClass('show');
        },
        /**
         * 隐藏loading
         */
        hideLoading: function () {
            if (--requestNumber <= 0) {
                if (showLoadingTimeout != null) {
                    clearTimeout(showLoadingTimeout);
                    showLoadingTimeout = null;
                }
                $("#loading").remove();
                requestNumber = 0;
            }
        },
        /**
         * ajax request
         * @param {String} url request url
         * @param {Object} params url parameter
         * @param {Function} callback function(data, status, xhr)
         * @param {Object} ajaxOptions ajax请求参数，参考zepto.ajax
         */
        ajax: function _ajax(url, params, callback, ajaxOptions) {
            if (typeof url !== "string") {
                throw TypeError("url is a string, got a " + url);
            }
            var baseUrl = this.baseUrl;
            mpos.log(baseUrl + url);
            if (typeof params == 'object') {
                mpos.log(JSON.stringify(params));
            }

            if (typeof params == 'function') {
                //noinspection JSValidateTypes
                callback = params;
                params = {};
            }
            if (typeof callback == 'object') {
                ajaxOptions = callback;
                callback = function () {
                };
            }
            callback = callback || function () {
                };
            ajaxOptions = ajaxOptions || {};
            if (typeof callback != 'function') {
                throw TypeError("callback is a function, got a " + callback);
            }
            if (typeof ajaxOptions != 'object') {
                throw TypeError("ajaxOptions is a function, got a " + ajaxOptions);
            }

            var errorCallback = typeof ajaxOptions["error"] === 'function' ? ajaxOptions["error"] : undefined;
            if (errorCallback) delete ajaxOptions["error"];

            var startTime = new Date();
            var options = {
                url: baseUrl + url,
                data: params,
                beforeSend: function () {
                    //未定义或者定义了hideLoading = false时显示，同时async不为false
                    if (!!ajaxOptions["hideLoading"] == false && ajaxOptions["async"] != false) {
                        requestNumber += 1;
                        appendLoading();
                        if (showLoadingTimeout == null) {
                            showLoadingTimeout = setTimeout(function () {
                                mpos.showLoading(false);
                                showLoadingTimeout = null;
                            }, Config.showLoadingDelay);
                        }
                    }
                },
                success: function (data, status, xhr) {
                    var totalTime = (new Date()).getTime() - startTime.getTime();
                    mpos.log("request time:" + totalTime);
                    //超时则发送警告信息到服务端
                    if (totalTime >= Config.requestWarnTimeout) {
                        var str = '请求：' + url + ', 耗时：' + totalTime + 'ms.';
                        //mpos.log(str);
                        $.ajax({
                            url: baseUrl + mpos.api.SaveJsLog,
                            type: 'POST',
                            data: {
                                ErrorMsg: str,
                                LogType: 1,
                            }
                        })
                    }
                    mpos.log(JSON.stringify(data));
                    var failedResult = true;
                    if (data.status == JsonResult.OK) {
                        callback(data.data, status, xhr);
                    } else if (data.status == JsonResult.NeedAuth) {
                        //需要授权， 将Header进行修改， 加入用户名和密码
                        if (typeof ajaxOptions["blFailed"] == 'function') {
                            failedResult = !!ajaxOptions["blFailed"](data);
                        }
                        if (failedResult === true) {
                            mpos.showDialog(mpos.dialogPage.userAuth, {
                                errMsg: data.data
                            }, function (result) {
                                if (typeof result == 'object') {
                                    var _options = ajaxOptions;
                                    _options.headers = $.extend(result, mpos.headers);
                                    _ajax.call(mpos, url, params, callback, _options);
                                } else {
                                    //mpos.alert(data.data);
                                }
                            });
                        }
                    } else if (data.status == JsonResult.NeedLogin) {
                        //mpos.log("当前登录已过期，请重新登陆！");
                        if (typeof ajaxOptions["blFailed"] == 'function') {
                            failedResult = !!ajaxOptions["blFailed"](data);
                        }
                        if (failedResult === true) {
                            mpos.showDialog(mpos.dialogPage.login, function (result) {
                                if (result) {
                                    _ajax.call(mpos, url, params, callback, ajaxOptions);
                                } else {
                                    mpos.alert(data.data);
                                }
                            });
                        }
                    } else {
                        if (typeof ajaxOptions["blFailed"] == 'function') {
                            failedResult = !!ajaxOptions["blFailed"](data);
                        }
                        if (failedResult === true) {
                            mpos.alert(data.data);
                        }
                    }
                },
                error: function (xhr, errorType, error) {
                    //mpos.log(errorType);
                    //mpos.log(error);
                    var failedResult = true;
                    if (errorCallback) {
                        failedResult = !!errorCallback(xhr, errorType, error);
                    }
                    if (failedResult === true) {
                        var data = null;
                        try {
                            //noinspection JSUnresolvedVariable
                            data = JSON.parse(xhr.resoponseText);
                        } catch (e) {
                            mpos.log("json parse error:", e);
                        }
                        mpos.alert(data == null ? "请求失败，请检查网络状况！" : data.data);
                    }
                },
                complete: function () {
                    if (!!ajaxOptions["hideLoading"] == false && ajaxOptions["async"] != false)
                        mpos.hideLoading();
                }
            };

            //判断使用原生请求 mpos.useNativeAjax
            if (mpos.useNativeAjax) {
                options.beforeSend();
                mpos.mposUtils.ajax({
                    headers: mpos.headers,
                    url: options.url.toLocaleString().startsWith("http") ? options.url : (location.origin + options.url),
                    data: options.data,
                    timeout: ajaxOptions["timeout"] || 0,
                    type: ajaxOptions["type"] || "POST"
                }, function (result) {
                    options.complete();
                    options.success(result, 200, null);
                }, function (err) {
                    options.complete();
                    options.error(null, 0, err);
                });
            } else {
                $.ajax($.extend(options, ajaxOptions));
            }
        },
        /**
         * ajax get
         * @param {String} url request url
         * @param {Object} [params] url parameter
         * @param {Function} [callback] function(data, status, xhr)
         * @param {Object} [ajaxOptions] ajax option for $.ajax
         */
        get: function (url, params, callback, ajaxOptions) {
            this.ajax(url, params, callback, ajaxOptions);
        },
        /**
         * ajax post
         * @param {String} url request url
         * @param {Object|Function} [params] url parameter
         * @param {Function|Object} [callback] function(data, status, xhr)
         * @param {Object} [ajaxOptions] ajax option for $.ajax
         */
        post: function (url, params, callback, ajaxOptions) {
            if (typeof params == 'function') {
                ajaxOptions = callback;
                callback = params;
                params = {};
            }
            if (typeof callback == 'object') {
                ajaxOptions = callback;
                callback = function () {
                };
            }
            this.ajax(url, params, callback, $.extend(ajaxOptions || {}, {
                type: 'POST'
            }));
        },
        /**
         * 预结打印份数
         * @param {Number} orderNumber
         */
        preBilledOrderNumber: function (orderNumber) {
            var val = localValueWithKey(PreBilledOrderNumberKey, orderNumber);
            if (val == undefined) {
                return 0;
            } else {
                return val;
            }
        },
        /**
         * 预结打印格式ID
         * @param {Number} id
         */
        preBilledOrderId: function (id) {
            var val = localValueWithKey(PreBilledOrderIdKey, id);
            if (val == undefined) {
                return 0;
            } else {
                return val;
            }
        },
        /**
         * 收银小票打印份数
         * @param {Number} orderNumber
         */
        cashOrderNumber: function (orderNumber) {
            var val = localValueWithKey(CashOrderNumberKey, orderNumber);
            if (val == undefined) {
                return 0;
            } else {
                return val;
            }
        },
        /**
         * 台单小票格式ID
         * @param {Number} id
         */
        tableBillId: function (id) {
            var val = localValueWithKey(TableBillIdKey, id);
            if (val == undefined) {
                return 0;
            } else {
                return val;
            }
        },
        /**
         * 台单小票打印份数
         * @param {Number} orderNumber
         */
        tableBillNumber: function (orderNumber) {
            var val = localValueWithKey(TableBillNumberKey, orderNumber);
            if (val == undefined) {
                return 0;
            } else {
                return val;
            }
        },
        /**
         * 小票起始空行数
         * @param {Number} orderNumber
         */
        billHeadNumber: function (orderNumber) {
            var val = localValueWithKey(BillHeadNumberKey, orderNumber);
            if (val == undefined) {
                return 0;
            } else {
                return val;
            }
        },
        /**
         * 小票结束空行数
         * @param {Number} orderNumber
         */
        billFootNumber: function (orderNumber) {
            var val = localValueWithKey(BillFootNumberKey, orderNumber);
            if (val == undefined) {
                return 0;
            } else {
                return val;
            }
        },
        /**
         * 打印总单
         * @param {Number} [orderNumber]
         */
        printTotalBill: function (orderNumber) {
            var val = localValueWithKey(PrintTotalBillKey, orderNumber);
            if (val == undefined) {
                return 0;
            } else {
                return val;
            }
        },
        /**
         * 打印分单
         * @param {Number} [orderNumber]
         */
        printSigleBill: function (orderNumber) {
            var val = localValueWithKey(PrintSigleBillKey, orderNumber);
            if (val == undefined) {
                return 0;
            } else {
                return val;
            }
        },

        /**
         * 存酒小票格式ID
         * @param {Number} id
         */
        saveWinesBillId: function (id) {
            var val = localValueWithKey(SaveWinesPrintIdKey, id);
            if (val == undefined) {
                return 0;
            } else {
                return val;
            }
        },
        /**
         * 存酒小票打印份数
         * @param {Number} orderNumber
         */
        saveWinesBillNumber: function (orderNumber) {
            var val = localValueWithKey(SaveWinesPrintNumberKey, orderNumber);
            if (val == undefined) {
                return 0;
            } else {
                return val;
            }
        },
        /**
         * 取酒小票格式ID
         * @param {Number} id
         */
        fetchWinesBillId: function (id) {
            var val = localValueWithKey(FetchWinesPrintIdKey, id);
            if (val == undefined) {
                return 0;
            } else {
                return val;
            }
        },
        /**
         * 取酒小票打印份数
         * @param {Number} orderNumber
         */
        fetchWinesBillNumber: function (orderNumber) {
            var val = localValueWithKey(FetchWinesPrintNumberKey, orderNumber);
            if (val == undefined) {
                return 0;
            } else {
                return val;
            }
        },
    };

    /**
     * 创建一个随机的DeviceId, 并将其缓存到localStorage中
     */
    function createGuidDeviceId () {
        // 先判断缓存中是否存在DeviceId，有就直接返回，没有就创建，并缓存后返回
        var guidDeviceId = localStorage.getItem("GuidDeviceId");
        if (!guidDeviceId) {
            guidDeviceId = genGUID();
            localStorage.setItem("GuidDeviceId", guidDeviceId);
        }
        return guidDeviceId;
    }

    /**
     * insert the loading div and return it
     * @returns {ZeptoCollection}
     */
    function appendLoading() {
        var loading = $('#loading');
        if (loading.length == 0) {
            $(document.body).append("<div id='loading' class='loading'><div><p></p><p></p><p></p><p></p><p></p></div></div>");
        }
        return loading;
    }

    /**
     * 本地存储定义
     */
    mpos.localStorage = (function (context) {
        var keys = [];
        var storage = {
            /**
             * clear local storage, if arguments is given, delete the given key
             */
            clear: function () {
                if (0 in arguments)
                    delete localStorage[transformKey(arguments[0])];
                else
                    keys.forEach(function (item) {
                        delete localStorage[transformKey(item)];
                    });
            },
            /**
             * get all keys
             * @returns {Array}
             */
            get keys() {
                return keys;
            }
        };

        /**
         * register localstorage property
         * @param props
         */
        context.registerStorageProperties = function (props) {
            if (!props) return;
            if (props instanceof Array) {
                props.forEach(function (item) {
                    registerStorageProperty(item);
                });
            } else {
                registerStorageProperty(props);
            }
        };

        /**
         * register localstorage property
         * @param {String} prop
         */
        function registerStorageProperty(prop) {
            if (typeof prop !== 'string' || keys.indexOf(prop) > -1) return;
            keys.push(prop);
            Object.defineProperty(storage, prop, {
                get: function () {
                    var v = localStorage[transformKey(prop)];
                    if (v === 'true')
                        return true;
                    if (v === 'false')
                        return false;
                    if (v === 'undefined')
                        return undefined;

                    return v;
                },
                set: function (value) {
                    localStorage[transformKey(prop)] = value;
                }
            });
        }

        /**
         * transform key to the localstorage key
         * @param key
         * @returns {string}
         */
        function transformKey(key) {
            return "__" + key + "Key__";
        }

        return storage;
    })(mpos);

    /**
     * 组件定义
     */
    mpos.Components = {
        extend: function (componentFunction) {
            if (typeof componentFunction !== 'function')
                throw TypeError("组件必须为函数");
            this[componentFunction.name] = componentFunction;
        }
    };

    /**
     * 处理后退按钮， 如果当前page堆栈有值，则执行后退操作， 否则直接退出app
     */
    function onBackKeyDown() {
        mpos.log("back key pressed.");
        //return when ispaying or scanning
        if (mpos.isPaying) {
            return;
        }
        //扫码需要这里复原
        if (mpos.isScanning) {
            mpos.isScanning = false;
            return;
        }
        //hide slide page
        if ($("body>.slide-page").length > 0) {
            mpos.slidePage.hide();
            return;
        }
        //hide table operation page
        if (mpos.tableOperationPage.isShow) {
            mpos.tableOperationPage.hide();
            return;
        }


        //hide dialog page exclude login dialog
        if ($("body>.app-dialog-container").length > 0) {
            /**
             * @typedef {Object} DialogPage
             * @property {Object} CONTEXT
             *
             * @type {ZeptoCollection|HTMLElement|DialogPage}
             */
            var dialogPage = $("body>.app-dialog-container .dialog-page");
            if (dialogPage.length == 1) {
                dialogPage = dialogPage[0];
                if (dialogPage.CONTEXT && typeof dialogPage.CONTEXT.onBackKeyDown === 'function') {
                    dialogPage.CONTEXT.onBackKeyDown();
                    return;
                }
            }
            app.back();
            return;
        }


        var currentPageContext = app._Stack.getCurrent()[2];
        if (typeof currentPageContext.onBackKeyDown === 'function') {
            if (!currentPageContext.onBackKeyDown()) return;
        }

        //只有单个界面，则
        if (app._Stack.get().length == 1) {
            mpos.exitApp();
            //return;
        } else {
            app.back();
        }

    }


    /**
     * 退出app执行清理
     */
    function exitApp() {
        var backCount = 0, backTimeout = null;
        return function () {
            if (++backCount < 2){
                mpos.alert('再按一次退出程序');
                setTimeout(function () {
                    backCount = 0;
                }, 3000);
                return;
            }
            clearTimeout(backTimeout);
            exitAppCallbacks.forEach(function (item) {
                if (typeof item === 'function')
                    item();
            });
            document.removeEventListener('backbutton', onBackKeyDown, false);
            document.removeEventListener('resume', onResume, false);
            document.removeEventListener('pause', onPause, false);
            /** @namespace navigator.app */
            navigator.app.exitApp();
        };
    }

    /**
     * 程序resume操作，注意该事件会在扫码、支付、唤醒等操作后均会执行
     */
    function onResume() {
        mpos.log("onresume");
        mpos.deviceFactory.onResume();
    }

    /**
     * 程序pause执行操作
     */
    function onPause() {
        mpos.log("onpause");
    }


    //处理弹出框

    //class
    var DIALOGPAGE_CLASS = "dialog-page";
    //attribute
    var DIALOGPAGE_NAME = "data-dialog-page";
    //cache for dialogpage
    var dialogPages = {};
    //cache for dialogpage controllers
    var dialogControllers = {};

    /**
     * 添加对话框界面
     * @param {HTMLElement} dialogPage 对话框DomNode
     * @param {String} [dialogPageName] 对话框名称
     */
    function addDialogPage(dialogPage, dialogPageName) {
        if (!dialogPageName) {
            dialogPageName = dialogPage.getAttribute(DIALOGPAGE_NAME);
        }
        if (!dialogPageName) {
            throw TypeError("dialog page name was not specified");
        }

        dialogPage.setAttribute(DIALOGPAGE_NAME, dialogPageName);
        if (dialogPage.parentNode) {
            dialogPage.parentNode.removeChild(dialogPage);
        }
        dialogPages[dialogPageName] = dialogPage.cloneNode(true);
    }

    /**
     * 添加对话框控制器
     * @param {String} dialogPageName 对话框名称
     * @param {Function} controller 对话框初始化控制器
     */
    function addDialogController(dialogPageName, controller) {
        dialogControllers[dialogPageName] = controller;
    }

    /**
     * 载入对话框
     * @param {String} dialogPageName 对话框名称
     * @param {Object} [args] 参数，@see showDialog
     * @param {Object} [options] 参数，@see showDialog
     * @param {Function} [callback] 回调函数，@see showDialog
     */
    function loadDialogPage(dialogPageName, args, options, callback) {
        var dialogPage = dialogPages[dialogPageName];
        if (!dialogPage)
            return;
        dialogPage = dialogPage.cloneNode(true);
        // $(dialogPage).on('click', function (e) {
        //     e.stopPropagation();
        // });

        var controller = dialogControllers[dialogPageName];
        if (!controller) return;
        var pageContext = {};
        controller.call(pageContext, dialogPage, args, options);
        dialogPage.CONTEXT = pageContext;
        //默认选中
        //noinspection JSUnresolvedFunction
        $.selectOnFocus(dialogPage);

        var dialogOptions = {
            rawHTML: dialogPage
        };
        if (args["okButton"]) {
            dialogOptions.okButton = args["okButton"];
        }
        if (args["cancelButton"]) {
            dialogOptions.cancelButton = args["cancelButton"];
        }
        mpos.dialog(dialogOptions, callback, true);

    }

    /**
     * 显示对话框
     * @param {String} dialogPageName 对话框名称
     * @param {Object} [args] 参数，譬如{"okButton":"OK", "cancelButton": "cancel"},将处理确定和取消按钮
     * @param {Object|Function|String} [options] 参数
     * @param {Function} [callback] 回调函数，接受一个参数status，为true时为确定，为false时为取消
     */
    mpos.showDialog = function (dialogPageName, args, options, callback) {
        if (typeof dialogPageName !== 'string') {
            throw TypeError('dialog pageName name must be a string, got ' + dialogPageName);
        }
        switch (typeof args) {
            case 'function':
                options = args;
                args = {};
                break;
            case 'string':
                callback = options;
                options = args;
                break;
            case 'undefined':
                args = {};
                break;
            case 'object':
                break;
            default:
                throw TypeError('page arguments must be an object if defined, got ' + args);
        }
        switch (typeof options) {
            case 'function':
                callback = options;
                break;
            case 'undefined':
                options = {};
                break;
            case 'object':
                break;
            case 'string':
                options = {
                    transition: options
                };
                break;
            default:
                throw TypeError('options must be an object if defined, got ' + options);
        }
        switch (typeof callback) {
            case 'undefined':
                callback = function () {
                };
                break;
            case 'function':
                break;
            default:
                throw TypeError('callback must be a function if defined, got ' + callback);
        }

        return loadDialogPage(dialogPageName, args, options, callback);
    };

    /**
     * 对话框的控制器定义
     * @param {String} dialogPageName 对话框名称
     * @param {Function} controller 处理函数
     */
    mpos.dialogController = function (dialogPageName, controller) {
        if (typeof dialogPageName !== 'string') {
            throw TypeError('dialog page name must be a string, got ' + dialogPageName);
        }

        if (typeof controller !== 'function') {
            throw TypeError('dialog page controller must be a function, got ' + controller);
        }

        if (controller) {
            addDialogController(dialogPageName, controller);
        }
    };

    //domcontentloaded 时处理UI
    $(function () {
        var dialogPageNodes = document.getElementsByClassName(DIALOGPAGE_CLASS);
        for (var i = dialogPageNodes.length; i--; i >= 0) {
            addDialogPage(dialogPageNodes[i]);
        }
    });

    //桥接App.js的调用
    ["load", "back", "pick", "dialog", "controller", "removeFromStack", "infiniteScroll"].forEach(function (item) {
        mpos[item] = app[item];
    });
    // mpos.controller = function () {
    //     var args = Array.prototype.slice.call(arguments);
    //     if (1 in arguments && typeof arguments[1] === 'function') {
    //         var oldFunc = args[1];
    //         var func = function (page) {
    //             $(page).on('click', function (e) {
    //                 e.stopPropagation();
    //             });
    //             oldFunc.apply(this, Array.prototype.slice.call(arguments))
    //         };
    //         args[1] = func;
    //     }
    //     return app.controller.apply(app, args);
    // };
    /**
     * 页面名称
     * @param {String} pageName
     * @param args
     * @param options
     * @param callback
     *
     */
    mpos.replace = function (pageName, args, options, callback) {
        app.load(pageName, args, options, callback);
        var l = app._Stack.size();
        if (l > 1) {
            app.removeFromStack(l - 2, l - 1);
        }
    };

    /**
     * 获取当前页面的名称数组
     */
    mpos.getStackPages = function () {
        return app.getStack().map(function (page) {
            return page[0];
        });
    };
    /**
     * 获取当前页面的名称
     */
    mpos.getCurrentPage = function () {
        return app._Stack.getCurrent()[0];
    };
    /**
     * 获取当前页面的Dom树
     */
    mpos.getCurrentPageDom = function () {
        return app._Stack.getCurrent()[3];
    };

    /**
     * 判断是否有对话框
     */
    mpos.hasDialog = function () {
        return app.dialog.status();
    };
    /**
     * 开启或者关闭页面跳转动画
     * 后续需要判断其他系统版本
     * @param isDisabled boolean value
     */
    mpos.disablePageAnimation = function (isDisabled) {
        if (isDisabled) {
            app.setDefaultTransition("instant");
        } else {
            app.setDefaultTransition("android-l-in");
        }
    };


    /**
     * 触发自定义事件， 只针对当前的栈中的page
     * @param {String} event 事件名称
     * @param {Array} args 数组
     */
    mpos.triggerEvent = function (event, args) {
        app.getStack().map(function (page) {
            return page[3];
        }).forEach(function (item) {
            $(item).triggerHandler(event, args);
        });
    };

    ////for debug, output page event
    //mpos.controller = function() {
    //    var page = arguments[0];
    //    var fun = arguments[1];
    //    fun.prototype.onLayout = function() {
    //        mpos.log(page + ", xoo][::::::::>appLayout.");
    //    }
    //    fun.prototype.onShow = function() {
    //        mpos.log(page + ", xoo][::::::::>appshow.");
    //    }
    //    fun.prototype.onHide = function() {
    //        mpos.log(page + ", xoo][::::::::>appHide.");
    //    }
    //    fun.prototype.onBack = function() {
    //        mpos.log(page + ", xoo][::::::::>appBack.");
    //    }
    //    fun.prototype.onForward = function() {
    //        mpos.log(page + ", xoo][::::::::>appForward.");
    //    }
    //    fun.prototype.onBeforeBack = function() {
    //        mpos.log(page + ", xoo][::::::::>appBeforeBack.");
    //    }
    //    fun.prototype.onReady = function() {
    //        mpos.log(page + ", xoo][::::::::>appReady.");
    //    }
    //    fun.prototype.onDestroy = function() {
    //        mpos.log(page + ", xoo][::::::::>appDestroy.");
    //    }
    //    app.controller.apply(app, arguments);
    //}


    /**
     * 设置本地存储，根据给定值判断
     * @param {String} key 本地存储key
     * @param {*} value 本地存储value, 为空时为读取
     */
    function localValueWithKey(key, value) {
        if (typeof key !== "string") {
            throw TypeError("key必须为字符串");
        }
        if (value !== undefined) {
            localStorage[key] = value;
        } else {
            return localStorage[key];
        }
    }

    /**
     * device ready之后调用
     */
    function generateHeaders() {
        mpos.headers["Paidui-Header"] = "DeviceId=" + mpos.headers.DeviceId +
            ";AppSign=" + mpos.headers.AppSign +
            ";AppVersion=" + appVersion +
            ";Package=" + packageName +
            ";DeviceType=" + mpos.headers.DeviceType;
    }

    /**
     * 初始化ajax配置
     */
    function initAjaxSettings() {
        $.extend($.ajaxSettings, {
            timeout: 10000,
            dataType: 'json',
            headers: mpos.headers
        });
    }

    /**
     * 生成GUID字符串
     */
    function genGUID() {
        return [gen(2), gen(1), gen(1), gen(1), gen(3)].join("-");
    }

    /**
     * 生成GUID字符串
     * 代码来源 https://github.com/dandean/guid/blob/master/guid.js
     * @param {Object} count 长度，1*4位
     */
    function gen(count) {
        var out = "";
        for (var i = 0; i < count; i++) {
            out += (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return out;
    }

    /**
     * 将汉字转成拼音，全拼音、简写拼音（首字母）
     * */
    mpos.Pinyin = function () {
        var Pinyin = function (ops){
              this.initialize(ops);
          },
          options = {
              checkPolyphone: false,
              charcase: 'default'
          };
        Pinyin.fn = Pinyin.prototype = {
            init: function (ops){
                this.options = extend(options, ops);
            },
            initialize: function(ops){
                this.init(ops);
                this.char_dict = " "
                this.full_dict = {"a":"\u554a\u963f\u9515","ai":"\u57c3\u6328\u54ce\u5509\u54c0\u7691\u764c\u853c\u77ee\u827e\u788d\u7231\u9698\u8bf6\u6371\u55f3\u55cc\u5ad2\u7477\u66a7\u7839\u953f\u972d","an":"\u978d\u6c28\u5b89\u4ffa\u6309\u6697\u5cb8\u80fa\u6848\u8c19\u57ef\u63de\u72b4\u5eb5\u6849\u94f5\u9e4c\u9878\u9eef","ang":"\u80ae\u6602\u76ce","ao":"\u51f9\u6556\u71ac\u7ff1\u8884\u50b2\u5965\u61ca\u6fb3\u5773\u62d7\u55f7\u5662\u5c99\u5ed2\u9068\u5aaa\u9a9c\u8071\u87af\u93ca\u9ccc\u93d6","ba":"\u82ad\u634c\u6252\u53ed\u5427\u7b06\u516b\u75a4\u5df4\u62d4\u8dcb\u9776\u628a\u8019\u575d\u9738\u7f62\u7238\u8307\u83dd\u8406\u636d\u5c9c\u705e\u6777\u94af\u7c91\u9c85\u9b43","bai":"\u767d\u67cf\u767e\u6446\u4f70\u8d25\u62dc\u7a17\u859c\u63b0\u97b4","ban":"\u6591\u73ed\u642c\u6273\u822c\u9881\u677f\u7248\u626e\u62cc\u4f34\u74e3\u534a\u529e\u7eca\u962a\u5742\u8c73\u94a3\u7622\u764d\u8228","bang":"\u90a6\u5e2e\u6886\u699c\u8180\u7ed1\u68d2\u78c5\u868c\u9551\u508d\u8c24\u84a1\u8783","bao":"\u82de\u80de\u5305\u8912\u96f9\u4fdd\u5821\u9971\u5b9d\u62b1\u62a5\u66b4\u8c79\u9c8d\u7206\u52f9\u8446\u5b80\u5b62\u7172\u9e28\u8913\u8db5\u9f85","bo":"\u5265\u8584\u73bb\u83e0\u64ad\u62e8\u94b5\u6ce2\u535a\u52c3\u640f\u94c2\u7b94\u4f2f\u5e1b\u8236\u8116\u818a\u6e24\u6cca\u9a73\u4eb3\u8543\u5575\u997d\u6a97\u64d8\u7934\u94b9\u9e41\u7c38\u8ddb","bei":"\u676f\u7891\u60b2\u5351\u5317\u8f88\u80cc\u8d1d\u94a1\u500d\u72c8\u5907\u60eb\u7119\u88ab\u5b5b\u9642\u90b6\u57e4\u84d3\u5457\u602b\u6096\u789a\u9e4e\u8919\u943e","ben":"\u5954\u82ef\u672c\u7b28\u755a\u574c\u951b","beng":"\u5d29\u7ef7\u752d\u6cf5\u8e66\u8ff8\u552a\u5623\u750f","bi":"\u903c\u9f3b\u6bd4\u9119\u7b14\u5f7c\u78a7\u84d6\u853d\u6bd5\u6bd9\u6bd6\u5e01\u5e87\u75f9\u95ed\u655d\u5f0a\u5fc5\u8f9f\u58c1\u81c2\u907f\u965b\u5315\u4ef3\u4ffe\u8298\u835c\u8378\u5421\u54d4\u72f4\u5eb3\u610e\u6ed7\u6fde\u5f3c\u59a3\u5a62\u5b16\u74a7\u8d32\u7540\u94cb\u79d5\u88e8\u7b5a\u7b85\u7be6\u822d\u895e\u8df8\u9ac0","bian":"\u97ad\u8fb9\u7f16\u8d2c\u6241\u4fbf\u53d8\u535e\u8fa8\u8fa9\u8fab\u904d\u533e\u5f01\u82c4\u5fed\u6c74\u7f0f\u7178\u782d\u78a5\u7a39\u7a86\u8759\u7b3e\u9cca","biao":"\u6807\u5f6a\u8198\u8868\u5a4a\u9aa0\u98d1\u98d9\u98da\u706c\u9556\u9573\u762d\u88f1\u9cd4","bie":"\u9cd6\u618b\u522b\u762a\u8e69\u9cd8","bin":"\u5f6c\u658c\u6fd2\u6ee8\u5bbe\u6448\u50a7\u6d5c\u7f24\u73a2\u6ba1\u8191\u9554\u9acc\u9b13","bing":"\u5175\u51b0\u67c4\u4e19\u79c9\u997c\u70b3\u75c5\u5e76\u7980\u90b4\u6452\u7ee0\u678b\u69df\u71f9","bu":"\u6355\u535c\u54fa\u8865\u57e0\u4e0d\u5e03\u6b65\u7c3f\u90e8\u6016\u62ca\u535f\u900b\u74ff\u6661\u949a\u91ad","ca":"\u64e6\u5693\u7924","cai":"\u731c\u88c1\u6750\u624d\u8d22\u776c\u8e29\u91c7\u5f69\u83dc\u8521","can":"\u9910\u53c2\u8695\u6b8b\u60ed\u60e8\u707f\u9a96\u74a8\u7cb2\u9eea","cang":"\u82cd\u8231\u4ed3\u6ca7\u85cf\u4f27","cao":"\u64cd\u7cd9\u69fd\u66f9\u8349\u8279\u5608\u6f15\u87ac\u825a","ce":"\u5395\u7b56\u4fa7\u518c\u6d4b\u5202\u5e3b\u607b","ceng":"\u5c42\u8e6d\u564c","cha":"\u63d2\u53c9\u832c\u8336\u67e5\u78b4\u643d\u5bdf\u5c94\u5dee\u8be7\u7339\u9987\u6c4a\u59f9\u6748\u6942\u69ce\u6aab\u9497\u9538\u9572\u8869","chai":"\u62c6\u67f4\u8c7a\u4faa\u8308\u7625\u867f\u9f87","chan":"\u6400\u63ba\u8749\u998b\u8c17\u7f20\u94f2\u4ea7\u9610\u98a4\u5181\u8c04\u8c36\u8487\u5edb\u5fcf\u6f7a\u6fb6\u5b71\u7fbc\u5a75\u5b17\u9aa3\u89c7\u7985\u9561\u88e3\u87fe\u8e94","chang":"\u660c\u7316\u573a\u5c1d\u5e38\u957f\u507f\u80a0\u5382\u655e\u7545\u5531\u5021\u4f25\u9b2f\u82cc\u83d6\u5f9c\u6005\u60dd\u960a\u5a3c\u5ae6\u6636\u6c05\u9cb3","chao":"\u8d85\u6284\u949e\u671d\u5632\u6f6e\u5de2\u5435\u7092\u600a\u7ec9\u6641\u8016","che":"\u8f66\u626f\u64a4\u63a3\u5f7b\u6f88\u577c\u5c6e\u7817","chen":"\u90f4\u81e3\u8fb0\u5c18\u6668\u5ff1\u6c89\u9648\u8d81\u886c\u79f0\u8c0c\u62bb\u55d4\u5bb8\u741b\u6987\u809c\u80c2\u789c\u9f80","cheng":"\u6491\u57ce\u6a59\u6210\u5448\u4e58\u7a0b\u60e9\u6f84\u8bda\u627f\u901e\u9a8b\u79e4\u57d5\u5d4a\u5fb5\u6d48\u67a8\u67fd\u6a18\u665f\u584d\u77a0\u94d6\u88ce\u86cf\u9172","chi":"\u5403\u75f4\u6301\u5319\u6c60\u8fdf\u5f1b\u9a70\u803b\u9f7f\u4f88\u5c3a\u8d64\u7fc5\u65a5\u70bd\u50ba\u5880\u82aa\u830c\u640b\u53f1\u54e7\u557b\u55e4\u5f73\u996c\u6cb2\u5ab8\u6555\u80dd\u7719\u7735\u9e31\u761b\u892b\u86a9\u87ad\u7b1e\u7bea\u8c49\u8e05\u8e1f\u9b51","chong":"\u5145\u51b2\u866b\u5d07\u5ba0\u833a\u5fe1\u61a7\u94f3\u825f","chou":"\u62bd\u916c\u7574\u8e0c\u7a20\u6101\u7b79\u4ec7\u7ef8\u7785\u4e11\u4fe6\u5733\u5e31\u60c6\u6eb4\u59af\u7633\u96e0\u9c8b","chu":"\u81ed\u521d\u51fa\u6a71\u53a8\u8e87\u9504\u96cf\u6ec1\u9664\u695a\u7840\u50a8\u77d7\u6410\u89e6\u5904\u4e8d\u520d\u61b7\u7ecc\u6775\u696e\u6a17\u870d\u8e70\u9edc","chuan":"\u63e3\u5ddd\u7a7f\u693d\u4f20\u8239\u5598\u4e32\u63be\u821b\u60f4\u9044\u5ddb\u6c1a\u948f\u9569\u8221","chuang":"\u75ae\u7a97\u5e62\u5e8a\u95ef\u521b\u6006","chui":"\u5439\u708a\u6376\u9524\u5782\u9672\u68f0\u69cc","chun":"\u6625\u693f\u9187\u5507\u6df3\u7eaf\u8822\u4fc3\u83bc\u6c8c\u80ab\u6710\u9e51\u877d","chuo":"\u6233\u7ef0\u851f\u8fb6\u8f8d\u955e\u8e14\u9f8a","ci":"\u75b5\u8328\u78c1\u96cc\u8f9e\u6148\u74f7\u8bcd\u6b64\u523a\u8d50\u6b21\u8360\u5472\u5d6f\u9e5a\u8785\u7ccd\u8d91","cong":"\u806a\u8471\u56f1\u5306\u4ece\u4e1b\u506c\u82c1\u6dd9\u9aa2\u742e\u7481\u679e","cu":"\u51d1\u7c97\u918b\u7c07\u731d\u6b82\u8e59","cuan":"\u8e7f\u7be1\u7a9c\u6c46\u64ba\u6615\u7228","cui":"\u6467\u5d14\u50ac\u8106\u7601\u7cb9\u6dec\u7fe0\u8403\u60b4\u7480\u69b1\u96b9","cun":"\u6751\u5b58\u5bf8\u78cb\u5fd6\u76b4","cuo":"\u64ae\u6413\u63aa\u632b\u9519\u539d\u811e\u9509\u77ec\u75e4\u9e7e\u8e49\u8e9c","da":"\u642d\u8fbe\u7b54\u7629\u6253\u5927\u8037\u54d2\u55d2\u601b\u59b2\u75b8\u8921\u7b2a\u977c\u9791","dai":"\u5446\u6b79\u50a3\u6234\u5e26\u6b86\u4ee3\u8d37\u888b\u5f85\u902e\u6020\u57ed\u7519\u5454\u5cb1\u8fe8\u902f\u9a80\u7ed0\u73b3\u9edb","dan":"\u803d\u62c5\u4e39\u5355\u90f8\u63b8\u80c6\u65e6\u6c2e\u4f46\u60ee\u6de1\u8bde\u5f39\u86cb\u4ebb\u510b\u5369\u840f\u5556\u6fb9\u6a90\u6b9a\u8d55\u7708\u7605\u8043\u7baa","dang":"\u5f53\u6321\u515a\u8361\u6863\u8c20\u51fc\u83ea\u5b95\u7800\u94db\u88c6","dao":"\u5200\u6363\u8e48\u5012\u5c9b\u7977\u5bfc\u5230\u7a3b\u60bc\u9053\u76d7\u53e8\u5541\u5fc9\u6d2e\u6c18\u7118\u5fd1\u7e9b","de":"\u5fb7\u5f97\u7684\u951d","deng":"\u8e6c\u706f\u767b\u7b49\u77aa\u51f3\u9093\u5654\u5d9d\u6225\u78f4\u956b\u7c26","di":"\u5824\u4f4e\u6ef4\u8fea\u654c\u7b1b\u72c4\u6da4\u7fdf\u5ae1\u62b5\u5e95\u5730\u8482\u7b2c\u5e1d\u5f1f\u9012\u7f14\u6c10\u7c74\u8bcb\u8c1b\u90b8\u577b\u839c\u837b\u5600\u5a23\u67e2\u68e3\u89cc\u7825\u78b2\u7747\u955d\u7f9d\u9ab6","dian":"\u98a0\u6382\u6ec7\u7898\u70b9\u5178\u975b\u57ab\u7535\u4f43\u7538\u5e97\u60e6\u5960\u6dc0\u6bbf\u4e36\u963d\u576b\u57dd\u5dc5\u73b7\u765c\u766b\u7c1f\u8e2e","diao":"\u7889\u53fc\u96d5\u51cb\u5201\u6389\u540a\u9493\u8c03\u8f7a\u94de\u8729\u7c9c\u8c82","die":"\u8dcc\u7239\u789f\u8776\u8fed\u8c0d\u53e0\u4f5a\u57a4\u581e\u63f2\u558b\u6e2b\u8f76\u7252\u74de\u8936\u800b\u8e40\u9cbd\u9cce","ding":"\u4e01\u76ef\u53ee\u9489\u9876\u9f0e\u952d\u5b9a\u8ba2\u4e22\u4ec3\u5576\u738e\u815a\u7887\u753a\u94e4\u7594\u8035\u914a","dong":"\u4e1c\u51ac\u8463\u61c2\u52a8\u680b\u4f97\u606b\u51bb\u6d1e\u578c\u549a\u5cbd\u5cd2\u5902\u6c21\u80e8\u80f4\u7850\u9e2b","dou":"\u515c\u6296\u6597\u9661\u8c46\u9017\u75d8\u8538\u94ad\u7aa6\u7aac\u86aa\u7bfc\u9161","du":"\u90fd\u7763\u6bd2\u728a\u72ec\u8bfb\u5835\u7779\u8d4c\u675c\u9540\u809a\u5ea6\u6e21\u5992\u828f\u561f\u6e0e\u691f\u6a50\u724d\u8839\u7b03\u9ad1\u9ee9","duan":"\u7aef\u77ed\u953b\u6bb5\u65ad\u7f0e\u5f56\u6934\u7145\u7c16","dui":"\u5806\u5151\u961f\u5bf9\u603c\u619d\u7893","dun":"\u58a9\u5428\u8e72\u6566\u987f\u56e4\u949d\u76fe\u9041\u7096\u7818\u7905\u76f9\u9566\u8db8","duo":"\u6387\u54c6\u591a\u593a\u579b\u8eb2\u6735\u8dfa\u8235\u5241\u60f0\u5815\u5484\u54da\u7f0d\u67c1\u94ce\u88f0\u8e31","e":"\u86fe\u5ce8\u9e45\u4fc4\u989d\u8bb9\u5a25\u6076\u5384\u627c\u904f\u9102\u997f\u5669\u8c14\u57a9\u57ad\u82ca\u83aa\u843c\u5443\u6115\u5c59\u5a40\u8f6d\u66f7\u816d\u786a\u9507\u9537\u9e57\u989a\u9cc4","en":"\u6069\u84bd\u6441\u5514\u55ef","er":"\u800c\u513f\u8033\u5c14\u9975\u6d31\u4e8c\u8d30\u8fe9\u73e5\u94d2\u9e38\u9c95","fa":"\u53d1\u7f5a\u7b4f\u4f10\u4e4f\u9600\u6cd5\u73d0\u57a1\u781d","fan":"\u85e9\u5e06\u756a\u7ffb\u6a0a\u77fe\u9492\u7e41\u51e1\u70e6\u53cd\u8fd4\u8303\u8d29\u72af\u996d\u6cdb\u8629\u5e61\u72ad\u68b5\u6535\u71d4\u7548\u8e6f","fang":"\u574a\u82b3\u65b9\u80aa\u623f\u9632\u59a8\u4eff\u8bbf\u7eba\u653e\u531a\u90a1\u5f77\u94ab\u822b\u9c82","fei":"\u83f2\u975e\u5561\u98de\u80a5\u532a\u8bfd\u5420\u80ba\u5e9f\u6cb8\u8d39\u82be\u72d2\u60b1\u6ddd\u5983\u7ecb\u7eef\u69a7\u8153\u6590\u6249\u7953\u7829\u9544\u75f1\u871a\u7bda\u7fe1\u970f\u9cb1","fen":"\u82ac\u915a\u5429\u6c1b\u5206\u7eb7\u575f\u711a\u6c7e\u7c89\u594b\u4efd\u5fff\u6124\u7caa\u507e\u7035\u68fc\u610d\u9cbc\u9f22","feng":"\u4e30\u5c01\u67ab\u8702\u5cf0\u950b\u98ce\u75af\u70fd\u9022\u51af\u7f1d\u8bbd\u5949\u51e4\u4ff8\u9146\u8451\u6ca3\u781c","fu":"\u4f5b\u5426\u592b\u6577\u80a4\u5b75\u6276\u62c2\u8f90\u5e45\u6c1f\u7b26\u4f0f\u4fd8\u670d\u6d6e\u6daa\u798f\u88b1\u5f17\u752b\u629a\u8f85\u4fef\u91dc\u65a7\u812f\u8151\u5e9c\u8150\u8d74\u526f\u8986\u8d4b\u590d\u5085\u4ed8\u961c\u7236\u8179\u8d1f\u5bcc\u8ba3\u9644\u5987\u7f1a\u5490\u5310\u51eb\u90db\u8299\u82fb\u832f\u83a9\u83d4\u544b\u5e5e\u6ecf\u8274\u5b5a\u9a78\u7ec2\u6874\u8d59\u9efb\u9efc\u7f58\u7a03\u99a5\u864d\u86a8\u8709\u8760\u876e\u9eb8\u8dba\u8dd7\u9cc6","ga":"\u5676\u560e\u86e4\u5c2c\u5477\u5c15\u5c1c\u65ee\u9486","gai":"\u8be5\u6539\u6982\u9499\u76d6\u6e89\u4e10\u9654\u5793\u6224\u8d45\u80f2","gan":"\u5e72\u7518\u6746\u67d1\u7aff\u809d\u8d76\u611f\u79c6\u6562\u8d63\u5769\u82f7\u5c34\u64c0\u6cd4\u6de6\u6f89\u7ec0\u6a44\u65f0\u77f8\u75b3\u9150","gang":"\u5188\u521a\u94a2\u7f38\u809b\u7eb2\u5c97\u6e2f\u6206\u7f61\u9883\u7b7b","gong":"\u6760\u5de5\u653b\u529f\u606d\u9f9a\u4f9b\u8eac\u516c\u5bab\u5f13\u5de9\u6c5e\u62f1\u8d21\u5171\u857b\u5efe\u54a3\u73d9\u80b1\u86a3\u86e9\u89e5","gao":"\u7bd9\u768b\u9ad8\u818f\u7f94\u7cd5\u641e\u9550\u7a3f\u544a\u777e\u8bf0\u90dc\u84bf\u85c1\u7f1f\u69d4\u69c1\u6772\u9506","ge":"\u54e5\u6b4c\u6401\u6208\u9e3d\u80f3\u7599\u5272\u9769\u845b\u683c\u9601\u9694\u94ec\u4e2a\u5404\u9b32\u4ee1\u54ff\u5865\u55dd\u7ea5\u643f\u8188\u784c\u94ea\u9549\u88bc\u988c\u867c\u8238\u9abc\u9ac2","gei":"\u7ed9","gen":"\u6839\u8ddf\u4e98\u831b\u54cf\u826e","geng":"\u8015\u66f4\u5e9a\u7fb9\u57c2\u803f\u6897\u54fd\u8d53\u9ca0","gou":"\u94a9\u52fe\u6c9f\u82df\u72d7\u57a2\u6784\u8d2d\u591f\u4f5d\u8bdf\u5ca3\u9058\u5abe\u7f11\u89cf\u5f40\u9e32\u7b31\u7bdd\u97b2","gu":"\u8f9c\u83c7\u5495\u7b8d\u4f30\u6cbd\u5b64\u59d1\u9f13\u53e4\u86ca\u9aa8\u8c37\u80a1\u6545\u987e\u56fa\u96c7\u560f\u8bc2\u83f0\u54cc\u5d2e\u6c69\u688f\u8f71\u726f\u727f\u80cd\u81cc\u6bc2\u77bd\u7f5f\u94b4\u9522\u74e0\u9e2a\u9e44\u75fc\u86c4\u9164\u89da\u9cb4\u9ab0\u9e58","gua":"\u522e\u74dc\u5250\u5be1\u6302\u8902\u5366\u8bd6\u5471\u681d\u9e39","guai":"\u4e56\u62d0\u602a\u54d9","guan":"\u68fa\u5173\u5b98\u51a0\u89c2\u7ba1\u9986\u7f50\u60ef\u704c\u8d2f\u500c\u839e\u63bc\u6dab\u76e5\u9e73\u9ccf","guang":"\u5149\u5e7f\u901b\u72b7\u6844\u80f1\u7592","gui":"\u7470\u89c4\u572d\u7845\u5f52\u9f9f\u95fa\u8f68\u9b3c\u8be1\u7678\u6842\u67dc\u8dea\u8d35\u523d\u5326\u523f\u5e8b\u5b84\u59ab\u6867\u7085\u6677\u7688\u7c0b\u9c91\u9cdc","gun":"\u8f8a\u6eda\u68cd\u4e28\u886e\u7ef2\u78d9\u9ca7","guo":"\u9505\u90ed\u56fd\u679c\u88f9\u8fc7\u9998\u8803\u57da\u63b4\u5459\u56d7\u5e3c\u5d1e\u7313\u6901\u8662\u951e\u8052\u872e\u873e\u8748","ha":"\u54c8","hai":"\u9ab8\u5b69\u6d77\u6c26\u4ea5\u5bb3\u9a87\u54b4\u55e8\u988f\u91a2","han":"\u9163\u61a8\u90af\u97e9\u542b\u6db5\u5bd2\u51fd\u558a\u7f55\u7ff0\u64bc\u634d\u65f1\u61be\u608d\u710a\u6c57\u6c49\u9097\u83e1\u6496\u961a\u701a\u6657\u7113\u9894\u86b6\u9f3e","hen":"\u592f\u75d5\u5f88\u72e0\u6068","hang":"\u676d\u822a\u6c86\u7ed7\u73e9\u6841","hao":"\u58d5\u568e\u8c6a\u6beb\u90dd\u597d\u8017\u53f7\u6d69\u8585\u55e5\u5686\u6fe0\u704f\u660a\u7693\u98a2\u869d","he":"\u5475\u559d\u8377\u83cf\u6838\u79be\u548c\u4f55\u5408\u76d2\u8c89\u9602\u6cb3\u6db8\u8d6b\u8910\u9e64\u8d3a\u8bc3\u52be\u58d1\u85ff\u55d1\u55ec\u9616\u76cd\u86b5\u7fee","hei":"\u563f\u9ed1","heng":"\u54fc\u4ea8\u6a2a\u8861\u6052\u8a07\u8605","hong":"\u8f70\u54c4\u70d8\u8679\u9e3f\u6d2a\u5b8f\u5f18\u7ea2\u9ec9\u8ba7\u836d\u85a8\u95f3\u6cd3","hou":"\u5589\u4faf\u7334\u543c\u539a\u5019\u540e\u5820\u5f8c\u9005\u760a\u7bcc\u7cc7\u9c8e\u9aba","hu":"\u547c\u4e4e\u5ffd\u745a\u58f6\u846b\u80e1\u8774\u72d0\u7cca\u6e56\u5f27\u864e\u552c\u62a4\u4e92\u6caa\u6237\u51b1\u553f\u56eb\u5cb5\u7322\u6019\u60da\u6d52\u6ef9\u7425\u69f2\u8f77\u89f3\u70c0\u7173\u623d\u6248\u795c\u9e55\u9e71\u7b0f\u9190\u659b","hua":"\u82b1\u54d7\u534e\u733e\u6ed1\u753b\u5212\u5316\u8bdd\u5290\u6d4d\u9a85\u6866\u94e7\u7a1e","huai":"\u69d0\u5f8a\u6000\u6dee\u574f\u8fd8\u8e1d","huan":"\u6b22\u73af\u6853\u7f13\u6362\u60a3\u5524\u75ea\u8c62\u7115\u6da3\u5ba6\u5e7b\u90c7\u5942\u57b8\u64d0\u571c\u6d39\u6d63\u6f36\u5bf0\u902d\u7f33\u953e\u9ca9\u9b1f","huang":"\u8352\u614c\u9ec4\u78fa\u8757\u7c27\u7687\u51f0\u60f6\u714c\u6643\u5e4c\u604d\u8c0e\u968d\u5fa8\u6e5f\u6f62\u9051\u749c\u8093\u7640\u87e5\u7bc1\u9cc7","hui":"\u7070\u6325\u8f89\u5fbd\u6062\u86d4\u56de\u6bc1\u6094\u6167\u5349\u60e0\u6666\u8d3f\u79fd\u4f1a\u70e9\u6c47\u8bb3\u8bf2\u7ed8\u8bd9\u8334\u835f\u8559\u54d5\u5599\u96b3\u6d04\u5f57\u7f0b\u73f2\u6656\u605a\u867a\u87ea\u9ebe","hun":"\u8364\u660f\u5a5a\u9b42\u6d51\u6df7\u8be8\u9984\u960d\u6eb7\u7f17","huo":"\u8c41\u6d3b\u4f19\u706b\u83b7\u6216\u60d1\u970d\u8d27\u7978\u6509\u56af\u5925\u94ac\u952a\u956c\u8020\u8816","ji":"\u51fb\u573e\u57fa\u673a\u7578\u7a3d\u79ef\u7b95\u808c\u9965\u8ff9\u6fc0\u8ba5\u9e21\u59ec\u7ee9\u7f09\u5409\u6781\u68d8\u8f91\u7c4d\u96c6\u53ca\u6025\u75be\u6c72\u5373\u5ac9\u7ea7\u6324\u51e0\u810a\u5df1\u84df\u6280\u5180\u5b63\u4f0e\u796d\u5242\u60b8\u6d4e\u5bc4\u5bc2\u8ba1\u8bb0\u65e2\u5fcc\u9645\u5993\u7ee7\u7eaa\u5c45\u4e0c\u4e69\u525e\u4f76\u4f74\u8114\u58bc\u82a8\u82b0\u8401\u84ba\u857a\u638e\u53fd\u54ad\u54dc\u5527\u5c8c\u5d74\u6d0e\u5f50\u5c50\u9aa5\u757f\u7391\u696b\u6b9b\u621f\u6222\u8d4d\u89ca\u7284\u9f51\u77f6\u7f81\u5d47\u7a37\u7620\u7635\u866e\u7b08\u7b04\u66a8\u8dfb\u8dfd\u9701\u9c9a\u9cab\u9afb\u9e82","jia":"\u5609\u67b7\u5939\u4f73\u5bb6\u52a0\u835a\u988a\u8d3e\u7532\u94be\u5047\u7a3c\u4ef7\u67b6\u9a7e\u5ac1\u4f3d\u90cf\u62ee\u5cac\u6d43\u8fe6\u73c8\u621b\u80db\u605d\u94d7\u9553\u75c2\u86f1\u7b33\u8888\u8dcf","jian":"\u6b7c\u76d1\u575a\u5c16\u7b3a\u95f4\u714e\u517c\u80a9\u8270\u5978\u7f04\u8327\u68c0\u67ec\u78b1\u7877\u62e3\u6361\u7b80\u4fed\u526a\u51cf\u8350\u69db\u9274\u8df5\u8d31\u89c1\u952e\u7bad\u4ef6\u5065\u8230\u5251\u996f\u6e10\u6e85\u6da7\u5efa\u50ed\u8c0f\u8c2b\u83c5\u84b9\u641b\u56dd\u6e54\u8e47\u8b07\u7f23\u67a7\u67d9\u6957\u620b\u622c\u726e\u728d\u6bfd\u8171\u7751\u950f\u9e63\u88e5\u7b15\u7bb4\u7fe6\u8dbc\u8e3a\u9ca3\u97af","jiang":"\u50f5\u59dc\u5c06\u6d46\u6c5f\u7586\u848b\u6868\u5956\u8bb2\u5320\u9171\u964d\u8333\u6d1a\u7edb\u7f30\u729f\u7913\u8029\u7ce8\u8c47","jiao":"\u8549\u6912\u7901\u7126\u80f6\u4ea4\u90ca\u6d47\u9a84\u5a07\u56bc\u6405\u94f0\u77eb\u4fa5\u811a\u72e1\u89d2\u997a\u7f34\u7ede\u527f\u6559\u9175\u8f7f\u8f83\u53eb\u4f7c\u50ec\u832d\u6322\u564d\u5ce4\u5fbc\u59e3\u7e9f\u656b\u768e\u9e6a\u86df\u91ae\u8de4\u9c9b","jie":"\u7a96\u63ed\u63a5\u7686\u79f8\u8857\u9636\u622a\u52ab\u8282\u6854\u6770\u6377\u776b\u7aed\u6d01\u7ed3\u89e3\u59d0\u6212\u85c9\u82a5\u754c\u501f\u4ecb\u75a5\u8beb\u5c4a\u5048\u8ba6\u8bd8\u5588\u55df\u736c\u5a55\u5b51\u6840\u7352\u78a3\u9534\u7596\u88b7\u9889\u86a7\u7faf\u9c92\u9ab1\u9aeb","jin":"\u5dfe\u7b4b\u65a4\u91d1\u4eca\u6d25\u895f\u7d27\u9526\u4ec5\u8c28\u8fdb\u9773\u664b\u7981\u8fd1\u70ec\u6d78\u5c3d\u537a\u8369\u5807\u5664\u9991\u5ed1\u5997\u7f19\u747e\u69ff\u8d46\u89d0\u9485\u9513\u887f\u77dc","jing":"\u52b2\u8346\u5162\u830e\u775b\u6676\u9cb8\u4eac\u60ca\u7cbe\u7cb3\u7ecf\u4e95\u8b66\u666f\u9888\u9759\u5883\u656c\u955c\u5f84\u75c9\u9756\u7adf\u7ade\u51c0\u522d\u5106\u9631\u83c1\u734d\u61ac\u6cfe\u8ff3\u5f2a\u5a67\u80bc\u80eb\u8148\u65cc","jiong":"\u70af\u7a98\u5182\u8fe5\u6243","jiu":"\u63ea\u7a76\u7ea0\u7396\u97ed\u4e45\u7078\u4e5d\u9152\u53a9\u6551\u65e7\u81fc\u8205\u548e\u5c31\u759a\u50e6\u557e\u9604\u67e9\u6855\u9e6b\u8d73\u9b0f","ju":"\u97a0\u62d8\u72d9\u75bd\u9a79\u83ca\u5c40\u5480\u77e9\u4e3e\u6cae\u805a\u62d2\u636e\u5de8\u5177\u8ddd\u8e1e\u952f\u4ff1\u53e5\u60e7\u70ac\u5267\u5028\u8bb5\u82e3\u82f4\u8392\u63ac\u907d\u5c66\u741a\u67b8\u6910\u6998\u6989\u6a58\u728b\u98d3\u949c\u9514\u7aad\u88fe\u8d84\u91b5\u8e3d\u9f83\u96ce\u97ab","juan":"\u6350\u9e43\u5a1f\u5026\u7737\u5377\u7ee2\u9104\u72f7\u6d93\u684a\u8832\u9529\u954c\u96bd","jue":"\u6485\u652b\u6289\u6398\u5014\u7235\u89c9\u51b3\u8bc0\u7edd\u53a5\u5282\u8c32\u77cd\u8568\u5658\u5d1b\u7357\u5b53\u73cf\u6877\u6a5b\u721d\u9562\u8e76\u89d6","jun":"\u5747\u83cc\u94a7\u519b\u541b\u5cfb\u4fca\u7ae3\u6d5a\u90e1\u9a8f\u6343\u72fb\u76b2\u7b60\u9e87","ka":"\u5580\u5496\u5361\u4f67\u5494\u80e9","ke":"\u54af\u5777\u82db\u67ef\u68f5\u78d5\u9897\u79d1\u58f3\u54b3\u53ef\u6e34\u514b\u523b\u5ba2\u8bfe\u5ca2\u606a\u6e98\u9a92\u7f02\u73c2\u8f72\u6c2a\u778c\u94b6\u75b4\u7aa0\u874c\u9ac1","kai":"\u5f00\u63e9\u6977\u51ef\u6168\u5240\u57b2\u8488\u5ffe\u607a\u94e0\u950e","kan":"\u520a\u582a\u52d8\u574e\u780d\u770b\u4f83\u51f5\u83b0\u83b6\u6221\u9f9b\u77b0","kang":"\u5eb7\u6177\u7ce0\u625b\u6297\u4ea2\u7095\u5751\u4f09\u95f6\u94aa","kao":"\u8003\u62f7\u70e4\u9760\u5c3b\u6832\u7292\u94d0","ken":"\u80af\u5543\u57a6\u6073\u57a0\u88c9\u9880","keng":"\u542d\u5fd0\u94ff","kong":"\u7a7a\u6050\u5b54\u63a7\u5025\u5d06\u7b9c","kou":"\u62a0\u53e3\u6263\u5bc7\u82a4\u853b\u53e9\u770d\u7b58","ku":"\u67af\u54ed\u7a9f\u82e6\u9177\u5e93\u88e4\u5233\u5800\u55be\u7ed4\u9ab7","kua":"\u5938\u57ae\u630e\u8de8\u80ef\u4f89","kuai":"\u5757\u7b77\u4fa9\u5feb\u84af\u90d0\u8489\u72ef\u810d","kuan":"\u5bbd\u6b3e\u9acb","kuang":"\u5321\u7b50\u72c2\u6846\u77ff\u7736\u65f7\u51b5\u8bd3\u8bf3\u909d\u5739\u593c\u54d0\u7ea9\u8d36","kui":"\u4e8f\u76d4\u5cbf\u7aa5\u8475\u594e\u9b41\u5080\u9988\u6127\u6e83\u9997\u532e\u5914\u9697\u63c6\u55b9\u559f\u609d\u6126\u9615\u9035\u668c\u777d\u8069\u8770\u7bd1\u81fe\u8dec","kun":"\u5764\u6606\u6346\u56f0\u6083\u9603\u7428\u951f\u918c\u9cb2\u9ae1","kuo":"\u62ec\u6269\u5ed3\u9614\u86de","la":"\u5783\u62c9\u5587\u8721\u814a\u8fa3\u5566\u524c\u647a\u908b\u65ef\u782c\u760c","lai":"\u83b1\u6765\u8d56\u5d03\u5f95\u6d9e\u6fd1\u8d49\u7750\u94fc\u765e\u7c41","lan":"\u84dd\u5a6a\u680f\u62e6\u7bee\u9611\u5170\u6f9c\u8c30\u63fd\u89c8\u61d2\u7f06\u70c2\u6ee5\u5549\u5c9a\u61d4\u6f24\u6984\u6593\u7f71\u9567\u8934","lang":"\u7405\u6994\u72fc\u5eca\u90ce\u6717\u6d6a\u83a8\u8497\u5577\u9606\u9512\u7a02\u8782","lao":"\u635e\u52b3\u7262\u8001\u4f6c\u59e5\u916a\u70d9\u6d9d\u5520\u5d02\u6833\u94d1\u94f9\u75e8\u91aa","le":"\u52d2\u4e50\u808b\u4ec2\u53fb\u561e\u6cd0\u9cd3","lei":"\u96f7\u956d\u857e\u78ca\u7d2f\u5121\u5792\u64c2\u7c7b\u6cea\u7fb8\u8bd4\u837d\u54a7\u6f2f\u5ad8\u7f27\u6a91\u8012\u9179","ling":"\u68f1\u51b7\u62ce\u73b2\u83f1\u96f6\u9f84\u94c3\u4f36\u7f9a\u51cc\u7075\u9675\u5cad\u9886\u53e6\u4ee4\u9143\u5844\u82d3\u5464\u56f9\u6ce0\u7eeb\u67c3\u68c2\u74f4\u8046\u86c9\u7fce\u9cae","leng":"\u695e\u6123","li":"\u5398\u68a8\u7281\u9ece\u7bf1\u72f8\u79bb\u6f13\u7406\u674e\u91cc\u9ca4\u793c\u8389\u8354\u540f\u6817\u4e3d\u5389\u52b1\u783e\u5386\u5229\u5088\u4f8b\u4fd0\u75e2\u7acb\u7c92\u6ca5\u96b6\u529b\u7483\u54e9\u4fea\u4fda\u90e6\u575c\u82c8\u8385\u84e0\u85dc\u6369\u5456\u5533\u55b1\u7301\u6ea7\u6fa7\u9026\u5a0c\u5ae0\u9a8a\u7f21\u73de\u67a5\u680e\u8f79\u623e\u783a\u8a48\u7f79\u9502\u9e42\u75a0\u75ac\u86ce\u870a\u8821\u7b20\u7be5\u7c9d\u91b4\u8dde\u96f3\u9ca1\u9ce2\u9ee7","lian":"\u4fe9\u8054\u83b2\u8fde\u9570\u5ec9\u601c\u6d9f\u5e18\u655b\u8138\u94fe\u604b\u70bc\u7ec3\u631b\u8539\u5941\u6f4b\u6fc2\u5a08\u740f\u695d\u6b93\u81c1\u81a6\u88e2\u880a\u9ca2","liang":"\u7cae\u51c9\u6881\u7cb1\u826f\u4e24\u8f86\u91cf\u667e\u4eae\u8c05\u589a\u690b\u8e09\u9753\u9b49","liao":"\u64a9\u804a\u50da\u7597\u71ce\u5be5\u8fbd\u6f66\u4e86\u6482\u9563\u5ed6\u6599\u84fc\u5c25\u5639\u7360\u5bee\u7f2d\u948c\u9e69\u8022","lie":"\u5217\u88c2\u70c8\u52a3\u730e\u51bd\u57d2\u6d0c\u8d94\u8e90\u9b23","lin":"\u7433\u6797\u78f7\u9716\u4e34\u90bb\u9cde\u6dcb\u51db\u8d41\u541d\u853a\u5d99\u5eea\u9074\u6aa9\u8f9a\u77b5\u7cbc\u8e8f\u9e9f","liu":"\u6e9c\u7409\u69b4\u786b\u998f\u7559\u5218\u7624\u6d41\u67f3\u516d\u62a1\u507b\u848c\u6cd6\u6d4f\u905b\u9a9d\u7efa\u65d2\u7198\u950d\u954f\u9e68\u938f","long":"\u9f99\u804b\u5499\u7b3c\u7abf\u9686\u5784\u62e2\u9647\u5f04\u5785\u830f\u6cf7\u73d1\u680a\u80e7\u783b\u7643","lou":"\u697c\u5a04\u6402\u7bd3\u6f0f\u964b\u55bd\u5d5d\u9542\u7618\u8027\u877c\u9ac5","lu":"\u82a6\u5362\u9885\u5e90\u7089\u63b3\u5364\u864f\u9c81\u9e93\u788c\u9732\u8def\u8d42\u9e7f\u6f5e\u7984\u5f55\u9646\u622e\u5786\u6445\u64b8\u565c\u6cf8\u6e0c\u6f09\u7490\u680c\u6a79\u8f73\u8f82\u8f98\u6c07\u80ea\u9565\u9e2c\u9e6d\u7c0f\u823b\u9c88","lv":"\u9a74\u5415\u94dd\u4fa3\u65c5\u5c65\u5c61\u7f15\u8651\u6c2f\u5f8b\u7387\u6ee4\u7eff\u634b\u95fe\u6988\u8182\u7a06\u891b","luan":"\u5ce6\u5b6a\u6ee6\u5375\u4e71\u683e\u9e3e\u92ae","lue":"\u63a0\u7565\u950a","lun":"\u8f6e\u4f26\u4ed1\u6ca6\u7eb6\u8bba\u56f5","luo":"\u841d\u87ba\u7f57\u903b\u9523\u7ba9\u9aa1\u88f8\u843d\u6d1b\u9a86\u7edc\u502e\u8366\u645e\u7321\u6cfa\u6924\u8136\u9559\u7630\u96d2","ma":"\u5988\u9ebb\u739b\u7801\u8682\u9a6c\u9a82\u561b\u5417\u551b\u72b8\u5b37\u6769\u9ebd","mai":"\u57cb\u4e70\u9ea6\u5356\u8fc8\u8109\u52a2\u836c\u54aa\u973e","man":"\u7792\u9992\u86ee\u6ee1\u8513\u66fc\u6162\u6f2b\u8c29\u5881\u5e54\u7f26\u71b3\u9558\u989f\u87a8\u9cd7\u9794","mang":"\u8292\u832b\u76f2\u5fd9\u83bd\u9099\u6f2d\u6726\u786d\u87d2","meng":"\u6c13\u840c\u8499\u6aac\u76df\u9530\u731b\u68a6\u5b5f\u52d0\u750d\u77a2\u61f5\u791e\u867b\u8722\u8813\u824b\u8268\u9efe","miao":"\u732b\u82d7\u63cf\u7784\u85d0\u79d2\u6e3a\u5e99\u5999\u55b5\u9088\u7f08\u7f2a\u676a\u6dfc\u7707\u9e4b\u8731","mao":"\u8305\u951a\u6bdb\u77db\u94c6\u536f\u8302\u5192\u5e3d\u8c8c\u8d38\u4f94\u88a4\u52d6\u8306\u5cc1\u7441\u6634\u7266\u8004\u65c4\u61cb\u7780\u86d1\u8765\u87ca\u9ae6","me":"\u4e48","mei":"\u73ab\u679a\u6885\u9176\u9709\u7164\u6ca1\u7709\u5a92\u9541\u6bcf\u7f8e\u6627\u5bd0\u59b9\u5a9a\u5776\u8393\u5d4b\u7338\u6d7c\u6e44\u6963\u9545\u9e5b\u8882\u9b45","men":"\u95e8\u95f7\u4eec\u626a\u739f\u7116\u61d1\u9494","mi":"\u772f\u919a\u9761\u7cdc\u8ff7\u8c1c\u5f25\u7c73\u79d8\u89c5\u6ccc\u871c\u5bc6\u5e42\u8288\u5196\u8c27\u863c\u5627\u7315\u736f\u6c68\u5b93\u5f2d\u8112\u6549\u7cf8\u7e3b\u9e8b","mian":"\u68c9\u7720\u7ef5\u5195\u514d\u52c9\u5a29\u7f05\u9762\u6c94\u6e4e\u817c\u7704","mie":"\u8511\u706d\u54a9\u881b\u7bfe","min":"\u6c11\u62bf\u76bf\u654f\u60af\u95fd\u82e0\u5cb7\u95f5\u6cef\u73c9","ming":"\u660e\u879f\u9e23\u94ed\u540d\u547d\u51a5\u8317\u6e9f\u669d\u7791\u9169","miu":"\u8c2c","mo":"\u6478\u6479\u8611\u6a21\u819c\u78e8\u6469\u9b54\u62b9\u672b\u83ab\u58a8\u9ed8\u6cab\u6f20\u5bde\u964c\u8c1f\u8309\u84e6\u998d\u5aeb\u9546\u79e3\u763c\u8031\u87c6\u8c8a\u8c98","mou":"\u8c0b\u725f\u67d0\u53b6\u54de\u5a7a\u7738\u936a","mu":"\u62c7\u7261\u4ea9\u59c6\u6bcd\u5893\u66ae\u5e55\u52df\u6155\u6728\u76ee\u7766\u7267\u7a46\u4eeb\u82dc\u5452\u6c90\u6bea\u94bc","na":"\u62ff\u54ea\u5450\u94a0\u90a3\u5a1c\u7eb3\u5185\u637a\u80ad\u954e\u8872\u7bac","nai":"\u6c16\u4e43\u5976\u8010\u5948\u9f10\u827f\u8418\u67f0","nan":"\u5357\u7537\u96be\u56ca\u5583\u56e1\u6960\u8169\u877b\u8d67","nao":"\u6320\u8111\u607c\u95f9\u5b6c\u57b4\u7331\u7459\u7847\u94d9\u86f2","ne":"\u6dd6\u5462\u8bb7","nei":"\u9981","nen":"\u5ae9\u80fd\u6798\u6041","ni":"\u59ae\u9713\u502a\u6ce5\u5c3c\u62df\u4f60\u533f\u817b\u9006\u6eba\u4f32\u576d\u730a\u6029\u6ee0\u6635\u65ce\u7962\u615d\u7768\u94cc\u9cb5","nian":"\u852b\u62c8\u5e74\u78be\u64b5\u637b\u5ff5\u5eff\u8f87\u9ecf\u9c87\u9cb6","niang":"\u5a18\u917f","niao":"\u9e1f\u5c3f\u8311\u5b32\u8132\u8885","nie":"\u634f\u8042\u5b7d\u556e\u954a\u954d\u6d85\u4e5c\u9667\u8616\u55eb\u8080\u989e\u81ec\u8e51","nin":"\u60a8\u67e0","ning":"\u72de\u51dd\u5b81\u62e7\u6cde\u4f5e\u84e5\u549b\u752f\u804d","niu":"\u725b\u626d\u94ae\u7ebd\u72c3\u5ff8\u599e\u86b4","nong":"\u8113\u6d53\u519c\u4fac","nu":"\u5974\u52aa\u6012\u5476\u5e11\u5f29\u80ec\u5b65\u9a7d","nv":"\u5973\u6067\u9495\u8844","nuan":"\u6696","nuenue":"\u8650","nue":"\u759f\u8c11","nuo":"\u632a\u61e6\u7cef\u8bfa\u50a9\u6426\u558f\u9518","ou":"\u54e6\u6b27\u9e25\u6bb4\u85d5\u5455\u5076\u6ca4\u6004\u74ef\u8026","pa":"\u556a\u8db4\u722c\u5e15\u6015\u7436\u8469\u7b62","pai":"\u62cd\u6392\u724c\u5f98\u6e43\u6d3e\u4ff3\u848e","pan":"\u6500\u6f58\u76d8\u78d0\u76fc\u7554\u5224\u53db\u723f\u6cee\u88a2\u897b\u87e0\u8e52","pang":"\u4e53\u5e9e\u65c1\u802a\u80d6\u6ec2\u9004","pao":"\u629b\u5486\u5228\u70ae\u888d\u8dd1\u6ce1\u530f\u72cd\u5e96\u812c\u75b1","pei":"\u5478\u80da\u57f9\u88f4\u8d54\u966a\u914d\u4f69\u6c9b\u638a\u8f94\u5e14\u6de0\u65c6\u952b\u9185\u9708","pen":"\u55b7\u76c6\u6e53","peng":"\u7830\u62a8\u70f9\u6f8e\u5f6d\u84ec\u68da\u787c\u7bf7\u81a8\u670b\u9e4f\u6367\u78b0\u576f\u580b\u562d\u6026\u87db","pi":"\u7812\u9739\u6279\u62ab\u5288\u7435\u6bd7\u5564\u813e\u75b2\u76ae\u5339\u75de\u50fb\u5c41\u8b6c\u4e15\u9674\u90b3\u90eb\u572e\u9f19\u64d7\u567c\u5e80\u5ab2\u7eb0\u6787\u7513\u7765\u7f74\u94cd\u75e6\u7656\u758b\u868d\u8c94","pian":"\u7bc7\u504f\u7247\u9a97\u8c1d\u9a88\u728f\u80fc\u890a\u7fe9\u8e41","piao":"\u98d8\u6f02\u74e2\u7968\u527d\u560c\u5ad6\u7f25\u6b8d\u779f\u87b5","pie":"\u6487\u77a5\u4e3f\u82e4\u6c15","pin":"\u62fc\u9891\u8d2b\u54c1\u8058\u62da\u59d8\u5ad4\u6980\u725d\u98a6","ping":"\u4e52\u576a\u82f9\u840d\u5e73\u51ed\u74f6\u8bc4\u5c4f\u4fdc\u5a09\u67b0\u9c86","po":"\u5761\u6cfc\u9887\u5a46\u7834\u9b44\u8feb\u7c95\u53f5\u9131\u6ea5\u73c0\u948b\u94b7\u76a4\u7b38","pou":"\u5256\u88d2\u8e23","pu":"\u6251\u94fa\u4ec6\u8386\u8461\u83e9\u84b2\u57d4\u6734\u5703\u666e\u6d66\u8c31\u66dd\u7011\u530d\u5657\u6fee\u749e\u6c06\u9564\u9568\u8e7c","qi":"\u671f\u6b3a\u6816\u621a\u59bb\u4e03\u51c4\u6f06\u67d2\u6c8f\u5176\u68cb\u5947\u6b67\u7566\u5d0e\u8110\u9f50\u65d7\u7948\u7941\u9a91\u8d77\u5c82\u4e5e\u4f01\u542f\u5951\u780c\u5668\u6c14\u8fc4\u5f03\u6c7d\u6ce3\u8bab\u4e9f\u4e93\u573b\u8291\u840b\u847a\u5601\u5c7a\u5c90\u6c54\u6dc7\u9a90\u7eee\u742a\u7426\u675e\u6864\u69ed\u6b39\u797a\u61a9\u789b\u86f4\u871e\u7da6\u7dae\u8dbf\u8e4a\u9ccd\u9e92","qia":"\u6390\u6070\u6d3d\u845c","qian":"\u7275\u6266\u948e\u94c5\u5343\u8fc1\u7b7e\u4edf\u8c26\u4e7e\u9ed4\u94b1\u94b3\u524d\u6f5c\u9063\u6d45\u8c34\u5811\u5d4c\u6b20\u6b49\u4f65\u9621\u828a\u82a1\u8368\u63ae\u5c8d\u60ad\u614a\u9a9e\u6434\u8930\u7f31\u6920\u80b7\u6106\u94a4\u8654\u7b9d","qiang":"\u67aa\u545b\u8154\u7f8c\u5899\u8537\u5f3a\u62a2\u5af1\u6a2f\u6217\u709d\u9516\u9535\u956a\u8941\u8723\u7f9f\u8deb\u8dc4","qiao":"\u6a47\u9539\u6572\u6084\u6865\u77a7\u4e54\u4fa8\u5de7\u9798\u64ac\u7fd8\u5ced\u4fcf\u7a8d\u5281\u8bee\u8c2f\u835e\u6100\u6194\u7f32\u6a35\u6bf3\u7857\u8df7\u9792","qie":"\u5207\u8304\u4e14\u602f\u7a83\u90c4\u553c\u60ec\u59be\u6308\u9532\u7ba7","qin":"\u94a6\u4fb5\u4eb2\u79e6\u7434\u52e4\u82b9\u64d2\u79bd\u5bdd\u6c81\u82a9\u84c1\u8572\u63ff\u5423\u55ea\u5659\u6eb1\u6a8e\u8793\u887e","qing":"\u9752\u8f7b\u6c22\u503e\u537f\u6e05\u64ce\u6674\u6c30\u60c5\u9877\u8bf7\u5e86\u5029\u82d8\u570a\u6aa0\u78ec\u873b\u7f44\u7b90\u8b26\u9cad\u9ee5","qiong":"\u743c\u7a77\u909b\u8315\u7a79\u7b47\u928e","qiu":"\u79cb\u4e18\u90b1\u7403\u6c42\u56da\u914b\u6cc5\u4fc5\u6c3d\u5def\u827d\u72b0\u6e6b\u9011\u9052\u6978\u8d47\u9e20\u866c\u86af\u8764\u88d8\u7cd7\u9cc5\u9f3d","qu":"\u8d8b\u533a\u86c6\u66f2\u8eaf\u5c48\u9a71\u6e20\u53d6\u5a36\u9f8b\u8da3\u53bb\u8bce\u52ac\u8556\u8627\u5c96\u8862\u9612\u74a9\u89d1\u6c0d\u795b\u78f2\u766f\u86d0\u883c\u9eb4\u77bf\u9ee2","quan":"\u5708\u98a7\u6743\u919b\u6cc9\u5168\u75ca\u62f3\u72ac\u5238\u529d\u8be0\u8343\u737e\u609b\u7efb\u8f81\u754e\u94e8\u8737\u7b4c\u9b08","que":"\u7f3a\u7094\u7638\u5374\u9e4a\u69b7\u786e\u96c0\u9619\u60ab","qun":"\u88d9\u7fa4\u9021","ran":"\u7136\u71c3\u5189\u67d3\u82d2\u9aef","rang":"\u74e4\u58e4\u6518\u56b7\u8ba9\u79b3\u7a70","rao":"\u9976\u6270\u7ed5\u835b\u5a06\u6861","ruo":"\u60f9\u82e5\u5f31","re":"\u70ed\u504c","ren":"\u58ec\u4ec1\u4eba\u5fcd\u97e7\u4efb\u8ba4\u5203\u598a\u7eab\u4ede\u834f\u845a\u996a\u8f6b\u7a14\u887d","reng":"\u6254\u4ecd","ri":"\u65e5","rong":"\u620e\u8338\u84c9\u8363\u878d\u7194\u6eb6\u5bb9\u7ed2\u5197\u5d58\u72e8\u7f1b\u6995\u877e","rou":"\u63c9\u67d4\u8089\u7cc5\u8e42\u97a3","ru":"\u8339\u8815\u5112\u5b7a\u5982\u8fb1\u4e73\u6c5d\u5165\u8925\u84d0\u85b7\u5685\u6d33\u6ebd\u6fe1\u94f7\u8966\u98a5","ruan":"\u8f6f\u962e\u670a","rui":"\u854a\u745e\u9510\u82ae\u8564\u777f\u868b","run":"\u95f0\u6da6","sa":"\u6492\u6d12\u8428\u5345\u4ee8\u6332\u98d2","sai":"\u816e\u9cc3\u585e\u8d5b\u567b","san":"\u4e09\u53c1\u4f1e\u6563\u5f61\u9993\u6c35\u6bf5\u7cc1\u9730","sang":"\u6851\u55d3\u4e27\u6421\u78c9\u98a1","sao":"\u6414\u9a9a\u626b\u5ac2\u57fd\u81ca\u7619\u9ccb","se":"\u745f\u8272\u6da9\u556c\u94e9\u94ef\u7a51","sen":"\u68ee","seng":"\u50e7","sha":"\u838e\u7802\u6740\u5239\u6c99\u7eb1\u50bb\u5565\u715e\u810e\u6b43\u75e7\u88df\u970e\u9ca8","shai":"\u7b5b\u6652\u917e","shan":"\u73ca\u82eb\u6749\u5c71\u5220\u717d\u886b\u95ea\u9655\u64c5\u8d61\u81b3\u5584\u6c55\u6247\u7f2e\u5261\u8baa\u912f\u57cf\u829f\u6f78\u59d7\u9a9f\u81bb\u9490\u759d\u87ee\u8222\u8dda\u9cdd","shang":"\u5892\u4f24\u5546\u8d4f\u664c\u4e0a\u5c1a\u88f3\u57a7\u7ef1\u6b87\u71b5\u89de","shao":"\u68a2\u634e\u7a0d\u70e7\u828d\u52fa\u97f6\u5c11\u54e8\u90b5\u7ecd\u52ad\u82d5\u6f72\u86f8\u7b24\u7b72\u8244","she":"\u5962\u8d4a\u86c7\u820c\u820d\u8d66\u6444\u5c04\u6151\u6d89\u793e\u8bbe\u538d\u4f58\u731e\u7572\u9e9d","shen":"\u7837\u7533\u547b\u4f38\u8eab\u6df1\u5a20\u7ec5\u795e\u6c88\u5ba1\u5a76\u751a\u80be\u614e\u6e17\u8bdc\u8c02\u5432\u54c2\u6e16\u6939\u77e7\u8703","sheng":"\u58f0\u751f\u7525\u7272\u5347\u7ef3\u7701\u76db\u5269\u80dc\u5723\u4e1e\u6e11\u5ab5\u771a\u7b19","shi":"\u5e08\u5931\u72ee\u65bd\u6e7f\u8bd7\u5c38\u8671\u5341\u77f3\u62fe\u65f6\u4ec0\u98df\u8680\u5b9e\u8bc6\u53f2\u77e2\u4f7f\u5c4e\u9a76\u59cb\u5f0f\u793a\u58eb\u4e16\u67ff\u4e8b\u62ed\u8a93\u901d\u52bf\u662f\u55dc\u566c\u9002\u4ed5\u4f8d\u91ca\u9970\u6c0f\u5e02\u6043\u5ba4\u89c6\u8bd5\u8c25\u57d8\u83b3\u84cd\u5f11\u5511\u9963\u8f7c\u8006\u8d33\u70bb\u793b\u94c8\u94ca\u87ab\u8210\u7b6e\u8c55\u9ca5\u9cba","shou":"\u6536\u624b\u9996\u5b88\u5bff\u6388\u552e\u53d7\u7626\u517d\u624c\u72e9\u7ef6\u824f","shu":"\u852c\u67a2\u68b3\u6b8a\u6292\u8f93\u53d4\u8212\u6dd1\u758f\u4e66\u8d4e\u5b70\u719f\u85af\u6691\u66d9\u7f72\u8700\u9ecd\u9f20\u5c5e\u672f\u8ff0\u6811\u675f\u620d\u7ad6\u5885\u5eb6\u6570\u6f31\u6055\u500f\u587e\u83fd\u5fc4\u6cad\u6d91\u6f8d\u59dd\u7ebe\u6bf9\u8167\u6bb3\u956f\u79eb\u9e6c","shua":"\u5237\u800d\u5530\u6dae","shuai":"\u6454\u8870\u7529\u5e05\u87c0","shuan":"\u6813\u62f4\u95e9","shuang":"\u971c\u53cc\u723d\u5b40","shui":"\u8c01\u6c34\u7761\u7a0e","shun":"\u542e\u77ac\u987a\u821c\u6042","shuo":"\u8bf4\u7855\u6714\u70c1\u84b4\u6420\u55cd\u6fef\u5981\u69ca\u94c4","si":"\u65af\u6495\u5636\u601d\u79c1\u53f8\u4e1d\u6b7b\u8086\u5bfa\u55e3\u56db\u4f3a\u4f3c\u9972\u5df3\u53ae\u4fdf\u5155\u83e5\u549d\u6c5c\u6cd7\u6f8c\u59d2\u9a77\u7f0c\u7940\u7960\u9536\u9e36\u801c\u86f3\u7b25","song":"\u677e\u8038\u6002\u9882\u9001\u5b8b\u8bbc\u8bf5\u51c7\u83d8\u5d27\u5d69\u5fea\u609a\u6dde\u7ae6","sou":"\u641c\u8258\u64de\u55fd\u53df\u55d6\u55fe\u998a\u6eb2\u98d5\u778d\u953c\u878b","su":"\u82cf\u9165\u4fd7\u7d20\u901f\u7c9f\u50f3\u5851\u6eaf\u5bbf\u8bc9\u8083\u5919\u8c21\u850c\u55c9\u612b\u7c0c\u89eb\u7a23","suan":"\u9178\u849c\u7b97","sui":"\u867d\u968b\u968f\u7ee5\u9ad3\u788e\u5c81\u7a57\u9042\u96a7\u795f\u84d1\u51ab\u8c07\u6fc9\u9083\u71e7\u772d\u7762","sun":"\u5b59\u635f\u7b0b\u836a\u72f2\u98e7\u69ab\u8de3\u96bc","suo":"\u68ad\u5506\u7f29\u7410\u7d22\u9501\u6240\u5522\u55e6\u5a11\u686b\u7743\u7fa7","ta":"\u584c\u4ed6\u5b83\u5979\u5854\u736d\u631e\u8e4b\u8e0f\u95fc\u6ebb\u9062\u69bb\u6c93","tai":"\u80ce\u82d4\u62ac\u53f0\u6cf0\u915e\u592a\u6001\u6c70\u90b0\u85b9\u80bd\u70b1\u949b\u8dc6\u9c90","tan":"\u574d\u644a\u8d2a\u762b\u6ee9\u575b\u6a80\u75f0\u6f6d\u8c2d\u8c08\u5766\u6bef\u8892\u78b3\u63a2\u53f9\u70ad\u90ef\u8548\u6619\u94bd\u952c\u8983","tang":"\u6c64\u5858\u642a\u5802\u68e0\u819b\u5510\u7cd6\u50a5\u9967\u6e8f\u746d\u94f4\u9557\u8025\u8797\u87b3\u7fb0\u91a3","thang":"\u5018\u8eba\u6dcc","theng":"\u8d9f\u70eb","tao":"\u638f\u6d9b\u6ed4\u7ee6\u8404\u6843\u9003\u6dd8\u9676\u8ba8\u5957\u6311\u9f17\u5555\u97ec\u9955","te":"\u7279","teng":"\u85e4\u817e\u75bc\u8a8a\u6ed5","ti":"\u68af\u5254\u8e22\u9511\u63d0\u9898\u8e44\u557c\u4f53\u66ff\u568f\u60d5\u6d95\u5243\u5c49\u8351\u608c\u9016\u7ee8\u7f07\u9e48\u88fc\u918d","tian":"\u5929\u6dfb\u586b\u7530\u751c\u606c\u8214\u8146\u63ad\u5fdd\u9617\u6b84\u754b\u94bf\u86ba","tiao":"\u6761\u8fe2\u773a\u8df3\u4f7b\u7967\u94eb\u7a95\u9f86\u9ca6","tie":"\u8d34\u94c1\u5e16\u841c\u992e","ting":"\u5385\u542c\u70c3\u6c40\u5ef7\u505c\u4ead\u5ead\u633a\u8247\u839b\u8476\u5a77\u6883\u8713\u9706","tong":"\u901a\u6850\u916e\u77b3\u540c\u94dc\u5f64\u7ae5\u6876\u6345\u7b52\u7edf\u75db\u4f5f\u50ee\u4edd\u833c\u55f5\u6078\u6f7c\u783c","tou":"\u5077\u6295\u5934\u900f\u4ea0","tu":"\u51f8\u79c3\u7a81\u56fe\u5f92\u9014\u6d82\u5c60\u571f\u5410\u5154\u580d\u837c\u83df\u948d\u9174","tuan":"\u6e4d\u56e2\u7583","tui":"\u63a8\u9893\u817f\u8715\u892a\u9000\u5fd2\u717a","tun":"\u541e\u5c6f\u81c0\u9968\u66be\u8c5a\u7a80","tuo":"\u62d6\u6258\u8131\u9e35\u9640\u9a6e\u9a7c\u692d\u59a5\u62d3\u553e\u4e47\u4f57\u5768\u5eb9\u6cb1\u67dd\u7823\u7ba8\u8204\u8dce\u9f0d","wa":"\u6316\u54c7\u86d9\u6d3c\u5a03\u74e6\u889c\u4f64\u5a32\u817d","wai":"\u6b6a\u5916","wan":"\u8c4c\u5f2f\u6e7e\u73a9\u987d\u4e38\u70f7\u5b8c\u7897\u633d\u665a\u7696\u60cb\u5b9b\u5a49\u4e07\u8155\u525c\u8284\u82cb\u83c0\u7ea8\u7efe\u742c\u8118\u7579\u873f\u7ba2","wang":"\u6c6a\u738b\u4ea1\u6789\u7f51\u5f80\u65fa\u671b\u5fd8\u5984\u7f54\u5c22\u60d8\u8f8b\u9b4d","wei":"\u5a01\u5dcd\u5fae\u5371\u97e6\u8fdd\u6845\u56f4\u552f\u60df\u4e3a\u6f4d\u7ef4\u82c7\u840e\u59d4\u4f1f\u4f2a\u5c3e\u7eac\u672a\u851a\u5473\u754f\u80c3\u5582\u9b4f\u4f4d\u6e2d\u8c13\u5c09\u6170\u536b\u502d\u504e\u8bff\u9688\u8473\u8587\u5e0f\u5e37\u5d34\u5d6c\u7325\u732c\u95f1\u6ca9\u6d27\u6da0\u9036\u5a13\u73ae\u97ea\u8ece\u709c\u7168\u71a8\u75ff\u8249\u9c94","wen":"\u761f\u6e29\u868a\u6587\u95fb\u7eb9\u543b\u7a33\u7d0a\u95ee\u520e\u6120\u960c\u6c76\u74ba\u97eb\u6b81\u96ef","weng":"\u55e1\u7fc1\u74ee\u84ca\u8579","wo":"\u631d\u8717\u6da1\u7a9d\u6211\u65a1\u5367\u63e1\u6c83\u83b4\u5e44\u6e25\u674c\u809f\u9f8c","wu":"\u5deb\u545c\u94a8\u4e4c\u6c61\u8bec\u5c4b\u65e0\u829c\u68a7\u543e\u5434\u6bcb\u6b66\u4e94\u6342\u5348\u821e\u4f0d\u4fae\u575e\u620a\u96fe\u6664\u7269\u52ff\u52a1\u609f\u8bef\u5140\u4ef5\u9622\u90ac\u572c\u82b4\u5e91\u6003\u5fe4\u6d6f\u5be4\u8fd5\u59a9\u9a9b\u727e\u7110\u9e49\u9e5c\u8708\u92c8\u9f2f","xi":"\u6614\u7199\u6790\u897f\u7852\u77fd\u6670\u563b\u5438\u9521\u727a\u7a00\u606f\u5e0c\u6089\u819d\u5915\u60dc\u7184\u70ef\u6eaa\u6c50\u7280\u6a84\u88ad\u5e2d\u4e60\u5ab3\u559c\u94e3\u6d17\u7cfb\u9699\u620f\u7ec6\u50d6\u516e\u96b0\u90d7\u831c\u8478\u84f0\u595a\u550f\u5f99\u9969\u960b\u6d60\u6dc5\u5c63\u5b09\u73ba\u6a28\u66e6\u89cb\u6b37\u71b9\u798a\u79a7\u94b8\u7699\u7a78\u8725\u87cb\u823e\u7fb2\u7c9e\u7fd5\u91af\u9f37","xia":"\u778e\u867e\u5323\u971e\u8f96\u6687\u5ce1\u4fa0\u72ed\u4e0b\u53a6\u590f\u5413\u6380\u846d\u55c4\u72ce\u9050\u7455\u7856\u7615\u7f45\u9ee0","xian":"\u9528\u5148\u4ed9\u9c9c\u7ea4\u54b8\u8d24\u8854\u8237\u95f2\u6d8e\u5f26\u5acc\u663e\u9669\u73b0\u732e\u53bf\u817a\u9985\u7fa1\u5baa\u9677\u9650\u7ebf\u51bc\u85d3\u5c98\u7303\u66b9\u5a34\u6c19\u7946\u9e47\u75eb\u86ac\u7b45\u7c7c\u9170\u8df9","xiang":"\u76f8\u53a2\u9576\u9999\u7bb1\u8944\u6e58\u4e61\u7fd4\u7965\u8be6\u60f3\u54cd\u4eab\u9879\u5df7\u6a61\u50cf\u5411\u8c61\u8297\u8459\u9977\u5ea0\u9aa7\u7f03\u87d3\u9c9e\u98e8","xiao":"\u8427\u785d\u9704\u524a\u54ee\u56a3\u9500\u6d88\u5bb5\u6dc6\u6653\u5c0f\u5b5d\u6821\u8096\u5578\u7b11\u6548\u54d3\u54bb\u5d24\u6f47\u900d\u9a81\u7ee1\u67ad\u67b5\u7b71\u7bab\u9b48","xie":"\u6954\u4e9b\u6b47\u874e\u978b\u534f\u631f\u643a\u90aa\u659c\u80c1\u8c10\u5199\u68b0\u5378\u87f9\u61c8\u6cc4\u6cfb\u8c22\u5c51\u5055\u4eb5\u52f0\u71ee\u85a4\u64b7\u5ee8\u7023\u9082\u7ec1\u7f2c\u69ad\u698d\u6b59\u8e9e","xin":"\u85aa\u82af\u950c\u6b23\u8f9b\u65b0\u5ffb\u5fc3\u4fe1\u8845\u56df\u99a8\u8398\u6b46\u94fd\u946b","xing":"\u661f\u8165\u7329\u60fa\u5174\u5211\u578b\u5f62\u90a2\u884c\u9192\u5e78\u674f\u6027\u59d3\u9649\u8347\u8365\u64e4\u60bb\u784e","xiong":"\u5144\u51f6\u80f8\u5308\u6c79\u96c4\u718a\u828e","xiu":"\u4f11\u4fee\u7f9e\u673d\u55c5\u9508\u79c0\u8896\u7ee3\u83a0\u5cab\u9990\u5ea5\u9e3a\u8c85\u9af9","xu":"\u589f\u620c\u9700\u865a\u5618\u987b\u5f90\u8bb8\u84c4\u9157\u53d9\u65ed\u5e8f\u755c\u6064\u7d6e\u5a7f\u7eea\u7eed\u8bb4\u8be9\u5729\u84ff\u6035\u6d2b\u6e86\u987c\u6829\u7166\u7809\u76f1\u80e5\u7cc8\u9191","xuan":"\u8f69\u55a7\u5ba3\u60ac\u65cb\u7384\u9009\u7663\u7729\u7eda\u5107\u8c16\u8431\u63ce\u9994\u6ceb\u6d35\u6e32\u6f29\u7487\u6966\u6684\u70ab\u714a\u78b9\u94c9\u955f\u75c3","xue":"\u9774\u859b\u5b66\u7a74\u96ea\u8840\u5671\u6cf6\u9cd5","xun":"\u52cb\u718f\u5faa\u65ec\u8be2\u5bfb\u9a6f\u5de1\u6b89\u6c5b\u8bad\u8baf\u900a\u8fc5\u5dfd\u57d9\u8340\u85b0\u5ccb\u5f87\u6d54\u66db\u7aa8\u91ba\u9c9f","ya":"\u538b\u62bc\u9e26\u9e2d\u5440\u4e2b\u82bd\u7259\u869c\u5d16\u8859\u6daf\u96c5\u54d1\u4e9a\u8bb6\u4f22\u63e0\u5416\u5c88\u8fd3\u5a05\u740a\u6860\u6c29\u7811\u775a\u75d6","yan":"\u7109\u54bd\u9609\u70df\u6df9\u76d0\u4e25\u7814\u8712\u5ca9\u5ef6\u8a00\u989c\u960e\u708e\u6cbf\u5944\u63a9\u773c\u884d\u6f14\u8273\u5830\u71d5\u538c\u781a\u96c1\u5501\u5f66\u7130\u5bb4\u8c1a\u9a8c\u53a3\u9765\u8d5d\u4fe8\u5043\u5156\u8ba0\u8c33\u90fe\u9122\u82ab\u83f8\u5d26\u6079\u95eb\u960f\u6d07\u6e6e\u6edf\u598d\u5ae3\u7430\u664f\u80ed\u814c\u7131\u7f68\u7b75\u917d\u9b47\u990d\u9f39","yang":"\u6b83\u592e\u9e2f\u79e7\u6768\u626c\u4f6f\u75a1\u7f8a\u6d0b\u9633\u6c27\u4ef0\u75d2\u517b\u6837\u6f3e\u5f89\u600f\u6cf1\u7080\u70ca\u6059\u86d8\u9785","yao":"\u9080\u8170\u5996\u7476\u6447\u5c27\u9065\u7a91\u8c23\u59da\u54ac\u8200\u836f\u8981\u8000\u592d\u723b\u5406\u5d3e\u5fad\u7039\u5e7a\u73e7\u6773\u66dc\u80b4\u9e5e\u7a88\u7e47\u9cd0","ye":"\u6930\u564e\u8036\u7237\u91ce\u51b6\u4e5f\u9875\u6396\u4e1a\u53f6\u66f3\u814b\u591c\u6db2\u8c12\u90ba\u63f6\u9980\u6654\u70e8\u94d8","yi":"\u4e00\u58f9\u533b\u63d6\u94f1\u4f9d\u4f0a\u8863\u9890\u5937\u9057\u79fb\u4eea\u80f0\u7591\u6c82\u5b9c\u59e8\u5f5d\u6905\u8681\u501a\u5df2\u4e59\u77e3\u4ee5\u827a\u6291\u6613\u9091\u5c79\u4ebf\u5f79\u81c6\u9038\u8084\u75ab\u4ea6\u88d4\u610f\u6bc5\u5fc6\u4e49\u76ca\u6ea2\u8be3\u8bae\u8c0a\u8bd1\u5f02\u7ffc\u7fcc\u7ece\u5208\u5293\u4f7e\u8bd2\u572a\u572f\u57f8\u61ff\u82e1\u858f\u5f08\u5955\u6339\u5f0b\u5453\u54a6\u54bf\u566b\u5cc4\u5db7\u7317\u9974\u603f\u6021\u6092\u6f2a\u8fe4\u9a7f\u7f22\u6baa\u8d3b\u65d6\u71a0\u9487\u9552\u9571\u75cd\u7617\u7654\u7fca\u8864\u8734\u8223\u7fbf\u7ff3\u914f\u9edf","yin":"\u8335\u836b\u56e0\u6bb7\u97f3\u9634\u59fb\u541f\u94f6\u6deb\u5bc5\u996e\u5c39\u5f15\u9690\u5370\u80e4\u911e\u5819\u831a\u5591\u72fa\u5924\u6c24\u94df\u763e\u8693\u972a\u9f88","ying":"\u82f1\u6a31\u5a74\u9e70\u5e94\u7f28\u83b9\u8424\u8425\u8367\u8747\u8fce\u8d62\u76c8\u5f71\u9896\u786c\u6620\u5b34\u90e2\u8314\u83ba\u8426\u6484\u5624\u81ba\u6ee2\u6f46\u701b\u745b\u748e\u6979\u9e66\u763f\u988d\u7f42","yo":"\u54df\u5537","yong":"\u62e5\u4f63\u81c3\u75c8\u5eb8\u96cd\u8e0a\u86f9\u548f\u6cf3\u6d8c\u6c38\u607f\u52c7\u7528\u4fd1\u58c5\u5889\u6175\u9095\u955b\u752c\u9cd9\u9954","you":"\u5e7d\u4f18\u60a0\u5fe7\u5c24\u7531\u90ae\u94c0\u72b9\u6cb9\u6e38\u9149\u6709\u53cb\u53f3\u4f51\u91c9\u8bf1\u53c8\u5e7c\u5363\u6538\u4f91\u83b8\u5466\u56ff\u5ba5\u67da\u7337\u7256\u94d5\u75a3\u8763\u9c7f\u9edd\u9f2c","yu":"\u8fc2\u6de4\u4e8e\u76c2\u6986\u865e\u611a\u8206\u4f59\u4fde\u903e\u9c7c\u6109\u6e1d\u6e14\u9685\u4e88\u5a31\u96e8\u4e0e\u5c7f\u79b9\u5b87\u8bed\u7fbd\u7389\u57df\u828b\u90c1\u5401\u9047\u55bb\u5cea\u5fa1\u6108\u6b32\u72f1\u80b2\u8a89\u6d74\u5bd3\u88d5\u9884\u8c6b\u9a6d\u79ba\u6bd3\u4f1b\u4fe3\u8c00\u8c15\u8438\u84e3\u63c4\u5581\u5704\u5709\u5d5b\u72f3\u996b\u5ebe\u9608\u59aa\u59a4\u7ea1\u745c\u6631\u89ce\u8174\u6b24\u65bc\u715c\u71e0\u807f\u94b0\u9e46\u7610\u7600\u7ab3\u8753\u7afd\u8201\u96e9\u9f89","yuan":"\u9e33\u6e0a\u51a4\u5143\u57a3\u8881\u539f\u63f4\u8f95\u56ed\u5458\u5706\u733f\u6e90\u7f18\u8fdc\u82d1\u613f\u6028\u9662\u586c\u6c85\u5a9b\u7457\u6a7c\u7230\u7722\u9e22\u8788\u9f0b","yue":"\u66f0\u7ea6\u8d8a\u8dc3\u94a5\u5cb3\u7ca4\u6708\u60a6\u9605\u9fa0\u6a3e\u5216\u94ba","yun":"\u8018\u4e91\u90e7\u5300\u9668\u5141\u8fd0\u8574\u915d\u6655\u97f5\u5b55\u90d3\u82b8\u72c1\u607d\u7ead\u6b92\u6600\u6c32","za":"\u531d\u7838\u6742\u62f6\u5482","zai":"\u683d\u54c9\u707e\u5bb0\u8f7d\u518d\u5728\u54b1\u5d3d\u753e","zan":"\u6512\u6682\u8d5e\u74d2\u661d\u7c2a\u7ccc\u8db1\u933e","zang":"\u8d43\u810f\u846c\u5958\u6215\u81e7","zao":"\u906d\u7cdf\u51ff\u85fb\u67a3\u65e9\u6fa1\u86a4\u8e81\u566a\u9020\u7682\u7076\u71e5\u5523\u7f2b","ze":"\u8d23\u62e9\u5219\u6cfd\u4ec4\u8d5c\u5567\u8fee\u6603\u7b2e\u7ba6\u8234","zei":"\u8d3c","zen":"\u600e\u8c2e","zeng":"\u589e\u618e\u66fe\u8d60\u7f2f\u7511\u7f7e\u9503","zha":"\u624e\u55b3\u6e23\u672d\u8f67\u94e1\u95f8\u7728\u6805\u69a8\u548b\u4e4d\u70b8\u8bc8\u63f8\u5412\u54a4\u54f3\u600d\u781f\u75c4\u86b1\u9f44","zhai":"\u6458\u658b\u5b85\u7a84\u503a\u5be8\u7826","zhan":"\u77bb\u6be1\u8a79\u7c98\u6cbe\u76cf\u65a9\u8f97\u5d2d\u5c55\u8638\u6808\u5360\u6218\u7ad9\u6e5b\u7efd\u8c35\u640c\u65c3","zhang":"\u6a1f\u7ae0\u5f70\u6f33\u5f20\u638c\u6da8\u6756\u4e08\u5e10\u8d26\u4ed7\u80c0\u7634\u969c\u4ec9\u9123\u5e5b\u5d82\u7350\u5adc\u748b\u87d1","zhao":"\u62db\u662d\u627e\u6cbc\u8d75\u7167\u7f69\u5146\u8087\u53ec\u722a\u8bcf\u68f9\u948a\u7b0a","zhe":"\u906e\u6298\u54f2\u86f0\u8f99\u8005\u9517\u8517\u8fd9\u6d59\u8c2a\u966c\u67d8\u8f84\u78d4\u9e67\u891a\u8707\u8d6d","zhen":"\u73cd\u659f\u771f\u7504\u7827\u81fb\u8d1e\u9488\u4fa6\u6795\u75b9\u8bca\u9707\u632f\u9547\u9635\u7f1c\u6862\u699b\u8f78\u8d48\u80d7\u6715\u796f\u755b\u9e29","zheng":"\u84b8\u6323\u7741\u5f81\u72f0\u4e89\u6014\u6574\u62ef\u6b63\u653f\u5e27\u75c7\u90d1\u8bc1\u8be4\u5ce5\u94b2\u94ee\u7b5d","zhi":"\u829d\u679d\u652f\u5431\u8718\u77e5\u80a2\u8102\u6c41\u4e4b\u7ec7\u804c\u76f4\u690d\u6b96\u6267\u503c\u4f84\u5740\u6307\u6b62\u8dbe\u53ea\u65e8\u7eb8\u5fd7\u631a\u63b7\u81f3\u81f4\u7f6e\u5e1c\u5cd9\u5236\u667a\u79e9\u7a1a\u8d28\u7099\u75d4\u6ede\u6cbb\u7a92\u536e\u965f\u90c5\u57f4\u82b7\u646d\u5e19\u5fee\u5f58\u54ab\u9a98\u6809\u67b3\u6800\u684e\u8f75\u8f7e\u6534\u8d3d\u81a3\u7949\u7957\u9ef9\u96c9\u9e37\u75e3\u86ed\u7d77\u916f\u8dd6\u8e2c\u8e2f\u8c78\u89ef","zhong":"\u4e2d\u76c5\u5fe0\u949f\u8877\u7ec8\u79cd\u80bf\u91cd\u4ef2\u4f17\u51a2\u953a\u87bd\u8202\u822f\u8e35","zhou":"\u821f\u5468\u5dde\u6d32\u8bcc\u7ca5\u8f74\u8098\u5e1a\u5492\u76b1\u5b99\u663c\u9aa4\u5544\u7740\u501c\u8bf9\u836e\u9b3b\u7ea3\u80c4\u78a1\u7c40\u8233\u914e\u9cb7","zhu":"\u73e0\u682a\u86db\u6731\u732a\u8bf8\u8bdb\u9010\u7af9\u70db\u716e\u62c4\u77a9\u5631\u4e3b\u8457\u67f1\u52a9\u86c0\u8d2e\u94f8\u7b51\u4f4f\u6ce8\u795d\u9a7b\u4f2b\u4f8f\u90be\u82ce\u8331\u6d19\u6e1a\u6f74\u9a7a\u677c\u69e0\u6a65\u70b7\u94e2\u75b0\u7603\u86b0\u7afa\u7bb8\u7fe5\u8e85\u9e88","zhua":"\u6293","zhuai":"\u62fd","zhuan":"\u4e13\u7816\u8f6c\u64b0\u8d5a\u7bc6\u629f\u556d\u989b","zhuang":"\u6869\u5e84\u88c5\u5986\u649e\u58ee\u72b6\u4e2c","zhui":"\u690e\u9525\u8ffd\u8d58\u5760\u7f00\u8411\u9a93\u7f12","zhun":"\u8c06\u51c6","zhuo":"\u6349\u62d9\u5353\u684c\u7422\u8301\u914c\u707c\u6d4a\u502c\u8bfc\u5ef4\u855e\u64e2\u555c\u6d5e\u6dbf\u6753\u712f\u799a\u65ab","zi":"\u5179\u54a8\u8d44\u59ff\u6ecb\u6dc4\u5b5c\u7d2b\u4ed4\u7c7d\u6ed3\u5b50\u81ea\u6e0d\u5b57\u8c18\u5d6b\u59ca\u5b73\u7f01\u6893\u8f8e\u8d40\u6063\u7726\u9531\u79ed\u8014\u7b2b\u7ca2\u89dc\u8a3e\u9cbb\u9aed","zong":"\u9b03\u68d5\u8e2a\u5b97\u7efc\u603b\u7eb5\u8159\u7cbd","zou":"\u90b9\u8d70\u594f\u63cd\u9139\u9cb0","zu":"\u79df\u8db3\u5352\u65cf\u7956\u8bc5\u963b\u7ec4\u4fce\u83f9\u5550\u5f82\u9a75\u8e74","zuan":"\u94bb\u7e82\u6525\u7f35","zui":"\u5634\u9189\u6700\u7f6a","zun":"\u5c0a\u9075\u6499\u6a3d\u9cdf","zuo":"\u6628\u5de6\u4f50\u67de\u505a\u4f5c\u5750\u5ea7\u961d\u963c\u80d9\u795a\u9162","cou":"\u85ae\u6971\u8f8f\u8160","nang":"\u652e\u54dd\u56d4\u9995\u66e9","o":"\u5594","dia":"\u55f2","chuai":"\u562c\u81aa\u8e39","cen":"\u5c91\u6d94","diu":"\u94e5","nou":"\u8028","fou":"\u7f36","bia":"\u9adf"};
                this.polyphone = {"19969":"DZ","19975":"WM","19988":"QJ","20048":"YL","20056":"SC","20060":"NM","20094":"QG","20127":"QJ","20167":"QC","20193":"YG","20250":"KH","20256":"ZC","20282":"SC","20285":"QJG","20291":"TD","20314":"YD","20340":"NE","20375":"TD","20389":"YJ","20391":"CZ","20415":"PB","20446":"YS","20447":"SQ","20504":"TC","20608":"KG","20854":"QJ","20857":"ZC","20911":"PF","20504":"TC","20608":"KG","20854":"QJ","20857":"ZC","20911":"PF","20985":"AW","21032":"PB","21048":"XQ","21049":"SC","21089":"YS","21119":"JC","21242":"SB","21273":"SC","21305":"YP","21306":"QO","21330":"ZC","21333":"SDC","21345":"QK","21378":"CA","21397":"SC","21414":"XS","21442":"SC","21477":"JG","21480":"TD","21484":"ZS","21494":"YX","21505":"YX","21512":"HG","21523":"XH","21537":"PB","21542":"PF","21549":"KH","21571":"E","21574":"DA","21588":"TD","21589":"O","21618":"ZC","21621":"KHA","21632":"ZJ","21654":"KG","21679":"LKG","21683":"KH","21710":"A","21719":"YH","21734":"WOE","21769":"A","21780":"WN","21804":"XH","21834":"A","21899":"ZD","21903":"RN","21908":"WO","21939":"ZC","21956":"SA","21964":"YA","21970":"TD","22003":"A","22031":"JG","22040":"XS","22060":"ZC","22066":"ZC","22079":"MH","22129":"XJ","22179":"XA","22237":"NJ","22244":"TD","22280":"JQ","22300":"YH","22313":"XW","22331":"YQ","22343":"YJ","22351":"PH","22395":"DC","22412":"TD","22484":"PB","22500":"PB","22534":"ZD","22549":"DH","22561":"PB","22612":"TD","22771":"KQ","22831":"HB","22841":"JG","22855":"QJ","22865":"XQ","23013":"ML","23081":"WM","23487":"SX","23558":"QJ","23561":"YW","23586":"YW","23614":"YW","23615":"SN","23631":"PB","23646":"ZS","23663":"ZT","23673":"YG","23762":"TD","23769":"ZS","23780":"QJ","23884":"QK","24055":"XH","24113":"DC","24162":"ZC","24191":"GA","24273":"QJ","24324":"NL","24377":"TD","24378":"QJ","24439":"PF","24554":"ZS","24683":"TD","24694":"WE","24733":"LK","24925":"TN","25094":"ZG","25100":"XQ","25103":"XH","25153":"PB","25170":"PB","25179":"KG","25203":"PB","25240":"ZS","25282":"FB","25303":"NA","25324":"KG","25341":"ZY","25373":"WZ","25375":"XJ","25384":"A","25457":"A","25528":"SD","25530":"SC","25552":"TD","25774":"ZC","25874":"ZC","26044":"YW","26080":"WM","26292":"PB","26333":"PB","26355":"ZY","26366":"CZ","26397":"ZC","26399":"QJ","26415":"ZS","26451":"SB","26526":"ZC","26552":"JG","26561":"TD","26588":"JG","26597":"CZ","26629":"ZS","26638":"YL","26646":"XQ","26653":"KG","26657":"XJ","26727":"HG","26894":"ZC","26937":"ZS","26946":"ZC","26999":"KJ","27099":"KJ","27449":"YQ","27481":"XS","27542":"ZS","27663":"ZS","27748":"TS","27784":"SC","27788":"ZD","27795":"TD","27812":"O","27850":"PB","27852":"MB","27895":"SL","27898":"PL","27973":"QJ","27981":"KH","27986":"HX","27994":"XJ","28044":"YC","28065":"WG","28177":"SM","28267":"QJ","28291":"KH","28337":"ZQ","28463":"TL","28548":"DC","28601":"TD","28689":"PB","28805":"JG","28820":"QG","28846":"PB","28952":"TD","28975":"ZC","29100":"A","29325":"QJ","29575":"SL","29602":"FB","30010":"TD","30044":"CX","30058":"PF","30091":"YSP","30111":"YN","30229":"XJ","30427":"SC","30465":"SX","30631":"YQ","30655":"QJ","30684":"QJG","30707":"SD","30729":"XH","30796":"LG","30917":"PB","31074":"NM","31085":"JZ","31109":"SC","31181":"ZC","31192":"MLB","31293":"JQ","31400":"YX","31584":"YJ","31896":"ZN","31909":"ZY","31995":"XJ","32321":"PF","32327":"ZY","32418":"HG","32420":"XQ","32421":"HG","32438":"LG","32473":"GJ","32488":"TD","32521":"QJ","32527":"PB","32562":"ZSQ","32564":"JZ","32735":"ZD","32793":"PB","33071":"PF","33098":"XL","33100":"YA","33152":"PB","33261":"CX","33324":"BP","33333":"TD","33406":"YA","33426":"WM","33432":"PB","33445":"JG","33486":"ZN","33493":"TS","33507":"QJ","33540":"QJ","33544":"ZC","33564":"XQ","33617":"YT","33632":"QJ","33636":"XH","33637":"YX","33694":"WG","33705":"PF","33728":"YW","33882":"SR","34067":"WM","34074":"YW","34121":"QJ","34255":"ZC","34259":"XL","34425":"JH","34430":"XH","34485":"KH","34503":"YS","34532":"HG","34552":"XS","34558":"YE","34593":"ZL","34660":"YQ","34892":"XH","34928":"SC","34999":"QJ","35048":"PB","35059":"SC","35098":"ZC","35203":"TQ","35265":"JX","35299":"JX","35782":"SZ","35828":"YS","35830":"E","35843":"TD","35895":"YG","35977":"MH","36158":"JG","36228":"QJ","36426":"XQ","36466":"DC","36710":"JC","36711":"ZYG","36767":"PB","36866":"SK","36951":"YW","37034":"YX","37063":"XH","37218":"ZC","37325":"ZC","38063":"PB","38079":"TD","38085":"QY","38107":"DC","38116":"TD","38123":"YD","38224":"HG","38241":"XTC","38271":"ZC","38415":"YE","38426":"KH","38461":"YD","38463":"AE","38466":"PB","38477":"XJ","38518":"YT","38551":"WK","38585":"ZC","38704":"XS","38739":"LJ","38761":"GJ","38808":"SQ","39048":"JG","39049":"XJ","39052":"HG","39076":"CZ","39271":"XT","39534":"TD","39552":"TD","39584":"PB","39647":"SB","39730":"LG","39748":"TPB","40109":"ZQ","40479":"ND","40516":"HG","40536":"HG","40583":"QJ","40765":"YQ","40784":"QJ","40840":"YK","40863":"QJG"};
            },
            // 获取全写拼音
            getFullChars: function(str){
                var result = '', name;
                var reg = new RegExp('[a-zA-Z0-9\- ]');
                for (var i=0, len = str.length; i < len; i++){
                    var ch = str.substr(i,1), unicode = ch.charCodeAt(0);
                    if(unicode > 40869 || unicode < 19968){
                        result += ch;
                    }else{
                        name = this._getFullChar(ch);
                        if(name !== false){
                            result += name;
                        }
                    }
                }
                return result;
            },
            // 获取简写拼音
            getCamelChars: function(str){
                if(typeof(str) !== 'string')
                    throw new Error(-1, "����getFisrt��Ҫ�ַ������Ͳ���!");
                var chars = []; //�����м���������
                for(var i=0,len=str.length; i < len; i++){
                    //���unicode��
                    var ch = str.charAt(i);
                    //����unicode���Ƿ��ڴ���Χ֮��,���򷵻ظ����ӳ���ֵ�ƴ������ĸ,���������������������
                    chars.push(this._getChar(ch));
                }
                //����arrResult,�������п��ܵ�ƴ������ĸ������
                return this._getResult(chars);
            },
            // ��ȡƴ��
            _getFullChar: function(str){
                for (var key in this.full_dict){
                    if(-1 !== this.full_dict[key].indexOf(str)){
                        return this._capitalize(key); break;
                    }
                }
                return false;
            },
            // ����ĸ��д
            _capitalize: function(str){
                if(str.length>0){
                    var first = str.substr(0,1).toUpperCase();
                    var spare = str.substr(1,str.length);
                    return first + spare;
                }
            },
            _getChar: function(ch){
                var unicode = ch.charCodeAt(0);
                //������ں��ִ���Χ֮��,����ԭ�ַ�,Ҳ���Ե����Լ��Ĵ�����
                if(unicode > 40869 || unicode < 19968)
                    return ch; //dealWithOthers(ch);
                //����Ƿ��Ƕ�����,�ǰ������ִ���,���Ǿ�ֱ����strChineseFirstPY�ַ������Ҷ�Ӧ������ĸ
                if(!this.options.checkPolyphone)
                    return this.char_dict.charAt(unicode-19968);
                return this.polyphone[unicode] ? this.polyphone[unicode] : this.char_dict.charAt(unicode-19968);
            },
            _getResult: function(chars){
                if(!this.options.checkPolyphone)
                    return chars.join('');
                var result = [''];
                for(var i=0,len=chars.length;i<len;i++){
                    var str = chars[i], strlen = str.length;
                    if(strlen == 1){
                        for(var j=0; j < result.length; j++){
                            result[k] += str;
                        }
                    }else{
                        var swap1 = result.slice(0);
                        result = [];
                        for(var j=0; j < strlen; j++){
                            //����һ����ͬ��arrRslt
                            var swap2 = swap1.slice(0);
                            //�ѵ�ǰ�ַ�str[k]��ӵ�ÿ��Ԫ��ĩβ
                            for(var k=0; k < swap2.length; k++){
                                swap2[k] += str.charAt(j);
                            }
                            //�Ѹ��Ʋ��޸ĺ���������ӵ�arrRslt��
                            result = result.concat(swap2);
                        }
                    }
                }
                return result;
            }
        };
        var extend = function(dst, src){
            for(var property in src){
                dst[property] = src[property];
            }
            return dst;
        };
        return new Pinyin(arguments);
    }

    return mpos;
})(App);

/**
 * 当前登录用户
 */
mpos.currentUser = null;
/**
 * 当前选择的餐台
 */
mpos.currentTable = null;

/**
 * 是否打开过付款窗体标识
 */
mpos.openedPayTable = true;

/**
 * 店铺配置
 */
mpos.shopConfig = {};
/**
 * 是否需要刷新餐台，用于跨多个界面刷新
 */
mpos.isNeedReloadTable = false;

//注册localstorage字段
/** @namespace mpos.localStorage.isDisableAnimation */
/** @namespace mpos.localStorage.UserName */
/** @namespace mpos.localStorage.OrderPropertyType */
/** @namespace mpos.localStorage.PreBilledOrderNumber */
/** @namespace mpos.localStorage.PreBilledOrderId */
/** @namespace mpos.localStorage.CashOrderNumber */
/** @namespace mpos.localStorage.CashOrderId */
/** @namespace mpos.localStorage.TableBillId */
/** @namespace mpos.localStorage.TableBillNumber */
/** @namespace mpos.localStorage.BillHeadNumber */
/** @namespace mpos.localStorage.BillFootNumber */
/** @namespace mpos.localStorage.PrintTotalBill */
/** @namespace mpos.localStorage.PrintSigleBill */
/** @namespace mpos.localStorage.CashMode */
/** @namespace mpos.localStorage.RechargePrintId */
/** @namespace mpos.localStorage.RechargePrintNumber */
/** @namespace mpos.localStorage.LocalTableOrder */
/** @namespace mpos.localStorage.enableSubmitOrderTips 开启下单确认提示*/
/** @namespace mpos.localStorage.enableEstimatedCost 开启毛利率显示*/
/** @namespace mpos.localStorage.enableToSettlePay 酒楼模式下点餐直接跳转结账界面*/
/** @namespace mpos.localStorage.enableBigDishTypes 酒楼模式下菜品大类显示*/
/** @namespace mpos.localStorage.enableOpenBookTable 酒楼模式下快速预订*/
/** @namespace mpos.localStorage.enableSystemKeyboard 启用系统键盘*/
/** @namespace mpos.localStorage.SaveWinesPrintId 存酒打印格式ID*/
/** @namespace mpos.localStorage.SaveWinesPrintNumber 存酒打印数量*/
/** @namespace mpos.localStorage.FetchWinesPrintId 取酒打印格式ID*/
/** @namespace mpos.localStorage.FetchWinesPrintNumber 取酒打印数量*/
/** @namespace mpos.localStorage.enableUsedDefaultUnit 点菜列表使用默认单位*/
/** @namespace mpos.localStorage.enableDiningTableAmount 开启餐台金额显示*/
/** @namespace mpos.localStorage.enableKeepOrderDish 点餐完停留在点餐页面*/
/** @namespace mpos.localStorage.enableFloorMenu 显示餐台区域列表*/
mpos.registerStorageProperties(['isDisableAnimation', 'UserName', 'OrderPropertyType',
    'PreBilledOrderNumber', 'PreBilledOrderId', 'CashOrderNumber', 'CashOrderId',
    'TableBillId', 'TableBillNumber', 'BillHeadNumber', 'BillFootNumber', 'PrintTotalBill',
    'PrintSigleBill', 'CashMode', 'RechargePrintId', 'RechargePrintNumber', 'LocalTableOrder',
    'enableSubmitOrderTips', 'enableEstimatedCost', 'PrinterIP', 'PrinterPort', 'enableToSettlePay', 'enableBigDishTypes',
    'enableOpenBookTable', 'enableSystemKeyboard', 'enableMutilOrderDish', 'PayToOrder', 'SaveWinesPrintId', 'SaveWinesPrintNumber',
    'FetchWinesPrintId', 'FetchWinesPrintNumber', 'enableUsedDefaultUnit', 'enableDiningTableAmount', 'enableKeepOrderDish', 
    'enableFloorMenu']);

//事件名称
mpos.event = {
    messageCountChanged: 'messageCountChanged'
};

/**
 * error事件处理, debug状态
 * @param {String}  errorMessage   错误信息
 * @param {String}  scriptURI      出错的文件
 * @param {Number}    lineNumber     出错代码的行号
 * @param {Number}    columnNumber   出错代码的列号
 * @param {Object}  errorObj       错误的详细信息，Anything
 */
window.onerror = function (errorMessage, scriptURI, lineNumber, columnNumber, errorObj) {
    mpos.hideLoading();
    if (mpos.isDebug) {
        console.log("错误信息：", errorMessage);
        console.log("出错文件：", scriptURI + ":" + lineNumber + ":" + columnNumber);
        console.log("出错行号：", lineNumber);
        console.log("出错列号：", columnNumber);
        console.log("错误详情：", errorObj);
    } else {
        var str = [
            "错误信息：" + errorMessage,
            "出错文件：" + scriptURI,
            "出错行号：" + lineNumber,
            "出错列号：" + columnNumber,
            "错误详情：" + errorObj
        ].join("\n");
        alert(str);
        mpos.post(mpos.api.SaveJsLog, {
            ErrorMsg: str,
            LogType: 0,
        }, function () { }, {
            hideLoading: true,
            error: function () {
            },
            blFailed: function () {
            }
        });
        return true;
    }
};

/**
 * 退出登录
 */
mpos.logout = function () {
    mpos.currentTable = null;
    mpos.currentUser = null;
    mpos.isNeedReloadTable = false;
    mpos.deviceFactory.onLogout();
    mpos.shopConfig = {};
    //判断是否为快餐模式
    if (mpos.localStorage.OrderPropertyType == OrderPropertyType.Snack)
        mpos.load(mpos.page.orderDishes);
    else
        mpos.load(mpos.page.home);
    mpos.removeFromStack();
};
/**
 * 格式化价格
 * @param {Number} price 价格,文本或数字
 * @param preFix 前缀，如果传入则以此为准
 */
mpos.formatPrice = function (price, preFix) {
    var prefix = preFix || mpos.shopConfig.AmountSymbol || "￥";
    return prefix + Number(price).toFixed(2);
};
/**
 * 修正浮点数
 * @param {Object} price
 */
mpos.priceFixed = function (price) {
    return Number(price).toFixed(2);
};

//api地址
$.extend(mpos.api, {
    login: "LoginByMPos", //登录
    showDiningTableList: "ShowDiningTableListByMpos", //显示餐台列表
    findDiningTable: "FindDiningTable", //查找餐台
    getSettleInfo: "GetSettleInfo", //获取结账信息
    loadFloors: "FindFloors", //获取区域
    /**
     //获取打印单据
     参数：
     {
     // 消费单及订单ID
     ConsumptionId:0,

     // 打印格式ID
     BillId:0,

     //1收银单，2预结单
     BillType:1,

     MergeType : 1, //预留
     }
     */
    getPrintBill: "GetPrintBill", //获取打印单据
    /**
     参数：
     {
     // 消费单及订单ID
     ConsumptionId:0,

     // 打印格式ID
     BillId:0,

     MergeType : 1, //预留

     // 预结类型：1-自动，2-只取消结，3-只预结
     PreBilledOrderType : 1
     }
     */
    preBilledOrder: "PreBilledOrder", //预结或取消预结，根据状态自动执行
    getMemberTicketCount: "GetMemberTicketCount", //获取会员可用的票券数
    searchMembers: "SearchMembers", //查询会员
    setMemberCard: "SetMemberCard", //设置会员卡
    setOrCanelFreeDish: "SetOrCanelFreeDish", //赠送或取消赠送
    getReasonList: "GetReasonList", //获取原因列表
    getShopConfigInfo: "GetShopConfigInfo", //获取店铺配置信息
    getReasonConfirm: "GetReasonConfirm", //获取是否必选
    returnDish: "ReturnDish", //退菜
    getOftenDiscounts: "getOftenDiscounts", //获取常用折扣
    setDishDiscount: "SetDishDiscount", //设置单个菜品折扣
    getPrintBillFormat: "GetPrintBillFormat", //获取小票打印格式(只返回BillTypeNo=PrtBillType.CashBill 和 BillTypeNo=PrtBillType.ReadyPayBill)
    /**
     参数
     {
     BusinessDate :"2015-01-01", //营业日
     Keyword :"",//流水号或餐台名
     PageSize :"50", //页大小
     PageIndex :1,//当前页索引
     }
     */
    queryConsumptionBill: "QueryConsumptionBill", //查账单
    /**
     参数:
     {
     DiningOrderId:0 //订单ID
     }
     */
    setServiceFeeStatus: "SetServiceFeeStatus", //服务费操作
    /**
     参数:
     {
     DiningOrderId:0 //订单ID
     }
     */
    setMinimumChargeFeeStatus: "SetMinimumChargeFeeStatus", //最低销操作

    cancelMemberCoupon: "CancelMemberCoupon",//取消会员优惠
    /**
     参数:
     {
     DiningOrderId:0 //订单ID
     }
     */
    setTeaStatus: "SetTeaStatus", //茶操作
    /**
     参数:
     {
     OrderId:0,//订单
     Amount :0 //金额
     }
     */
    setManualCutMoney: "SetManualCutMoney", //减免
    /**
     设置整单折扣
     参数：
     {
     OrderId:0//订单ID
     Discount:100//折扣值
     IsRateDiscount:true//是否比例折扣
     ReasonId:0//原因
     }
     */
    applyDiscount: "ApplyDiscount",
    /**
     获取折扣方案
     参数：无
     */
    getDiscountSchemes: "GetDiscountSchemes", //获取折扣方案
    /**
     应用折扣方案：
     参数：
     {
     OrderId:0, //订单ID
     SchemeId:0,//方案ID
     ReasonId:0 //原因ID
     }
     */
    applyDiscountScheme: "ApplyDiscountScheme", //应用折扣方案
    /**
     获取当前营业日
     */
    getCurrentBusinessDate: "GetCurrentBusinessDate",
    /**
     获取消费单详细
     参数：
     {
     ConsumptionId:0 //单据ID
     }
     */
    getConsumptionInfo: "GetConsumptionInfo",

    /**
     反结账
     参数：
     {
     ConsumptionId:0 //单据ID
     ReasonId:0//原因ID
     }
     */
    reverseSettle: "ReverseSettle",
    /**
     获取一个单的可开发票信息
     参数：
     {
     ConsumptionId:0
     }
     */
    getConsumptionInvoiceConfig: "GetConsumptionInvoiceConfig",

    /**
     补开发票
     参数：
     {
     ConsumptionId:0,
     InvoiceAmount:0
     }
     */
    setConsumptionInvoice: "SetConsumptionInvoice",
    /**
     根据卡ID获取会员卡
     参数：
     {
     MemberCardId:0
     }
     */
    getMemberByMemberCardId: "GetMemberByMemberCardId",
    /**
     付款
     参数：
     {
     // 付款方式ID
     PaymentPatternId :0,
     // 订单ID
     OrderId :0,
     // 付款金额
     Amount :0,
     // 会员ID或挂账客户ID
     MemberId :0,
     // 会员卡ID
     MemberCardId:0,
     // 票券ID
     TicketId:0,
     // 备注
     Remark:"",
     // 挂账人ID
     CreditUserId :0,
     // 是否会员挂账
     IsMemberCredit:false,
     }
     */
    settlePayment: "SettlePayment",
    /**
     提交结账
     参数：
     {
     OrderId:0,//订单ID
     CashBillId:0,//收银单ID
     InvoiceAmount:0//发票金额
     }
     */
    submitSettle: "SubmitSettle",

    /**
     删除付款方式
     参数：
     {
     OrderId:0,
     PaymentId:0,
     Amount:0
     }
     */
    clearSettlePaymentItem: "ClearSettlePaymentItem",
    /**
     获取会员可用票券
     参数
     {
     ConsumptionId:0,
     MemberId:0
     }
     */
    getMemberTickets: "GetMemberTickets",
    /**
     获取票券
     参数：{
     ConsumptionNo:"",
     }
     */
    getTicketIdByTicketConsumptionNo: "GetTicketIdByTicketConsumptionNo",

    /**
     临时计算结账的待收金额
     参数：
     {
     MemberCardId:0,
     OrderId:0
     }
     */
    calculateMemberSettleAmount: "CalculateMemberSettleAmount",

    /**
     查询挂账客户
     参数：
     {
     Keyword:'' //关键字
     }
     */
    queryCreditCustomers: "QueryCreditCustomers",
    /**
     查询挂账人：
     参数：
     {
     CustomerId:0,//挂账客户ID
     IsMember:0,//是否为会员 1 or 0
     }
     */
    queryCreditCustomerUsers: "QueryCreditCustomerUsers",

    /**
     检查是否存在未完成的在线支付
     参数:
     {
     OrderId:0,
     ThirdPaymentType:0
     }
     */
    checkHasOnlinePay: "CheckHasOnlinePay",

    /**
     开始在线支付
     参数：
     {
     OrderId:0,
     ThirdPaymentType:0,
     PaymentPatternId:0,
     Amount:0,
     BarCode:""
     }
     */
    beginOnlinePay: "BeginOnlinePay",

    /**
     检查在线付款状态
     参数：
     {
     OnlinePayId:0
     }
     */
    checkOnlinePayResult: "CheckOnlinePayResult",
    /**
     锁订单
     参数：
     {
     WholeOrderId:0
     }
     */
    lockTableForSettle: "LockTableForSettle",
    /**
     强制解锁
     参数：无
     */
    forceUnLockTable: "ForceUnLockTable",
    /**
     检查是否被踢出
     参数：
     {
     WholeOrderId:0
     }
     */
    checkTableLockedForSettle: "CheckTableLockedForSettle",
    /**
    检查是否被踢出
    参数：
    {
    WholeOrderId:0
    }
    */
    checkTableLockedForOrderDish: "CheckTableLockedForOrderDish",

    /**
     检测是否有来自线上的付款方式
     参数：
     {
     ConsumptionId:0,
     HasPaymentIds:""
     }
     */
    checkAutoInputOnlinePay: "CheckAutoInputOnlinePay",

    /**
     创建盒子支付：
     参数
     {
     ConsumptionId:0,
     PaymentPatternId:0,
     Amount:0,
     }
     */
    createBoxPay: "CreateBoxPay",
    /**
     更新盒子支付
     参数{
     PaymentPatternId:0,
     OnlineBankPayId:0,
     IsOk:true,
     TradeNo:"".
     ErrMessage:"",
     UsedPaymentType:""//具体使用的付款方式
     }
     */
    updateBoxPay: "UpdateBoxPay",

    /**
     撤销盒子支付申请
     参数：{
     PaymentId:0,
     ConsumptionId:0,
     }
     */
    cancelBoxPay: "CancelBoxPay",
    /**
     更新撤销结果
     参数：
     {
     PaymentId:0,
     OutTradeNo:"",
     ConsumptionId:0,
     }
     */
    updateCancelBoxPay: "UpdateCancelBoxPay",
    /**
     清台
     参数：
     {
     TableId:0,
     OrderId:0
     }
     */
    cleanUpTable: "CleanUpTable",
    /**
     获取二维码
     参数：OrderId
     */
    getPrepayBillQr: "GetPrepayBillQr",

    /**
     获取二维码中的餐台ID
     参数：
     {
     Url:""
     }
     */
    queryShopDiningTableQrcode: "QueryShopDiningTableQrcode",

    /**
     获取所有消息数
     参数：无
     */
    getAllNewMessageCount: "GetAllNewMessageCount",

    /**
     获取消息
     参数：
     {
     ConsumptionMessageType:0,
     PageIndex:1,
     PageSize:15,
     }
     */
    findConsumptionMessages: "FindConsumptionMessages",

    /**
     设置消息为已读
     参数：
     {
     MessageId:0
     }
     */
    setMessageReader: "SetMessageReader",

    /**
     设置已服务
     参数：
     {
     MessageId:0
     }
     */
    setMessageToServiced: "SetMessageToServiced",

    /**
     验证会员卡密码：
     参数：
     {
     MemberCardId:0,
     Password:''
     }
     */
    verifyMemberCardPassword: "VerifyMemberCardPassword",
    /**
     写日志
     参数:
     {
     ErrorMsg:""
     }
     */
    SaveJsLog: "SaveJsLog",
    /**
     获取所有服务员
     参数：无
     */
    getAllWaiters: "GetAllWaiters",
    /**
     获取市别
     参数：无
     */
    getAllBusinessTimeSpan: "GetAllBusinessTimeSpan",

    /**
     开台
     参数：
     {
     TableId :0,
     WaiterId :0,
     PeopleNum :0,
     BusinessTimeSpanId :0,
     TableCard :'',
     Remark :'',
     }
     */
    openTableByMPOS: "OpenTableByMPOS",
    /**
     修改台头
     参数：
     {
     OrderId :0,
     WaiterId :0,
     PeopleNum :0,
     BusinessTimeSpanId :0,
     TableCard :'',
     Remark :'',
     IsMainTable:false
     }
     */
    modifyTableHeaderByMPOS: "ModifyTableHeaderByMPOS",
    /**
     检查修改台头
     参数：
     {
     OrderId :0,
     WaiterId :0,
     PeopleNum :0,
     BusinessTimeSpanId :0,
     TableCard :'',
     Remark :'',
     IsMainTable:false
     }
     */
    checkModifyTableHeaderData: "CheckModifyTableHeaderData",
    /**
     打印单台
     参数：
     {
     OrderId:0,
     BillId:0,
     }
     */
    printTableBillByMPOS: "PrintTableBillByMPOS",
    /**
     撤销开台
     参数：
     {
     OrderId:0,
     }
     */
    cancelTable: "CancelTable",

    /**
     整单起菜
     参数：
     {
     // 订单ID
     OrderId:0,
     // 打印总单
     PrintTotalBill:true,
     // 打印分单
     PrintSigleBill:false,
     // 在起菜的菜品，如果为0，则全部起菜
     OrderDishId:0,
     }
     */
    takeOrderDishes: "TakeOrderDishes",
    /**
     整单催菜
     参数：
     {
       // 订单ID
       OrderId:0,
     }
     */
    reminderWholeOrder: "ReminderWholeOrder",
    /**
     * 单品催菜
     参数：
     {
         OrderId: 订单Id
         // 订单商品ID
         OrderDishId:0,
     }
     */
    reminderDish: "ReminderDish",
    /**
     * 单品划菜
     参数：
     {
           OrderId: 订单Id
           // 订单商品ID
           OrderDishId:0,
       }
     */
    setFinishOrderDish: "SetFinishOrderDish",
    /**
     获取称重菜品
     参数:
     {
     DiningOrderId:0
     }
     */
    findNeedWeightDishes: "FindNeedWeightDishes",

    /**
     称重确认
     参数：
     {
     ConfirmData:[{
     OrderDishId:0,
     DishNum:0
     }]
     }
     */
    confirmWeightDishes: "ConfirmWeightDishes",
    /**
     预订开台
     参数：
     {
     BookOrderId:0，
     TableId:0
     }
     */
    openTableForBookInfo: "OpenTableForBookInfo",
    /**
     加载点菜配置信息
     参数
     {
     OrderIds:[],
     BookOrderId：0,
     NeedClearOrderDish:false
     }
     */
    loadOrderDishDatas: "LoadOrderDishDatas",

    /**
     点菜
     参数：
     {

     }
     */
    //addOrderDishes: "AddOrderDishes",
    /**
     加减点菜数量
     参数：
     {
     OrderId:0,
     OrderDishId:0,
     Num:1
     }
     */
    //increaseOrderDishNumForShoppingCar: "IncreaseOrderDishNumForShoppingCar",

    /**
     删除已点的菜品
     参数：
     {
     OrderDishIds:[],
     }
     */
    //deleteOrderDishesForShoppingCar: "DeleteOrderDishesForShoppingCar",
    /**
     获取套餐信息
     参数：
     {
     DishId:0
     }
     */
    //getPackageInfo: "GetPackageInfo",
    /**
     修改购物车的菜品，不包括套餐
     */
    //changeOrderDishInfoForShoppingCar: "ChangeOrderDishInfoForShoppingCar",

    /**
     修改购物车的套餐子菜菜品
     */
    //changePackageDishesForShoppingCar: "ChangePackageDishesForShoppingCar",
    /**
     修改菜品数量
     参数：
     {
     OrderDishId:0,
     DishNum:1,
     OrderId:0
     }
     */
    //changeOrderDishNumShoppingCar: "ChangeOrderDishNumShoppingCar",
    /**
     叫起
     参数：
     {
     OrderDishIds:[1,2],
     OrderId:0
     }
     */
    //setOrderDishHangUpDish: "SetOrderDishHangUpDish",
    /**
     点茶芥
     参数：
     {
     TeasAndSnaks:[{DishId:0,UnitId:0,TeaType:0}],
     OrderId:0,
     }
     */
    //addTeaAndSnackToShoppingCar: "AddTeaAndSnackToShoppingCar",
    /**
     下单
     参数：
     {
     Dishes:[],
     OrderIds:[0],
     TableBillId:0,
     IsPrint:true,
     IsAllHangUp:false,
     OnlineOrderId:0,
     WaiterId:0
     }
     */
    saveOrderDishes: "SaveOrderDishes",

    /**
     修改单价
     参数：
     {
     OrderDishId:0,
     Price:0,
     ReasonId:0,
     }
     */
    changeOrderDishPrice: "ChangeOrderDishPrice",

    /**
     创建快餐订单，返回快餐
     参数：无
     */
    createSnackOrder: "CreateSnackOrder",

    /**
     清除快餐订单
     参数：无
     */
    clearSnackOrder: "ClearSnackOrder",

    /**
     获取快餐结账对象
     */
    getSnackSettle: "GetSnackSettle",

    /**
     * 获取支付下单付款
     * */
    getConsumptionPaySettle: "GetConsumptionPaySettle",

    /**
     * 保存下单支付
     */
    saveConsumptionPaySettle: "SaveConsumptionPaySettle",
    /**
     更新快餐餐牌
     参数：
     {
     TableSerial:"",
     OrderId:0,
     PeopleNum:0,
     }
     */
    updateSnackTableBrandNo: "UpdateSnackTableBrandNo",
    /**
     获取快餐餐牌
     参数：无
     */
    getSnackBrands: "GetSnackBrands",
    /**
     设置外带
     参数：{
     DiningOrderId:0
     }
     */
    setSnackOrderToTakeOut: "SetSnackOrderToTakeOut",

    /**
     导入线上订单：
     参数：{
     Url:""
     OrderId:""
     }
     */
    importOnlineOrder: "ImportOnlineOrder",

    /**
     加载缓存数据
     参数：{
     // 基础菜品缓存标记
     BaseDishFlag = "",
     //基础套餐数据缓存标记
     BasePackageDishFlag = "",
     // 菜品小类缓存标识
     BaseDishTypeFlag = "",
     // 做法缓存标识
     BaseCookingFlag = "",
     // 做法类型缓存标识
     BaseCookingTypeFlag = "",
     }
     */
    loadBaseDataCache: "LoadBaseDataCache",

    /**
    验证团购券
    */
    checkGrouponCode: "CheckGrouponCode",
    /**
    使用团购券
    */
    useGrouponCode: "UseGrouponCode",
    /**
    登录团购网站
    */
    loginGroupon: "LoginGroupon",

    /**
    检查是否已登录
    */
    checkGrouponIsLogin: "CheckGrouponIsLogin",

    /*
    获取充值的付款方式
    */
    getRechargePayments: "GetRechargePayments",

    /*
    获取充值赠送信息
    */
    getRechargePresent: "GetRechargePresent",
    /*
       获取充值赠送票券库存信息
        true 需要提示库存
       false 不需要提示库存
       参数：{
            StrategyId:0,
            TicketTypeId:0,
            Count:0
       }
    */
    rechTicketTypeCount: "RechTicketTypeCount",
    /*
    现金充值
    */
    rechargeNormalPay: "RechargeNormalPay",

    /*开始支付宝和微信充值*/
    beginWxOrAliRechargePay: "BeginWxOrAliRechargePay",

    /*
    检查支付宝和微信充值结果
    */
    checkWxOrAliRechargePayResult: "CheckWxOrAliRechargePayResult",

    /*
    创建拉卡拉充值支付
    */
    createLklRechargePay: "CreateLklRechargePay",

    /*
    更新拉卡拉充值结果
    */
    updateLklRechargePay: "UpdateLklRechargePay",

    /*
    查询充值数据
    */
    queryRecharges: "QueryRecharges",

    /*
    获取充值明细
    */
    getRechargeDetail: "GetRechargeDetail",

    /*
    充值重试
    */
    retryRecharge: "RetryRecharge",

    /*
    拉卡拉充值退款
    */
    lklRechargeReturnMoney: "LklRechargeReturnMoney",

    /*
    充值退款
    */
    rechargeReturnMoney: "RechargeReturnMoney",

    /*
    获取充值格式
    */
    getRechargePrintFormat: "GetRechargePrintFormat",

    /**
      获取没有会员优惠的待收金额
    */
    getNoMemPreferentialTotalObligationAmount: "getNoMemPreferentialTotalObligationAmount",

    /*
    获取可兑换的充值金额
    参数：{
    CardId:0,
    Score:0
    }
    */
    getScoreConvertionMoney: "GetScoreConvertionMoney",
    /*
    积分兑换充值
    参数：{
        CardId:0,
        Score:0,
        Amount:0
    }
    */
    scoreFillMoney: "ScoreFillMoney",

    /*
    查询换台可用餐台
    参数：{
        DiningOrderId:0
    }
    */
    queryCanUseChangeOrderTable: "QueryCanUseChangeOrderTable",

    /**
     * 获取计时方案列表
     * 参数：{
     *   TableId: 桌台ID,
     *   OrgId: 机构ID
     * }
     * */
    getTableSelectTimeChargeOffers: 'GetTableSelectTimeChargeOffers',

    /*
    换台
    参数：{
        OrderId:0,
        TableId:0,
        IsPrintKit:1
    }
    */
    changeOrderTable: "ChangeOrderTable",

    /*
    搭台:
    参数：{
        OrderId:0,
        PeopleNum:0,
        BusinessTimespanId:0
    }
    */
    mPosCutTable: "MPosCutTable",

    /*
    加台
    */
    addTableOrders: "AddTableOrders",
    /*
    获取可转台的菜品
    */
    getChangeDishInfoByOrderId: "GetChangeDishInfoByOrderId",

    /*
    获取可转台餐台信息
    */
    getCanChangeDishTables: "GetCanChangeDishTables",

    /*
    菜品转台
    参数：{
        OrderId: 0,
        AimOrderId:0,
        IsPrintKit: 0,
        OrderDishIds: ""
    }
    */
    changeDishTable: "ChangeDishTable",

    /*
     * 获取操作购物车中已下单菜品后的最新数据
     * 参数: {
     *     DiningOrderId: 0 ,
     * }
     * */
    getAlreadyOrderedDishes: "GetAlreadyOrderedDishes",

    getPayToOrderDishes: "GetPayToOrderDishes",

    getPayToOrdeDetails: "GetPayToOrdeDetails",

    getPayToOrderPrintData: "GetPayToOrderPrintData",

    /**
     * 获取订单类别起菜的菜别数据
     * 参数{
     *   DiningOrderId: 0 ,
     * }
     */
    getDishTypeTakeUpData: "GetDishTypeTakeUpData",

    /**
    * 类别起菜
    * 参数{
    *   DiningOrderId: 0 ,
    *   DishTypeIds:"[1,2,3,4,5]"
    * }
    */
    takeOrderDishByDishType: "TakeOrderDishByDishType",

    /**
     * 沽清时获取菜品展示
     * 参数： 无
     */
    getDishListForSaleOut: "GetDishListForSaleOut",

    /**
     * 菜品沽清操作
     * 参数{
     *   DishId:  菜品id ,
     *   Type: （1-沽清 2-取消沽清）
     * }
     * */
    dishSaleOut: "DishSaleOut",

    /**
     * 获取存酒列表
     * 参数{
         BeginTime: 开始时间,
         EndTime: 结束时间,
         keyWord: 查询关键字,
         Status: 状态
     * }
     * */
    getSaveWineList: "GetSaveWineList",

    /**
     * 查询取酒详情
     * 参数 {
     *   StorageSaveId: 存酒ID
     * }
     *
     * */
    getSaveWineDetail: "GetSaveWineDetail",

    /**
     * 获取存酒位置
     *
     * */
    getAllWinePosition: "GetAllWinePosition",

    /**
     * 添加取酒
     * 参数 {
     *  StorageSaveId: 存酒ID,
     *  FetchUserName": 取酒客户名称,
     *  FetchRemark": 取酒备注,
     *  FetchDetails": [
            {
              "SaveDetailId": 存酒详细ID,
              "DishName": 菜品名称,
              "FetchNum": 取酒数量
            }
          ]
        }
     * */
    addFetchWine: "AddFetchWine",

    /**
     * 获取会员信息
     * 参数 Mobile: 手机号
     * */
    getFindMember: "GetFindMember",

    /**
     * 添加/编辑存酒
     * 参数 {
     *    "StorageSaveId": 0,    //  存酒ID
          "Mobile": "13249050001",  //手机号
          "CustomerName": "唯品会",  // 客户名称
          "MemberId": 0,   //会员ID
          "CardId": 0,   // 卡ID
          "ExpiryDate": "2021-10-13 20:19:00",  // 过期时间
          "Checked": false,   //是否永久
          "Remark": "",   //备注
          "Details": [
              {
                  "DetailId": 0,   // 详细ID
                  "AssessPrice": 0,  // 估价，没有默认0
                  "DishId": 14067,  // 菜品ID
                  "DishName": "0629比克品牌",  // 菜品名称
                  "UnitId": 10003,  // 单位ID
                  "UnitName": "份", // 单位名称
                  "SaveNum": 5,   // 存酒数量
                  "PositionId": 2,   // 位置ID
                  "PositionName": "东A1柜"  // 位置名称
              }
          ]
     * }
     * * */
    addSaveWineStorage: "AddSaveWineStorage",

    /**
     * 获取操作人信息
     * 参数 staffId  员工ID
     * */
    getStaffById: "GetStaffById",

    /**
     * 取酒时发送验证码
     * 参数：mobile 手机号
     * */
    SendFetchValidSms: "SendFetchValidSms",

    /**
     * 验证取酒时发送验证码
     * post
     * 参数 {mobile: 手机号码， code: 验证码}
     * */
    ValidFetchSms: "ValidFetchSms",

    /**
     * 验证取酒时发送验证码
     * get
     * 参数 {mobile: 手机号码}
    * */
    GetBookCustomersByMPOS: "GetBookCustomersByMPOS",

    /**
     * MPOS酒楼模式下快速预订
     * post
     * 参数 {
     * mobile: 手机号码,
     * UserId: 用户ID，根据手机号没有搜索到则默认0。
     * UserType: 客户类型。0-未指定，1-粉丝，2-线下客户，3-会员,
     * RealName: 客户名字,
     * ExpectedArrivalTime: 预抵时间,
     * TableId: 餐台ID,
     * WaiterId: 服务员ID,
     * PeopleNum: 人数,
     * Remark: 顾客留言(备注)
     * }
    * */
    SaveTableBookByMPOS: "SaveTableBookByMPOS",

    /**
     * MPOS酒楼模式下获取该餐台最近快速预订信息
     * post
     * 参数 {
     * TableId: 餐台ID,
     * }
     * */
    GetLatestDiningBookByMPOS: "GetLatestDiningBookByMPOS",

    /**
     * 发送会员消费短信验证码接口
     * post
     * 参数 {
     *   memberCardId    会员卡ID
     *   realMobile    手机号
     *   consumptionId
     *   payAmount     付款金额
     * }
     * */
    SendConsumePayVerifyCode: "SendConsumePayVerifyCode",

    /**
     * 会员卡支付前短信验证
     * post
     * 参数 {
     *   Code: 验证码
     *   RealMobile：  手机号
     * }
     * */
    ValidConsumePayCode: 'ValidConsumePayCode',

    /**
     * 跳过会员消费短信验证
     * post
     * 参数 {
     * }
     * */
    SkipMemberConsumeSmsValid: 'SkipMemberConsumeSmsValid',

    /**
     * 桌台解锁
     * post 
     * 参数 {
     *  orderId: 0
     * }
     */
    UnLockTableByWholeOrderId: 'UnLockTableByWholeOrderId'

});

/**
 * 界面路由
 */
mpos.page = {
    "home": "home", //餐台列表
    "tableTaken": "tableTaken", //占菜餐台的操作界面
    "settle": "settle", //结账的操作界面
    "memberInput": "memberInput", //会员卡操作界面
    "billOrder": "billOrder", //账单界面
    "billOrderDetail": "billOrderDetail", //账单详情
    "settingPage": "settingPage", //设置界面
    "printStyle": "printStyle", //打印格式设置
    "aboutUs": "aboutUs", //关于我们
    "changeServer": "changeServer", //切换服务器
    "messageList": "messageList", //消息列表
    "settleOperationMore": "settleOperationMore", //占用餐台更多操作
    "weightdishes": "weightdishes", //菜品称重
    "orderDishes": "orderDishes", //点菜
    "orderMultiUnitDish": "orderMultiUnitDish", //多份量点菜没有做法时
    "orderDishForCooking": "orderDishForCooking", //有做法时点菜
    "allCookingForDishes": "allCookingForDishes", //整单做法
    "orderDishForGroupPackage": "orderDishForGroupPackage", //点分组套餐
    "orderDishForNormalPackage": "orderDishForNormalPackage", //点普通套餐
    "orderDishForMultiDish": "orderDishForMultiDish", //点一品多吃
    "memberRecharge": "memberRecharge", //会员卡充值
    "rechargeList": "rechargeList", //充值历史列表
    "rechargeDetail": "rechargeDetail", //充值详情
    "payToOrdeDetails": "payToOrdeDetails",
    "pushFood": "pushFood",  // 催菜
    "sellOut": "sellOut",  // 沽清
    "saveWinesManage": "saveWinesManage",   // 存酒管理
    "fetchWines": "fetchWines",   // 取酒
    "saveWines": "saveWines",   // 存酒
    "saveWinesChoose": "saveWinesChoose"   // 选择酒水
};

/**
 * 对话框路由
 */
mpos.dialogPage = {
    "login": "login", //登录界面
    "userAuth": "userAuth", //授权界面
    "authUnlockTable": "authUnlockTable", // 授权解锁餐台
    "giveDish": "giveDish", //赠送菜品
    "returnDish": "returnDish", //退菜
    "discountDish": "discountDish", //退菜
    "reductionAmount": "reductionAmount", //减免
    "wholeDiscount": "wholeDiscount", //整单折扣
    "discountScheme": "discountScheme", //折扣方案
    "invoicing": "invoicing", //补开发票
    "reverseSettle": "reverseSettle", //反结账
    "cashPay": "cashPay", //现金付款
    "freePay": "freePay", //免单付款
    "memberPay": "memberPay", //会员付款
    "creditPay": "creditPay", //挂账付款
    "ticketPay": "ticketPay", //票券付款
    "bankPay": "bankPay", //普通银行卡付款
    "wxOrAliPay": "wxOrAliPay", //第三支付付款
    "iBoxPayPay": "iBoxPayPay", //第三方银行付款
    "returnMemberPay": "returnMemberPay", //会员卡退款
    "prepayBillQr": "prepayBillQr", //预结二维码
    "inputCardPassword": "inputCardPassword", //输入会员卡密码
    "grouponPay": "grouponPay", //团购券付款
    "inputGrouponCode": "inputGrouponCode", //输入团购验证码
    "openTable": "openTable", //开台
    "tableOperation": "tableOperation", //餐台操作
    "modifyOpenTable": "modifyOpenTable", //修改台头
    "openBookOrderTable": "openBookOrderTable", //预订开台
    "changeRandomPriceDishPrice": "changeRandomPriceDishPrice", //临时菜改价
    "orderTempDish": "orderTempDish", //点临时菜
    "changeDishNum": "changeDishNum", //修改菜品数量
    "teaSelect": "teaSelect", //茶芥选择
    "selectSnackBrand": "selectSnackBrand", //选择餐牌
    "changeOrderDishPrice": "changeOrderDishPrice", //改价
    "selectWaiter": "selectWaiter", //选择服务员
    "rechargeCashPay": "rechargeCashPay", //充值现金支付,
    "wxOrAliRechargePay": "wxOrAliRechargePay", //微信或支付宝充值支付
    "lklRechargePay": "lklRechargePay", //拉卡拉充值支付
    "thirdPreferentialPay": "thirdPreferentialPay", //优惠买单
    "changeOrderTable": "changeOrderTable", //换台
    "cutTable": "cutTable", //搭台
    "addTableOrder": "addTableOrder", //加台
    "changeDishTable": "changeDishTable", //菜品转台
    "selectChangeDishTable": "selectChangeDishTable", //菜品转台选台
    "thirdCustomPay": "thirdCustomPay", //第三方自定义支付
    "changeOrderedTable": "changeOrderedTable", //下单换台
    "takeTypeDish": "takeTypeDish",  //类别点菜
    "saveWinesDetail": "saveWinesDetail",  //存酒详情
    "fetchWinesRemark": "fetchWinesRemark",  //存酒详情
    "saveWinesNumber": "saveWinesNumber",  //存酒数量
    "fetchWinesNumber": "fetchWinesNumber",  //取酒数量
    "saveWinesPlace": "saveWinesPlace",  //存酒位置
    "addSaveWinesInfo": "addSaveWinesInfo",  // 添加酒水信息
    "cookingSearch": "cookingSearch",  // 做法搜索
    "changeCookingNum": "changeCookingNum", //修改做法数量
    "memberSmsVerify": "memberSmsVerify", // 会员卡短信验证
    "fixedTicketPay": "fixedTicketPay",  // 固定面额抵扣票券
    "allHangupOrder": "allHangupOrder",  // 整单等叫界面
};

/**
 * 业务处理
 */
mpos.bl = {};

/**
 * 获取结账的数据
 * @param {Object} orderData 订单数据
 * @param {Function} callback 回调
 * @param {Object} options 参数
 */
mpos.getSettleInfo = function (orderData, callback, options) {
    var orderId = 0;
    var allowGetDish = true;
    var isSnackSettle = false;
    var allowGetPayment = true;
    if (typeof orderData == "object") {
        orderId = orderData.OrderId;
        allowGetDish = orderData.AllowGetDish == undefined ? true : orderData.AllowGetDish;
        isSnackSettle = orderData.IsSnackSettle == undefined ? false : orderData.IsSnackSettle;
        allowGetPayment = orderData.AllowGetPayment == undefined ? true : orderData.AllowGetPayment;
    } else {
        orderId = orderData;
    }
    mpos.post(mpos.api.getSettleInfo, {
        OrderId: orderId,
        AllowGetDish: allowGetDish,
        IsSnackSettle: isSnackSettle,
        AllowGetPayment: allowGetPayment
    }, function (data) {
        for (var i = 0; i < data.Orders.length; i++) {
            if (data.Orders[i].Order.OrderId == data.EnterOrderId) {
                data.EnterOrder = data.Orders[i];
                break;
            }
        }
        callback(data);
    }, options);
};

/**
 完善结账对象数据
 */
mpos.fixSettleInfo = function (settle) {
    for (var i = 0; i < settle.Orders.length; i++) {
        if (settle.Orders[i].Order.OrderId == settle.EnterOrderId) {
            settle.EnterOrder = settle.Orders[i];
            break;
        }
    }

    return settle;
};

/*获取简单的结账对象*/
mpos.getSimpleSettleInfo = function (orderId, callback, options) {
    mpos.getSettleInfo({
        OrderId: orderId,
        IsSnackSettle: false,
        AllowGetDish: false,
        AllowGetPayment: false
    }, callback, options);
};

/*付款*/
mpos.settlePayment = function (params, callback) {
    mpos.post(mpos.api.settlePayment, params, function (data) {
        for (var i = 0; i < data.Orders.length; i++) {
            if (data.Orders[i].Order.OrderId == data.EnterOrderId) {
                data.EnterOrder = data.Orders[i];
                break;
            }
        }
        callback(data);
    }, {timeout: 30000});
};

/*删除付款*/
mpos.clearSettlePaymentItem = function (params, callback) {
    mpos.post(mpos.api.clearSettlePaymentItem, params, function (data) {
        for (var i = 0; i < data.Orders.length; i++) {
            if (data.Orders[i].Order.OrderId == data.EnterOrderId) {
                data.EnterOrder = data.Orders[i];
                break;
            }
        }
        callback(data);
    })
};


/**
 * 获取原因
 * @param {Number} reasonType reason type
 * @param {Function} callback callback
 */
mpos.getReason = function (reasonType, callback) {
    mpos.post(mpos.api.getReasonList, {
        ReasonType: reasonType
    }, callback);
};

/**
 获取配置信息(同步)
 */
mpos.getShopConfigInfo = function () {
    mpos.post(mpos.api.getShopConfigInfo, null, function (data) {
        mpos.shopConfig = data;
        if (mpos.isDevice && data && typeof data === 'object') {
            mpos.mposUtils.loadShopConfig(data);
        }
        mpos.deviceFactory.onLogin();
    }, {
        hideLoading: true
    });
};

/**
 停卡监听磁卡
 */
mpos.isStopSearchMagCard = false;
mpos.stopSearchMagCard = function () {
    if (mpos.deviceFactory.deviceType != DeviceType.Normal) {
        mpos.isStopSearchMagCard = true;
        mpos.mposUtils.stopSearchMagCard();
    }
};

/**
 开始监听磁卡
 */
mpos.startSearchMagCard = function () {
    if (mpos.deviceFactory.deviceType != DeviceType.Normal) {
        mpos.isStopSearchMagCard = false;

        mpos.mposUtils.startSearchMagCard();
    }
};

/**
 获取刷卡值
 */
mpos.getMagCardNum = function (callback) {
    if (mpos.deviceFactory.deviceType != DeviceType.Normal) {
        mpos.mposUtils.getMagCardNum(null, function (data) {
            if (typeof (data) == 'object') {
                callback(data.CardNum);
                if (data.IsStop && !mpos.isStopSearchMagCard) {
                    mpos.startSearchMagCard();
                }
                return;
            }
            callback("");
        });
    }
};

/**
 * 
 * @param {any} config
 * @param {any} callback
 */
mpos.aliNfcPay = function (config, success, error) {
    if (mpos.deviceFactory.deviceType == DeviceType.AlipayNfcPos) {
        mpos.mposUtils.aliNfcPay(config, success, error);
    }
}

/**
 * 
 * @param {any} config
 * @param {any} callback
 */
mpos.alipayscanbarcode = function (success, error) {
    if (mpos.deviceFactory.deviceType == DeviceType.AlipayNfcPos) {
        mpos.mposUtils.alipayscanbarcode({}, success, error);
    }
}

mpos.alipayVoice = function (amount) {
    if (mpos.deviceFactory.deviceType == DeviceType.AlipayNfcPos) {
        mpos.mposUtils.alipayVoice({ "amount": amount }, function () { }, function () { });
    }
}

/**
 获取原因是否必选
 */
mpos.getReasonConfirm = function (callback) {
    mpos.post(mpos.api.getReasonConfirm, null, callback);
};

/**
 获取常用折扣
 */
mpos.getOftenDiscounts = function (callback) {
    mpos.post(mpos.api.getOftenDiscounts, null, callback);
};

/**
 获取当前营业日期
 */
mpos.getCurrentBusinessDate = function (callback) {
    var fmt = "yyyy-MM-dd";
    var currentDate = new Date();
    mpos.post(mpos.api.getCurrentBusinessDate, null, function (data) {
        //noinspection JSUnresolvedVariable
        currentDate = new Date(data.Date);
        if (typeof callback == 'function') {
            callback(currentDate.formatDate(fmt));
        }
    });
};

/**
 *添加exitApp事件
 */
mpos.addExitAppCallback(function () {
    if (mpos.currentUser != null) {
        mpos.post(mpos.api.forceUnLockTable, null, {
            timeout: 2000,
            hideLoading: true
        });
    }
});

/**
 获取菜品标签
 */
mpos.getDishTag = function (dish) {

    var dishProTag = "";
    if (dish.IsMainPackage) {
        dishProTag = "[套]";
    } else if (dish.IsPackageDishChild) {
        dishProTag = "&nbsp;&nbsp;-";
    } else if (dish.IsMultiMain) {
        dishProTag = "[多]";
    } else if (dish.IsMultiDishChild) {
        dishProTag = "&nbsp;&nbsp;-";
    }
    if (dish.IsTemporary) {
        dishProTag = "(临)" + dishProTag;
    }
    var dishBusinessTag = "<span>";
    if (dish.IsSpecialOfferDish) {
        dishBusinessTag += "(特)";
    }
    if (dish.PriceType == OrderDishPriceType.CustomerManual) {
        dishBusinessTag += "(砍)";
    }
    if (dish.IsFreeDish != 0) {
        dishBusinessTag += dish.IsFreeDish == 1 ? "(赠)" : "(券)";
    }
    if (dish.ReturnOrderDishId > 0) {
        dishBusinessTag += "(退)";
    }
    dishBusinessTag += "</span>";

    return dishBusinessTag + dishProTag;
};

/**
 转跳到结账
 @callBack 执行返回 参数1：true,false  参数2:结账实体
 */
mpos.jumpToSettlePage = function (orderId, fromWehere, callBack) {
    // var me = this;
    mpos.post(mpos.api.lockTableForSettle, {
        WholeOrderId: orderId
    }, function (r) {
        if (r != undefined) {
            if (r != "") {
                mpos.alert(r);
            } else {
                mpos.getSettleInfo(orderId, function (data) {
                    if (data.HasNeedConfirmWeighted) {
                        mpos.post(mpos.api.findNeedWeightDishes, {
                            DiningOrderId: orderId
                        }, function (r) {
                            if (r == undefined || r == null || r.length == 0) {
                                goSettle(data);
                            } else {
                                mpos.pick(mpos.page.weightdishes, {
                                    OrderId: orderId,
                                    Dishes: r,
                                    "wholeBillId": data.EnterOrder.Order.WholeBillId
                                }, function (status) {
                                    if (status) {
                                        mpos.getSettleInfo(orderId, function (r1) {
                                            goSettle(r1);
                                        });
                                        // return;
                                    }
                                });
                            }
                        });
                        // return;
                    } else {
                        goSettle(data);
                    }
                });
            }
        }

        //去结账
        function goSettle(data) {
            /*2016/11/14 去掉此功能*/
            //if (data.IsMarkServingDish && data.ExistsUndoneDish) {
            //    mpos.dialog({
            //        title: "提醒",
            //        text: "该餐台有菜品未划菜，确定是否付款？",
            //        okButton: "是",
            //        cancelButton: "否"
            //    }, function (status) {
            //        if (callBack) {
            //            callBack(status, data);
            //        }
            //        if (status) {
            //            mpos.load(mpos.page.settle, {
            //                settle: data,
            //                from: fromWehere
            //            });
            //            mpos.openedPayTable = true;
            //        }
            //    });
            //} else {
            if (callBack) {
                callBack(true, data);
            }
            mpos.load(mpos.page.settle, {
                settle: data,
                from: fromWehere
            });
            mpos.openedPayTable = true;
            //}
        }
    }, {
        blFailed: function(err) {
            mpos.showDialog(mpos.dialogPage.authUnlockTable, {
                errMsg: err.data
            }, function (result) {
                if (result) {
                    mpos.post(mpos.api.forceUnLockTable, null, null, {
                        hideLoading: true
                    });
                }
            }); 
            return false;   
        }
    });
};

/**
 * 预结
 * @param consumptionId 消费ID
 * @param preBilledOrderType 预结类型：1-自动，2-只取消结，3-只预结
 * @param callback callback function
 */
mpos.preBilledOrder = function (consumptionId, preBilledOrderType, callback) {
    var billId = mpos.preBilledOrderId();
    mpos.post(mpos.api.preBilledOrder, {
        ConsumptionId: consumptionId,
        BillId: billId, //打印单格式ID
        PreBilledOrderType: preBilledOrderType,
    }, function (data, status, xhr) {
        if (billId > 0) {
            //打印
            if (data != undefined && data.length > 0) {
                $.each(data, function (idx, item) {
                    for (var i = 0; i < mpos.preBilledOrderNumber(); i++) { //打印多份
                        var printData = mpos.addPrintEmptyLine(item);
                        mpos.deviceFactory.printTicket(printData, null, function (err) {
                            //打印
                            mpos.alert(err);
                        });
                    }
                });
            }
        }

        if (typeof callback == 'function') {
            callback();
        }
    });
};

/**
 * 验证金额输入
 * 2016-05-03：忽略掉type=number的判断，原因是加了focus时select之后，下面的判断会有问题
 * selectionStart和selectionEnd在type=number的时候不受支持，判断将不对
 *
 * @param {ZeptoCollection} $input input HTMLElement
 * @param type InputType
 */
mpos.checkInputValue = function ($input, type) {
    // //只有下面的几种input才有selectionStart和selectionEnd
    // if (!(/text|password|search|tel|url/.test($input[0].type)))
    //     return;
    $input.on("keypress", function (e) {
        // 如果输入框是number类型，在输入小数0.时下一个输入时，输入框的内容将只能取到0，无法取到小数点 ，思路在下面
        var num = $.trim(this.value);
        var keynum = e.which || e.keyCode;
        var keychar = String.fromCharCode(keynum);
        var ep = InputType[type];

        if (ep == null) {
            return true;
        }
        //判断是否有选中的部分
        //type 为以下类型的处理选中部分
        if (/text|password|search|tel|url/.test(this.type)) {
            if (this.selectionEnd > this.selectionStart) {
                num = num.substr(0, this.selectionStart) + keychar + num.substr(this.selectionEnd);
            } else {
                num += keychar;
            }
        } else {
            //根据window.getSelection来处理选中的内容
            //注意这里的处理是替换，所以可能会不准，由于默认是全部选中，以及还有其他判断，可以忽略
            var sel = window.getSelection ? window.getSelection().toString() : "";
            if (sel.length > 0 && document.activeElement == this) {
                num = num.replace(sel, keychar);
            } else {
                /*
                 * 思路：如果输入框类型是number，在判断拼接的值num为01这样的，同时正则类型为DishNum=2，可以统一修改为0.1，因为01正则无法通过
                 * 这个思路是解决所有的number输入框，但没有开始使用，不确定是否有问题  wang.p  2021-09-08
                 */
                num += keychar;
            }
        }
        return ep.test(num);
    });
};

/**
 检查是否为金额
*/
mpos.isAmount = function (str) {
    if ($.trim(str).length == 0) {
        return false;
    }
    if (isNaN(str)) {
        return false;
    }
    var ep = InputType[InputType.Amount];

    return ep.test(str);
}

/**
 打印数据增加前后空行
 */
mpos.addPrintEmptyLine = function (data) {

    if (Array.isArray(data) && data.length > 0) {
        var insertObj = {
            text: " ",
            type: 1,
            size: 1
        };
        var headerLine = mpos.billHeadNumber();
        var footLine = mpos.billFootNumber();
        var returnData = [];
        if (headerLine == 0 || footLine == 0) {
            return data;
        }
        for (var i = 0; i < headerLine; i++) {
            returnData.push(insertObj);
        }
        for (var j = 0; j < data.length; j++) {
            returnData.push(data[j]);
        }
        for (var k = 0; k < footLine; k++) {
            returnData.push(insertObj);
        }

        return returnData;
    }

    return data;
};

mpos.BaseData = {
    /*菜品对象*/
    Dishes: [], //基础菜品数据
    DishesFlag: "",
    DishTypes: [], //类别数据
    DishTypesFlag: "",
    Cookings: [], //做法
    CookingsFlag: "",
    CookingTypes: [], //做法类型
    CookingTypesFlag: "",
    PackageDishes: [], //套餐数据
    PackageDishesFlag: "",
    Staffs: [], //员工
    StaffsFlag: "",
    BusinessTimespans: [], //市别
    BusinessTimespansFlag: "",
    BigDishType: [],  // 商品大类
    BaseBigDishTypeFlag: "",  //
    BaseMulitDishFlag: '', // 一品多吃更新标识
    BaseMulitDishes: [],  // 一品多吃数据
    BeginRequestBaseInfo: false, //是否正在请求
    HasStartSyncGetBaseInfo: false, //是否开始获取基础数据
    IntervalTimeoutHandle: null, //timeout 对象
    IntervalTimeout: 60 * 1000, //定时取数据时间
};

/**
 停止获取基础数据
 */
mpos.StopSyncGetBaseInfo = function () {
    if (mpos.BaseData.IntervalTimeoutHandle) {
        clearTimeout(mpos.BaseData.IntervalTimeoutHandle);
    }
    mpos.BaseData.HasStartSyncGetBaseInfo = false;
    mpos.BaseData.BeginRequestBaseInfo = false;
    mpos.BaseData.Dishes = []; //基础菜品数据
    mpos.BaseData.DishesFlag = "";
    mpos.BaseData.DishTypes = []; //类别数据
    mpos.BaseData.DishTypesFlag = "";
    mpos.BaseData.Cookings = []; //做法
    mpos.BaseData.CookingsFlag = "";
    mpos.BaseData.CookingTypes = []; //做法类型
    mpos.BaseData.CookingTypesFlag = "";
    mpos.BaseData.PackageDishes = []; //套餐数据
    mpos.BaseData.PackageDishesFlag = "";
    mpos.BaseData.BigDishType = [];  // 商品大类
    mpos.BaseData.BigDishTypeFlag = "";  //
    Staffs = []; //员工
    StaffsFlag = "";
    BusinessTimespans = []; //市别
    BusinessTimespansFlag = "";
};

/**
 获取基础菜品数据
 @param {Number} dishId
 @return {Object|null} Dish dish object
 */
mpos.GetBaseDishInfo = function (dishId) {
    var dish = mpos.BaseData.Dishes[dishId];
    if (dish == undefined) {
        return null;
    }
    return dish;
};

/**
 获取基础菜品的单位
 @param {Object} baseDish
 @param {Number} unitId
 @return {Object|null} dishUnit
 */
mpos.GetBaseUnitInfo = function (baseDish, unitId) {
    if (baseDish.Units && baseDish.Units.length > 0) {
        var units = baseDish.Units.filter(function (item, index) {
            return item.PortionsId == unitId;
        });
        if (units == null || units.length == 0) {
            return null;
        }
        return units[0];
    }

    return null;
};

/**
 获取套餐数据
 @param {Number} dishId
 @return {Object|null} package dish object
 */
mpos.GetPackageDishInfo = function (dishId) {
    var packageDish = mpos.BaseData.PackageDishes.filter(function (item, index) {
        return item.DishId == dishId;
    });
    if (packageDish == null || packageDish.length == 0) {
        return null;
    }
    return packageDish[0];
};

/**
 获取一品多吃数据
 @param {Number} dishId
 @return {Object|null} package dish object
 */
mpos.GetMulitDishInfo = function (dishId, orderDishId, orderDishData) {
    var multiDish = mpos.BaseData.BaseMulitDishes.filter(function (item, index) {
        return item.DishId == dishId;
    });
    if (multiDish == null || multiDish.length == 0) {
        return null;
    }

    // multiSubDishList: r.MultiSubDishList,   // 一品多吃的子菜集合
    //   dishNum: 1,   // 主菜数量
    //   dishCookings: dishCookings,   // 做法数组
    //   orderDishCookings: [],  // 已选主菜做法
    //   orderMultiSubDishList: [], // 已选子菜


    return JSON.parse(JSON.stringify(multiDish[0]));
};


/**
 开始异步加载基础数据
 */
mpos.StarSyncGetBaseInfo = function () {
    if (mpos.BaseData.HasStartSyncGetBaseInfo) {
        return;
    }

    function SyncGetBaseInfo() {
        mpos.InitBaseInfo();
        mpos.BaseData.IntervalTimeoutHandle = setTimeout(SyncGetBaseInfo, mpos.BaseData.IntervalTimeout);
    }

    setTimeout(SyncGetBaseInfo, 5000);
    mpos.BaseData.HasStartSyncGetBaseInfo = true;
};

/**
 获取基础数据
 */
mpos.InitBaseInfo = function (okCallback, errorCallback) {
    if (mpos.BaseData.BeginRequestBaseInfo) {
        if (okCallback) {
            okCallback();
        }
        return;
    }
    mpos.BaseData.BeginRequestBaseInfo = true;
    mpos.post(mpos.api.loadBaseDataCache, {
        // 基础菜品缓存标记
        BaseDishFlag: mpos.BaseData.DishesFlag,
        //基础套餐数据缓存标记
        BasePackageDishFlag: mpos.BaseData.PackageDishesFlag,
        // 菜品小类缓存标识
        BaseDishTypeFlag: mpos.BaseData.DishTypesFlag,
        // 做法缓存标识
        BaseCookingFlag: mpos.BaseData.CookingsFlag,
        // 做法类型缓存标识
        BaseCookingTypeFlag: mpos.BaseData.CookingTypesFlag,
        StaffsFlag: mpos.BaseData.StaffsFlag,
        BusinessTimespansFlag: mpos.BaseData.BusinessTimespansFlag,
        BaseBigDishTypeFlag: mpos.BaseData.BigDishTypeFlag
    }, function (result) {
        if (result.DishCache.RequireUpdate) {
            mpos.BaseData.DishesFlag = result.DishCache.Flag;
            var dishes = {};
            result.DishCache.Data.forEach(function (item) {
                dishes[item.Dish.DishId] = item;
            });
            mpos.BaseData.Dishes = dishes;
        }
        if (result.DishTypeCache.RequireUpdate) {
            mpos.BaseData.DishTypesFlag = result.DishTypeCache.Flag;
            mpos.BaseData.DishTypes = result.DishTypeCache.Data;
        }
        // 商品大类
        if (result.BigDishTypeCache.RequireUpdate) {
            mpos.BaseData.BigDishTypeFlag = result.BigDishTypeCache.Flag;
            mpos.BaseData.BigDishType = result.BigDishTypeCache.Data;
        }
        if (result.CookingCache.RequireUpdate) {
            mpos.BaseData.CookingsFlag = result.CookingCache.Flag;
            mpos.BaseData.Cookings = result.CookingCache.Data;
        }
        if (result.CookingTypeCache.RequireUpdate) {
            mpos.BaseData.CookingTypesFlag = result.CookingTypeCache.Flag;
            mpos.BaseData.CookingTypes = result.CookingTypeCache.Data;
        }
        if (result.PackageCache.RequireUpdate) { //套餐需要额外处理
            mpos.BaseData.PackageDishesFlag = result.PackageCache.Flag;
            var packageData = result.PackageCache.Data;
            var packageModels = [];
            $.each(packageData, function (idex, item) {
                var model = {};
                model.DishId = item.DishId;
                model.PackageDishList = item.PackageDishList;
                //分组套餐
                var group = item.PackageGroupList;
                var packageGroupList = [];
                $.each(group, function (idx, item) {
                    var groupModel = {};
                    groupModel.PackageGroup = item.PackageGroup;
                    groupModel.PackageDishList = [];
                    groupModel.PackageGroupMustDishList = [];
                    groupModel.PackageGroupNotMustDishList = [];
                    $.each(model.PackageDishList, function (idx, itemMain) {
                        if (itemMain.PackageDish.DishPackageGroupId == item.PackageGroup.DishPackageGroupId) {
                            groupModel.PackageDishList.push(itemMain);
                            if (itemMain.PackageDish.IsMust == 1) {
                                groupModel.PackageGroupMustDishList.push(itemMain);
                            } else {
                                groupModel.PackageGroupNotMustDishList.push(itemMain);
                            }
                        }
                    });
                    packageGroupList.push(groupModel);
                });
                model.PackageGroupList = packageGroupList;

                //必选
                var must = [];
                $.each(model.PackageDishList, function (idx, item) {
                    if (item.PackageDish.IsMust == 1) {
                        must.push(item);
                    }
                });
                model.MustPackageDishList = must;
                //可选
                var notmust = [];
                $.each(model.PackageDishList, function (idx, item) {
                    if (item.PackageDish.IsMust == 0) {
                        notmust.push(item);
                    }
                });
                model.NotMustPackageDishList = notmust;
                //替换菜
                var replaceModel = [];
                $.each(model.PackageDishList, function (idx, item) {
                    replaceModel = replaceModel.concat(item.ReplacePackageDishList);
                });
                model.DishPackageReplaceList = replaceModel;

                packageModels.push(model);
            });
            mpos.BaseData.PackageDishes = packageModels;
        }
        // 一品多吃
        if (result.MulitDishCache && result.MulitDishCache.RequireUpdate) {
            mpos.BaseData.BaseMulitDishFlag = result.MulitDishCache.Flag;
            mpos.BaseData.BaseMulitDishes = result.MulitDishCache.Data
        }

        if (result.StaffsCache.RequireUpdate) {
            mpos.BaseData.StaffsFlag = result.StaffsCache.Flag;
            mpos.BaseData.Staffs = result.StaffsCache.Data;
        }

        mpos.BaseData.BeginRequestBaseInfo = false;
        if (okCallback) {
            okCallback();
        }
    }, {
        hideLoading: true,
        error: function () {
            mpos.BaseData.BeginRequestBaseInfo = false;
            if (errorCallback) {
                errorCallback();
            }
        }
    });
};


/**
 赠送
 * @param {Object} dish
 * @param {Function} [callback]
 * @parms {boolean}  unSubmit  未下单的赠送
 */
mpos.giveDish = function (dish, callback, unSubmit) {
    mpos.showDialog(mpos.dialogPage.giveDish, {
        Dish: dish,
        UnSubmit: unSubmit
    }, function (status) {
        if (status) {
            if (callback) {
                callback(status);
            }
        }
    });
};

/**
 取消赠送
 * @param {Object} dish
 * @param {Function} [callback]
 */
mpos.cancelGiveDish = function (dish, callback) {
    mpos.post(mpos.api.setOrCanelFreeDish, {
        OrderDishId: dish.OrderDishId,
        DiningOrderId: dish.DiningOrderId,
        DishNum: dish.RealDishNum
    }, function (data) {
        if (callback) {
            callback();
        }
    });
};

/**
 退菜
 * @param {Object} dish
 * @param {Function} [callback]
 */
mpos.returndish = function (dish, callback) {
    mpos.showDialog(mpos.dialogPage.returnDish, {
        Dish: dish
    }, function (status) {
        if (status) {
            if (callback) {
                callback();
            }
        }
    });
};

/**
 * 折扣
 * @param {Object} dish
 * @param {Function} [callback]
 */
mpos.discountDish = function (dish, callback) {
    mpos.showDialog(mpos.dialogPage.discountDish, {
        Dish: dish
    }, function (status) {
        if (status) {
            if (callback) {
                callback();
            }
        }
    });
};

/**
 * 改价
 * @param {Object} dish 需要改价的菜品
 * @param {Function} [callback]
 */
mpos.changeDishPrice = function (dish, callback) {
    mpos.showDialog(mpos.dialogPage.changeOrderDishPrice, {
        Dish: dish
    }, function (status) {
        if (status) {
            if (callback) {
                callback();
            }
        }
    });
};

/**
 * 起菜
 * @param {Object} dish
 * @param {Number} orderId
 * @param {Function} callback
 */
mpos.qicai = function (dish, orderId, callback) {
    var printSigleBill = mpos.printSigleBill();
    var printTotalBill = mpos.printTotalBill();
    mpos.post(mpos.api.takeOrderDishes, {
        OrderId: orderId,
        PrintTotalBill: printTotalBill == 1,
        PrintSigleBill: printSigleBill == 1,
        OrderDishId: dish.OrderDishId,
    }, function (r) {
        //本地打印总单
        if (r.TotalBillGrids != null && Array.isArray(r.TotalBillGrids)) {
            $.each(r.TotalBillGrids, function (index, item) {
                var printData = mpos.addPrintEmptyLine(item);
                mpos.deviceFactory.printTicket(printData, null, function (err) {
                    //打印
                    mpos.alert(err);
                });
            })
        }
        //本地打印分单
        if (r.SigleBillGrids != null && Array.isArray(r.SigleBillGrids)) {
            $.each(r.SigleBillGrids, function (index, item) {
                var printData = mpos.addPrintEmptyLine(item);
                mpos.deviceFactory.printTicket(printData, null, function (err) {
                    //打印
                    mpos.alert(err);
                });
            })
        }
        mpos.alert("已" + mpos.shopConfig.TakeCalledDescption);
        // 回调函数
        if (callback && typeof callback == 'function') {
          callback();
        }
    });
};

/**
 * 催菜
 * @param {Object} dish
 * @param {Number} orderId
 * @param {Function} callback
 */
mpos.cuicai = function (dish, orderId, callback) {
    mpos.post(mpos.api.reminderDish, {
        OrderId: orderId,
        OrderDishId: dish.OrderDishId,
    }, function (r) {
        if (r != undefined) {
            mpos.alert(r);

            if (r.indexOf('失败') != -1) {
              return;
            }
            // 回调函数
            if (callback && typeof callback == 'function') {
              callback();
            }
        }

    });
};

/**
 * 划菜
 * @param {Object} dish
 * @param {Number} orderId
 * @param {Function} callback
 */
mpos.huacai = function (dish, orderId, callback) {
  mpos.post(mpos.api.setFinishOrderDish, {
    OrderId: orderId,
    OrderDishId: dish.OrderDishId,
  }, function (r) {
    if (r != undefined) {
      if (r != '') {
        mpos.alert(r);
      } else {
        mpos.alert("划菜成功！");
      }
      callback && callback();
    }
  });
};

/**
 * 是否为下单支付模式
 */
mpos.isPayToOrderModel = function () {
    if (mpos.localStorage.OrderPropertyType == OrderPropertyType.Snack) {
        return false;
    }

    if (mpos.localStorage.PayToOrder == undefined) {
        return false;
    }

    return mpos.localStorage.PayToOrder;
}

/**
 * 日期格式化
 * @fmt  格式化类型
 * @date 日期
 * */
mpos.dateFormat = function (date, fmt) {
    var ret = '';
    var format = fmt || 'YYYY-MM-DD';
    var opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "M+": (date.getMonth() + 1).toString(),     // 月
        "D+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "m+": date.getMinutes().toString(),         // 分
        "s+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };

    var padStartFunc = function (value, total, str) {
        var len = value.toString().length;
        if (len < total) {
            var strArray = '';
            var count = total - len;
            for (var i = 0; i < count; i++) {
                strArray += str;
                if (strArray.length > count) {
                    break;
                }
            }
            strArray = strArray.substring(0, count);
            return strArray + value.toString();

        } else {
            return value;
        }

    }

    for (var k in opt) {
        ret = new RegExp("(" + k + ")").exec(format);
        if (ret) {
            format = format.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : padStartFunc(opt[k], ret[1].length, "0"))
        };
    };
    return format;
}


/**
 * DES-解密
 * @encryptedBase64  密文
 * @key  秘钥
 * */
mpos.decryptDES = function (encryptedBase64, key) {
  // 处理密钥（截取前8字符，UTF8编码）
  const truncatedKey = key.substring(0, 8);
  const keyBytes = CryptoJS.enc.Utf8.parse(truncatedKey);

  // IV与密钥相同（转换为UTF8编码）
  const ivBytes = CryptoJS.enc.Utf8.parse(truncatedKey);

  // 转换Base64密文为CipherParams对象
  const cipherParams = CryptoJS.lib.CipherParams.create({
    ciphertext: CryptoJS.enc.Base64.parse(encryptedBase64)
  });

  // 执行DES解密（CBC模式 + PKCS7填充）
  const decrypted = CryptoJS.DES.decrypt(
    cipherParams,
    keyBytes,
    {
      iv: ivBytes,
      mode: CryptoJS.mode.CBC,    // 需与C#默认的CBC模式一致[5,7](@ref)
      padding: CryptoJS.pad.Pkcs7 // 需与C#的PKCS7填充一致[1](@ref)
    }
  );

  // 将解密结果转为UTF8字符串
  return decrypted.toString(CryptoJS.enc.Utf8);
}

/**
 * 关于我们界面
 */
mpos.controller(mpos.page.aboutUs, function (page) {
    $(page).find(".app-content").find(".pos-version").text(appVersion);
    var config = mpos.shopConfig.UserOemInfo;
    var random = Math.round(Math.random()*1000);
    if (!!config && config.IsEnableOem) {
      $(page).find(".app-content").find(".pos-icon").css({
        "background": "url(" + config.OemCloudPosSoftLogo + "&" + random + ") 0 0/230px 130px no-repeat"
      });
      $(page).find(".app-content").find(".company-logo").css({
        "background": "url(" + config.OemCloudPosCompanyLogo + "&" + random + ") 0 0/56px 20px no-repeat"
      });
      $(page).find(".app-content").find(".company-name").text(config.OemCompanyName);
      var $companyInfo = $(page).find(".app-content").find(".company-info");
      $companyInfo.find(".address").text(config.OemCompanyAddress);
      $companyInfo.find(".tel").text(config.OemCompanyPhone);
      $companyInfo.find(".post-code").text(config.OemCompanyPostCode);
      $companyInfo.find(".email").text(config.OemCompanyEmail);
      $companyInfo.find(".website").text(config.OemCompanyWebSite);
    }
});
/**
 * Created by xeonwell on 2016/2/16.
 *
 * 整单做法
 */
mpos.controller(mpos.page.allCookingForDishes, function (page, data) {

    var orderDishData = data.OrderDishData;

    var wholeBillId = data.WholeBillId;
    var selectedCookings = []; //选中的做法
    var hasOrderDishes = [];//已点菜品
    var customCookings = [];  // 手写做法

    $.selectOnFocus(page);
    var $page = $(page);
    $page.data("whole_order_id", wholeBillId); //设置被踢出检测

    var $orderNewDish = $page.find(".order-new-dish");//点新菜

    var cookingContainer = $page.find(".cooking-container");
    var $cookingItem = cookingContainer.find(".cooking-item").remove();

    var moreCookingContainer = $page.find(".more-cooking-container");
    var $moreCookingItem = moreCookingContainer.find(".cooking-item").remove();

    var $handCookieName = $page.find("input[name='hand_cookie_name']");
    var $handCookiePrice = $page.find("input[name='hand_cooke_price']");
    // 手写做法新增按钮 
    var $customCookingBtn = $page.find("button.custom-cooking-btn");
    var $customCookingList = $page.find(".custom-cooking-list");   // 手写做法的列表

    var me = this;

    //加载UI
    initUI();

    $.selectOnFocus(page);

    //返回事件
    function backToPrev() {
        me.reply();
    }
    this.onBackKeyDown = backToPrev;
    $page.find("#goBack").on("click", backToPrev);

    //提交
    $page.find(".ok.app-submit").on("click", function (e) { 
        //移除手写做法
        for (var i = 0; i < selectedCookings.length; i++) {
            if (selectedCookings[i].CookingId <= 0) {
                selectedCookings.splice(i, 1);
                break;
            }
        }
        // 添加手写做法
        if (customCookings.length > 0) {
            for(var i = 0; i < customCookings.length; i++) {
                selectedCookings.push(customCookings[i]);
            } 
        }  

        if (selectedCookings.length > 0) {
            orderDishData.applyAllCookies(selectedCookings);
        }

        me.reply();

    });

    /*
     加载做法
     */
    function loadDishCooking() {
        cookingContainer.empty();
        //填充所有做法到更多
        var allCookingIds = [];
        for (var i = 0; i < orderDishData.cookings.length; i++) {
            allCookingIds.push(orderDishData.cookings[i].RequestId);
        }
        var allCookingGroup = orderDishData.getGroupCookingsSort(allCookingIds);
        moreCookingContainer.empty();
        var fragment = $(document.createDocumentFragment());
        for (var cookingGroup=0; cookingGroup < allCookingGroup.length; cookingGroup++) {
            var cookingItem = $moreCookingItem.clone();
            cookingItem.find(".cooking-type-name").text(allCookingGroup[cookingGroup].RequestName);
            var cookinglist = cookingItem.find(".cooking-list");
            for (var j = 0; j < allCookingGroup[cookingGroup].Cookings.length; j++) {
                var c = allCookingGroup[cookingGroup].Cookings[j];
                var price = "";
                if (c.RequestPrice > 0) {
                    price = "(+" + mpos.formatPrice(c.RequestPrice) + ")";
                }
                cookinglist.append("<span data-c_id='" + c.RequestId + "' class='cooking-name textEllipsis'>" + c.CookingName + price + "</span>");
            }
            fragment.append(cookingItem);
        }

        moreCookingContainer.append(fragment);
        fragment = null;

        //做法选中事件
        cookingContainer.find("span[data-c_id]").on("click", function (e) {
            selectCooking(e);
        });
        //更多中的做法选中事件
        moreCookingContainer.find("span[data-c_id]").on("click", function (e) {
            selectCooking(e);
        });
    }

    /*
     点击做法事件
     */
    function selectCooking(e) {
        var $target = $(e.currentTarget);
        var cookingId = $target.data("c_id");
        var cooking = orderDishData.getCookingById(cookingId);
        var cookingName = cooking.RequestName;
        var requestPrice = cooking.RequestPrice;
        var requestId = cooking.RequestId;
        if ($target.hasClass("selected")) {
            for (var i = 0; i < selectedCookings.length; i++) {
                if (selectedCookings[i].CookingId == requestId) {
                    selectedCookings.splice(i, 1);
                    break;
                }
            }
        } else {
            selectedCookings.push({
                CookingId: requestId,
                CookingName: cookingName,
                CookingPrice: requestPrice,
                Num: 1
            });
        }
        //更新选中的样式
        var allCookingTargets = $page.find("span[data-c_id='" + cookingId + "']");
        var isSelected = $target.hasClass("selected");
        for (var j = 0; j < allCookingTargets.length; j++) {
            if (isSelected) {
                $(allCookingTargets[j]).removeClass("selected");
            } else {
                $(allCookingTargets[j]).addClass("selected");
            }
        }
    }

    /**
     * 加载UI
     */
    function initUI() {
        mpos.checkInputValue($handCookiePrice, InputType.Amount);
        //加载做法
        loadDishCooking();
    }

    /**
     * 点击添加手写做法按钮
     * */
    $customCookingBtn.on('click', function () { 
        //手写做法
        var handCookieName = $.trim($handCookieName.val());
        var handCookiePrice = $handCookiePrice.val(); 
        if (handCookieName == "") {
            mpos.alert("手写做法名称不能为空！");
            return;
        }

        if (handCookiePrice == "") {
            handCookiePrice = 0;
        }
        if (!mpos.isAmount(handCookiePrice)) {
            mpos.alert("手写做法价格输入错误");
            return;
        }
        handCookiePrice = Number(handCookiePrice);
        if (handCookiePrice < 0) {
            mpos.alert("手写做法价格不能小于0！");
            return;
        }
        // 遍历最小的ID
        var minCookingId = 0;
        if (customCookings.length > 0) {
            for(var i=0;i<customCookings.length;i++) {
                if (customCookings[i].CookingId < minCookingId) {
                    minCookingId = customCookings[i].CookingId;
                }
            }
        }

        customCookings.push({
            CookingId: (minCookingId - 1),
            CookingName: handCookieName,
            CookingPrice: handCookiePrice,
            Num: 1
        });

        // 重新渲染手写做法数组
        initHandCookie();
        // 清空手写输入内容
        $handCookieName.val('');
        $handCookiePrice.val(''); 
    })

    /**
     * 加载手写做法
     */
    function initHandCookie() {
        $customCookingList.empty();
        if (!customCookings || customCookings.length == 0) {
            return;
        }  
        for (var j = 0; j < customCookings.length; j++) {
            var c = customCookings[j];
            var price = "";
            if (c.CookingPrice > 0) {
                price = "(+" + mpos.formatPrice(c.CookingPrice) + ")";
            }
            $customCookingList.append("<span data-c_id='" + c.CookingId + "' class='cooking-name textEllipsis'><span class='delete-icon'>x</span>" + c.CookingName + price + "</span>");
        }
        //异常手写做法
        $customCookingList.find("span[data-c_id]").on("click", function (e) { 
            deleteCustomCooking(e);
        });
    }

    /**
     * 删除手写做法  
     */
    function deleteCustomCooking(e) {
        var $target = $(e.currentTarget);
        var cookingId = $target.data("c_id"); 
        for (var i = 0; i < customCookings.length; i++) {
            if (customCookings[i].CookingId == cookingId) {
                customCookings.splice(i, 1);
                break;
            }
        } 
        initHandCookie();
    }
});

/**
 * 账单列表
 */
mpos.controller(mpos.page.billOrder, function (page) {
    var $page = $(page);
    //date format
    var fmt = "yyyy-MM-dd",
        fmtTime = "HH:mm";


    var pageIndex = 1;
    var keyword = "";

    //list for operate
    var $list = $page.find(".app-list.billOrder-list");
    //template
    var $item = $list.find("li.app-button").remove();
    //loading animation
    var $loading = $page.find(".scrollLoading").remove();
    // can load more?
    var canLoadMore = true;

    var currentDate = new Date();
    mpos.getCurrentBusinessDate(function(businessDate){
        currentDate = new Date(businessDate);
        $page.find("span.bill-date").text(currentDate.formatDate(fmt));
        $page.find('input[name=currentDay]').val(currentDate.formatDate(fmt));
        getBillOrderList();
    });


    /**
     * 重置条件并开始请求
     */
    function resetConditions() {
        $page.find("span.bill-date").text(currentDate.formatDate(fmt));
        pageIndex = 1;
        canLoadMore = true;
        $list.empty();
        getBillOrderList();
    }

    //搜索框
    $page.find("form.billOrder-search-form").on("submit", function(){
       keyword = $page.find("input[name=billOrderKeyword]").val().trim();
       resetConditions();
       return false;
    });

    //日期控件
    $page.find("span.bill-date").text(currentDate.formatDate(fmt));
    $page.find('input[name=currentDay]').val(currentDate.formatDate(fmt))
        .on("change", function () {
            currentDate = new Date(this.value);
            resetConditions();
        });

    //前一天
    $page.find(".previous-day").on("click", function () {
        currentDate = currentDate.yesterday();
        $page.find('input[name=currentDay]').val(currentDate.formatDate(fmt));
        resetConditions();
    });

    //后一天
    $page.find(".next-day").on("click", function () {
        currentDate = currentDate.tomorrow();
        $page.find('input[name=currentDay]').val(currentDate.formatDate(fmt));
        resetConditions();
    });

    /**
     * 从服务端获取账单列表
     */
    function getBillOrderList() {

        mpos.infiniteScroll($list, {
            loading: $loading
        }, function (callback) {
            if (!canLoadMore)
                return null;

            mpos.post(mpos.api.queryConsumptionBill, {
                BusinessDate: currentDate.formatDate(fmt),
                Keyword: keyword,
                PageSize: Config.DefaultPageSize,
                PageIndex: pageIndex++
            }, function (data) {
                if (!Array.isArray(data)) {
                    mpos.alert("返回数据格式不对");
                    canLoadMore = false;
                    return;
                }
                var list = [];
                canLoadMore = data.length == Config.DefaultPageSize;
                data.forEach(function (item, index) {
                    //if (typeof jsonModelBillOrder == 'object') {
                    //    item = jsonModelBillOrder;
                    //}

                    var $node = $item.clone();
                    $node.find(".billOrder-number").text(item.SerialNumber);
                    $node.find(".diningtable-number").text(item.TableName);
                    $node.find(".billOrder-time").text((new Date(item.BillDate)).formatDate(fmtTime));
                    $node.find(".billOrder-amount").text(mpos.formatPrice(item.NeedPayAmount));
                    $node.on('click', function (e) {
                        e.stopPropagation();
                        mpos.pick(mpos.page.billOrderDetail, item, function (data) {
                            if (data == "1") {
                                //这里刷新单据，因为有反结账的了
                                resetConditions();
                            }
                        });
                    });

                    list.push($node);
                });
                callback(list);

            }, {
                hideLoading: true
            });
        });
    }

});

/**
 * 账单详情
 */
mpos.controller(mpos.page.billOrderDetail, function (page, args) {
    var $page = $(page);
    var fmt = "yy-MM-dd HH:mm:ss";
    var consumptionId = args.ConsumptionId;
    var settleData = [];
    var currentBusinessDate;
    var $repaymentSettle = $page.find("#repaymentSettle");
    var $invoicing = $page.find("#invoicing");
    //var me = this;

    var $tableName = $page.find(".table-name").remove();
    var $tableInfo = $page.find(".table-info").remove();
    var $dishItem = $page.find(".dish-item").remove();
    var $dishList = $page.find(".table-dish-list").remove();
    var $consumptionAmount = $page.find(".consumption-amount").remove();

    loadConsumptionDetailData();
    /*
    补打银单
    */
    $page.find("#printBill").on("click", function () {
        var billId = mpos.localStorage.CashOrderId;
        var printNum = mpos.cashOrderNumber();
        if (billId == 0) {
            mpos.alert("未设置打印小票格式！");
            //mpos.load(mpos.page.printStyle);
            return;
        }
        mpos.post(mpos.api.getPrintBill, {
            ConsumptionId: consumptionId,
            BillId: billId, //打印单格式ID
            BillType: 1,
        }, function (data, status, xhr) {
            //打印
            if (data != undefined && data.length > 0) {
                for (var i = 0; i < printNum; i++) { //打印多份
                    mpos.deviceFactory.printTicket(data, null, function (err) {
                        //打印
                        mpos.alert(err);
                    });
                }
            }
        });
    });

    /*
   补开发票
   */
    $invoicing.on("click", function () {
        mpos.showDialog(mpos.dialogPage.invoicing, {
            settle: settleData
        }, function (status) {
            if (status) {
                loadConsumptionDetailData();
            }
        });
    });

    /*
   反结账
   */
    $repaymentSettle.on("click", function () {
        mpos.showDialog(mpos.dialogPage.reverseSettle, {
            settle: settleData
        }, function (status) {
            if (status) {
                mpos.isNeedReloadTable = true;
                mpos.jumpToSettlePage(settleData.EnterOrder.Order.WholeBillId, "home");
            }
        });
    });

    /*
    显示单据
    */
    function showConsumptionDetail() {
        //快餐不显示反结账和开发票
        if (settleData.EnterOrder.Order.OrderProperty == OrderPropertyType.Snack) {
            $repaymentSettle.hide();
            $invoicing.hide();
        }
        //不是当前营业日不显示反结账
        if (new Date(currentBusinessDate).getDate() != new Date(settleData.Consumption.BusinessDate).getDate()) {
            $repaymentSettle.hide();
        }

        //移除
        $page.find(".app-content").empty();

        var fragment = $(document.createDocumentFragment());

        var tableName = $tableName.clone();
        var tableInfo = $tableInfo.clone();
        var dishList = $dishList.clone();

        //输出开台信息
        var openTableInfo = findOpenTableInfo(settleData.EnterOrder.Order.OrderId);

        //餐台名称
        tableName.find(".name").text(settleData.EnterOrder.Table.TableName + (settleData.EnterOrder.Order.IsMain == 1 ? "(主)" : ""));
        //交易流水号
        tableName.find(".serail-number").text("交易流水号：" + settleData.Consumption.SerialNumber);
        //会员
        if (settleData.MemberName != "") {
            $('<div class="member-name" />').text("会员：" + settleData.MemberName).appendTo(tableName);
        }
        //输出开台信息
        tableInfo.find(".table-time").text("开台时间：" + (new Date(settleData.EnterOrder.Order.BeginTime)).formatDate(fmt));
        tableInfo.find(".table-people").text("人数：" + settleData.EnterOrder.Order.PeopleNum);
        tableInfo.find(".table-user").text("开台人：" + (openTableInfo == null ? "" : openTableInfo.OpenTableUser));
        tableInfo.find(".table-businesstimespan").text("市别：" + (openTableInfo == null ? "" : openTableInfo.BusinessTimeSpanName));

        //输入当前餐台的菜品

        $.each(settleData.EnterOrder.Dishes, function (idx, item) {
            var dishItem = $dishItem.clone();
            dishItem.find(".dish-name").html(mpos.getDishTag(item) + item.DishName);
            dishItem.find(".dish-num").text("X" + item.DishNum);
            if (item.IsPackageDishChild) {
                dishItem.find(".dish-amount").text("-");
            } else if (item.IsMultiDishChild) {
                // 一品多吃子菜
                dishItem.find(".dish-amount").text("-");
            } else {
                dishItem.find(".dish-amount").text(mpos.formatPrice(item.DishSaleAmount));
            }
            var cookies = "";
            var dishUnit = item.DishPortions;
            if (item.Discount < 100) {
                dishUnit += "/" + parseFloat((item.Discount / 10).toFixed(2)) + "折";
            }
            $.each(item.DishRequestList, function (idx, re) {
                cookies += re.RequestName + (Math.abs(re.RequestNum) == 1 ? "" : ("*" + re.RequestNum)) + "、"; //做法
            });

            if (cookies.length > 0) {
                dishItem.find(".dish-cookies").text(dishUnit + "/" + cookies.substr(0, cookies.length - 1));
            } else {
                dishItem.find(".dish-cookies").text(dishUnit);
            }
            dishList.append(dishItem);
        });

        fragment.append(tableName);
        fragment.append(tableInfo);
        fragment.append(dishList);

        //输出其它餐台及菜品
        $.each(settleData.Orders, function (idx, order) {
            if (order.Order.OrderId == settleData.EnterOrder.Order.OrderId)
                return;

            tableName = $tableName.clone();
            tableInfo = $tableInfo.clone();
            dishList = $dishList.clone();

            //餐台名称
            tableName.find(".name").text(order.Table.TableName + (order.Order.IsMain == 1 ? "(主)" : ""));
            //交易流水号
            tableName.find(".serail-number").text("交易流水号：" + settleData.Consumption.SerialNumber);
            //会员
            if (settleData.MemberName != "") {
                $('<div class="member-name" />').text("会员：" + settleData.MemberName).appendTo(tableName);
            }

            //输出开台信息
            var openTableInfo = findOpenTableInfo(order.Order.OrderId);
            var orderTimeStr = (new Date(order.Order.BeginTime)).formatDate(fmt);
            // 总时长
            if (order.Order.TotalTime) {
              orderTimeStr += "("+order.Order.TotalTime+")";
            }
            tableInfo.find(".table-time").text("开台时间：" + orderTimeStr);
            tableInfo.find(".table-people").text("人数：" + order.Order.PeopleNum);
            tableInfo.find(".table-user").text("开台人：" + (openTableInfo == null ? "" : openTableInfo.OpenTableUser));
            tableInfo.find(".table-businesstimespan").text("市别：" + (openTableInfo == null ? "" : openTableInfo.BusinessTimeSpanName));

            //输出菜品
            $.each(order.Dishes, function (index, item) {
                var dishItem = $dishItem.clone(true);

                dishItem.find(".dish-name").html(mpos.getDishTag(item) + item.DishName);
                dishItem.find(".dish-num").text("X" + item.DishNum);
                if (item.IsPackageDishChild) {
                    dishItem.find(".dish-amount").text("-");
                } else if (item.IsMultiDishChild) {
                    // 一品多吃子菜
                    dishItem.find(".dish-amount").text("-");
                } else {
                    dishItem.find(".dish-amount").text(mpos.formatPrice(item.DishSaleAmount));
                }
                var cookies = "";
                var dishUnit = item.DishPortions;
                if (item.Discount < 100) {
                    dishUnit += "/" + parseFloat((item.Discount / 10).toFixed(2)) + "折";
                }
                $.each(item.DishRequestList, function (idx, re) {
                    cookies += re.RequestName + (Math.abs(re.RequestNum) == 1 ? "" : ("*" + re.RequestNum)) + "、"; //做法
                });
                if (cookies.length > 0) {
                    dishItem.find(".dish-cookies").text(dishUnit + "/" + cookies.substr(0, cookies.length - 1));
                } else {
                    dishItem.find(".dish-cookies").text(dishUnit);
                }

                dishList.append(dishItem);

            });

            fragment.append(tableName);
            fragment.append(tableInfo);
            fragment.append(dishList);
        });

        //显示金额信息
        var consumptionAmount = $consumptionAmount.clone();

        var amountDsc = "";
        $.each(settleData.AmountDesc, function (index, item) { //获取订单金额合集
            amountDsc += "<li>" + item.AmountName + "<span>" + mpos.shopConfig.AmountSymbol + item.Amount + "</span></li>";
        });
        var content = consumptionAmount.find(".content").empty();
        content.append(amountDsc);
        content.append("<li class='amount-total sep-line'>应收金额<span>" + mpos.shopConfig.AmountSymbol + settleData.TotalPayableAmount + "</span></li>");
        //处理并显示付款信息
        /*********付款信息***********/
        $.each(settleData.PaymentItems, function (index, item) {
            content.append("<li class='amount-total'>" + item.PaymentName + "<span>" + mpos.shopConfig.AmountSymbol + item.Amount + "</span></li>");
        });
        content.append("<li class='amount-total'>找零<span>" + mpos.shopConfig.AmountSymbol + settleData.Consumption.ChangeMoney + "</span></li>");
        fragment.append(consumptionAmount);

        $page.find(".app-content").append(fragment);
    }

    /*
    加载单据数据
    */
    function loadConsumptionDetailData() {
        mpos.post(mpos.api.getConsumptionInfo, {
            ConsumptionId: consumptionId
        }, function (data) {
            settleData = data;
            mpos.getCurrentBusinessDate(function(businessDate) {
                currentBusinessDate = businessDate;
                showConsumptionDetail();
            });

        })
    }

    /*
     获取开台信息
     * */
    function findOpenTableInfo(orderId) {
        if (settleData.OpenTableInfos) {
            for (var i = 0; i < settleData.OpenTableInfos.length; i++) {
                if (settleData.OpenTableInfos[i].OrderId == orderId) {
                    return settleData.OpenTableInfos[i];
                }
            }
        }
        return null;
    }
});

mpos.controller(mpos.page.changeServer, function(page) {
    //检查API是否正常
    var checkUrl = "/mpos/index.html";

    $.selectOnFocus(page);

    setTimeout(function () {
        $(page).find("input[name=ServerUrl]")[0].focus();
    }, 300);

    $(page).find("#check-server").on('click', function(event) {
        $(page).find(".server-check-form").triggerHandler('submit');
    });

    $(page).find("#scan-server").on('click', function(event) {
        //扫描服务器
        showUdpScan({isAutoClose: 0});
    });

    /**
     * 检查服务器URL
     */
    function checkServerUrl() {
        //获取serverurl， 如果有则检测是否联通， 无则弹出udp扫描
        plugins.appPreferences.fetch(function(value) {
            if (value != null) {
                //console.log("server url is " + value);
                var url = value.replace(/\//g,"").split(":");
                if (url.length == 3) {
                    $(page).find("[name=ServerUrl]").val(url[1]);
                    $(page).find("[name=ServerPort]").val(url[2]);
                }
                checkUrlStatus(value);
            } else {
                showUdpScan();
            }
        }, function(err) {
            console.log(err);
        }, "ServerUrl");
    }

    /**
     * 显示UDP扫描界面
     */
    function showUdpScan() {
        cordova.plugins.UdpScanner.scan(
            function(result) {
                // console.log("We got a url," +
                //     "ServerUrl: " + result.ServerUrl + "," +
                //     "Cancelled: " + result.cancelled);
                //未取消则检测api联通状态
                if (!result.cancelled) {
                    var url = result.ServerUrl.replace(/\//g,"").split(":");
                    if (url.length == 3) {
                        $(page).find("[name=ServerUrl]").val(url[1]);
                        $(page).find("[name=ServerPort]").val(url[2]);
                    }

                    checkUrlStatus(result.ServerUrl);
                }
            },
            function(error) {
                alert("服务器扫描失败，请联系管理员， 错误：" + error);
            },
            0 in arguments ? arguments[0] : undefined
        );
    }

    /**
     * 检查指定URL是否为API地址
     * @param {Object} url 服务器地址
     */
    function checkUrlStatus(url) {

        $.ajax({
            url: url + checkUrl,
            async: true,
            dataType: "html",
            beforeSend: function () {
                mpos.showLoading();
            },
            success: function() {
                plugins.appPreferences.store(function() {
                    navigator.app.loadUrl(url + checkUrl);
                }, function(error) {
                    console.log("save url " + url + " failed. error: " + error);
                }, "ServerUrl", url);
            },
            error: function() {
                alert("服务器连接失败，请重新输入或查找！");
            },
            complete: function () {
                mpos.hideLoading();
            }
        });
    }

    $(page).find("form.server-check-form").on("submit", function () {

        //检测服务器状态
        var url = $(page).find("input[name=ServerUrl]").val().trim();
        var port = parseInt($(page).find("input[name=ServerPort]").val().trim());
        if (url.length == 0) {
            alert("请输入服务器IP地址");
            return false;
        }
        if (isNaN(port) || port < 1 || port > 65535) {
            alert("请输入服务器端口号");
            return false;
        }

        checkUrlStatus("http://" + url + ":" + port);
        return false;
    });
});

/**
 * Created by xeonwell on 2016/5/18.
 * 组件定义
 */

/**
 * @typedef {Object} SegOptions 分段控件参数
 * @property {Array} data - 初始化时传入的显示的文本数组
 * @property {ZeptoCollection|HTMLElement|String} parent - 初始化后插入的地方
 * @property {Number} [initIndex] - 初始化时的索引, 默认为0
 * @property {Function} [callback] - 回调函数，当数值变化后
 * @property {String} [className] - 带入的className
 *
 */

/**
 * @typedef {Object} SegmentControl
 * @property {Number} index - 当前索引
 * @property {ZeptoCollection} container - 当前容器
 */

(function () {
    /**
     * 初始化一个分段控件
     * @namespace mpos.Components.SegmentControl
     * @param {SegOptions} options
     * @constructor
     */
    function SegmentControl(options) {
        if (!options || typeof options !== 'object' || !options.parent || !Array.isArray(options.data))
            throw TypeError("参数必须有值");

        var context = this;
        this.index = parseInt(options.initIndex) || 0;
        this.container = $('<ul class="segment-control"></ul>');
        if (typeof options.className === 'string')
            this.container.addClass(options.className);
        if (typeof options.callback === 'function')
            this.callback = options.callback;

        var $segItem = $('<li><label class="checkStatus"><input type="radio" name="segment' + parseInt(Math.random() * 10000) + '"><span></span></label></li>');
        var fragment = $(document.createDocumentFragment());
        options.data.forEach(function (item, idx) {
            var seg = $segItem.clone();
            seg.find('input').val(idx);
            if (idx === context.index) seg.find('input').prop('checked', true);
            seg.find('span').text(item);
            fragment.append(seg);
        });
        this.container.append(fragment);
        fragment = null;

        this.container.on('click', function (e) {
            var index = parseInt($(e.currentTarget).find('input:checked').val()) || 0;
            if (index === context.index)
                return;
            context.index = index;
            if (context.callback)
                context.callback.call(context, context.index);
        });

        $(options.parent).append(this.container);
    }

    mpos.Components.extend(SegmentControl);
})();


/**
 * @typedef {Object} DOOptions 菜品操作选项
 * @property {ZeptoCollection|HTMLElement|String} parent - 父界面
 * @property {Function} callback - 点击之后的操作
 * @property {Number} giveDish - 赠菜
 * @property {Boolean} discountDish - 菜品折扣
 * @property {Boolean} returnDish - 退菜
 * @property {Boolean} changeDishPrice - 改价
 * @property {Boolean} qicai - 起菜
 */

(function () {

    /**
     * 菜品操作生成
     * @namespace mpos.Components.OrderedDishOperation
     * @param {DOOptions} options 菜品操作选项
     * @constructor
     */
    function OrderedDishOperation(options) {
        if (!options || typeof options !== 'object') {
            throw TypeError("参数必须传入");
        }

        var container = $('<ul class="ordered-dish-operation clearfix"></ul>');
        //根据options显示UI
        var discountDish = $("<li class='discountDish'>商品折扣</li>").data("operation", 3);
        if (!options.discountDish) {
            discountDish.addClass('disabled');
        }
        discountDish.appendTo(container);

        var returnDish = $("<li class='returnDish'>退货</li>").data("operation", 2);
        if (!options.returnDish) {
            returnDish.addClass('disabled');
        }
        returnDish.appendTo(container);

        var giveDish = $("<li class='giveDish' />")
            .text(options.giveDish == 0 ? "取消赠送" : "赠送")
            .data("operation", options.giveDish == 0 ? 4 : 1);
        if (options.giveDish === -1) {
            giveDish.addClass('disabled');
        }
        giveDish.appendTo(container);

        var changeDishPrice = $("<li class='changeDishPrice'>改价</li>").data("operation", 5);
        if (!options.changeDishPrice) {
            changeDishPrice.addClass('disabled');
        }
        changeDishPrice.appendTo(container);

        var qicai = $("<li class='qicai'>" + mpos.shopConfig.TakeCalledDescption + "</li>").data("operation", 6);
        if (!options.qicai) {
            qicai.addClass('disabled');
        }
        qicai.appendTo(container);

        var cuicai = $("<li class='cuicai'>催菜</li>").data("operation", 7);
        if (!options.cuicai) {
          cuicai.addClass('disabled');
        }
        cuicai.appendTo(container);

        var huacai = $("<li class='huacai'>划菜</li>").data("operation", 8);
        if (!options.huacai) {
            huacai.addClass('disabled');
        }
        huacai.appendTo(container);


      if (typeof options.callback === 'function') {
            container.find("li:not(.disabled)").on("click", function (e) {
                if ($(e.currentTarget).hasClass('disabled')) {
                  return;
                }

                options.callback({
                    operationType: $(e.currentTarget).data("operation")
                });
                setTimeout(function () {
                    container.parent().removeClass('expand');
                    container.remove();
                }, 0);
                e.stopPropagation();
            });
        }

        setTimeout(function () {
            $(options.parent).append(container);
            container.parent().addClass('expand');
        }, 0);
    }

    /**
     * 判断当前元素是否有菜品操作界面
     * @namespace mpos.Components.OrderedDishOperation.has
     * @param {ZeptoCollection|HTMLElement|String} parent
     * @returns {boolean}
     */
    OrderedDishOperation.has = function (parent) {
        return $(parent).find('.ordered-dish-operation').length > 0;
    };
    /**
     * 移除当前元素下的菜品操作界面
     * @namespace mpos.Components.OrderedDishOperation.remove
     * @param {ZeptoCollection|HTMLElement|String} parent
     */
    OrderedDishOperation.remove = function (parent) {
        $(parent).removeClass('expand').find('.ordered-dish-operation').remove();
    };

    mpos.Components.extend(OrderedDishOperation);
})();

/**
 * @typedef {Object} SDObject - 购物车菜品操作
 * @property {ZeptoCollection|HTMLElement|String} parent - 父界面
 * @property {Function} callback - 点击之后的操作
 * @property {Boolean} showJiaoqi - 显示叫起还是取消叫起
 * @property {Boolean} showNumber - 是否显示修改数量
 * @property {Boolean} showModify - 是否显示修改菜品
 * @property {Boolean} showAddMore - 是否显示继续搭配
 *
 */

(function () {

    /**
     * 购物车菜品操作组件
     * @namespace mpos.Components.ShoppingDishOperation
     * @param {SDObject} options
     * @constructor
     */
    function ShoppingDishOperation(options) {
        if (!options || typeof options !== 'object')
            throw TypeError("参数必须传入");

        var container = $('<ul class="shopping-dish-operation clearfix"></ul>');

        // 未下单前显示赠送
        var item = $("<li class='giveDish' />")
          .text(options.isFreeDish == 1 ? "取消赠送" : "赠送")
          .data("operation", options.isFreeDish == 1 ? 6 : 5);
        if (!options.showGive) {
            item.addClass('disabled');
        }
        container.append(item);

        var item = $("<li class='show-add-more' data-operation='4'>继续搭配</li>");
        if (!options.showAddMore)
            item.addClass('disabled');
        container.append(item);

        item = $("<li class='jiaoqi' data-operation='1'></li>").text((options.showJiaoqi ? '':'取消') + mpos.shopConfig.WaitCallUpDescption);
        container.append(item);

        item = $("<li class='changeDishNumber' data-operation='2'>数量</li>");
        if (!options.showNumber)
            item.addClass('disabled');
        container.append(item);

        item = $("<li class='changeDishPrice' data-operation='3'>修改</li>");
        if (!options.showModify)
            item.addClass('disabled');
        container.append(item);

        if (typeof options.callback === 'function') {
            container.find("li:not(.disabled)").on("click", function (e) {
                if ($(e.currentTarget).hasClass('disabled'))
                    return;

                options.callback($(e.currentTarget).data("operation"));
                setTimeout(function () {
                    container.parent().removeClass('expand');
                    container.remove();
                }, 0);
                e.stopPropagation();
            });
        }

        setTimeout(function () {
            $(options.parent).append(container);
            container.parent().addClass('expand');
        }, 0);
    }

    /**
     * 判断当前元素是否有菜品操作界面
     * @namespace mpos.Components.ShoppingDishOperation.has
     * @param {ZeptoCollection|HTMLElement|String} parent
     * @returns {boolean}
     */
    ShoppingDishOperation.has = function (parent) {
        return $(parent).find('.shopping-dish-operation').length > 0;
    };
    /**
     * 移除当前元素下的菜品操作界面
     * @namespace mpos.Components.ShoppingDishOperation.remove
     * @param {ZeptoCollection|HTMLElement|String} parent
     */
    ShoppingDishOperation.remove = function (parent) {
        $(parent).removeClass('expand').find('.shopping-dish-operation').remove();
    };

    mpos.Components.extend(ShoppingDishOperation);
})();

/**
 * Created by xeonwell on 2016/1/29.
 *
 * 处理不同设备的操作
 * 不同设备需要重写下面的方法
 */
mpos.deviceFactory = (function () {
    return {
        initialize: initialize,
        onLogin: onLogin,
        onLogout: onLogout,
        onResume: onResume,
        printTest: printTest,
        printTicket: printTicket,
        payOrder: payOrder,
        clearOnExit: clearOnExit,
        /**
         * 是否支持打印
         */
        canSupportPrint: false,
        /**
         * 是否支持刷卡支付
         */
        canSupporPay: false,
        /**
         * 设备类型
         */
        deviceType: DeviceType.Normal
    };


    /**
     * 支付设备初始化
     *
     * 1. 盒子设备安装插件, 设置退出函数清理盒子认证信息
     *
     * @param deviceConfig 从设备返回的设备配置
     */
    function initialize(deviceConfig) {
        if (typeof deviceConfig != 'object') {
            throw TypeError("设备配置为对象，当前传入为" + deviceConfig);
        }
        var deviceType = deviceConfig.deviceType || DeviceType.Normal;
        switch (deviceType) {
            case DeviceType.IboxPayDevice:
                initializeIboxPayDevice();
                break;
            case DeviceType.LklPayDevice:
                initializeLklPayDevice();
                break;
            case DeviceType.WangPosPayDevice:
                initializeWangPosPayDevice();
                break;
            case DeviceType.SunmiM1Device:
            case DeviceType.SunmiV1Device:
                initializeSunmiDevice();
                break;
            case DeviceType.ShangRunDevice:
                initializeShangRunDevice();
                break;
            case DeviceType.LandicorpDevice:
                initializeLandicorpDevice();
                break;
            case DeviceType.AlipayNfcPos:
                initializeAlipayNfcPosDevice();
                break;
            default:
                initializeMobileDevice();
                break;
        }
    }

    /**
     * 获取店铺配置之后的操作
     *
     * 1. 盒子设备需要在登录时拿到apikey之后开始每隔15分钟进行认证
     *
     */
    function onLogin() {

    }

    /**
     * 退出登录
     */
    function onLogout() {

    }

    /**
     * 系统激活
     */
    function onResume() {

    }

    /**
     * 测试打印
     * @param  {Function} successCallback 成功回调
     * @param  {Function} errorCallback   失败回调
     */
    function printTest(successCallback, errorCallback) {
        if (typeof errorCallback == 'function') {
            errorCallback("该设备不支持打印");
        } else {
            mpos.alert("该设备不支持打印");
        }
    }

    /**
     * 打印票据
     *
     * @param  {Object} config          小票、台单格式,格式为[[{},{}],[{},{}]],多套打印票据
     * @param  {Function} successCallback 成功后的回调
     * @param  {Function} errorCallback   失败后的回调
     */
    function printTicket(config, successCallback, errorCallback) {
        mpos.log(JSON.stringify(config));
        autoSelectPrinter(config, successCallback, errorCallback);
    }

    /**
     * 支付
     * @param  {Object} config          配置信息
     * @param  {Function} successCallback 成功后的回调
     * @param  {Function} errorCallback   失败后的回调
     */
    function payOrder(config, successCallback, errorCallback) {
        mpos.log(JSON.stringify(config));
        if (typeof errorCallback == 'function') {
            errorCallback("该设备不支持刷卡支付");
        } else {
            mpos.alert("该设备不支持刷卡支付");
        }
    }

    /**
     * 退出程序时清理
     */
    function clearOnExit() {

    }

    /**
     * 网口打印
     * @param {any} printData
     * @param {any} errCallback
     */
    function autoSelectPrinter(printData, successCallBack, errCallback, defaultPrintTicket) {
        if (printData == null || printData == undefined) {
            return;
        }
        var port = mpos.localStorage.PrinterPort;
        var ip = mpos.localStorage.PrinterIP;
        if (ip != undefined && port != undefined && ip.length != 0 && port != 0) {
            mpos.mposUtils.doPrint({
                printdata: printData,
                ip: ip,
                port: port,
                type: 0
            }, function () {
                if (successCallBack) {
                    successCallBack();
                }
            }, function (err) {
                if (errCallback) {
                    errCallback(err);
                }
            });
        } else {
            if (defaultPrintTicket) {
                defaultPrintTicket(printData, successCallBack, errCallback);
            } else {
                mpos.alert("未设置打印机");
            }
        }
    }

    /**
     * 初始化手机打印
     * */
    function initializeMobileDevice() {
        //覆盖工厂的方法
        $.extend(mpos.deviceFactory, {
            printTicket: function (data, suc, err) {
                autoSelectPrinter(data, suc, err, null);
            },
            deviceType: DeviceType.Normal
        });
    }

    /**
     * 初始化盒子设备
     */
    function initializeIboxPayDevice() {
        //盒子支付使用原生请求
        mpos.useNativeAjax = true;
        var iboxpay = cordova.plugins.iboxpay;

        var authBoxTimeout = null;
        //15分钟认证一次盒子支付
        var authBoxTimeInteval = 15 * 60 * 1000;

        /**
         * 开始认证盒子；每15分钟一次
         */
        function startAuthBox() {
            stopAuthBox();
            //检测是否有配置盒子支付信息
            if (typeof mpos.shopConfig.IBoxConfig != "object"
                || mpos.shopConfig.IBoxConfig == null
                || typeof mpos.shopConfig.IBoxConfig.IBoxApiKey != "string"
                || mpos.shopConfig.IBoxConfig.IBoxApiKey.length == 0) {
                mpos.log("没有找到配置信息");
                return;
            }

            var authbox = function () {
                iboxpay.authBox(mpos.shopConfig.IBoxConfig,
                    function () {
                        mpos.log("盒子支付认证成功");
                    },
                    function (err) {
                        mpos.alert(err);
                    });
            };
            authBoxTimeout = setInterval(authbox, authBoxTimeInteval);
            authbox();
        }

        /**
         * 停止认证盒子
         */
        function stopAuthBox() {
            if (authBoxTimeout != null) {
                clearInterval(authBoxTimeout);
                authBoxTimeout = null;
            }
        }


        //退出时清理
        mpos.addExitAppCallback(function () {
            stopAuthBox();
            iboxpay.clearOnExit();
        });

        //覆盖工厂的方法
        $.extend(mpos.deviceFactory, {
            onLogin: startAuthBox,
            onLogout: stopAuthBox,
            printTest: iboxpay.printTest,
            printTicket: function (data, suc, err) {
                autoSelectPrinter(data, suc, err, iboxpay.printTicket);
            },
            payOrder: iboxpay.payOrder,
            clearOnExit: iboxpay.clearOnExit,
            canSupportPrint: true,
            canSupporPay: true,
            deviceType: DeviceType.IboxPayDevice
        });

        //检查环境：盒子支付SDK是否安装
        iboxpay.checkEnv();
    }

    /**
     * 初始化拉卡拉设备
     */
    function initializeLklPayDevice() {
        var lklpos = cordova.plugins.lklpos;

        $('body').addClass("lklpos");

        //退出时清理
        mpos.addExitAppCallback(function () {
            lklpos.clearOnExit();
        });

        //覆盖工厂的方法
        $.extend(mpos.deviceFactory, {
            printTest: lklpos.printTest,
            printTicket: function (data, suc, err) {
                autoSelectPrinter(data, suc, err, lklpos.printTicket);
            },
            payOrder: lklpos.payOrder,
            clearOnExit: lklpos.clearOnExit,
            canSupportPrint: true,
            canSupporPay: true,
            deviceType: DeviceType.LklPayDevice
        });

        //检查环境：
        //lklpos.checkEnv();
    }

    /**
     * 初始化旺POS设备
     */
    function initializeWangPosPayDevice() {
        var wangpos = cordova.plugins.wangpos;

        $('body').addClass("lklpos");

        //退出时清理
        mpos.addExitAppCallback(function () {
            wangpos.clearOnExit();
        });

        //覆盖工厂的方法
        $.extend(mpos.deviceFactory, {
            printTest: wangpos.printTest,
            printTicket: function (data, suc, err) {
                autoSelectPrinter(data, suc, err, wangpos.printTicket);
            },
            payOrder: wangpos.payOrder,
            clearOnExit: wangpos.clearOnExit,
            canSupportPrint: true,
            canSupporPay: true,
            deviceType: DeviceType.WangPosPayDevice
        });
    }

   /**
   * 初始化联迪设备
   */
    function initializeLandicorpDevice() {
        var landicorp = cordova.plugins.landicorp;
        var deviceType = mpos.deviceConfig.deviceType;

        $('body').addClass("sunmi");
        //退出时清理
        mpos.addExitAppCallback(function () {
            landicorp.clearOnExit();
        });

        //覆盖工厂的方法
        $.extend(mpos.deviceFactory, {
            printTest: landicorp.printTest,
            printTicket: function (data, suc, err) {
                autoSelectPrinter(data, suc, err, landicorp.printTicket);
            },
            // payOrder: sunmi.payOrder,
            clearOnExit: landicorp.clearOnExit,
            canSupportPrint: deviceType == DeviceType.LandicorpDevice,
            canSupporPay: false,
            deviceType: deviceType
        });
    }

    /**
      * 初始化阿里NFC设备
      */
    function initializeAlipayNfcPosDevice() {
        //var landicorp = cordova.plugins.landicorp;
        var deviceType = mpos.deviceConfig.deviceType;

        $('body').addClass("sunmi");
        //退出时清理
        mpos.addExitAppCallback(function () {
            //landicorp.clearOnExit();
        });

        //覆盖工厂的方法
        $.extend(mpos.deviceFactory, {
            printTest: null,
            printTicket: function (data, suc, err) {
                autoSelectPrinter(data, suc, err, null);
            },
            clearOnExit: null,
            canSupportPrint: false,
            canSupporPay: false,
            deviceType: DeviceType.AlipayNfcPos
        });
    }

    /**
    * 初始化商睿设备
    */
    function initializeShangRunDevice() {
        var shangrun = cordova.plugins.shangrun;
        var deviceType = mpos.deviceConfig.deviceType;

        $('body').addClass("sunmi");
        //退出时清理
        mpos.addExitAppCallback(function () {
            shangrun.clearOnExit();
        });

        //覆盖工厂的方法
        $.extend(mpos.deviceFactory, {
            printTest: shangrun.printTest,
            printTicket: function (data, suc, err) {
                autoSelectPrinter(data, suc, err, shangrun.printTicket);
            },
            // payOrder: sunmi.payOrder,
            clearOnExit: shangrun.clearOnExit,
            canSupportPrint: deviceType == DeviceType.ShangRunDevice,
            canSupporPay: false,
            deviceType: deviceType
        });
    }
    
    /**
     * 初始化商米设备
     */
    function initializeSunmiDevice() {
        var sunmi = cordova.plugins.sunmi;
        var deviceType = mpos.deviceConfig.deviceType;

        $('body').addClass("sunmi");
        //退出时清理
        mpos.addExitAppCallback(function () {
            sunmi.clearOnExit();
        });

        //覆盖工厂的方法
        $.extend(mpos.deviceFactory, {
            printTest: sunmi.printTest,
            printTicket: function (data, suc, err) {
                autoSelectPrinter(data, suc, err, sunmi.printTicket);
            },
            // payOrder: sunmi.payOrder,
            clearOnExit: sunmi.clearOnExit,
            canSupportPrint: deviceType == DeviceType.SunmiV1Device,
            canSupporPay: false,
            deviceType: deviceType
        });
    }

})();

/**
 * 加台
 */
mpos.dialogController(mpos.dialogPage.addTableOrder, function (page, data) {
    var orderId = data.OrderId;
    var $page = $(page);
    var $peopleNum = $page.find("input[name='peopleNum']");
    var $selectTimeSpan = $page.find("select[name='selectTimeSpan']");
    var $selectFloor = $page.find("select[name='selectFloor']");
    var $tableLlist = $page.find(".table-list");
    var $tableLlistItem = $tableLlist.find("li").remove();
    var allTables = null;
    var currentSelectedFloorId = 0;
    mpos.checkInputValue($peopleNum, InputType.Num1To999);

    //select标签赋值
    $selectTimeSpan.on("change", function () {
        var t = $(this);
        t.parent().find('span').text(this.options[this.selectedIndex].text);
    });

    //select标签赋值
    $selectFloor.on("change", function () {
        var t = $(this);
        t.parent().find('span').text(this.options[this.selectedIndex].text);
        currentSelectedFloorId = this.options[this.selectedIndex].value;
        BindTables();
    });

    loadBusinessTimeSpans();
    loadTables();

    $page.find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var peopleNum = $peopleNum.val();
            if (peopleNum == "") {
                mpos.alert("请输入每桌人数");
                return;
            }

            peopleNum = parseInt(peopleNum);

            if (peopleNum == 0) {
                mpos.alert("请输入每桌人数");
                return;
            }

            if (peopleNum > 999) {
                mpos.alert("人数不能大于999");
                return;
            }

            var timeSpanId = $selectTimeSpan.val();
            if (timeSpanId == undefined || timeSpanId == 0) {
                mpos.alert("请选择市别！");
                return;
            }
            var tableIds = [];
            $.each($tableLlist.find("li"), function (idx, item) {
                var chk = $(item).find("input[name='table']")[0].checked;
                if (chk) {
                    var tbId = $(item).data("tid");
                    tableIds.push(tbId);
                }
            });
            if (tableIds.length == 0) {
                mpos.alert("请选择加台餐台！");
                return;
            }
            mpos.post(mpos.api.addTableOrders, {
                OrderId: orderId,
                PeopleNum: peopleNum,
                BusinessTimespanId: timeSpanId,
                TableIds: JSON.stringify(tableIds)
            }, function () {
                mpos.dialog.close(true);
            });
        }
    });

    /*
     加载市别
     */
    function loadBusinessTimeSpans() {
        mpos.post(mpos.api.getAllBusinessTimeSpan, null, function (timeSpan) {
            $selectTimeSpan.empty();
            var fm = $(document.createDocumentFragment());
            //增加请选择项
            var optionDefault = $('<option/>').attr("value", 0).text("请选择市别");
            if (timeSpan.CurrentTimeSpanId == 0) {
                optionDefault.attr("selected", true);
                $selectTimeSpan.parent().find('span').text(optionDefault.text());
            }
            fm.append(optionDefault);
            //增加所有市别
            $.each(timeSpan.TimeSpans, function (index, item) {
                var option = $('<option/>').attr("value", item.BusinessTimespanId).text(item.Name);
                if (item.BusinessTimespanId == timeSpan.CurrentTimeSpanId) { //选中当前市别
                    option.attr("selected", true);
                    $selectTimeSpan.parent().find('span').text(item.Name);
                }
                fm.append(option);
            });

            fm.appendTo($selectTimeSpan);
        }, {
            hideLoading: true
        });
    }

    /*
    加载要换到的餐台
    */
    function loadTables() {
        mpos.post(mpos.api.queryCanUseChangeOrderTable, {
            DiningOrderId: orderId
        }, function (r) {
            $page.find(".title").text("加台-" + r.CurrentTableName);
            $selectFloor.empty();
            if (r.Floors) {
                var fm = $(document.createDocumentFragment());
                var itemIndex = 0;
                $.each(r.Floors, function (index, item) {
                    var option = $('<option/>').attr("value", item.Id).text(item.Name);
                    if (itemIndex == 0) { //选中第一个
                        option.attr("selected", true);
                        $selectFloor.parent().find('span').text(option.text());
                    }
                    itemIndex++;
                    fm.append(option);
                });
                fm.appendTo($selectFloor);
            }
            allTables = r.Tables;
            $tableLlist.empty();
            $.each(allTables, function (index, item) {
                var $clone = $tableLlistItem.clone();
                $clone.find("span").text(item.TableName);
                $clone.data("tid", item.TableId);
                $tableLlist.append($clone);
            });
            BindTables();
        });
    }

    function BindTables() {
        $.each($tableLlist.find("li"), function (idx, item) {
            var chk = $(item).find("input[name='table']")[0].checked;
            $(item).show();
            if (!chk) {
                if (currentSelectedFloorId > 0) {
                    var tbId = $(item).data("tid");
                    var table = GetTableById(tbId);
                    if (table != null && table.FloorId != currentSelectedFloorId) {
                        $(item).hide();
                    }
                }
            }
        });
    }

    function GetTableById(id) {
        for (var i = 0; i < allTables.length; i++) {
            if (allTables[i].TableId == id) {
                return allTables[i];
            }
        }
        return null;
    }
});

/**
 * author: wang.p  2025/5/23
 *
 * description: dialogAllHangup.js
 *             整单等叫时选择商品的界面
 */

mpos.dialogController(mpos.dialogPage.allHangupOrder, function (page, data) {
  var hangupDishes = data.Dishes;  // 购物车下单菜品
  var $page = $(page);
  var $dishContainer = $page.find(".dish-select");
  var $dishItem = $dishContainer.find("li").remove();

  loadShoppingDish();

  // 全选按钮操作
  $page.find("input[name='allCheckHangup']").on('click', function(e) {
    console.log(e);
    var checked = e.target.checked;
    var selectedDishes = $page.find("input[name='selectedDish']");
    for(var i=0;i<selectedDishes.length;i++) {
      $(selectedDishes[i]).prop("checked", checked);
    }
  })

  // 确认、取消按钮操作
  $page.find(".app-submit").on("click", function (e) {
    var operationType = $(e.currentTarget).data("operation");
    if (operationType == 2) {
      mpos.dialog.close(false);
    } else {
      var selectedDishes = [];
      var selectedLi = $dishContainer.find("input[name='selectedDish']:checked").parents("li");
      for(var i=0;i<selectedLi.length; i++) {
        var orderDishId = $(selectedLi[i]).data("order_dishId");
        selectedDishes.push(orderDishId)
      }
      mpos.dialog.close({dishes: selectedDishes});
    }
  });

  /*
   * 加载购物车菜品
  */
  function loadShoppingDish() {
    $dishContainer.empty();
    var fragment = $(document.createDocumentFragment());
    for (var i = 0; i < hangupDishes.length; i++) {
      var item = $dishItem.clone();
      var hangupDish = hangupDishes[i];
      item.data("order_dishId", hangupDish.OrderDishId);

      var checkBox = item.find("input[name='selectedDish']");
      checkBox.val(hangupDish.OrderDishId);

      if (hangupDish.KitchenRemark == 4) {
        checkBox.prop("checked", true);
      }

      item.find(".name").text(hangupDish.DishName);
      item.find(".unit").text(hangupDish.DishPortions);

      fragment.append(item);
    }

    $dishContainer.append(fragment);
    fragment = null;
  }

});

/**
 * author: wang.p 2021-12-13
 * description: 修改做法数量
 */
mpos.dialogController(mpos.dialogPage.changeCookingNum, function (page, data) {
  var $page = $(page);
  var CookingData = data.CookingData;
  var $num = $page.find("input[name='cookingNum']");
  $num.val(Number(CookingData.Num));

  $page.find(".title").text(CookingData.CookingName);

  //确定和取消事件
  $page.find(".app-submit").on("click", function (e) {
    var operationType = $(e.currentTarget).data("operation");
    var cookingNum = 1;
    if (operationType == 1) {
      var num = $.trim($num.val());
      if (num == "" || Number(num) <= 0) {
        mpos.alert("数量必须大于0");
        return;
      }
      if (!InputType[InputType.DishNum].test(num)) {
        mpos.alert("数量格式不对，最多四位小数");
        return;
      }
      cookingNum = Number(num);
    }
    var newCookingData = JSON.parse(JSON.stringify(CookingData));
    newCookingData.Num = cookingNum;
    newCookingData.BaseRequestNum = cookingNum;  // 基础做法数量
    mpos.dialog.close({
      status: true,
      data: newCookingData
    });
  });

  $num.focus(function(){
    $(this).addClass('focus-bg-color');
  });
  $num.blur(function(){
    $(this).removeClass('focus-bg-color');
  });

  // 显示修改数量时，延迟获取输入框焦点
  setTimeout(function(){
    $num.focus();
  }, 200);

});

/**
 * 菜品转台
 */
mpos.dialogController(mpos.dialogPage.changeDishTable, function (page, data) {
    var orderId = data.OrderId;
    var $page = $(page);
    var $dishList = $page.find(".change-dish-list");
    var $dishListItem = $dishList.find("li").remove();
    var allDishes = null;
    loadDishes();
    $page.find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var selectedDishIds = [];
            $.each($dishList.find("li"), function (idx, item) {
                var chk = $(item).find("input[name='dish']")[0].checked;
                if (chk) {
                    var dishId = $(item).data("o_dish_id");
                    selectedDishIds.push(dishId);
                }
            });
            if (selectedDishIds.length == 0) {
                mpos.alert("请选择要转台的菜品！");
                return;
            }
            var isPrintKit = $page.find("input[name='printToKitchen']")[0].checked;
            if (isPrintKit == true) {
                isPrintKit = 1;
            } else {
                isPrintKit = 0;
            }

            mpos.showDialog(mpos.dialogPage.selectChangeDishTable, {
                OrderId: orderId
            }, function (oid) {
                if (oid) {
                    mpos.post(mpos.api.changeDishTable, {
                        OrderId: orderId,
                        AimOrderId:oid,
                        IsPrintKit: isPrintKit,
                        OrderDishIds: JSON.stringify(selectedDishIds)
                    }, function (r) {
                        if (r) { //打印总分单
                            var printSigleBill = mpos.printSigleBill();
                            var printTotalBill = mpos.printTotalBill();
                            //本地打印总单
                            if (printTotalBill && r.TotalBillGrids != null && Array.isArray(r.TotalBillGrids)) {
                                $.each(r.TotalBillGrids, function (index, item) {
                                    var printData = mpos.addPrintEmptyLine(item);
                                    mpos.deviceFactory.printTicket(printData, null, function (err) {
                                        //打印
                                        mpos.alert(err);
                                    });
                                })
                            }
                            //本地打印分单
                            if (printSigleBill && r.SigleBillGrids != null && Array.isArray(r.SigleBillGrids)) {
                                $.each(r.SigleBillGrids, function (index, item) {
                                    var printData = mpos.addPrintEmptyLine(item);
                                    mpos.deviceFactory.printTicket(printData, null, function (err) {
                                        //打印
                                        mpos.alert(err);
                                    });
                                })
                            }
                        }
                        mpos.alert("转台成功！");
                        mpos.dialog.close(true);
                    });
                }
            });
        }
    });

    /*
     加载要换到的餐台
     */
    function loadDishes() {
        mpos.post(mpos.api.getChangeDishInfoByOrderId, {
            DiningOrderId: orderId
        }, function (r) {
            $page.find(".title").text("商品转台-" + r.CurrentTableName);
            allDishes = r.Dishes;
            BindDishes();
        });
    }

    /*
    绑定菜品
    */
    function BindDishes() {
        $dishList.empty();
        $.each(allDishes, function (index, item) {
            var $clone = $dishListItem.clone();
            $clone.find("span").html(mpos.getDishTag(item) + item.DishName + "×" + item.DishNum + "/" + item.DishPortions);
            $clone.data("o_dish_id", item.OrderDishId);
            $dishList.append($clone);
        });
    }
});

/**
 * 修改菜品价格界面
 */
mpos.dialogController(mpos.dialogPage.changeOrderDishPrice, function (page, data) {
    var dish = data.Dish;
    var reasons = [];
    var shopConfig;
    
    var $reasonItem = $(page).find(".reason-list>li").remove();
    var $priceInput = $(page).find("input[name='price']");
    $(page).find("span.price-org").text(mpos.formatPrice(dish.DishPrice));
    $priceInput.val(dish.DishPrice);
    mpos.checkInputValue($priceInput, InputType.Amount);

    //菜品名称
    $(page).find("div.title").html(dish.DishName);

    //加载原因
    mpos.getReason(ReasonType.ChangePrice, loadReason);
   
    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var price = $.trim($priceInput.val());

            if (price == "") {
                mpos.alert("请输入价格");
                return;
            }

            if (!InputType[InputType.Amount].test(price)) {
                mpos.alert("价格输入有误");
                return;
            }

            price = Number(price);

            //没有修改时直接关闭
            if (price == dish.DishPrice && dish.Discount == 100) {
                mpos.dialog.close(false);
                return;
            }

            var reasonId = $(page).find("input[name='selectReason']:checked").val();
            if (reasonId == undefined || reasonId == null) {
                if (shopConfig.DiscountRequire) {
                    mpos.alert("请选择改价原因");
                    return;
                }
                reasonId = 0;
            }

            mpos.post(mpos.api.changeOrderDishPrice, {
                OrderDishId: dish.OrderDishId,
                Price: price,
                ReasonId: reasonId,
            }, function (data) {
                mpos.dialog.close(true);
            });
        }
    });

    /*
    加载原因
    */
    function loadReason(data) {
        mpos.getReasonConfirm(function(config) {
            reasons = data.ReasonList;
            shopConfig = config;
            var fragment = $(document.createDocumentFragment());
            $.each(reasons, function (index, item) {
                var reasonItem = $reasonItem.clone();
                reasonItem.find("input").val(item.ReasonId);
                reasonItem.find("span").text(item.ReasonText);
                fragment.append(reasonItem);
            });
            $(page).find(".reasonContainer").empty().append(fragment);
        });
    }
  
    $priceInput.focus(function(){
        $(this).addClass('focus-bg-color');
    });
    $priceInput.blur(function(){
        $(this).removeClass('focus-bg-color');
    });

    // 显示修改数量时，延迟获取输入框焦点
    setTimeout(function(){
        $priceInput.focus();
    }, 200);

});
/**
 * Created by wang.p on 2019/3/27.
 * 下单换台
 * 下单换台界面，显示的餐台是所有（包括已开台和未开台）， 选择未开台的餐台要显示开台界面（即输入人数和服务员等信息，原因与茶位有关）
 */
mpos.dialogController(mpos.dialogPage.changeOrderedTable, function (page, data) {
    var orderId = data.OrderId;  // 订单id
    var currentTableId = data.TableId;  //当前桌台id
    var hasDishes = data.HasDishes;  // 开台已有下单菜品
    var $page = $(page);
    var $menuList = $page.find(".table-list");
    var $menuListItem = $menuList.find("li").remove();
    var $selectFloor = $page.find("select[name='selectFloor']");
    var floorListData = [];
    var allTables = null;
    var currentSelectedFloorId = 0;
    //select标签赋值
    $selectFloor.on("change", function () {
        var t = $(this);
        t.parent().find('span').text(this.options[this.selectedIndex].text);
        currentSelectedFloorId = this.options[this.selectedIndex].value;
        BindTables();
    });
    loadFloors();  // 查询餐台区域信息
    $page.find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var selectedTableId = $menuList.find("input[name='selectMenu']:checked").parents("li").data("t_id");
            if (selectedTableId == undefined)
            {
                mpos.alert("请选择餐台");
                return;
            }

            //判断餐台是否已经开台了，未开台，先进行开台操作
            var selectedTable = allTables.find(function(t){
                return t.TableId === selectedTableId;
            });

            var isPrintKit = $page.find("input[name='printToKitchen']")[0].checked;
            if (isPrintKit == true) {
                isPrintKit = 1;
            } else {
                isPrintKit = 0;
            }
            // 如果当前选中的桌台是已经开台的，同时原来的桌台没有下单的菜品，就可以进行撤销原来桌台操作
            if (!hasDishes && selectedTable.TableStatus === TableStatus.Taken) {
                mpos.post(mpos.api.cancelTable, {
                    OrderId: orderId
                }, function () {
                    mpos.dialog.close({table: selectedTable, isPrint: isPrintKit});
                })
            } else {
                mpos.dialog.close({table: selectedTable, isPrint: isPrintKit});
            }

        }
    });

    /**
     刷新餐台区域
     */
    function loadFloors() {
        floorListData = [];
        // 判断sessionStorage是否存储了餐台区域信息
        if (sessionStorage) {
            var sessionfloorList = sessionStorage.getItem('floorList');
            if (sessionfloorList) {
                floorListData = JSON.parse(sessionfloorList);
            }
        }
        if (floorListData.length === 0) {
            mpos.post(mpos.api.loadFloors, function (data, status, xhr) {
                floorListData = [{Id: 0, Name: '全部'}].concat(data);
                sessionStorage.setItem('floorList', JSON.stringify(floorListData));
                loadTables(); //查询餐台信息
            });
        } else {
            loadTables(); //查询餐台信息
        }
    }

    /*
     加载要换到的餐台
     */
    function loadTables() {
        // showDiningTableList queryCanUseChangeOrderTable
        mpos.post(mpos.api.showDiningTableList , {
            DiningOrderId: orderId
        }, function (r) {
            allTables = [];
            var useStatus = [TableStatus.Empty, TableStatus.Taken, TableStatus.Reservation]
            $.each(r.TableList, function (index, item) {
                if (item.TableId != currentTableId && useStatus.indexOf(item.TableStatus) !== -1) {
                    allTables.push(item);
                }
            });

            var currentTable = r.TableList.find(function(t){return t.TableId === currentTableId;})
            $page.find(".title").text("换台-" + currentTable.TableName);
            $selectFloor.empty();
            if (floorListData) {
                var fm = $(document.createDocumentFragment());
                var itemIndex = 0;
                $.each(floorListData, function (index, item) {
                    var option = $('<option/>').attr("value", item.Id).text(item.Name);
                    if (itemIndex == 0) { //选中第一个
                        option.attr("selected", true);
                        $selectFloor.parent().find('span').text(option.text());
                    }
                    itemIndex++;
                    fm.append(option);
                });
                fm.appendTo($selectFloor);
            }
            BindTables();
        });
    }

    function BindTables() {
        $menuList.empty();
        var tables = [];
        $.each(allTables, function (index, item) {
            if (item.TableId != currentTableId) {
                if (currentSelectedFloorId > 0) {
                    if (item.FloorSettingId == currentSelectedFloorId) {
                        tables.push(item);
                    }
                } else {
                    tables.push(item);
                }
            }
        });
        $.each(tables, function (idx, item) {
            var $clone = $menuListItem.clone();
            $clone.find("span").text(item.TableName);
            $clone.data("t_id", item.TableId);
            //判断桌台是否已开台，已开台桌台，设置样式
            if (item.TableStatus === TableStatus.Taken) {
                $clone.find("span").addClass('taken-table');
            }
            $menuList.append($clone);
        });
    }
});

/**
 * 换台
 */
mpos.dialogController(mpos.dialogPage.changeOrderTable, function (page, data) {
    var orderId = data.OrderId;  // 订单ID
    var oldTableId = data.TableId;  // 原桌台ID
    var $page = $(page);
    var $menuList = $page.find(".table-list");
    var $menuListItem = $menuList.find("li").remove();
    var $selectFloor = $page.find("select[name='selectFloor']");
    var $timerList = $page.find(".time-charge-list");
    var $timerListItem = $timerList.find("li").remove();
    var allTables = null;
    var currentSelectedFloorId = 0;
    //select标签赋值
    $selectFloor.on("change", function () {
        var t = $(this);
        t.parent().find('span').text(this.options[this.selectedIndex].text);
        currentSelectedFloorId = this.options[this.selectedIndex].value;
        BindTables();
    });
    loadTables();
    $page.find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        var showTimerList = $page.find(".timer-list-container").hasClass('show-timer-list-container');
        if (operationType == 2) {
            if (showTimerList) {
              changeContainerStatus(false);
            } else {
              mpos.dialog.close(false);
            }
        } else {
            var selectedTableId = $menuList.find("input[name='selectMenu']:checked").parents("li").data("t_id");
            if (selectedTableId == undefined)
            {
                mpos.alert("请选择餐台");
                return;
            }
            // 查找出当前对应的桌台信息
            var targetTable = allTables.find(function(item) {
              return item.TableId == selectedTableId;
            })

            var isPrintKit = $page.find("input[name='printToKitchen']")[0].checked;
            var enabledTimeCharge = $page.find("input[name='enabledTimeCharge']")[0].checked;
            if (isPrintKit == true) {
                isPrintKit = 1;
            } else {
                isPrintKit = 0;
            }

            var params = {
              OrderId: orderId,
              TableId: selectedTableId,
              IsPrintKit: isPrintKit,
              TimeChargeId: enabledTimeCharge == true ? 0 : -1
            }

            // 选择新的计时方案
            if (enabledTimeCharge == true && targetTable.TimeChargeType == 3) {
              if (!showTimerList) {
                loadTimerData(params); // 请求计时方案
                return;
              }
              var selectedTimerId = $timerList.find("input[name='selectTimer']:checked").parents("li").data("t_id");
              if (selectedTimerId == undefined) {
                mpos.alert("请选择计时方案");
                return;
              }
              params.TimeChargeId = selectedTimerId;
              fetchChangeOrderTable(params)
            } else {
              fetchChangeOrderTable(params)
            }
        }
    });

    /**
     * 请求换台操作
     * @data
     * */
    function fetchChangeOrderTable (data) {
      mpos.post(mpos.api.changeOrderTable, data, function (r) {
        if (r) { //打印总分单
          var printSigleBill = mpos.printSigleBill();
          var printTotalBill = mpos.printTotalBill();
          //本地打印总单
          if (printTotalBill && r.TotalBillGrids != null && Array.isArray(r.TotalBillGrids)) {
            $.each(r.TotalBillGrids, function (index, item) {
              var printData = mpos.addPrintEmptyLine(item);
              mpos.deviceFactory.printTicket(printData, null, function (err) {
                //打印
                mpos.alert(err);
              });
            })
          }
          //本地打印分单
          if (printSigleBill && r.SigleBillGrids != null && Array.isArray(r.SigleBillGrids)) {
            $.each(r.SigleBillGrids, function (index, item) {
              var printData = mpos.addPrintEmptyLine(item);
              mpos.deviceFactory.printTicket(printData, null, function (err) {
                //打印
                mpos.alert(err);
              });
            })
          }
        }
        // 换台后将原餐台缓存的菜品数据转移到新桌台下
        changeTableCacheDishes(data.TableId);
        // 还原桌台计时方案信息
        changeContainerStatus(false);

        mpos.dialog.close(true);
      });
    }

    // 换台后将原餐台缓存的菜品数据转移到新桌台下
    function changeTableCacheDishes (newTableId) {
        var localOrder = mpos.localStorage.LocalTableOrder || {};
        if (typeof localOrder === 'string')
            localOrder = JSON.parse(localOrder)
        if (localOrder[oldTableId] && localOrder[oldTableId][orderId]) {
            if (!localOrder[newTableId]) {
                localOrder[newTableId] = {}
            }
            var cacheDishes = localOrder[oldTableId][orderId];
            localOrder[newTableId][orderId] = cacheDishes;  // 缓存新桌台未下单菜品
            // 移除原桌台的缓存数据
            delete localOrder[oldTableId][orderId];
            mpos.localStorage.LocalTableOrder = JSON.stringify(localOrder);
        }
    }


    /*
     加载要换到的餐台
     */
    function loadTables() {
        mpos.post(mpos.api.queryCanUseChangeOrderTable, {
            DiningOrderId: orderId
        }, function (r) {
            $page.find(".title").text("换台-" + r.CurrentTableName);
            $selectFloor.empty();
            if (r.Floors) {
                var fm = $(document.createDocumentFragment());
                var itemIndex = 0;
                $.each(r.Floors, function (index, item) {
                    var option = $('<option/>').attr("value", item.Id).text(item.Name);
                    if (itemIndex == 0) { //选中第一个
                        option.attr("selected", true);
                        $selectFloor.parent().find('span').text(option.text());
                    }
                    itemIndex++;
                    fm.append(option);
                });
                fm.appendTo($selectFloor);
            }
            allTables = r.Tables;
            BindTables();
        });
    }

    function BindTables() {
        $menuList.empty();
        var tables = [];
        $.each(allTables, function (index, item) {
            if (currentSelectedFloorId > 0) {
                if (item.FloorId == currentSelectedFloorId) {
                    tables.push(item);
                }
            } else {
                tables.push(item);
            }
        });
        $.each(tables, function (idx, item) {
            var $clone = $menuListItem.clone();
            $clone.find("span").text(item.TableName);
            $clone.data("t_id", item.TableId);
            $menuList.append($clone);
        });
    }

    /**
     * 加载计时方案
     * */
    function loadTimerData (data) {
        $timerList.empty();
        mpos.post(mpos.api.getTableSelectTimeChargeOffers, {
          TableId: data.TableId,
        }, function (r) {
          $.each(r, function (idx, item) {
            var $clone = $timerListItem.clone();
            $clone.find("span").text(item.OfferName);
            $clone.data("t_id", item.TimeChargeOfferId);
            $timerList.append($clone);
          });
          changeContainerStatus(true);
        });
    }

    /**
     * 修改界面显示的状态
     * */
    function changeContainerStatus (isShowTimer) {
      if (isShowTimer == true) {
        // 修改app-content 样式
        $page.find(".app-content").addClass('no-overflow');
        // 显示计时方案的容器
        $page.find(".timer-list-container").addClass('show-timer-list-container');
      } else {
        // 修改app-content 样式
        $page.find(".app-content").removeClass('no-overflow');
        // 隐藏计时方案的容器
        $page.find(".timer-list-container").removeClass('show-timer-list-container');
      }
    }

});

/**
 * author: wang.p  2021-12-05
 * 做法搜索界面
 */
mpos.dialogController(mpos.dialogPage.cookingSearch, function (page, data) {

  var $page = $(page);
  var dish = data.Dish;  // 搜索的菜品
  var orderDishData = data.OrderDishData;
  var CheckCookings = data.CheckCookings; // 之前已选中的做法

  var SelectedCookings = []; // 选中的做法
  var CookingContainer = []; // 专用做法的数组
  var MoreCookingContainer = []; // 更多做法的数组

  var selectedCookingContainer = $page.find('.selected-cooking-container');
  var $selectedCookingList = selectedCookingContainer.find(".cooking-list");
  var $selectedCookingItem = $selectedCookingList.find('span').remove();

  var cookingContainer = $page.find(".cooking-container");
  var $cookingItem = cookingContainer.find(".cooking-item").remove();

  var moreCookingContainer = $page.find(".more-cooking-container");
  var $moreCookingItem = moreCookingContainer.find(".cooking-item").remove();

  var $searchInput = $page.find('input[name=cooking-name]');
  var $searchBtn = $page.find('button.search-btn'); // 搜索按钮
  var pinyin = mpos.Pinyin();  // 将中文转成拼音首字母

  /*
    加载做法
    */
  function loadDishCooking() {
    CookingContainer = [];
    MoreCookingContainer = [];
    var dishType = orderDishData.getDishType(dish.Dish.DishTypeId);
    var hasMoreCookings = true; //是否显示更多做法
    if (dish.DishCookings.length > 0) { //有菜品关联做法时
      CookingContainer = orderDishData.getGroupCookingsSort(dish.DishCookings);
    } else if (dishType.DishTypeCookings.length) { //有做法类型关联做法时
      CookingContainer = orderDishData.getGroupCookingsSort(dishType.DishTypeCookings);
    } else { //都没有时，显示全部做法
      hasMoreCookings = false;
    }
    var scookings = [];
    if (hasMoreCookings) {
      for (var cookingGroup=0; cookingGroup< CookingContainer.length; cookingGroup++) {
        for (var j = 0; j < CookingContainer[cookingGroup].Cookings.length; j++) {
          var c = CookingContainer[cookingGroup].Cookings[j];
          scookings.push(c.RequestId);
        }
      }
    }
    //填充所有做法到更多
    var allCookingIds = [];
    for (var i = 0; i < orderDishData.cookings.length; i++) {
      if (scookings.findIndex(function (t) {
        return t == orderDishData.cookings[i].RequestId;
      }) == -1) {
        allCookingIds.push(orderDishData.cookings[i].RequestId);
      }
    }
    MoreCookingContainer = orderDishData.getGroupCookingsSort(allCookingIds);
  }

  // 获取做法的数据组
  loadDishCooking();

  // 点击搜索做法
  $searchBtn.on('click', function(e) {
    var searchValue = $searchInput.val().trim();
    if (searchValue) {
      filterCookings(searchValue.toUpperCase());
    } else {
      mpos.alert("请输入搜索的做法名称");
    }
  });

  /*
   * 遍历出要搜索的做法
   * @filterName   过滤的做法名称
   */
  function filterCookings (filterName) {
    cookingContainer.empty();
    moreCookingContainer.empty();

    // 显示已选的做法
    var fragment = $(document.createDocumentFragment());
    for (var cookingGroup=0; cookingGroup< CookingContainer.length; cookingGroup++) {
      var cookingItem = $cookingItem.clone();
      cookingItem.find(".cooking-type-name").text(CookingContainer[cookingGroup].RequestName);
      var $list = cookingItem.find(".cooking-list");
      var hasCook = false;  // 是否有查询的做法
      for (var j = 0; j < CookingContainer[cookingGroup].Cookings.length; j++) {
        var c = CookingContainer[cookingGroup].Cookings[j];
        if (c.CookingName.indexOf(filterName) !== -1 || pinyin.getCamelChars(c.CookingName).indexOf(filterName) != -1) {
          hasCook = true;
          var price = "";
          if (c.RequestPrice > 0) {
            price = "(+" + mpos.formatPrice(c.RequestPrice) + ")";
          }
          $list.append("<span data-c_id='" + c.RequestId + "' class='cooking-name textEllipsis'>" + c.CookingName + price + "</span>");
        }
      }
      if (hasCook) {
        fragment.append(cookingItem);
      } else {
        $list = null;
        cookingItem = null;
      }
    }

    cookingContainer.append(fragment);
    fragment = null;

    // 显示搜索的做法
    var fragment = $(document.createDocumentFragment());
    for (var cookingGroup=0; cookingGroup < MoreCookingContainer.length; cookingGroup++) {
      var cookingItem = $moreCookingItem.clone();
      cookingItem.find(".cooking-type-name").text(MoreCookingContainer[cookingGroup].RequestName);
      var cookinglist = cookingItem.find(".cooking-list");
      var hasCook = false; // 记录是否包含查询的做法
      for (var j = 0; j < MoreCookingContainer[cookingGroup].Cookings.length; j++) {
        var c = MoreCookingContainer[cookingGroup].Cookings[j];
        if (c.CookingName.indexOf(filterName) !== -1 || pinyin.getCamelChars(c.CookingName).indexOf(filterName) != -1) {
          hasCook = true;
          var price = "";
          if (c.RequestPrice > 0) {
            price = "(+" + mpos.formatPrice(c.RequestPrice) + ")";
          }
          cookinglist.append("<span data-c_id='" + c.RequestId + "' class='cooking-name textEllipsis'>" + c.CookingName + price + "</span>");
        }
      }

      if (hasCook) {
        fragment.append(cookingItem);
      } else {
        cookinglist = null;
        cookingItem = null;
      }
    }

    moreCookingContainer.append(fragment);
    fragment = null;

    //选中修改菜品的做法
    if (SelectedCookings != null) { //取到修改的菜品的做法
      for (var k = 0; k < SelectedCookings.length; k++) {
        var allCookingTargets = $page.find("span[data-c_id='" + SelectedCookings[k].CookingId + "']");
        for (var j = 0; j < allCookingTargets.length; j++) {
          $(allCookingTargets[j]).addClass("selected");
        }
      }
    }

    //做法选中事件
    cookingContainer.find("span[data-c_id]").on("click", function (e) {
      selectCooking(e);
    });
    //更多中的做法选中事件
    moreCookingContainer.find("span[data-c_id]").on("click", function (e) {
      selectCooking(e);
    });

  }

  /*
  点击做法事件
  */
  function selectCooking(e) {
    var $target = $(e.currentTarget);
    var cookingId = $target.data("c_id");
    var cooking = orderDishData.getCookingById(cookingId);
    var requestId = cooking.RequestId;
    if ($target.hasClass("selected")) {
      for (var i = 0; i < SelectedCookings.length; i++) {
        if (SelectedCookings[i].CookingId == requestId) {
          SelectedCookings.splice(i, 1);
          break;
        }
      }
      showSelectedCookings();
    } else {
      var cookingData = {
        CookingId: requestId,
        CookingName: cooking.RequestName,   // 做法名称
        CookingPrice: cooking.RequestPrice,  // 做法加价
        RequestTypeId: cooking.RequestTypeId,  // 做法类型ID
        Num: 1,
        BaseRequestNum: 1
      }
      if (cooking.IsRequestNum == 1) {
        // 需要增加一个判断做法是否支持即时录入数量
        mpos.showDialog(mpos.dialogPage.changeCookingNum, {CookingData: cookingData}, function (status) {
          if (status.status) {
            SelectedCookings.push(status.data);
            showSelectedCookings();
          }
        });
      } else {
        SelectedCookings.push(cookingData);
        showSelectedCookings();
      }
    }
    //更新选中的样式
    var allCookingTargets = $page.find("span[data-c_id='" + cookingId + "']");
    var isSelected = $target.hasClass("selected");
    for (var j = 0; j < allCookingTargets.length; j++) {
      if (isSelected) {
        $(allCookingTargets[j]).removeClass("selected");
      } else {
        $(allCookingTargets[j]).addClass("selected");
      }
    }

  }

  /**
   * 渲染已选做法
   * */
  function showSelectedCookings () {
    if (SelectedCookings.length > 0) {
      selectedCookingContainer.removeClass('nd')
      $selectedCookingList.empty();

      var fragment = $(document.createDocumentFragment());
      for (var i=0;i<SelectedCookings.length;i++) {
        var cookingItem = $selectedCookingItem.clone();
        var c = SelectedCookings[i];
        var price = "";
        if (c.CookingPrice > 0) {
          price = "(+" + mpos.formatPrice(c.CookingPrice) + ")";
        }
        cookingItem.data('c_id', c.CookingId);
        cookingItem.text(c.CookingName + price);
        fragment.append(cookingItem)
      }
      $selectedCookingList.append(fragment);
      fragment = null;

      //做法选中事件
      $selectedCookingList.find("span[data-c_id]").on("click", function (e) {
        selectCooking(e);
      });
    } else {
      selectedCookingContainer.addClass('nd');
    }

  }

  /**
   * 提交数据
   * */
  $page.find(".app-submit").on("click", function (e) {
    var operationType = $(e.currentTarget).data("operation");
    if (operationType == 2) {
      mpos.dialog.close(false);
    } else {
      if (SelectedCookings.length > 0) {
        var newCookings = [];
        var cookingsId = [];
        for (var i=0;i<CheckCookings.length;i++) {
          // 查找之前添加的做法
          var exiseCooking = SelectedCookings.find(function(item){
            return item.CookingId == CheckCookings[i].CookingId;
          })
          if (exiseCooking) {
            newCookings.push(exiseCooking);
          } else {
            newCookings.push(CheckCookings[i]);
          }
          // 不用判断手输入做法
          CheckCookings[i].CookingId && cookingsId.push(CheckCookings[i].CookingId);
        }
        for (var c=0;c<SelectedCookings.length; c++) {
          if (cookingsId.indexOf(SelectedCookings[c].CookingId) === -1) {
            newCookings.push(SelectedCookings[c]);
          }
        }
        mpos.dialog.close(newCookings);
      } else {
        mpos.dialog.close(false);
      }
    }
  });

});

/**
 * 搭台
 */
mpos.dialogController(mpos.dialogPage.cutTable, function (page, data) {
    var table = data.Table;
    var $page = $(page);
    var $peopleNum = $page.find("input[name='peopleNum']");
    var $selectTimeSpan = $page.find("select[name='selectTimeSpan']");
    $peopleNum.val(table.TablePeopleNum);
    mpos.checkInputValue($peopleNum, InputType.Num1To999);

    //select标签赋值
    $selectTimeSpan.on("change", function () {
        var t = $(this);
        t.parent().find('span').text(this.options[this.selectedIndex].text);
    });

    loadBusinessTimeSpans();
    $page.find(".title").text("搭台-" + table.TableName);
    $page.find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var peopleNum = $peopleNum.val();
            if (peopleNum == "") {
                mpos.alert("请输入每桌人数");
                return;
            }

            peopleNum = parseInt(peopleNum);

            if (peopleNum == 0) {
                mpos.alert("请输入每桌人数");
                return;
            }

            if (peopleNum > 999) {
                mpos.alert("人数不能大于999");
                return;
            }

            var timeSpanId = $selectTimeSpan.val();
            if (timeSpanId == undefined || timeSpanId == 0) {
                mpos.alert("请选择市别！");
                return;
            }
            mpos.post(mpos.api.mPosCutTable, {
                OrderId: table.DiningOrderId,
                PeopleNum: peopleNum,
                BusinessTimespanId: timeSpanId
            }, function () {
                mpos.dialog.close(true);
            });
        }
    });

    /*
     加载市别
     */
    function loadBusinessTimeSpans() {
        mpos.post(mpos.api.getAllBusinessTimeSpan, null, function (timeSpan) {
            $selectTimeSpan.empty();
            var fm = $(document.createDocumentFragment());
            //增加请选择项
            var optionDefault = $('<option/>').attr("value", 0).text("请选择市别");
            if (timeSpan.CurrentTimeSpanId == 0) {
                optionDefault.attr("selected", true);
                $selectTimeSpan.parent().find('span').text(optionDefault.text());
            }
            fm.append(optionDefault);
            //增加所有市别
            $.each(timeSpan.TimeSpans, function (index, item) {
                var option = $('<option/>').attr("value", item.BusinessTimespanId).text(item.Name);
                if (item.BusinessTimespanId == timeSpan.CurrentTimeSpanId) { //选中当前市别
                    option.attr("selected", true);
                    $selectTimeSpan.parent().find('span').text(item.Name);
                }
                fm.append(option);
            });

            fm.appendTo($selectTimeSpan);
        }, {
            hideLoading: true
        });
    }
});

/**
 * 菜品折扣界面
 */
mpos.dialogController(mpos.dialogPage.discountDish, function (page, data) {
    var dish = data.Dish;
    var reasons = [];
    var shopConfig;
    
    var $discountItem = $(page).find(".discount-list>li").remove();
    var $reasonItem = $(page).find(".reason-list>li").remove();
    
    var dishTotalPrice = (((dish.DishSaleAmount - dish.ActualCookingPrice) / dish.Discount) * 100).toFixed(2);
    var $discountValue = $(page).find("input[name='discountValue']");
    var $beforeDiscountAmount = $(page).find("#beforeDiscountAmount");
    var $memberDiscount = $(page).find("#memberDiscount");
    var $afterDiscountAmount = $(page).find("#afterDiscountAmount");

    //加载折扣
    loadOftenDiscounts();
    //折前金额 
    $beforeDiscountAmount.text(dishTotalPrice);
    //会员折扣
    $memberDiscount.text(dish.MemberDiscount + "%");
    $discountValue.val(dish.NormalDiscount);
    mpos.checkInputValue($discountValue, InputType.Num0To100);
    changeDiscount();
    //菜品名称
    $(page).find("#dishName").html(dish.DishName);
    //加载原因
    mpos.getReason(ReasonType.Discount, loadReason);
    $discountValue.on("input", function () {
        changeDiscount();
    });
    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var dishDiscount = $discountValue.val();

            if (dishDiscount == "") {
                mpos.alert("请输入折扣");
                return;
            }

            var re = /^[1-9]+[0-9]*]*$/;
            if (!re.test(dishDiscount)) {
                mpos.alert("折扣必需为0~100间的整数");
                return;
            }

            dishDiscount = parseInt(dishDiscount);

            if (dishDiscount < 0 || dishDiscount > 100) {
                mpos.alert("折扣必需为0~100间的整数");
                return;
            }

            var reasonId = $(page).find("input[name='selectReason']:checked").val();
            if (reasonId == undefined || reasonId == null) {
                if (shopConfig.DiscountRequire) {
                    mpos.alert("请选择折扣原因");
                    return;
                }
                reasonId = 0;
            }
            mpos.post(mpos.api.setDishDiscount, {
                OrderDishId: dish.OrderDishId,
                Discount: dishDiscount,
                DishDiscountReasonId: reasonId
            }, function (data) {
                mpos.dialog.close(true);
            });
        }
    });

    /*
    加载原因
    */
    function loadReason(data) {
        mpos.getReasonConfirm(function(config){
            shopConfig = config;
            reasons = data.ReasonList;
            var fragment = $(document.createDocumentFragment());
            $.each(reasons, function (index, item) {
                var reasonItem = $reasonItem.clone();
                reasonItem.find("input").val(item.ReasonId);
                reasonItem.find("span").text(item.ReasonText);
                fragment.append(reasonItem);
            });
            $(page).find(".reasonContainer").empty().append(fragment);
        });

    }

    /*
    刷新折扣金额
    */
    function changeDiscount() {
        var dishDiscount = $discountValue.val();
        if (dishDiscount == "") {
            return;
        }

        var re = /^[1-9]+[0-9]*]*$/;
        if (!re.test(dishDiscount)) {
            return;
        }

        dishDiscount = parseInt(dishDiscount);

        if (dishDiscount < 0 || dishDiscount > 100) {
            return;
        }

        var d1 = (dishDiscount * dish.MemberDiscount) / 100;
        $afterDiscountAmount.text((d1 * dishTotalPrice / 100).toFixed(2));
    }

    /*
    加载常用折扣
    */
    function loadOftenDiscounts() {
        mpos.getOftenDiscounts(function(discounts){
            var fragment = $(document.createDocumentFragment());
            $.each(discounts, function (index, item) {
                var discountItem = $discountItem.clone();
                discountItem.find("input").val(item);
                discountItem.find("span").text(item);
                fragment.append(discountItem);
            });
            $(page).find(".commonDiscountList").empty().append(fragment);
            //折扣点击事件
            $(page).find("input[name='selectDiscount']").on("click", function (e) {
                $discountValue.val(e.currentTarget.value);
                changeDiscount();
            });
        });
    }

    $discountValue.focus(function(){
        $(this).addClass('focus-bg-color');
    });
    $discountValue.blur(function(){
        $(this).removeClass('focus-bg-color');
    });

    // 显示修改数量时，延迟获取输入框焦点
    setTimeout(function(){
        $discountValue.focus();
    }, 200);
});
/**
 * 折扣方案
 */
mpos.dialogController(mpos.dialogPage.discountScheme, function (page, data) {
    var settleData = data.settle;
    var reasons = [];
    var shopConfig;
    var schemes = [];//所有方案

    var $discountItem = $(page).find(".commonDiscountList>li").remove();
    var $reasonItem = $(page).find(".reasonContainer>li").remove();

    //加载折扣方案
    loadDiscountSchemes();

    //加载原因
    mpos.getReason(ReasonType.Discount, loadReason);
    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var dishDiscount = $(page).find("input[name='selectDiscount']:checked").val();

            if (dishDiscount == undefined || dishDiscount == null) {
                mpos.alert("请选择折扣方案");
                return;
            }

            var reasonId = $(page).find("input[name='selectReason']:checked").val();
            if (reasonId == undefined || reasonId == null) {
                if (shopConfig.DiscountRequire) {
                    mpos.alert("请选择折扣原因");
                    return;
                }
                reasonId = 0;
            }
            mpos.post(mpos.api.applyDiscountScheme, {
                OrderId: settleData.EnterOrder.Order.OrderId,
                SchemeId: dishDiscount,
                ReasonId: reasonId,
            }, function (data) {
                mpos.dialog.close(true);
            });
        }
    });

    /*
    加载原因
    */
    function loadReason(data) {
        mpos.getReasonConfirm(function (config) {
            shopConfig = config;
            reasons = data.ReasonList;
            var fragment = $(document.createDocumentFragment());
            $.each(reasons, function (index, item) {
                var reasonItem = $reasonItem.clone();
                reasonItem.find("inpu").val(item.ReasonId);
                reasonItem.find("span").text(item.ReasonText);
                fragment.append(reasonItem);
            });
            $(page).find(".reasonContainer").empty().append(fragment);
        });
    }

    /*
    加载折扣方案
    */
    function loadDiscountSchemes() {
        mpos.post(mpos.api.getDiscountSchemes, {}, function (data) {
            schemes = data;
            var fragment = $(document.createDocumentFragment());
            $.each(schemes, function (index, item) {
                var discountItem = $discountItem.clone();
                discountItem.find("input").val(item.PriceScheme.PriceSchemeId);
                discountItem.find("span").text(item.PriceScheme.SchemeName);
                fragment.append(discountItem);
            });
            $(page).find(".commonDiscountList").empty().append(fragment);
            //折扣点击事件
            $(page).find("input[name='selectDiscount']").on("click", function (e) {
                var schemeId = e.currentTarget.value;
                var scheme = findScheme(schemeId);
                if (scheme != null) {
                    var detail = "<fieldset><legend>" + scheme.PriceScheme.SchemeName + "-" + scheme.DiscountType + "</legend>";
                    $.each(scheme.Des, function (index, item) {
                        detail += "<div>" + item.Title + ":" + item.Discount + "</div>";
                    });
                    detail += "</fieldset>";
                    if (scheme.Des.length > 0) {
                        $(page).find("#schemeDetail").html(detail);
                    } else {
                        $(page).find("#schemeDetail").empty();
                    }
                }
            });
        });
    }

    /*
    查找方案
    */
    function findScheme(schemeId) {
        if (schemes) {
            for (var i = 0; i < schemes.length; i++) {
                if (schemes[i].PriceScheme.PriceSchemeId == schemeId) {
                    return schemes[i];
                }
            }
        }
        return null;
    }
});
/**
 * 赠送菜品界面
 */
mpos.dialogController(mpos.dialogPage.giveDish, function (page, data) {
    var dish = data.Dish;
    var unSubmit = data.UnSubmit;  // 是否未下单， true=未下单，否则为已下单
    var reasons = [];
    var shopConfig;
    var $dishNum = $(page).find("input[name='dishNum']");
    //菜品名称
    $(page).find("#dishName").html(dish.DishName);
    //数量
    $dishNum.val(dish.RealDishNum);

    mpos.checkInputValue($dishNum, InputType.DishNum);
    // 未下单隐藏赠送原因title
    unSubmit && $(page).find('.give-dish-reason').addClass('nd');
    //加载原因
    !unSubmit && mpos.getReason(ReasonType.Present, loadReason);

    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var dishNum = $.trim($dishNum.val());

            if (dishNum == "") {
                mpos.alert("请输入赠送数量");
                return;
            }

            if (!InputType[InputType.DishNum].test(dishNum)) {
                mpos.alert("数量输入有误");
                return;
            }

            dishNum = parseFloat(dishNum);

            if (dishNum == 0) {
                mpos.alert("请输入要赠送的商品数量");
                return;
            }
            if (dishNum > dish.RealDishNum) {
                mpos.alert("赠送数量不能大于当前商品数量");
                return;
            }

            if (unSubmit) {
                /* 未下单的菜品，进行赠送操作，需要增加一个赠送菜品权限判断的接口 未完成 wang.p 2021-11-09 */
                mpos.dialog.close({
                    OrderDishId: dish.OrderDishId,
                    DishNum: dishNum,
                    DishFreeReasonId: reasonId
                });
            } else {
                var reasonId = $(page).find("input[name='selectReason']:checked").val();
                if (reasonId == undefined || reasonId == null) {
                    if (shopConfig.PresentRequire) {
                        mpos.alert("请选择赠送原因");
                        return;
                    }
                    reasonId = 0;
                }

                mpos.post(mpos.api.setOrCanelFreeDish, {
                    OrderDishId: dish.OrderDishId,
                    DiningOrderId: dish.DiningOrderId,
                    DishNum: dishNum,
                    DishFreeReasonId: reasonId
                }, function (data) {
                    mpos.dialog.close(true);
                });
            }
        }
    });

    /*
    加载原因
    */
    function loadReason(data) {
        mpos.getReasonConfirm(function(config) {
            shopConfig = config;
            reasons = data.ReasonList;
            var reasonContainer = $(page).find("#reasonContainer");
            var listHtml = "";
            $.each(reasons, function (index, item) {
                listHtml += "<li><label class='checkStatus'><input type='radio' name='selectReason' value='" + item.ReasonId + "' /><span>";
                listHtml += item.ReasonText;
                listHtml += "</span></label></li>"
            });
            reasonContainer.html(listHtml);
        });

    }

    $dishNum.focus(function(){
        $(this).addClass('focus-bg-color');
    });
    $dishNum.blur(function(){
        $(this).removeClass('focus-bg-color');
    });

    // 显示修改数量时，延迟获取输入框焦点
    setTimeout(function(){
        $dishNum.focus();
    }, 200);
});

/**
 * 补开发票
 */
mpos.dialogController(mpos.dialogPage.invoicing, function(page, data) {
    var settleData = data.settle;
    var canInvoiceAmount = 0;
    var maxInvoiceAmount = 0;
    var $needPaymentAmount = $(page).find("#needPaymentAmount");
    var $canInvoiceAmount = $(page).find("#canInvoiceAmount");
    var $invoiceAmount = $(page).find("input[name='invoiceAmount']");
    //结算金额
    $needPaymentAmount.text(mpos.formatPrice(settleData.Consumption.NeedPayAmount));
    //已开票金额
    $invoiceAmount.val(settleData.Consumption.InvoiceMoney);
    //加载可开发票配置
    loadConsumptionInvoiceConfig();
    mpos.checkInputValue($invoiceAmount, InputType.Amount);
    //确定和取消事件
    $(page).find(".app-submit").on("click", function(e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var amount = $invoiceAmount.val().trim();

            if (amount == "") {
                mpos.alert("请输入发票金额");
                return;
            }

            amount = parseFloat(amount);

            if (amount < 0) {
                mpos.alert("发票金额不能小于0");
                return;
            }
            if (amount - canInvoiceAmount > maxInvoiceAmount) {
                mpos.alert("“开发票金额”减“可开发票金额”不能大于 " + maxInvoiceAmount);
                return;
            }

            mpos.post(mpos.api.setConsumptionInvoice, {
                ConsumptionId: settleData.Consumption.ConsumptionId,
                InvoiceAmount: amount
            }, function(data) {
                mpos.dialog.close(true);
            });
        }
    });

    /*
    获取开发票配置
    */
    function loadConsumptionInvoiceConfig() {
        mpos.post(mpos.api.getConsumptionInvoiceConfig, {
            ConsumptionId: settleData.Consumption.ConsumptionId
        }, function(data) {
            $canInvoiceAmount.text(mpos.formatPrice(data.CanInvoiceMoney));
            canInvoiceAmount = data.CanInvoiceMoney;
            maxInvoiceAmount = data.MaxMoney;
        });
    }
});
/**
 * 登录界面
 */
mpos.dialogController(mpos.dialogPage.login, function (dialogPage) {

    //登陆界面点击后退键失效
    this.onBackKeyDown = function () {
        mpos.exitApp();
    };

    $(dialogPage).find("input[name=username]").val(mpos.localStorage.UserName || "");
    if (mpos.isDebug) {
        $(dialogPage).find("input[name=password]").val("0000");
    }
    $(dialogPage).find(".login-button").on("click", function () {
        var username = $(dialogPage).find("input[name=username]").val().trim(),
            password = $(dialogPage).find("input[name=password]").val();
        if (username == null || username.length == 0) {
            mpos.alert("用户名不能为空!");
            return;
        }
        mpos.post(mpos.api.login, {
            LoginName: username,
            Password: password
        }, function (data, status, xhr) {
            mpos.currentUser = data.UserInfo;
            mpos.localStorage.UserName = username;
            mpos.getShopConfigInfo();
            mpos.StarSyncGetBaseInfo();
            if (data.Msg != "") {
                alert(data.Msg);
            }
            mpos.InitBaseInfo(function () {
                mpos.dialog.close(true);
            }, function () {
                alert("加载数据失败，请重试！");
            });
        });
    });

    var $usernameInput = $(dialogPage).find("input[name=username]");
    var $passwordInput = $(dialogPage).find("input[name=password]");

    $usernameInput.focus(function(){
        $(this).addClass('focus-bg-color');
    });
    $usernameInput.blur(function(){
        $(this).removeClass('focus-bg-color');
    });

    $passwordInput.focus(function(){
        $(this).addClass('focus-bg-color');
    });
    $passwordInput.blur(function(){
        $(this).removeClass('focus-bg-color');
    });


    // 商米v2使用android7版本，导致莫名的花屏，界面动画，花屏既可以取消， 自动获取焦点，促使页面刷新
    var bodyElement = document.getElementsByTagName('body');
    if (bodyElement && $(bodyElement[0]).hasClass('app-android-7')) {
        if (mpos.localStorage.UserName) {
            setTimeout(function () {
                $passwordInput.focus();
            }, 500);
        } else {
            setTimeout(function () {
                $usernameInput.focus();
            }, 500);
        }
    }

});


/**
 * author: wang.p 2022-07-13
 * description: 会员卡发送验证码
 */
mpos.dialogController(mpos.dialogPage.memberSmsVerify, function (page, data) {
  var memberData = data.MemberCard;
  var amount = data.Amount;
  var consumptionId = data.ConsumptionId;  // 消费单号ID
  var $page = $(page);
  var totalTime = 60;
  var sendTimeout = null;
  var $memberName = $page.find('.member-name');  // 会员名称
  var $memberPhone = $page.find('.member-phone');  // 手机号码
  var $sendBtn = $page.find('.send-btn');  // 发送短信验证码按钮
  var $verifyInput = $page.find('.verify-input'); // 输入验证码输入框
  $memberName.text(memberData.MemberName);
  $memberPhone.text(memberData.Mobile);

  this.onBackKeyDown = function () {
    stopTimeout();
    mpos.dialog.close(false);
  };

  /**
   * 发送短信验证按钮
   * */
  $sendBtn.on("click", function (e) {
    if (!sendTimeout) {
      // console.log(memberData)
      var params = {
        memberCardId: memberData.MemberCardId,   // 会员卡Id
        realMobile: getRealMobile(memberData),   // 手机号
        consumptionId: consumptionId,   // 消费单号ID
        payAmount: amount   // 付款金额
      }
      mpos.post(mpos.api.SendConsumePayVerifyCode, params, function (data) {
        if (data == 'ok') {
          startTimeout();
        }
      });
    }
  });

  /**
   * 开启倒计时
   * */
  function startTimeout () {
    if (sendTimeout) {
      clearTimeout(sendTimeout);
    }
    totalTime = 60;
    $sendBtn.text(totalTime);
    $sendBtn.addClass('start-time');
    sendTimeout = setTimeout(timeoutCallback, 1000);
  }

  /**
   * 停止倒计时
   * */
  function stopTimeout () {
    if (sendTimeout) {
      clearTimeout(sendTimeout);
      totalTime = 60;
      sendTimeout = null;
      $sendBtn.removeClass('start-time');
      $sendBtn.text('发送验证码');
    }

  }

  /**
   * 定时器执行的回调函数
   * */
  function timeoutCallback() {
    totalTime--;
    if (totalTime === 0) {
      stopTimeout();
    } else {
      $sendBtn.text(totalTime);
      sendTimeout = setTimeout(timeoutCallback, 1000);
    }
  }

  /**
   * 跳过短信验证
   * */
  $page.find('.jump-verfiy').on("click", function (e) {
    stopTimeout();
    // 查询跳过验证的权限
    mpos.post(mpos.api.SkipMemberConsumeSmsValid, {}, function (data) { 
      mpos.dialog.close(true);
    }, {
      hideLoading: true,
      error: function () {
        mpos.alert("跳过验证的权限不足");
      }
    });
  });

  //确定和取消事件
  $(page).find(".app-submit").on("click", function (e) {
    var operationType = $(e.currentTarget).data("operation");
    if (operationType == 2) {
      stopTimeout();
      mpos.dialog.close(false);
    } else {
      // 验证短信验证码是否正确
      var code = $verifyInput.val().trim();
      if (code == '') {
        mpos.alert("请输入验证码");
        return;
      }
      var params = {
        Code: code,
        RealMobile: getRealMobile(memberData),   // 手机号
      }
      mpos.post(mpos.api.ValidConsumePayCode, params, function (data) {
        if (data) {
          mpos.dialog.close(true);
        } else {
          mpos.alert("验证码输入有误");
        }
      });
    }
  });

  /**
   * 获取真实的手机号
   * @data  会员卡信息
   * */
  function getRealMobile (data) {
    if (data.Mobile.indexOf('*') != -1) {
      var keyIV = data.EncryptSalt+data.MemberCardId.toString().padStart(8, '0');  // IV 必须是8字节
      return mpos.decryptDES(data.EncryptMobile, keyIV);
    } else {
      return data.Mobile;
    }
  }

});

/**
 * 修改台头
 */
mpos.dialogController(mpos.dialogPage.modifyOpenTable, function (page, data) {
    var orderId = data.OrderId;
    var settleData = null;
    var $peopleNum = $(page).find("input[name='peopleNum']");
    var $tableCard = $(page).find("input[name='tableCard']");
    var $remark = $(page).find("input[name='remark']");
    var $selectWaiter = $(page).find("select[name='selectWaiter']");
    var $selectTimeSpan = $(page).find("select[name='selectTimeSpan']");
    var $isMainTable = $(page).find(".is-main-table");
    mpos.checkInputValue($peopleNum, InputType.Num1To999);

    //select标签赋值
    $selectWaiter.on("change", function () {
        var t = $(this);
        t.parent().find('span').text(this.options[this.selectedIndex].text);
    });
    $selectTimeSpan.on("change", function () {
        var t = $(this);
        t.parent().find('span').text(this.options[this.selectedIndex].text);
    });

    //显示/隐藏全部
    $(page).find(".show-all").on("click", function () {
        $(this).remove();
    });
    $(page).find(".hide-all").on("click", function () {
        $(page).find(".app-content>label").eq(2).before($("<div class='show-all'>显示全部</div>").on("click", function () {
            $(this).remove();
        }));
    });

    loadOrderData();

    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close({
                Status:false
            });
        } else {
            var peopleNum = $peopleNum.val();
            var tableCard = $tableCard.val();
            var remark = $remark.val();
            var waiterId = $selectWaiter.val();
            var timeSpanId = $selectTimeSpan.val();
            var isMainTable = false;
            var order = settleData.EnterOrder.Order;
            if (order.GroupSerial > 0) {
                $isMainTable.show();
                var $checkBox = $isMainTable.find("input[type='checkbox']");
                if (order.IsMain != 1) {
                    isMainTable = $checkBox.prop("checked");
                } else {
                    isMainTable = true;
                }
            }
            if (timeSpanId == undefined || timeSpanId == 0) {
                mpos.alert("请选择市别！");
                return;
            }
            mpos.post(mpos.api.checkModifyTableHeaderData, {
                OrderId: settleData.EnterOrder.Order.OrderId,
                WaiterId: waiterId,
                PeopleNum: peopleNum,
                BusinessTimeSpanId: timeSpanId,
                TableCard: tableCard,
                Remark: remark,
                IsMainTable: isMainTable,
            }, function (r) {
                if (r.IsPrompt) {
                    mpos.mposUtils.showAlertDialog({
                        title: "提醒",
                        message: "已经" + r.PromptType + "的茶位不会受到影响，但可以手工取消" + r.PromptType + "。继续修改吗？",
                        ok: "是",
                        cancel: "否"
                    }, function (result) {
                        if (!result) {
                            return;
                        }
                        mpos.post(mpos.api.modifyTableHeaderByMPOS, {
                            OrderId: settleData.EnterOrder.Order.OrderId,
                            WaiterId: waiterId,
                            PeopleNum: peopleNum,
                            BusinessTimeSpanId: timeSpanId,
                            TableCard: tableCard,
                            Remark: remark,
                            IsMainTable: isMainTable,
                        }, function (r) {
                            mpos.dialog.close({
                                Status:true,
                                PeopleNum: peopleNum,
                                BusinessTimeSpanId: timeSpanId
                            });
                        });
                    }, function (err) {
                        mpos.alert(err);
                    });
                } else {
                    mpos.post(mpos.api.modifyTableHeaderByMPOS, {
                        OrderId: settleData.EnterOrder.Order.OrderId,
                        WaiterId: waiterId,
                        PeopleNum: peopleNum,
                        BusinessTimeSpanId: timeSpanId,
                        TableCard: tableCard,
                        Remark: remark,
                        IsMainTable: isMainTable,
                    }, function (r) {
                        mpos.dialog.close({
                            Status:true,
                            PeopleNum: peopleNum,
                            BusinessTimeSpanId: timeSpanId
                        });
                    });
                }
            })
        }
    });

    /*
    加载餐台信息
    */
    function loadOrderData() {
        mpos.getSimpleSettleInfo(orderId, function (settle) {
            settleData = settle;
            var order = settle.EnterOrder.Order;
            if (order.GroupSerial > 0) {
                $isMainTable.show();
                var $checkBox = $isMainTable.find("input[type='checkbox']");
                if (order.IsMain == 1) {
                    $checkBox.prop("checked", true);
                    $checkBox.prop("disabled", true)
                } else {
                    $checkBox.prop("checked", false);
                    $checkBox.prop("readonly", false)
                }
            } else {
                $isMainTable.hide();
            }
            $peopleNum.val(settle.EnterOrder.Table.PeopleNum);
            $tableCard.val(order.TableCardNo);
            $remark.val(order.DiningRemark);
            $(page).find(".title").text("修改台头-" + settle.EnterOrder.Table.TableName);
            loadWaiters();
            loadBusinessTimeSpans();
        });
    }

    /*
    加载服务员
    */
    function loadWaiters() {
        $selectWaiter.empty();
        var fm = $(document.createDocumentFragment());
        var itemIndex = 0;
        $.each(mpos.BaseData.Staffs, function (index, item) {
            //if (item.IsAllowPushMoney == 1) {
                var option = $('<option/>').attr("value", item.StaffId).text(item.StaffDisplayName);
                if (item.StaffId == settleData.EnterOrder.Order.Waiter) {
                    option.attr("selected", true);
                    $selectWaiter.parent().find('span').text(option.text());
                }
                itemIndex++;
                fm.append(option);
            //}
        });
        fm.appendTo($selectWaiter);
    }

    /*
    加载市别
    */
    function loadBusinessTimeSpans() {
        mpos.post(mpos.api.getAllBusinessTimeSpan, null, function (timeSpan) {
            $selectTimeSpan.empty();
            var fm = $(document.createDocumentFragment());
            //增加请选择项
            var optionDefault = $('<option/>').attr("value", 0).text("请选择市别");
            fm.append(optionDefault);
            //增加所有市别
            $.each(timeSpan.TimeSpans, function (index, item) {
                var option = $('<option/>').attr("value", item.BusinessTimespanId).text(item.Name);
                if (item.BusinessTimespanId == settleData.EnterOrder.Order.BusinessTimespanId) { //选中当前市别
                    option.attr("selected", true);
                    $selectTimeSpan.parent().find('span').text(item.Name);
                }
                fm.append(option);
            });

            fm.appendTo($selectTimeSpan);
        });
    }
});

/*
预订入座
*/
mpos.dialogController(mpos.dialogPage.openBookOrderTable, function (page, data) {
    var tableId = data.TableId;//餐台ID
    var bookInfo = data.BookInfo;//取信息
    var tableName = data.TableName;//餐台名称
    var $userInfo = $(page).find(".book-user-info");
    var $bookTime = $(page).find(".book-time");
    $(page).find(".title").text("开台-" + tableName);

    loadBookInfo();//加载预订
    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close({ Status: 0 });
        } else {
            var op = $(page).find("input[name='selectOperation']:checked").val();
            if (op == "1") {//预订开台
                var bookOrderId = bookInfo.BookOrderId;
                //预订入座
                mpos.post(mpos.api.openTableForBookInfo, {
                    BookOrderId: bookOrderId,
                    TableId: tableId
                }, function (r) {
                    mpos.dialog.close({
                        Status: 1,
                        OrderId: r.OrderId,
                        DishCount: r.DishCount,
                        BookOrderId: bookOrderId
                    });
                });
            } else {//直接开台
                mpos.dialog.close({ Status: 2 });
            }
        }
    });

    /*
    加载预订数据
    */
    function loadBookInfo() {
        $userInfo.text(bookInfo.BookUser + "--" + bookInfo.BookMobile);
        $bookTime.text(new Date(bookInfo.BookArriveTime).formatDate("yyyy-MM-dd HH:mm"));
    }
});

/**
 * 开台
 */
mpos.dialogController(mpos.dialogPage.openTable, function (page, data) {
    var table = data.Table;
    var $page = $(page);
    var isFetchLatestDiningBook = true;  // 允许请求该餐台最近快速预订的信息
    var LatestDiningBookData = null;  // 记录获取餐台最近快速预订的信息
    var $peopleNum = $page.find("input[name='peopleNum']");
    var $tableCard = $page.find("input[name='tableCard']");
    var $remark = $page.find("input[name='remark']");
    var $selectWaiter = $page.find("select[name='selectWaiter']");
    var $selectTimeSpan = $page.find("select[name='selectTimeSpan']");
    var $selectTimeCharge = $page.find("select[name='selectTimeCharge']");

    var $bookName = $page.find("input[name='bookName']");   // 顾客姓名
    var $bookPhone = $page.find("input[name='bookPhone']");  // 预订手机号码
    var $bookDate = $page.find("input[name='bookDate']");   // 预抵日期
    var $bookTime = $page.find("input[name='bookTime']");   // 预抵时间
    var $bookCustomerList = $page.find('.book-customer-list');  // 展示查询的手机号列表
    var $CustomerListUL = $bookCustomerList.find('.customer-list');
    var $CustomerLI = $CustomerListUL.find('li').remove();
    var fetchCustomerData = [];  // 搜索的粉丝名称信息
    var operationValue = 1;  // 操作，1=开台，2=快速预订
    var selectUserId = 0;  // 记录选中的客户信息

    var dialogLoading = $page.find('.dialog-loading'); // 加载等待进度
    var enableOpenBookTable = mpos.localStorage.enableOpenBookTable || false;  // 查看是否启用快速预订
    // 酒楼模式下查看是否开启快速预订
    if (mpos.localStorage.OrderPropertyType != OrderPropertyType.Snack && enableOpenBookTable) {
        $page.find('.operation-content').removeClass('hide-status');
    }

    $peopleNum.val(data.Table.TablePeopleNum);
    mpos.checkInputValue($peopleNum, InputType.Num1To999);

    var nowDate = new Date();
    var year = nowDate.getFullYear();
    var month = nowDate.getMonth()+1;
    var date = nowDate.getDate()
    var dateStr = year +'-'+ (month.length === 1 ? ('0'+month) : month) + '-' + (date.length === 1 ? ('0' + date) : date)
    $bookDate.val(dateStr);

    //select标签赋值
    $selectWaiter.on("change", function () {
        var t = $(this);
        t.parent().find('span').text(this.options[this.selectedIndex].text);
    });
    $selectTimeSpan.on("change", function () {
        var t = $(this);
        t.parent().find('span').text(this.options[this.selectedIndex].text);
    });
    $selectTimeCharge.on("change", function () {
      var t = $(this);
      t.parent().find('span').text(this.options[this.selectedIndex].text);
    });

    //显示全部
    $page.find(".show-all").on("click", function () {
        toggleTimeChargeStatus(true);
        $(this).remove();
    });
    //隐藏全部
    $page.find(".hide-all").on("click", function () {
        toggleTimeChargeStatus(false);
        $page.find(".open-table-content>label").eq(2).before($("<div class='show-all'>显示全部</div>").on("click", function () {
            toggleTimeChargeStatus(true);
            $(this).remove();
        }));
    });

    loadWaiters();
    loadBusinessTimeSpans();
    loadTimeChargeList();
    $page.find(".title").text(table.TableName);
    var requestStatus = 0;
    /**
     * 提交数据
     * */
    $page.find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            if (requestStatus == 1) {
                return;
            }
            var peopleNum = parseInt(Number($peopleNum.val()));
            var remark = $remark.val();
            var waiterId = $selectWaiter.val();

            // 判断操作是开台还是预订
            if (operationValue === 2) {
                // 预订
                var bookName = $bookName.val().trim();
                var bookPhone = $bookPhone.val().trim();
                var bookDate = $bookDate.val().trim();
                var bookTime = $bookTime.val().trim();
                if (!bookName) {
                    mpos.alert("请输入顾客姓名！");
                    return;
                }
                if (!bookPhone || !(/^1[3456789]\d{9}$/.test(bookPhone))) {
                    mpos.alert("请输入正确手机号！");
                    return;
                }
                if (!bookDate) {
                    mpos.alert("请输入预抵日期！");
                    return;
                }
                if (!bookTime) {
                    mpos.alert("请输入预抵时间！");
                    return;
                }
                // 比较预抵日期时间不能小于当前时间
                if (new Date(bookDate +" " + bookTime).getTime() <= new Date().getTime()) {
                    mpos.alert("预抵日期和时间不能小于当前时间");
                    return;
                }
                if (peopleNum <= 0) {
                    mpos.alert("顾客人数必须大于1整数");
                    return;
                }
                var UserType = 0;
                if (selectUserId && fetchCustomerData.length > 0) {
                    // 查询搜索的客户信息
                    var findUser = fetchCustomerData.find(function(item) {
                        return item.UserId === selectUserId;
                    });
                    if (findUser) {
                        UserType = findUser.UserType;
                    }
                }

                requestStatus = 1;
                dialogLoading.removeClass('nd');
                // 快速预订
                mpos.post(mpos.api.SaveTableBookByMPOS, {
                    Mobile: bookPhone,
                    UserId: selectUserId || 0,
                    UserType: UserType || 0,
                    RealName: bookName,
                    ExpectedArrivalTime: bookDate + ' ' + bookTime,
                    TableId: table.TableId,
                    WaiterId: waiterId,
                    PeopleNum: peopleNum,
                    Remark: remark,
                }, function (orderId) {
                    requestStatus = 0;
                    dialogLoading.addClass('nd');
                    mpos.dialog.close(-99);
                }, {
                    error: function (err) {
                        requestStatus = 0;
                        dialogLoading.addClass('nd');
                    },
                    blFailed: function (err) {
                        requestStatus = 0;
                        dialogLoading.addClass('nd');
                        mpos.alert(err.data || '快速预订失败！');
                    }
                });

            } else {
                if (peopleNum <= 0) {
                    mpos.alert("顾客人数必须大于1的整数");
                    return;
                }
                var tableCard = $tableCard.val();
                var timeSpanId = $selectTimeSpan.val();
                var timeSchemeId = 0;
                if (timeSpanId == undefined || timeSpanId == 0) {
                    mpos.alert("请选择市别！");
                    return;
                }
                if (table.TimeChargeType == 3) {
                  timeSchemeId = $selectTimeCharge.val();
                  if (timeSchemeId == undefined || timeSchemeId == 0) {
                    mpos.alert("请选择计时方案！");
                    return;
                  }
                }

                requestStatus = 1;
                dialogLoading.removeClass('nd');
                mpos.post(mpos.api.openTableByMPOS, {
                    TableId: table.TableId,
                    WaiterId: waiterId,
                    PeopleNum: peopleNum,
                    BusinessTimeSpanId: timeSpanId,
                    TableCard: tableCard,
                    TimeSchemeId: timeSchemeId,   // 计时方式ID
                    Remark: remark,
                }, function (orderId) {
                    requestStatus = 0;
                    dialogLoading.addClass('nd');
                    mpos.dialog.close(orderId);
                }, {
                    error: function () {
                        requestStatus = 0;
                        dialogLoading.addClass('nd');
                    },
                    blFailed: function (err) {
                        requestStatus = 0;
                        dialogLoading.addClass('nd');
                        mpos.alert(err.data || '开台失败！');
                    }
                });
            }
        }
    });

    /**
     * 监听预订手机号输入，输入8位数字进行模糊匹配，将查询的用户列出来
     * 弹出新的窗体，展示搜索的用户信息，没有就不展示
     */
    $bookPhone.on('input', function(e) {
        var inputValue = $(this).val().trim();
        if (inputValue.length === 11) {
            // 通过手机号模糊查询
            fetchCustomer(inputValue);
        } else {
            selectUserId = 0;
        }
    });

    var clickBookNameCount = 0; // 记录点击客户姓名的次数
    // 获取焦点时，显示搜索的手机号信息
    $bookName.on('click', function(e) {
        if (fetchCustomerData.length > 0) {
            if (clickBookNameCount > 0) {
                $bookCustomerList.addClass('nd');
                clickBookNameCount = 0;
            } else {
                clickBookNameCount++;
                // 通过手机号模糊查询
                $bookCustomerList.removeClass('nd');
            }
        }
    });

    /**
     * 模糊匹配手机号，查询客户
     * 查询到客户，就要将其客户姓名输入框置灰，不能手输，否则就手动输入
     * */
    function fetchCustomer (mobile) {
        dialogLoading.removeClass('nd');
        mpos.get(mpos.api.GetBookCustomersByMPOS, {
            mobile: mobile
        }, function (result) {
            dialogLoading.addClass('nd');
            if (result && result.length > 0) {
                $bookName.attr('readOnly', true);
                $bookName.addClass('read-only');
            } else {
                $bookName.removeAttr('readOnly');
                $bookName.removeClass('read-only');
            }
            fetchCustomerData = result || [];
            showBookCustomer(fetchCustomerData);
        }, {
            error: function () {
                dialogLoading.addClass('nd');
            },
            blFailed: function () {
                dialogLoading.addClass('nd');
            }
        });
    }

    /**
     * 渲染展示搜索的手机信息
     * */
    function showBookCustomer (data) {
        $CustomerListUL.empty();
        var fragment = $(document.createDocumentFragment());
        $.each(data, function (idx, item) {
            var clone = $CustomerLI.clone();
            clone.find(".customer-name").text(item.RealName);
            clone.find(".customer-type").text(UserTypeEnum[item.UserType]);
            clone.data('user-id', item.UserId)
            fragment.append(clone);
        });
        $CustomerListUL.append(fragment);

        // 选择姓名
        $CustomerListUL.find('li').on('click', function(e){
            e.stopPropagation();
            var name = $(this).find('.customer-name').text();
            selectUserId = Number($(this).data('user-id'));  // 记录选择的客户ID
            if (name) {
                $bookName.val(name);
                $bookCustomerList.addClass('nd');
            }
        })
    }

    //功能操作
    $page.find('.operation-content .operation-item').on('click', function(e){
        if ($(this).hasClass('selected')) {
            return;
        }
        $page.find('.operation-content .selected').removeClass('selected');
        $(this).addClass('selected');
        var value = Number($(this).data('value'));
        operationValue = value; // 保存开台操作类型
        var $openBookTableContent = $page.find('.open-book-table-content');
        var $okSubmit = $page.find('.button.ok');
        var $openShow = $page.find('.open-show')
        if (value === 1) {
            // 开台
            $openShow.removeClass('nd');
            $openBookTableContent.addClass('nd');
            $okSubmit.text('开台');
            focusFunc(value);
        } else if (value === 2) {
            // 快速预订
            $openShow.addClass('nd');
            $openBookTableContent.removeClass('nd');
            $okSubmit.text('预订');
            fetchBookTable();  // 查询最近快速预订的信息
        }
    })

    /*
     加载服务员
     */
    function loadWaiters() {
        $selectWaiter.empty();
        var fm = $(document.createDocumentFragment());
        var itemIndex = 0;
        $.each(mpos.BaseData.Staffs, function (index, item) {
            //if (item.IsAllowPushMoney == 1) {
            var option = $('<option/>').attr("value", item.StaffId).text(item.StaffDisplayName);
            if (itemIndex == 0) { //选中第一个
                option.attr("selected", true);
                $selectWaiter.parent().find('span').text(option.text());
            }
            itemIndex++;
            fm.append(option);
            //}
        });
        fm.appendTo($selectWaiter);
    }

    /*
     加载市别
     */
    function loadBusinessTimeSpans() {
        mpos.post(mpos.api.getAllBusinessTimeSpan, null, function (timeSpan) {
            $selectTimeSpan.empty();
            var fm = $(document.createDocumentFragment());
            //增加请选择项
            var optionDefault = $('<option/>').attr("value", 0).text("请选择市别");
            if (timeSpan.CurrentTimeSpanId == 0) {
                optionDefault.attr("selected", true);
                $selectTimeSpan.parent().find('span').text(optionDefault.text());
            }
            fm.append(optionDefault);
            //增加所有市别
            $.each(timeSpan.TimeSpans, function (index, item) {
                var option = $('<option/>').attr("value", item.BusinessTimespanId).text(item.Name);
                if (item.BusinessTimespanId == timeSpan.CurrentTimeSpanId) { //选中当前市别
                    option.attr("selected", true);
                    $selectTimeSpan.parent().find('span').text(item.Name);
                }
                fm.append(option);
            });

            fm.appendTo($selectTimeSpan);
        }, {
                hideLoading: true
            });
    }

    /**
     * 加载计时方案
     * */
    function loadTimeChargeList () {
      if (table.TimeChargeType != 3) {
        return;
      }
      mpos.post(mpos.api.getTableSelectTimeChargeOffers, {TableId: table.TableId,}, function (res) {
        $selectTimeCharge.empty();
        var fm = $(document.createDocumentFragment());
        //增加请选择项
        var optionDefault = $('<option/>').attr("value", 0).text("请选择计时方案");
        if(res.TimeChargeOfferId === 0) {
          optionDefault.attr("selected", true);
          $selectTimeCharge.parent().find('span').text(optionDefault.text());
        }
        fm.append(optionDefault);
        //增加所有市别
        $.each(res, function (index, item) {
          var option = $('<option/>').attr("value", item.TimeChargeOfferId).text(item.OfferName);
          if (item.TimeChargeOfferId == res.TimeChargeOfferId) { //选中当前计时方案
            option.attr("selected", true);
            $selectTimeCharge.parent().find('span').text(item.OfferName);
          }
          fm.append(option);
        });

        fm.appendTo($selectTimeCharge);
      }, {
        hideLoading: true
      });
    }

    /**
     * 修改计时方案的显示样式
     * */
    function toggleTimeChargeStatus (status) {
      if (table.TimeChargeType != 3) {
        return;
      }
      if (status == true) {
        // 显示计时方案
        $page.find('.time-charge-row').addClass('show-time-charge-row');
      } else {
        // 显示计时方案
        $page.find('.time-charge-row').removeClass('show-time-charge-row');
      }
    }

    /**
     * 查询最近预订该餐台的用户信息
     * */
    function fetchBookTable () {
        // 如果手机号为空，就进行查询
        if (!LatestDiningBookData && isFetchLatestDiningBook) {
            isFetchLatestDiningBook = false;
            mpos.get(mpos.api.GetLatestDiningBookByMPOS, {TableId: table.TableId}, function (res) {
                LatestDiningBookData = res;
                setFormData();
            }, {
                hideLoading: true,
                blFailed: function (err) {
                }
            });
        } else {
            setFormData();
        }
    }

    // 赋值快速预订界面数据
    function setFormData () {
        if (LatestDiningBookData) {
            var res = LatestDiningBookData;
            var expectedArrivalTime = res.ExpectedArrivalTime.split(' ');
            var timeArr = expectedArrivalTime[1].split(":");
            var timeString = timeArr[0]+":"+timeArr[1];

            $bookPhone.val(res.Mobile);
            $bookName.val(res.RealName); // 赋值顾客姓名
            $bookDate.val(expectedArrivalTime[0]);
            $bookTime.val(timeString);
            $peopleNum.val(res.PeopleNum);
            $remark.val(res.Remark);
            if (res.WaiterId) {
                $selectWaiter.val(res.WaiterId);
                var waiterName = $selectWaiter.find("option:selected").text();
                $selectWaiter.parent().find('span').text(waiterName)
            }
        }
        focusFunc(2);
    }


    // 默认焦点定位
    function focusFunc(value) {
        if (value === 2) {
            // 默认焦点定位到输入框
            setTimeout(function () {
                $bookPhone.focus();
            }, 200);
        } else {
            // 默认焦点定位到输入框
            setTimeout(function () {
                $peopleNum.focus();
            }, 200);
        }
    }

    // 调用默认焦点定位
    focusFunc();
});

mpos.dialogController(mpos.dialogPage.prepayBillQr, function(page, data) {
    var settleData = data.settle;
    $(page).find(".button.cancel").on("click", function(e) {
        mpos.dialog.close(false);
    });

    mpos.post(mpos.api.getPrepayBillQr, {
        OrderId: settleData.EnterOrder.Order.OrderId
    }, function(url) {
        if (url != undefined) {
            if (url != "") {
                if (url.toLowerCase().indexOf("http") == -1) {
                    mpos.alert(url);
                } else {
                    $("<img  height='250' width='250' />")
                        .attr("src", "/Image/GetPrepayBillQr?Height=250&Width=250&Url=" + encodeURIComponent(url))
                        .on("error", function() {
                            mpos.alert("加载二维码失败，请检查网络是否正常！");
                        })
                        .appendTo($(page).find(".qr-img"));
                }
            }
        }
    });
});
/*
减免
*/
mpos.dialogController(mpos.dialogPage.reductionAmount, function (page, data) {
    var settleData = data.settle;
    var amountValueDom = $(page).find("input[name='amountValue']");
    //填充原减免金额
    amountValueDom.val(settleData.Consumption.ManualCutMoney);
    //事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var amount = $.trim(amountValueDom.val());

            if (amount == "") {
                amount = 0;
            }

            amount = parseFloat(amount);

            if (amount < 0) {
                mpos.alert("减免金额必需大于0");
                return;
            }

            if (settleData.AllowManualCutAmount >= amount) {
                if (amount == settleData.Consumption.ManualCutMoney) {
                    mpos.dialog.close(false);
                    return;
                }
            }

            if (amount >= settleData.AllowManualCutAmount) {
                mpos.alert("减免金额不能大于等于应收金额");
                return;
            }
            if (amount > (settleData.TotalPayableAmountNotForManualCutAmount - settleData.VoucherAmount)) {
                mpos.alert("减免金额不能大于可减免的金额");
                return;
            }

            mpos.post(mpos.api.setManualCutMoney, {
                OrderId: settleData.EnterOrder.Order.OrderId,//订单
                Amount: amount //金额
            }, function (data) {
                mpos.dialog.close(true);
            });
        }
    });
});
/**
 * 退菜界面
 */
mpos.dialogController(mpos.dialogPage.returnDish, function (page, data) {
    var dish = data.Dish;
    var reasons = [];
    var shopConfig;
    var $dishNum = $(page).find("input[name='dishNum']");
    var $reasonItem = $(page).find(".reason-list>li").remove();

    //菜品名称
    $(page).find("#dishName").html(dish.DishName);
    //数量
    $dishNum.val(dish.RealDishNum);
    mpos.checkInputValue($dishNum, InputType.DishNum);
    //加载原因
    mpos.getReason(ReasonType.ReturnDish, loadReason);
    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var dishNum = $dishNum.val();

            if (dishNum == "") {
                mpos.alert("请输入退货数量");
                return;
            }

            dishNum = parseFloat(dishNum);

            if (dishNum == 0) {
                mpos.alert("请输入要退的商品数量");
                return;
            }
            if (dishNum > dish.RealDishNum) {
                mpos.alert("要退的商品数量不能大于当前商品数量");
                return;
            }
            var reasonId = $(page).find("input[name='selectReason']:checked").val();
            if (reasonId == undefined || reasonId == null) {
                if (shopConfig.ReturnDishRequire) {
                    mpos.alert("请选退货的原因");
                    return;
                }
                reasonId = 0;
            }
            var isPrintKit = $(page).find("input[name='printToKitchen']")[0].checked;
            if (isPrintKit == true) {
                isPrintKit = 1;
            } else {
                isPrintKit = 0;
            }
            var tableBillId = mpos.tableBillId();
            mpos.post(mpos.api.returnDish, {
                OrderDishId: dish.OrderDishId,
                DiningOrderId: dish.DiningOrderId,
                DishNum: dishNum,
                DishReturnReasonId: reasonId,
                IsPrintKit: isPrintKit,
                TableBillId: tableBillId
            }, function (r) {
                if (r.TableBills) { //台单
                    if (r.TableBills != null && Array.isArray(r.TableBills) && tableBillId > 0 && r.TableBills.length > 0) {
                        var printNum = mpos.tableBillNumber();
                        for (var j = 0; j < r.TableBills.length; j++) {
                            for (var i = 0; i < printNum; i++) { //打印多份
                                var printData = mpos.addPrintEmptyLine(r.TableBills[j]);
                                mpos.deviceFactory.printTicket(printData, null, function (err) {
                                    //打印
                                    mpos.alert(err);
                                });
                            }
                        }
                    }
                }

                var printSigleBill = mpos.printSigleBill();
                var printTotalBill = mpos.printTotalBill();
                if (printTotalBill == 1 && r.TotalBills) { //总单
                    if (r.TotalBills != null && Array.isArray(r.TotalBills) && r.TotalBills.length > 0) {
                        $.each(r.TotalBills, function (index, item) {
                            var printData = mpos.addPrintEmptyLine(item);
                            mpos.deviceFactory.printTicket(printData, null, function (err) {
                                //打印
                                mpos.alert(err);
                            });
                        })
                    }
                }

                if (printSigleBill == 1 && r.SigleBills) { //分单
                    if (r.SigleBills != null && Array.isArray(r.SigleBills) && r.SigleBills.length > 0) {
                        $.each(r.SigleBills, function (index, item) {
                            var printData = mpos.addPrintEmptyLine(item);
                            mpos.deviceFactory.printTicket(printData, null, function (err) {
                                //打印
                                mpos.alert(err);
                            });
                        })
                    }
                }
                mpos.dialog.close(true);
            });
        }
    });

    /*
    加载原因
    */
    function loadReason(data) {
        mpos.getReasonConfirm(function (config) {
            shopConfig = config;
            reasons = data.ReasonList;
            var reasonContainer = $(page).find("#reasonContainer");
            var fragment = $(document.createDocumentFragment());
            $.each(reasons, function (index, item) {
                var reasonItem = $reasonItem.clone();
                reasonItem.find("input").val(item.ReasonId);
                reasonItem.find("span").text(item.ReasonText);
                fragment.append(reasonItem);
            });
            $(page).find(".reasonContainer").empty().append(fragment);
        });
    }
});

/**
 * 反结账
 */
mpos.dialogController(mpos.dialogPage.reverseSettle, function (page, data) {
    var settleData = data.settle;
    var reasons = [];
    var shopConfig;
    
    var $reasonItem = $(page).find(".reason-list>li").remove();
    
    //菜品名称
    $(page).find("#serialNumber").text(settleData.Consumption.SerialNumber);

    //加载原因
    mpos.getReason(ReasonType.AntiPayment, loadReason);
    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var reasonId = $(page).find("input[name='selectReason']:checked").val();
            if (reasonId == undefined || reasonId == null) {
                if (shopConfig.AntiPaymentRequire) {
                    mpos.alert("请选择反结账原因");
                    return;
                }
                reasonId = 0;
            }
            mpos.post(mpos.api.reverseSettle, {
                ConsumptionId: settleData.Consumption.ConsumptionId, //单据ID
                ReasonId: reasonId//原因ID
            }, function (data) {
                mpos.dialog.close(true);
            });
        }
    });

    /*
    加载原因
    */
    function loadReason(data) {
        mpos.getReasonConfirm(function(config){
            shopConfig = config;
            reasons = data.ReasonList;
            var fragment = $(document.createDocumentFragment());
            $.each(reasons, function (index, item) {
                var reasonItem = $reasonItem.clone();
                reasonItem.find("input").val(item.ReasonId);
                reasonItem.find("span").text(item.ReasonText);
                fragment.append(reasonItem);
            });
            $(page).find(".reasonContainer").empty().append(fragment);
        });

    }
});
/**
 * author: wang.p  2021-09-07
 * description: 存酒详情
 */
mpos.dialogController(mpos.dialogPage.saveWinesDetail, function (page, data) {

  var $page = $(page);
  var winesId = data.winesId;
  var winesPlaceData = data.winesPlaceData;
  var winesDetail = null;

  var $title = $page.find('.title');
  var $baseDetail = $page.find('.base-detail');
  var $saveDetailList = $page.find('.save-detail-ul');
  var $saveDetailNode = $saveDetailList.find('li').remove();
  var $fetchDetailList = $page.find('.fetch-detail-ul');
  var $fetchDetailNode = $fetchDetailList.find('li').remove();
  var $tipsContainer = $page.find('.tips-container');

  initSaveWinesDetail();

  // 加载存酒详情数据
  function initSaveWinesDetail () {
    mpos.get(mpos.api.getSaveWineDetail, {StorageSaveId: winesId}, function (res) {
      winesDetail = res;
      renderDetail(res);
    });
  }

  /*
  * 获取员工信息
  * @staffId  员工Id
  * */
  function getStaffInfo (staffId) {
    if (staffId) {
      mpos.get(mpos.api.getStaffById, {staffId: staffId}, function (res) {
        if (res && res.User) {
          $baseDetail.find('.CreatedBy').text(res.User.StaffName);
        }
      });
    }
  }

  // 获取存酒位置信息
  function getPositionName (positionId) {
    var place = winesPlaceData.find(function(item) {
      return item.StoragePositionId == positionId;
    });
    return  place ? place.DisplayName : '';
  }

  // 渲染
  function renderDetail (data) {

    var detailData = null; // 基本信息
    var saveList = [];  // 存酒的记录
    var fetchList = [];  // 取酒的记录
    var saveTotal = 0;  // 存酒总数量
    var leftTotal = 0;  // 剩余总数量
    if (data) {
      detailData = data.Save.MainStorage;
      saveList = data.Save.Details;  // 存酒的记录
      fetchList = data.Fetch;  // 取酒的记录
    }

    // 赋值存酒记录
    $saveDetailList.empty();
    if (saveList.length > 0) {
      var fragment = $(document.createDocumentFragment());
      saveList.forEach(function(item, idx) {
        saveTotal += item.SaveNum;
        leftTotal += item.LeftNum;

        var $node = $saveDetailNode.clone();
        $node.find('.DishName').text(item.DishName);
        $node.find('.SaveNum').text(item.SaveNum);
        $node.find('.LeftNum').text(item.LeftNum);
        $node.find('.PositionId').text(getPositionName(item.PositionId));

        fragment.append($node);
      })
      $saveDetailList.append(fragment);
    } else {
      var $cloneNode = $tipsContainer.clone();
      $cloneNode.removeClass('nd');
      $saveDetailList.append($cloneNode);
    }

    // 赋值基本信息
    if (detailData) {
      $title.text(detailData.StorageSaveSerial);
      $baseDetail.find('.CustomerName').text(detailData.CustomerName);
      $baseDetail.find('.Mobile').text(detailData.Mobile);
      $baseDetail.find('.SaveTotal').text(saveTotal);
      $baseDetail.find('.LeftTotal').text(leftTotal);
      $baseDetail.find('.CreatedOn').text(detailData.CreatedOn);
      $baseDetail.find('.ExpiryDate').text(detailData.ExpiryDate);
      $baseDetail.find('.StorageStatus').text(SaveWinesStorageStatusEnum[detailData.StorageStatus]);
      $baseDetail.find('.CreatedBy').text(detailData.CreatedBy);
      $baseDetail.find('.Remark').text(detailData.Remark);
    }

    // 赋值取酒记录
    $fetchDetailList.empty();
    if (fetchList.length > 0) {
      var fragment = $(document.createDocumentFragment());
      fetchList.forEach(function(item, idx) {
        var $node = $fetchDetailNode.clone();
        $node.find('.DishName').text(item.DishName);
        $node.find('.FetchSerialNum').text(item.FetchSerialNum);
        $node.find('.FetchNum').text(item.FetchNum);
        $node.find('.CreatedOn').text(item.CreatedOn);

        fragment.append($node);
      })
      $fetchDetailList.append(fragment);
    } else {
      var $cloneNode = $tipsContainer.clone();
      $cloneNode.removeClass('nd');
      $fetchDetailList.append($cloneNode);
    }

    detailData && getStaffInfo(detailData.CreatedBy)
  }

  //确定和取消事件
  $page.find(".app-submit").on("click", function (e) {
    var operationType = $(e.currentTarget).data("operation");
    if (operationType == 2) {
      // 取消
      mpos.dialog.close(false);
    } else {
      //修改
      var detailData = winesDetail.Save.MainStorage;  // 基本信息
      var saveList = winesDetail.Save.Details;  // 存酒的记录
      var newWinesDetail = createSaveWinesObj(detailData);
      var details = [];
      saveList.forEach(function(item){
        details.push({
          DetailId: item.SaveDetailId,   // 详细ID
          AssessPrice: item.AssessPrice,   /// 估价，没有默认0
          DishId: item.DishId,   // 菜品ID
          DishName: item.DishName,  // 菜品名称
          UnitId: item.UnitId,   // 单位ID
          UnitName: item.UnitName,   // 单位名称
          SaveNum: item.SaveNum,   // 存酒数量
          PositionId: item.PositionId,   // 位置ID
        })
      });
      newWinesDetail.Details = details;
      mpos.dialog.close({data: newWinesDetail});
    }
  });

});


/**
 * 存酒的详细信息对象
 *
 */
function saveWinesDetailObj () {
  var detailObj = {
    // 取酒记录
    Fetch: [
      {
        "FetchSerialNum": "",   /// 取酒单号
        "DishName": "",    /// 商品名称
        "UnitName": "",   /// 单位
        "FetchNum": 0,    /// 取酒数量
        "CreatedOn": ""   /// 取酒时间
      }
    ],
    // 存酒记录
    Save: {
      // 基本信息
      MainStorage: {
        "StorageSaveId": 0,   /// 主键
        "StorageSaveSerial": "",   /// 存酒单号
        "Mobile": "",    /// 客户手机号码
        "CustomerName": "",   /// 客户名称
        "StorageStatus": 1,   // 状态，1－正常，2－已取完，3－已作废
        "Remark": "",    /// 备注
        "ExpiryDate": "",    /// 有效期
        "MemberId": 0,   /// 会员ID
        "CardId": 0,     /// Card ID
        "CustomerIdNum": "",    /// 身份证
        "OtherIdNum": "",    /// 其它证号
        "OtherIdName": "",      /// 其它证名
        "CreatedBy": 0,   /// 创建人
        "CreatedOn": "",   /// 创建时间
        "ModifiedBy": 0,     /// 修改人
        "ModifiedOn": "",   /// 修改时间
        "StatusCode": 1,    /// 状态（0：删除，1：有效，2：回收站）
        "SyncStatus": 0   /// 同步状态，0：需要同步，127：不需要同步
      },
      Details: [
        {
          "SaveDetailId": 0,
          "StorageSaveId": 0,  /// 存酒主表ID
          "DishId": 0,    /// 商品ID
          "DishName": "",  /// 商品名称
          "UnitName": "",   /// 商品单位名称
          "UnitId": 0,   /// 单位ID
          "SaveNum": 0,    /// 存入数量
          "LeftNum": 0,   /// 剩余数量
          "FetchNum": 0,  /// 已取出数量
          "PositionId": 0,   /// 位置ID
          "AssessPrice": 0,  /// 估价
          "Remark": "",   /// 说明，备注
          "CreatedBy": 0,   /// 创建人
          "CreatedOn": "",    /// 创建时间
          "ModifiedBy": 0,    /// 修改人
          "ModifiedOn": "",   /// 修改时间
          "StatusCode": 1,   /// 状态（0：删除，1：有效，2：回收站）
          "SyncStatus": 0   /// 同步状态，0：需要同步，127：不需要同步
        }
      ]
    }
  }

}

/**
 * 菜品转台选台
 */
mpos.dialogController(mpos.dialogPage.selectChangeDishTable, function (page, data) {
    var orderId = data.OrderId;
    var $page = $(page);
    var $selectFloor = $page.find("select[name='selectFloor']");
    var $tableLlist = $page.find(".table-list");
    var $tableLlistItem = $tableLlist.find("li").remove();
    var allTables = null;
    var currentSelectedFloorId = 0;

    //select标签赋值
    $selectFloor.on("change", function () {
        var t = $(this);
        t.parent().find('span').text(this.options[this.selectedIndex].text);
        currentSelectedFloorId = this.options[this.selectedIndex].value;
        BindTables();
    });

    loadTables();

    $page.find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(null);
        } else {
            var selectedOrderId = $tableLlist.find("input[name='selectMenu']:checked").parents("li").data("oid");
            if (selectedOrderId == undefined) {
                mpos.alert("请选择餐台");
                return;
            }
            mpos.dialog.close(selectedOrderId);
        }
    });

    /*
    加载要换到的餐台
    */
    function loadTables() {
        mpos.post(mpos.api.getCanChangeDishTables, {
            DiningOrderId: orderId
        }, function (r) {
            $selectFloor.empty();
            if (r.Floors) {
                var fm = $(document.createDocumentFragment());
                var itemIndex = 0;
                $.each(r.Floors, function (index, item) {
                    var option = $('<option/>').attr("value", item.Id).text(item.Name);
                    if (itemIndex == 0) { //选中第一个
                        option.attr("selected", true);
                        $selectFloor.parent().find('span').text(option.text());
                    }
                    itemIndex++;
                    fm.append(option);
                });
                fm.appendTo($selectFloor);
            }
            allTables = r.Tables;
            BindTables();
        });
    }

    function BindTables() {
        $tableLlist.empty();
        var tables = [];
        $.each(allTables, function (index, item) {
            if (currentSelectedFloorId > 0) {
                if (item.FloorId == currentSelectedFloorId) {
                    tables.push(item);
                }
            } else {
                tables.push(item);
            }
        });
        $.each(tables, function (idx, item) {
            var $clone = $tableLlistItem.clone();
            $clone.find("span").text(item.TableName);
            $clone.data("tid", item.TableId);
            $clone.data("oid", item.OrderId);
            $tableLlist.append($clone);
        });
    }
});

/**
 * 选餐牌
 */
mpos.dialogController(mpos.dialogPage.selectSnackBrand, function (page, data) {
    var table = data.Table;
    var $menuList = $(page).find(".menu-list");
    var $menuListItem = $menuList.find("li").remove();
    var $peopleNum = $(page).find("input[name='peopleNum']");
    var $menuNum = $(page).find("input[name='menuNum']");
    var brands = [];
    var oldTableSerial = data.TableSerial;
    var oldPeopleNum = data.PeopleNum;

    $menuNum.val(oldTableSerial);
    $peopleNum.val(oldPeopleNum);

    mpos.checkInputValue($peopleNum, InputType.Num1To999);

    loadBrands();

    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var peopleNum = $peopleNum.val();
            var tableSerial = $.trim($menuNum.val());

            if (peopleNum == "" || peopleNum == 0) {
                mpos.alert("请输入人数！");
                return;
            }
            var changed = false;
            if (peopleNum != oldPeopleNum || tableSerial != oldTableSerial) {
                changed = true;
            }

            var exitsBrand = false;
            $.each(brands, function (idx, item) {
                if (exitsBrand) {
                    return;
                }
                if (item.TableSerial == tableSerial) {
                    exitsBrand = true;
                    return ;
                }
            });

            if(!exitsBrand){
                mpos.alert("输入的餐牌不存在！");
                return;
            }

            mpos.dialog.close({
                PeopleNum: peopleNum,
                TableSerial: tableSerial,
                Changed: changed
            });
        }
    });

    /*
     加载餐牌信息
     */
    function loadBrands() {
        mpos.post(mpos.api.getSnackBrands, null, function (r) {
            $menuList.empty();
            brands = r;
            $.each(brands, function (idx, item) {
                var $clone = $menuListItem.clone();
                $clone.find("span").text(item.TableSerial);
                $clone.data("b_s", item.TableSerial);
                $menuList.append($clone);
            });

            $(page).find("input[name='selectMenu']").tap(function (e) {
                $menuNum.val($(e.currentTarget).parents("li").data("b_s"));
            });
        });
    }
    /*
    餐牌输入事件
    */
    $menuNum.on("input", function () {
        var brand = $menuNum.val();
        $.each($menuList.find("li"), function (idx, item) {
            var $item = $(item);
            if ($.trim(brand) == "") {
                $item.show();
                return;
            }
            var brandSerial = $item.data("b_s").toString();
            if (brandSerial.indexOf(brand) != -1) {
                $item.show();
            } else {
                $item.hide();
            }
            if (brandSerial == brand) {
                $item.find("input[name='selectMenu']").prop("checked", true);
            }
        });
    });
});

/**
 * 选择服务员
 */
mpos.dialogController(mpos.dialogPage.selectWaiter, function (page, data) {
    var $selectWaiter = $(page).find("select[name='selectWaiter']");

    //select标签赋值
    $selectWaiter.on("change", function () {
        var t = $(this);
        t.parent().find('span').text(this.options[this.selectedIndex].text);
    });

    loadWaiters();

    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close({
                WaiterId: 0
            });
        } else {
            var waiterId = $selectWaiter.val();
            mpos.dialog.close({
                WaiterId: waiterId
            });
        }
    });

    /*
     加载服务员
     */
    function loadWaiters() {
        $selectWaiter.empty();
        var fm = $(document.createDocumentFragment());
        var itemIndex = 0;
        $.each(mpos.BaseData.Staffs, function (index, item) {
            //if (item.IsAllowPushMoney == 1) {
            var option = $('<option/>').attr("value", item.StaffId).text(item.StaffDisplayName);
            if (itemIndex == 0) { //选中第一个
                option.attr("selected", true);
                $selectWaiter.parent().find('span').text(option.text());
            }
            itemIndex++;
            fm.append(option);
            //}
        });
        fm.appendTo($selectWaiter);
    }
});

/**
 通用金额选择
 @param page page
 @param selectedBack click callback function
 */
mpos.loadPaymentAmountSelect = function (page, selectedBack) {
    // var amounts = [5, 10, 50, 100];
    // var container = $(page).find(".amounts-select");
    // if (container && container != undefined) {
    //     var selectHtml = "";
    //     $.each(amounts, function (index, item) {
    //         selectHtml += "<span data-amount='" + item + "'>+" + item + "</span>";
    //     });
    //     container.html(selectHtml);
    //     $(page).find(".amounts-select span[data-amount]").on("click", function (e) {
    //         var amount = $(e.currentTarget).data("amount");
    //         selectedBack(amount);
    //     });
    // }
};

/**
 现金结账对话框
 */
mpos.dialogController(mpos.dialogPage.cashPay, function (page, data) {
    var settleData = data.settle;
    var paymentPattern = data.paymentPattern;
    var $paymentInput = $(page).find("input[name='payAmount']");
    var $totalObligationAmount = $(page).find(".totalObligationAmount"); //待收
    var IsPayToOrder = data.IsPayToOrder;
    $totalObligationAmount.text(mpos.formatPrice(settleData.TotalObligationAmount));
    $paymentInput.val(settleData.TotalObligationAmount);

    mpos.checkInputValue($paymentInput, InputType.NegativeAmount);

    $(page).find(">div.title").text(paymentPattern.PaymentPatternName);

    //加载金额选择项
    mpos.loadPaymentAmountSelect(page, function (amount) {
        var oldAmount = $.trim($paymentInput.val());
        if (oldAmount == "") {
            oldAmount = 0;
        } else {
            oldAmount = Number(oldAmount);
        }
        $paymentInput.val(mpos.priceFixed(oldAmount + amount));

    });
    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var amount = $.trim($paymentInput.val());
            if (amount == "") {
                mpos.alert("请输入金额");
                return;
            }
            amount = parseFloat(amount);
            if (amount == 0) {
                mpos.alert("金额不能为零");
                return;
            }
            mpos.settlePayment({
                // 付款方式ID
                PaymentPatternId: paymentPattern.PaymentPatternId,
                // 订单ID
                OrderId: settleData.EnterOrder.Order.OrderId,
                // 付款金额
                Amount: amount,
                // 会员ID或挂账客户ID
                MemberId: 0,
                // 会员卡ID
                MemberCardId: 0,
                // 票券ID
                TicketId: 0,
                // 备注
                Remark: "",
                // 挂账人ID
                CreditUserId: 0,
                // 是否会员挂账
                IsMemberCredit: false,
                IsPayToOrder: IsPayToOrder
            }, function (data) {
                mpos.dialog.close(data);
            });
        }
    });
});

/**
 银行卡结账对话框
 */
mpos.dialogController(mpos.dialogPage.bankPay, function (page, data) {
    var settleData = data.settle;
    var paymentPattern = data.paymentPattern;
    var $paymentInput = $(page).find("input[name='payAmount']");
    var $payRemarkInput = $(page).find("input[name='payRemark']");
    var $totalObligationAmount = $(page).find(".totalObligationAmount"); //待收
    var IsPayToOrder = data.IsPayToOrder;
    $totalObligationAmount.text(mpos.formatPrice(settleData.TotalObligationAmount));
    $paymentInput.val(settleData.TotalObligationAmount);
    $(page).find(">div.title").text(paymentPattern.PaymentPatternName);
    if (paymentPattern.IsAllowNegative != 0) {
        mpos.checkInputValue($paymentInput, InputType.NegativeAmount);
    } else {
        mpos.checkInputValue($paymentInput, InputType.Amount);
    }

    //加载金额选择项
    mpos.loadPaymentAmountSelect(page, function (amount) {
        var oldAmount = $.trim($paymentInput.val());
        if (oldAmount == "") {
            oldAmount = 0;
        } else {
            oldAmount = Number(oldAmount);
        }
        $paymentInput.val(mpos.priceFixed(oldAmount + amount));
    });
    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var amount = $paymentInput.val().trim();
            if (amount == "") {
                mpos.alert("请输入金额");
                return;
            }
            amount = parseFloat(amount);
            if (amount == 0) {
                mpos.alert("金额不能为零");
                return;
            }

            if (amount <= 0) {
                if (paymentPattern.IsAllowNegative == 0) {
                    mpos.alert("付款金额不能小于等于0");
                    return;
                }
            }
            if (amount > settleData.TotalObligationAmount) {
                mpos.alert("付款金额不能大于待收金额");
                return;
            }

            var remark = $payRemarkInput.val();

            mpos.settlePayment({
                // 付款方式ID
                PaymentPatternId: paymentPattern.PaymentPatternId,
                // 订单ID
                OrderId: settleData.EnterOrder.Order.OrderId,
                // 付款金额
                Amount: amount,
                // 备注
                Remark: remark,
                IsPayToOrder: IsPayToOrder
            }, function (data) {
                mpos.dialog.close(true);
            });
        }
    });
});

/**
 自定义第三方支付
 */
mpos.dialogController(mpos.dialogPage.thirdCustomPay, function (page, data) {
    var settleData = data.settle;
    var paymentPattern = data.paymentPattern;
    var $paymentInput = $(page).find("input[name='payAmount']");
    //var $payRemarkInput = $(page).find("input[name='payRemark']");
    var $saleIncomeAmountInput = $(page).find("input[name='saleIncomeAmount']");
    var $totalObligationAmount = $(page).find(".totalObligationAmount"); //待收
    var totalObligationAmount = 0;
    var IsPayToOrder = data.IsPayToOrder;
    $paymentInput.val(settleData.TotalObligationAmount);
    $totalObligationAmount.text(mpos.formatPrice(settleData.TotalObligationAmount));
    totalObligationAmount = settleData.TotalObligationAmount;
    onInputAmountChange();
    $(page).find(">div.title").text(paymentPattern.PaymentPatternName);
    if (paymentPattern.IsAllowNegative != 0) {
        mpos.checkInputValue($paymentInput, InputType.NegativeAmount);
    } else {
        mpos.checkInputValue($paymentInput, InputType.Amount);
    }

    $paymentInput.on("input", onInputAmountChange);

    function onInputAmountChange() {
        var amount = $paymentInput.val().trim();
        if (amount == "") {
            return;
        }

        if (paymentPattern.PaymentProperty == 1) {
            $saleIncomeAmountInput.prop("disabled", true);
            $saleIncomeAmountInput.val(amount);
        } else if (paymentPattern.PaymentProperty == 2) {
            $saleIncomeAmountInput.prop("disabled", true);
            $saleIncomeAmountInput.val("0.00");
        } else if (paymentPattern.PaymentProperty == 3) {
            $saleIncomeAmountInput.prop("disabled", false);
            amount = parseFloat(amount);
            var denominationAmount = paymentPattern.DenominationAmount;
            var realAmount = paymentPattern.RealAmount;
            if (denominationAmount == 0) {
                this.txtSaleIncome.Text = amount.toFixed(2).toString();
            } else {
                $saleIncomeAmountInput.val(
                    ((parseInt(amount / denominationAmount) * realAmount)
                        + ((amount % denominationAmount) > realAmount ? realAmount : (amount % denominationAmount)))
                );
            }
        }
    }

    //加载金额选择项
    mpos.loadPaymentAmountSelect(page, function (amount) {
        var oldAmount = $.trim($paymentInput.val());
        if (oldAmount == "") {
            oldAmount = 0;
        } else {
            oldAmount = Number(oldAmount);
        }
        $paymentInput.val(mpos.priceFixed(oldAmount + amount));
    });
    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var saleIncountAmount = $saleIncomeAmountInput.val().trim();
            var amount = $paymentInput.val().trim();
            if (amount == "" || saleIncountAmount == "") {
                mpos.alert("请输入金额");
                return;
            }
            amount = parseFloat(amount);
            saleIncountAmount = parseFloat(saleIncountAmount);
            if (amount == 0) {
                mpos.alert("金额不能为零");
                return;
            }

            if (amount <= 0) {
                if (paymentPattern.IsAllowNegative == 0) {
                    mpos.alert("付款金额不能小于等于0");
                    return;
                }
            }
            if (amount > totalObligationAmount) {
                mpos.alert("付款金额不能大于待收金额");
                return;
            }

            if (saleIncountAmount > amount) {
                mpos.alert("实收金额不能大于收款金额");
                return;
            }

            var remark = ""; //$payRemarkInput.val();

            mpos.settlePayment({
                // 付款方式ID
                PaymentPatternId: paymentPattern.PaymentPatternId,
                // 订单ID
                OrderId: settleData.EnterOrder.Order.OrderId,
                // 付款金额
                Amount: amount,
                // 实收金额
                SaleIncomeAmount: saleIncountAmount,
                // 备注
                Remark: remark,
                IsPayToOrder: IsPayToOrder
            }, function (data) {
                mpos.dialog.close(true);
            });
        }
    });
});


/**
 免单结账对话框
 */
mpos.dialogController(mpos.dialogPage.freePay, function (page, data) {
    var settleData = data.settle;
    var paymentPattern = data.paymentPattern;
    var $paymentInput = $(page).find("input[name='payAmount']");
    var $payRemarkInput = $(page).find("input[name='payRemark']");
    var $totalObligationAmount = $(page).find(".totalObligationAmount"); //待收
    var IsPayToOrder = data.IsPayToOrder;
    $paymentInput.val(settleData.TotalObligationAmount);
    $totalObligationAmount.text(mpos.formatPrice(settleData.TotalObligationAmount));
    $(page).find(">div.title").text(paymentPattern.PaymentPatternName);

    if (paymentPattern.IsAllowNegative != 0) {
        mpos.checkInputValue($paymentInput, InputType.NegativeAmount);
    } else {
        mpos.checkInputValue($paymentInput, InputType.Amount);
    }

    //加载金额选择项
    mpos.loadPaymentAmountSelect(page, function (amount) {
        var oldAmount = $.trim($paymentInput.val());
        if (oldAmount == "") {
            oldAmount = 0;
        } else {
            oldAmount = Number(oldAmount);
        }
        $paymentInput.val(mpos.priceFixed(oldAmount + amount));
    });
    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var amount = $.trim($paymentInput.val());
            if (amount == "") {
                mpos.alert("请输入金额");
                return;
            }
            amount = parseFloat(amount);
            if (amount == 0) {
                mpos.alert("金额不能为零");
                return;
            }
            var remark = $payRemarkInput.val();
            if (amount <= 0) {
                if (paymentPattern.IsAllowNegative == 0) {
                    mpos.alert("免单金额不能小于等于0");
                    return;
                }
            }
            if (amount > settleData.TotalObligationAmount) {
                mpos.alert("免单金额不能大于待收金额");
                return;
            }
            mpos.settlePayment({
                // 付款方式ID
                PaymentPatternId: paymentPattern.PaymentPatternId,
                // 订单ID
                OrderId: settleData.EnterOrder.Order.OrderId,
                // 付款金额
                Amount: amount,
                // 备注
                Remark: remark,
                IsPayToOrder: IsPayToOrder
            }, function (data) {
                mpos.dialog.close(data);
            });
        }
    });
});

/**
 票券结账对话框
 */
mpos.dialogController(mpos.dialogPage.ticketPay, function (page, data) {
    var settleData = data.settle;
    var paymentPattern = data.paymentPattern;
    var $ticketNo = $(page).find("input[name='ticketNo']");
    var $ticketScan = $(page).find(".ticket-scan");
    var $memberTicketSelect = $(page).find(".member-ticket-select");
    var $ticketItem = $memberTicketSelect.find("li").remove();
    var $totalObligationAmount = $(page).find(".totalObligationAmount"); //待收
    var needRefresh = false;
    var IsPayToOrder = data.IsPayToOrder;
    $totalObligationAmount.text(mpos.formatPrice(settleData.TotalObligationAmount));
    $(page).find(">div.title").text(paymentPattern.PaymentPatternName);

    //扫码事件
    $ticketScan.on("click", function () {
        mpos.scanQR(function (result) {
            result = typeof jsonModelScanResult == "object" ?
                jsonModelScanResult : result;
            if (result.cancelled == true) {
                return;
            }
            var barCode = result.text;
            $ticketNo.val(barCode);
            submitTicketValidate();
        }, function (err) {
            mpos.alert("扫码错误!");
        });

    });

    //加载会员票券
    if (settleData.MemberCard != null) {
        mpos.post(mpos.api.getMemberTickets, {
            ConsumptionId: settleData.Consumption.ConsumptionId,
            MemberId: settleData.MemberCard.MemberId
        }, function (data) {
            if (_.isArray(data) && data.length > 0) {
                var fm = $(document.createDocumentFragment());
                data.forEach(function (item) {
                    var ticketItem = $ticketItem.clone();
                    ticketItem.find(".ticket-title").text(item.Title);
                    ticketItem.find(".ticket-type").text(item.TicketType);
                    ticketItem.find(".selectTicket").data("ticket_id", item.TicketId);
                    fm.append(ticketItem);
                });

                fm.find(".selectTicket").on("click", function (e) {
                    var $target = $(e.currentTarget);
                    var ticketId = $target.data("ticket_id");
                    //使用票券
                    mpos.settlePayment({
                        PaymentPatternId: paymentPattern.PaymentPatternId,
                        OrderId: settleData.EnterOrder.Order.OrderId,
                        Amount: 0,
                        TicketId: ticketId,
                        IsPayToOrder: IsPayToOrder
                    }, function (data) {
                        $target.parent().remove();
                        needRefresh = true;
                        settleData = data;
                        $totalObligationAmount.text(settleData.TotalObligationAmount);
                        mpos.alert("成功使用此票券");
                    });
                });

                $memberTicketSelect.append(fm);

            } else {
                $memberTicketSelect.hide();
            }
        });
    } else {
        $memberTicketSelect.hide();
    }

    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(needRefresh);
        } else {
            submitTicketValidate();
        }
    });

    /**
     验证票券
     */
    function submitTicketValidate() {
        var consumptionNo = $.trim($ticketNo.val());
        if (consumptionNo == '') {
            mpos.alert("请输入消费券号");
            return;
        }
        mpos.post(mpos.api.getTicketIdByTicketConsumptionNo, {
            ConsumptionNo: consumptionNo
        }, function (ticket) {
            mpos.settlePayment({
                PaymentPatternId: paymentPattern.PaymentPatternId,
                OrderId: settleData.EnterOrder.Order.OrderId,
                Amount: 0,
                TicketId: ticket.TicketId,
                IsPayToOrder: IsPayToOrder
            }, function (data) {
                mpos.dialog.close(data);
            });
        })
    }
});

/**
 会员结账对话框
 */
mpos.dialogController(mpos.dialogPage.memberPay, function (page, data) {
    var settleData = data.settle;
    var currentMember = settleData.MemberCard;
    var paymentPattern = data.paymentPattern;
    var queryCards = [];
    var $page = $(page);
    var $paymentInput = $page.find("input[name='payAmount']"); //付款金额
    var $totalObligationAmount = $page.find(".totalObligationAmount"); //待收
    var $keyWord = $page.find("input[name='keyWord']");
    var $exchageScore = $page.find("input[name='exchangeScore']");
    var $exchangeAmount = $page.find("span.exchange-amount");
    var $memberList = $page.find(".member-list");
    var $cardItem = $memberList.find("li").remove();
    var $memberDetail = $page.find(".member-detail");
    var $memberScoreExchange = $page.find(".member-score-exchange"); //积分兑换容器
    var $useScoreButton = $page.find("#useScoreButton");
    // var $memberSearch = $(page).find(".member-search");
    var $memberScan = $page.find(".member-scan");
    var totalObligationAmount = settleData.TotalObligationAmount;
    var onlySelectCardNum = false;
    var IsPayToOrder = data.IsPayToOrder;

    if (paymentPattern.IsAllowNegative != 0) {
        mpos.checkInputValue($paymentInput, InputType.NegativeAmount);
    } else {
        mpos.checkInputValue($paymentInput, InputType.Amount);
    }

    var searchMemberCarTimeout = 0;

    this.onBackKeyDown = function () {
        if (searchMemberCarTimeout)
            clearTimeout(searchMemberCarTimeout);
        mpos.dialog.close(false);
    };

    mpos.startSearchMagCard();

    /**
     获取磁条卡号
     */
    function getMagCardNum() {
        searchMemberCarTimeout = setTimeout(function () {
            mpos.getMagCardNum(function (num) {
                if (num.length > 0) {
                    if (num == "0") {
                        mpos.alert("请重刷!");
                    } else {
                        //mpos.alert("卡号：" + num);
                        onlySelectCardNum = true;
                        $keyWord.val(num);
                        searchMember();
                    }
                }
                if (!mpos.isStopSearchMagCard) {
                    getMagCardNum();
                }
            });
        }, 300);
    }

    if (mpos.deviceFactory.deviceType == DeviceType.LklPayDevice) {
        getMagCardNum();
    }

    $memberDetail.hide();
    //充值
    $memberDetail.find('.recharge-button').on('click', function () {
        mpos.dialog.close({
            redirectRecharge: true,
            memberCard: currentMember
        });
    });

    $totalObligationAmount.text(mpos.formatPrice(totalObligationAmount));
    $(page).find(">div.title").text(paymentPattern.PaymentPatternName);

    if (currentMember != null && currentMember.MemberCardId > 0) {
        if (currentMember.IsStored == 1) {
            mpos.post(mpos.api.getMemberByMemberCardId, {
                MemberCardId: currentMember.MemberCardId
            }, function (memberCard) {
                currentMember = memberCard;
                var existsMemberPay = false;
                $.each(settleData.PaymentItems, function (index, item) {
                    if (item.ExistsPaid && item.PaymentPattern.PaymentPatternType == 2) {
                        existsMemberPay = true;
                        return;
                    }
                });
                // OnlyStorePayForCoupon: 1-仅会员卡支付，2-仅会员卡支付，排除票券，3-只要包含会员卡支付
                if ([1, 2, 3].indexOf(memberCard.OnlyStorePayForCoupon) != -1 && !existsMemberPay) {
                    mpos.post(mpos.api.calculateMemberSettleAmount, {
                        MemberCardId: currentMember.MemberCardId,
                        OrderId: settleData.EnterOrder.Order.OrderId,
                        IsPayToOrder: IsPayToOrder
                    }, function (data) {
                        totalObligationAmount = data.TotalObligationAmount;
                        showTotalObligationAmount();
                        $paymentInput.val(data.TotalObligationAmount);
                    });
                }
                showMemberCardDetail(currentMember);
            });
        } else { //非储值卡
            currentMember = null;
            showMemberCardDetail(currentMember);
        }
    } else {
        //显示会员
        showMemberCardDetail(currentMember);
    }

    //扫码事件
    $memberScan.on("click", function () {
        mpos.scanQR(function (result) {
            result = typeof jsonModelScanResult == "object" ?
                jsonModelScanResult : result;
            if (result.cancelled == true) {
                return;
            }
            var txt = result.text;
            $keyWord.val(txt);
            searchMember();
        }, function (err) {
            mpos.alert("扫码错误!");
        });

    });

    //默认隐藏会员详情
    $memberList.hide();
    //显示待金额
    showTotalObligationAmount();
    $paymentInput.val(totalObligationAmount);

    $keyWord.on("focus", function () {
        if ($memberList.find("li").length > 1) {
            $memberList.show();
        } else {
            $memberList.hide();
        }
    });

    //加载金额选择项
    mpos.loadPaymentAmountSelect(page, function (amount) {
        var oldAmount = $.trim($paymentInput.val());
        if (oldAmount == "") {
            oldAmount = 0;
        } else {
            oldAmount = Number(oldAmount);
        }
        $paymentInput.val(mpos.priceFixed(oldAmount + amount));
    });

    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            if (searchMemberCarTimeout)
                clearTimeout(searchMemberCarTimeout);
            mpos.dialog.close(false);
        } else {
            beginPay(true);
        }
    });

    function beginPay(needPassword) {
        if (currentMember == null) {
            mpos.alert("请选择付款会员");
            return;
        }
        var amount = $.trim($paymentInput.val());
        if (amount == "") {
            mpos.alert("请输入金额");
            return;
        }
        amount = parseFloat(amount);

        if (amount <= 0) {
            mpos.alert("付款金额不能小于等于0");
            return;
        }
        if (amount > totalObligationAmount) {
            mpos.alert("付款金额不能大于待收金额");
            return;
        }

        // 消费时需要短信验证 0-不启用，1-启用
        if (currentMember.ConsumeSmsValid == 1) {
            // 要求短信验证会员卡
            mpos.showDialog(mpos.dialogPage.memberSmsVerify, {
                ConsumptionId: settleData.Consumption.ConsumptionId,
                Amount: amount,
                MemberCard: currentMember
            }, function (status) {
                // 执行支付操作
                if (!status) {
                    return;
                }
                mpos.settlePayment({
                    // 付款方式ID
                    PaymentPatternId: paymentPattern.PaymentPatternId,
                    // 订单ID
                    OrderId: settleData.EnterOrder.Order.OrderId,
                    // 付款金额
                    Amount: amount,
                    // 会员ID或挂账客户ID
                    MemberId: currentMember.MemberId,
                    // 会员卡ID
                    MemberCardId: currentMember.MemberCardId,
                    IsPayToOrder: IsPayToOrder
                }, function (data) {
                    if (searchMemberCarTimeout)
                        clearTimeout(searchMemberCarTimeout);
                    mpos.dialog.close(data);
                });

            });

        } else if (needPassword && currentMember.CardPassword.length > 0) { //要求输入密码
            mpos.showDialog(mpos.dialogPage.inputCardPassword, {
                "MemberCardId": currentMember.MemberCardId,
            }, function (status) {
                if (!status) {
                    return;
                }
                mpos.settlePayment({
                    // 付款方式ID
                    PaymentPatternId: paymentPattern.PaymentPatternId,
                    // 订单ID
                    OrderId: settleData.EnterOrder.Order.OrderId,
                    // 付款金额
                    Amount: amount,
                    // 会员ID或挂账客户ID
                    MemberId: currentMember.MemberId,
                    // 会员卡ID
                    MemberCardId: currentMember.MemberCardId,
                    IsPayToOrder: IsPayToOrder
                }, function (data) {
                    if (searchMemberCarTimeout)
                        clearTimeout(searchMemberCarTimeout);
                    mpos.dialog.close(data);
                });
            });
        } else {
            mpos.settlePayment({
                // 付款方式ID
                PaymentPatternId: paymentPattern.PaymentPatternId,
                // 订单ID
                OrderId: settleData.EnterOrder.Order.OrderId,
                // 付款金额
                Amount: amount,
                // 会员ID或挂账客户ID
                MemberId: currentMember.MemberId,
                // 会员卡ID
                MemberCardId: currentMember.MemberCardId,
                IsPayToOrder: IsPayToOrder
            }, function (data) {
                mpos.dialog.close(data);
            });
        }
    }

    //查询事件
    // $memberSearch;
    $page.find(".dialog-search-form").on("submit", function () {
        onlySelectCardNum = false;
        searchMember();
        return false;
    });

    //获取焦点时
    $exchageScore.on("focus", function (ev) {
        $useScoreButton.addClass("disabled");
    });

    //离开焦点时
    $exchageScore.on("blur", function (ev) {
        getExchangeAmount(currentMember);
    });

    //兑换并付款
    $useScoreButton.on("click", function () {
        if ($useScoreButton.hasClass("disabled")) {
            return;
        }
        var score = Number($.trim($exchageScore.val()));
        var amount = $.trim($exchangeAmount.text());
        if (amount == "") {
            return;
        }
        amount = parseFloat(amount);

        if (amount <= 0) {
            return;
        }
        if (amount > totalObligationAmount) {
            mpos.alert("兑换付款金额不能大于待收金额");
            return;
        }

        mpos.post(mpos.api.scoreFillMoney, {
            CardId: currentMember.MemberCardId,
            Score: score,
            Amount: amount
        }, function (data) {
            $paymentInput.val(amount);
            beginPay(false);
        });
    });

    /*查找会员*/
    function searchMember() {
        var keyword = $.trim($keyWord.val());
        if (keyword == "") {
            mpos.alert("请输入查询条件");
            return;
        }
        $memberList.empty().hide();
        mpos.post(mpos.api.searchMembers, {
            Keyword: keyword
        }, function (data) {
            queryCards = data;
            if (data != null) {
                if (data.length == 0) {
                    mpos.alert("未找到对应卡信息");
                    return;
                }
                if (onlySelectCardNum && data.length) {
                    data = data.filter(function (item) {
                        return item.CardNumber == keyword;
                    });
                }
                if (data.length == 1) { //当找到一个时，直接显示
                    loadPayAmountAndMemberInfo(data[0]);
                } else { //多个时，显示列表
                    //循环显示会员卡
                    var fm = $(document.createDocumentFragment());
                    $.each(data, function (idx, item) {
                        var cardItem = $cardItem.clone();
                        cardItem.find("input").val(item.MemberCardId);
                        cardItem.find(".member-card").text(item.CardNumber);
                        cardItem.find(".member-cardNO").text(item.MemberCardNo);
                        cardItem.find(".member-name").text(item.MemberName);
                        fm.append(cardItem);
                    });
                    //监听选中事件
                    $(fm).find("input[name='cardSelect']").on("click", function (e) {
                        var value = e.currentTarget.value;
                        var card = null;
                        for (var i = 0; i < queryCards.length; i++) {
                            if (queryCards[i].MemberCardId == value) {
                                card = queryCards[i];
                                break;
                            }
                        }
                        if (card != null) {
                            if (card.IsStored != 1) {
                                mpos.alert("此卡为非储值卡，不能支付！");
                                return;
                            }
                            loadPayAmountAndMemberInfo(card);
                            $memberList.hide();
                        }
                    });

                    $memberList.append(fm).show();
                }
            } else {
                mpos.alert("未找到对应卡信息");
                // return;
            }
        });
    }

    /**
     加载待收金额
     */
    function loadPayAmountAndMemberInfo(memberCard) {
        currentMember = memberCard;
        if (settleData.MemberCard == null) { //如果会员卡为空时，待收金额要重新计算
            mpos.post(mpos.api.calculateMemberSettleAmount, {
                MemberCardId: currentMember.MemberCardId,
                OrderId: settleData.EnterOrder.Order.OrderId,
                IsPayToOrder: IsPayToOrder
            }, function (data) {
                totalObligationAmount = data.TotalObligationAmount;
                showTotalObligationAmount();
                $paymentInput.val(data.TotalObligationAmount);
            });
        } else {
            showTotalObligationAmount();
        }
        showMemberCardDetail(memberCard);
    }

    /**
     显示待收金额
     */
    function showTotalObligationAmount() {
        if (totalObligationAmount < 0) {
            totalObligationAmount = 0;
        }
        $totalObligationAmount.text(mpos.formatPrice(totalObligationAmount));
    }

    /**
     显示会员明细
     */
    function showMemberCardDetail(card) {
        if (card) {
            $memberDetail.find(".member-name").text(card.MemberName);
            $memberDetail.find(".member-mobile").text(card.Mobile);
            $memberDetail.find(".member-actualMoney").text(mpos.formatPrice(card.ActualMoney));
            $memberDetail.find(".member-score").text(card.Score);
            $memberDetail.find(".member-levelName").text(card.LevelName);
            $memberDetail.find(".member-couponName").text(card.CouponName);
            $memberDetail.find(".member-cardNO").text(card.MemberCardNo);

            $memberDetail.show();
            if (card.AllowScore && card.AllowConversion) {
                $memberScoreExchange.removeClass("nd");
                $exchageScore.val(card.Score);
                if (card.Score <= 0) { //如果是零，则不能使用
                    $exchageScore.prop("disabled", true);
                    $useScoreButton.addClass("disabled");
                } else {
                    $exchageScore.prop("disabled", false);
                    getExchangeAmount(card);
                }
            }
        } else {
            $memberDetail.hide();
            if (!$memberScoreExchange.hasClass("nd")) {
                $memberScoreExchange.addClass("nd");
            }
        }
    }

    /*
    获取可兑换的金额
    */
    function getExchangeAmount(card) {
        var score = Number($.trim($exchageScore.val()));
        if (score <= 0) {
            $exchangeAmount.text(0);
        } else {
            if (score > card.Score) {
                $exchangeAmount.text(0);
                mpos.alert("输入积分不能大于" + card.Score);
                return;
            }
            mpos.post(mpos.api.getScoreConvertionMoney, {
                CardId: card.MemberCardId,
                Score: score
            }, function (data) {
                if (data.Amout == -1) {
                    $exchangeAmount.text(0);
                    mpos.alert(data.Message);
                    return;
                }
                $exchangeAmount.text(Number(data.Amount));
                $useScoreButton.removeClass("disabled");
            });
        }
    }
});

/**
 输入会员卡密码
 */
mpos.dialogController(mpos.dialogPage.inputCardPassword, function (page, data) {
    var memberCard = data.MemberCardId;
    var $pwd = $(page).find("input[name='cardPassword']");
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var pwd = $pwd.val();
            if (pwd == "") {
                mpos.alert("请输入密码");
                return;
            }
            mpos.post(mpos.api.verifyMemberCardPassword, {
                MemberCardId: memberCard,
                Password: pwd
            }, function (r) {
                if (r != undefined && r == true) {
                    mpos.dialog.close(true);
                } else {
                    mpos.alert("密码错误");
                    // return;
                }
            });
        }
    });
});

/**
 挂账付款对话框
 */
mpos.dialogController(mpos.dialogPage.creditPay, function (page, data) {
    var settleData = data.settle;
    var currentCredit = null;
    var paymentPattern = data.paymentPattern;
    var queryCustomers = [];
    var $paymentInput = $(page).find("input[name='payAmount']"); //付款金额
    var $totalObligationAmount = $(page).find(".totalObligationAmount"); //待收
    var $keyWord = $(page).find("input[name='keyWord']");
    var $creditList = $(page).find(".credit-list");
    var $creditItem = $creditList.find("li").remove();
    // var $creditSearch = $(page).find(".credit-search");
    var $totalCreditMoney = $(page).find("#totalCreditMoney");
    var $dayCreditMoney = $(page).find("#dayCreditMoney");
    var $dayHasCreditMoney = $(page).find("#dayHasCreditMoney");
    var $selectCreditCustomerUser = $(page).find("select[name='selectCreditCustomerUser']");
    var onlySelectCardNum = false;
    var IsPayToOrder = data.IsPayToOrder;
    $totalObligationAmount.text(mpos.formatPrice(settleData.TotalObligationAmount));
    $(page).find(">div.title").text(paymentPattern.PaymentPatternName);
    $paymentInput.val(settleData.TotalObligationAmount);
    if (paymentPattern.IsAllowNegative != 0) {
        mpos.checkInputValue($paymentInput, InputType.NegativeAmount);
    } else {
        mpos.checkInputValue($paymentInput, InputType.Amount);
    }
    //处理模拟select的赋值
    $selectCreditCustomerUser.on("change", function () {
        var t = $(this);
        t.parent().find("span").text(t.text());
    });

    var searchMemberCarTimeout = 0;

    this.onBackKeyDown = function () {
        if (searchMemberCarTimeout)
            clearTimeout(searchMemberCarTimeout);
        mpos.dialog.close(false);
    };

    mpos.startSearchMagCard();

    /**
     获取磁条卡号
     */
    function getMagCardNum() {
        searchMemberCarTimeout = setTimeout(function () {
            mpos.getMagCardNum(function (num) {
                if (num.length > 0) {
                    if (num == "0") {
                        mpos.alert("请重刷!");
                    } else {
                        //mpos.alert("卡号：" + num);
                        $keyWord.val(num);
                        $(page).find(".dialog-search-form").trigger("submit");
                    }
                }
                if (!mpos.isStopSearchMagCard) {
                    getMagCardNum();
                }
            });
        }, 300);
    }

    if (mpos.deviceFactory.deviceType == DeviceType.LklPayDevice) {
        getMagCardNum();
    }

    $keyWord.on("focus", function () {
        if ($creditList.find("li").length > 1) {
            $creditList.show();
        } else {
            $creditList.hide();
        }
    });

    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            if (searchMemberCarTimeout)
                clearTimeout(searchMemberCarTimeout);
            mpos.dialog.close(false);
        } else {
            var amount = $.trim($paymentInput.val());
            if (amount == "") {
                mpos.alert("请输入金额");
                return;
            }
            amount = parseFloat(amount);

            if (amount <= 0) {
                mpos.alert("付款金额不能小于等于0");
                return;
            }
            if (amount > settleData.TotalObligationAmount) {
                mpos.alert("付款金额不能大于待收金额");
                return;
            }

            if (currentCredit == null) {
                mpos.alert("请选择挂账客户");
                return;
            }

            var customerUserId = $selectCreditCustomerUser.val();
            if (customerUserId == undefined) {
                mpos.alert("请选择挂账人");
                return;
            }
            var remark = $(page).find("input[name='payRemark']").val();
            mpos.settlePayment({
                // 付款方式ID
                PaymentPatternId: paymentPattern.PaymentPatternId,
                // 订单ID
                OrderId: settleData.EnterOrder.Order.OrderId,
                // 付款金额
                Amount: amount,
                // 会员ID或挂账客户ID
                MemberId: currentCredit.Id,
                // 备注
                Remark: remark,
                // 挂账人ID
                CreditUserId: customerUserId,
                // 是否会员挂账
                IsMemberCredit: currentCredit.IsMember == 1,
                IsPayToOrder: IsPayToOrder
            }, function (data) {
                if (searchMemberCarTimeout)
                    clearTimeout(searchMemberCarTimeout);
                mpos.dialog.close(data);
            });
        }
    });

    //查询事件
    // $creditSearch;
    $(page).find(".dialog-search-form").on("submit", function () {
        var keyword = $.trim($keyWord.val());
        if (keyword == "") {
            mpos.alert("请输入查询条件");
            return false;
        }
        currentCredit = null;
        $creditList.empty().hide();
        mpos.post(mpos.api.queryCreditCustomers, {
            Keyword: keyword
        }, function (data) {
            queryCustomers = data;
            if (data != null) {
                if (data.length == 0) {
                    currentCredit = null;
                    loadCreditCustomerInfo(currentCredit);
                    mpos.alert("未找到任何挂账客户信息");
                    return;
                }

                if (data.length == 1) { //当找到一个时，直接显示
                    currentCredit = data[0];
                    loadCreditCustomerInfo(data[0]);
                } else { //多个时，显示列表
                    //循环显示挂账客户
                    var fm = $(document.createDocumentFragment());
                    $.each(data, function (idx, item) {
                        var creditItem = $creditItem.clone();
                        creditItem.find("input").data("id", item.Id).data("is_member", item.IsMember);
                        creditItem.find(".credit-serial").text(item.Serial);
                        creditItem.find(".credit-name").text(item.Name);
                        creditItem.find(".credit-level").text(item.Level);
                        fm.append(creditItem);
                    });
                    //监听选中事件
                    fm.find("input[name='creditSelect']").on("click", function (e) {
                        var $target = $(e.currentTarget);
                        var cid = $target.data("id");
                        var isMember = $target.data("is_member");
                        var customer = findCustomer(cid, isMember);
                        currentCredit = customer;
                        if (customer != null) {
                            loadCreditCustomerInfo(customer);
                            $creditList.hide();
                        }
                    });

                    $creditList.append(fm).show();
                }
            } else {
                mpos.alert("未找到任何挂账客户信息");
                // return;
            }
        });
        return false;
    });

    /**
     加载客户信息
     */
    function loadCreditCustomerInfo(customer) {
        $selectCreditCustomerUser.empty();
        if (customer == null) {
            $totalCreditMoney.text("");
            $dayCreditMoney.text("");
            $keyWord.val("");
            $dayHasCreditMoney.text("");
            return;
        }
        if (customer.TotalQuota < 0) {
            $totalCreditMoney.text("无限制");
        } else {
            $totalCreditMoney.text(mpos.formatPrice(customer.TotalQuota));
        }
        if (customer.DayQuota < 0) {
            $dayCreditMoney.text("无限制");
        } else {
            $dayCreditMoney.text(mpos.formatPrice(customer.DayQuota));
        }

        $keyWord.val(customer.Name);


        $dayHasCreditMoney.text(mpos.formatPrice(customer.UsedDayQuota));
        //加载挂账人
        mpos.post(mpos.api.queryCreditCustomerUsers, {
            CustomerId: customer.Id, //挂账客户ID
            IsMember: customer.IsMember, //是否为会员 1 or 0
        }, function (data) {
            var selectedId = 0;
            var fm = $(document.createDocumentFragment());
            $.each(data, function (index, item) {
                var option = $('<option/>').attr("value", item.MemberCreditorID).text(item.CreditorName);
                if (selectedId == 0) { //选中第一个
                    option.attr("selected", true);
                    selectedId = item.MemberCreditorID;
                }
                fm.append(option);
            });
            fm.appendTo($selectCreditCustomerUser);
            $selectCreditCustomerUser.parent().find("span").text($selectCreditCustomerUser.text());
        });
    }

    /**
     查找挂账客户
     */
    function findCustomer(id, isMember) {
        for (var i = 0; i < queryCustomers.length; i++) {
            if (queryCustomers[i].Id == id && queryCustomers[i].IsMember == isMember) {
                return queryCustomers[i];
            }
        }

        return null;
    }
});

/**
 微信或支付宝结账对话框
 */
mpos.dialogController(mpos.dialogPage.wxOrAliPay, function (page, data) {
    var settleData = data.settle;
    var paymentPattern = data.paymentPattern;
    var thirdPaymentType = data.thirdPaymentType;
    var isAlipay = thirdPaymentType == ThirdPaymentType.ZFBBarcodePay;
    var $paymentInput = $(page).find("input[name='payAmount']");
    var $totalObligationAmount = $(page).find(".totalObligationAmount"); //待收
    var $payScan = $(page).find(".pay-scan");
    var $payResultMsg = $(page).find(".pay-result-msg");
    var $alinfcPay = $(page).find(".alinfcpay");
    if (mpos.deviceConfig.deviceType != DeviceType.AlipayNfcPos || !isAlipay) {
        $alinfcPay.hide();
    }
    var currentOnlinePayId = 0;
    var setTimeoutVar = 0;
    var isPaying = false;
    var hasPay = false;
    var leftCloseSecond = 2;
    var setTimeoutCloseVar = null;
    var IsPayToOrder = data.IsPayToOrder;
    $payResultMsg.hide();
    $totalObligationAmount.text(mpos.formatPrice(settleData.TotalObligationAmount));
    $paymentInput.val(settleData.TotalObligationAmount);
    $(page).find(">div.title").text(paymentPattern.PaymentPatternName);
    if (paymentPattern.IsAllowNegative != 0) {
        mpos.checkInputValue($paymentInput, InputType.NegativeAmount);
    } else {
        mpos.checkInputValue($paymentInput, InputType.Amount);
    }
    //加载金额选择项
    mpos.loadPaymentAmountSelect(page, function (amount) {
        var oldAmount = $.trim($paymentInput.val());
        if (oldAmount == "") {
            oldAmount = 0;
        } else {
            oldAmount = Number(oldAmount);
        }
        $paymentInput.val(mpos.priceFixed(oldAmount + amount));
    });

    //检测之前是否有支付记录
    checkHasOnlinePay();

    /**
     * NFC支付 
     */
    $alinfcPay.on("click", function () {
        var amount = $.trim($paymentInput.val());
        if (amount == "") {
            mpos.alert("请输入金额");
            return;
        }
        amount = parseFloat(amount);
        if (amount == 0) {
            mpos.alert("金额不能为零");
            return;
        }

        if (amount <= 0) {
            mpos.alert("付款金额不能小于等于0");
            return;
        }
        if (amount > settleData.TotalObligationAmount) {
            mpos.alert("付款金额不能大于待收金额");
            return;
        }
        mpos.aliNfcPay({ "amount": amount, "tradeNo": "", "bussinessType": "1" }, function (msg) {
            var jsonData = JSON.parse(msg);
            var barCode = jsonData.barCode;
            if (!barCode || barCode.length < 15) {
                return;
            }
            $payResultMsg.show();
            $payResultMsg.text("正在支付......");
            mpos.post(mpos.api.beginOnlinePay, {
                OrderId: settleData.EnterOrder.Order.OrderId,
                ThirdPaymentType: thirdPaymentType,
                PaymentPatternId: paymentPattern.PaymentPatternId,
                Amount: amount,
                BarCode: barCode,
                IsPayToOrder: IsPayToOrder
            }, function (data) {
                if (data.OnlinePayId > 0) {
                    currentOnlinePayId = data.OnlinePayId;
                    beginPay();
                }
            });
        }, function (err) {
            formatAlipayErr(err);
            return;
        });
    });

    /**
     扫描
     */
    $payScan.on("click", function (e) {
        var amount = $.trim($paymentInput.val());
        if (amount == "") {
            mpos.alert("请输入金额");
            return;
        }
        amount = parseFloat(amount);
        if (amount == 0) {
            mpos.alert("金额不能为零");
            return;
        }

        if (amount <= 0) {
            mpos.alert("付款金额不能小于等于0");
            return;
        }
        if (amount > settleData.TotalObligationAmount) {
            mpos.alert("付款金额不能大于待收金额");
            return;
        }
        if (mpos.deviceConfig.deviceType == DeviceType.AlipayNfcPos && isAlipay) {
            mpos.aliNfcPay({ "amount": amount, "tradeNo": "", "bussinessType": "2" }, function (msg) {
                var jsonData = JSON.parse(msg);
                var barCode = jsonData.barCode;
                if (!barCode || barCode.length < 15) {
                    return;
                }
                $payResultMsg.show();
                $payResultMsg.text("正在支付......");
                mpos.post(mpos.api.beginOnlinePay, {
                    OrderId: settleData.EnterOrder.Order.OrderId,
                    ThirdPaymentType: thirdPaymentType,
                    PaymentPatternId: paymentPattern.PaymentPatternId,
                    Amount: amount,
                    BarCode: barCode,
                    IsPayToOrder: IsPayToOrder
                }, function (data) {
                    if (data.OnlinePayId > 0) {
                        currentOnlinePayId = data.OnlinePayId;
                        beginPay();
                    }
                });
            }, function (err) {
                formatAlipayErr(err);
            });
            return;
        }

        if (mpos.deviceConfig.deviceType == DeviceType.AlipayNfcPos && !isAlipay) {
            mpos.alipayscanbarcode(function (msg) {
                var jsonData = JSON.parse(msg);
                var barCode = jsonData.qrCode;
                if (!barCode || barCode.length < 15) {
                    return;
                }
                mpos.post(mpos.api.beginOnlinePay, {
                    OrderId: settleData.EnterOrder.Order.OrderId,
                    ThirdPaymentType: thirdPaymentType,
                    PaymentPatternId: paymentPattern.PaymentPatternId,
                    Amount: amount,
                    BarCode: barCode,
                    IsPayToOrder: IsPayToOrder
                }, function (data) {
                    if (data.OnlinePayId > 0) {
                        currentOnlinePayId = data.OnlinePayId;
                        beginPay();
                    }
                });
            }, function (err) {
                formatAlipayErr(err);
            });
            return;
        }

        mpos.scanQR(function (result) {
            result = typeof jsonModelScanResult == "object" ?
                jsonModelScanResult : result;
            if (result.cancelled == true) {
                return;
            }
            var barCode = result.text;
            $payResultMsg.show();
            $payResultMsg.text("正在支付......");
            mpos.post(mpos.api.beginOnlinePay, {
                OrderId: settleData.EnterOrder.Order.OrderId,
                ThirdPaymentType: thirdPaymentType,
                PaymentPatternId: paymentPattern.PaymentPatternId,
                Amount: amount,
                BarCode: barCode,
                IsPayToOrder: IsPayToOrder
            }, function (data) {
                if (data.OnlinePayId > 0) {
                    currentOnlinePayId = data.OnlinePayId;
                    beginPay();
                }
            });
        }, function (err) {
            mpos.alert("扫码错误!");
        });

    });

    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        if (isPaying) {
            mpos.alert("正在付款，无法操作....");
            return;
        }
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            clearTimeout(setTimeoutVar);
            mpos.dialog.close(hasPay);
        } else if (operationType == 1) {
            clearTimeout(setTimeoutVar);
            mpos.dialog.close(hasPay);
        }
    });

    function formatAlipayErr(err) {
        if (err == "0") {
            mpos.alert("系统未初始化完成！");
        } else if (err == "1") {
            mpos.alert("支付参数错误！");
        } else {
            mpos.alert("支付异常！");
        }
    }

    /**
     检查是否有线上支付
     如果有线上支付，直接扫描获取付款结果
     */
    function checkHasOnlinePay() {
        mpos.post(mpos.api.checkHasOnlinePay, {
            OrderId: settleData.EnterOrder.Order.OrderId,
            ThirdPaymentType: thirdPaymentType
        }, function (data) {
            if (data.OnlinePayId > 0) {
                currentOnlinePayId = data.OnlinePayId;
                beginPay();
            }
        });
    }

    /**
     开始付款
     */
    function beginPay() {
        isPaying = true;
        $payResultMsg.show();
        $payResultMsg.text("正在查询支付结果......");
        mpos.showLoading();
        setTimeoutVar = setTimeout(checkPayResult, 1500);
    }

    /**
     开始检查付款检查
     */
    function checkPayResult() {
        if (currentOnlinePayId > 0) {
            mpos.post(mpos.api.checkOnlinePayResult, {
                OnlinePayId: currentOnlinePayId,
                IsPayToOrder: IsPayToOrder
            }, function (result) {
                if (result.PayStatus == OnlinePayStatus.PayStart) {
                    setTimeoutVar = setTimeout(checkPayResult, 1000);
                } else if (result.PayStatus == OnlinePayStatus.PayFail) {
                    clearTimeout(setTimeoutVar);
                    isPaying = false;
                    hasPay = true;
                    $payResultMsg.text("支付失败：" + result.Message);
                    mpos.hideLoading();
                } else if (result.PayStatus == OnlinePayStatus.PaySuccess) {
                    clearTimeout(setTimeoutVar);
                    isPaying = false;
                    $payResultMsg.text("支付成功！");
                    mpos.hideLoading();
                    if (isAlipay) {
                        mpos.alipayVoice(result.Amount);
                    }
                    hasPay = true;
                    $payScan.hide();
                    leftCloseSecond = 2;
                    setTimeoutCloseVar = setTimeout(autoClose);
                } else if (result.PayStatus == OnlinePayStatus.PayCancel || result.PayStatus == OnlinePayStatus.CancelError) {
                    clearTimeout(setTimeoutVar);
                    $payResultMsg.text("支付已取消！");
                    if (result.PayStatus == OnlinePayStatus.CancelError) {
                        $payResultMsg.text("支付已取消,但撤销失败！");
                    }
                    mpos.hideLoading();
                    isPaying = false;
                    hasPay = true;
                } else if (result.PayStatus == OnlinePayStatus.Paying) {
                    $payResultMsg.text("等待用户手机上确认");
                    setTimeoutVar = setTimeout(checkPayResult, 1000);
                }
            });
        } else {
            clearTimeout(setTimeoutVar);
            isPaying = false;
            mpos.hideLoading();
        }
    }

    /**
     自动关闭
     */
    function autoClose() {
        if (leftCloseSecond <= 0) {
            clearTimeout(setTimeoutCloseVar);
            mpos.dialog.close(hasPay);
            return;
        }
        $payResultMsg.text("支付成功！" + leftCloseSecond + "秒后自动关闭");
        leftCloseSecond -= 1;
        setTimeoutCloseVar = setTimeout(autoClose, 1000);
    }
});

/**
 会员或线上微信退款对话框
 */
mpos.dialogController(mpos.dialogPage.returnMemberPay, function (page, data) {
    var paymentId = data.paymentId;
    var hasPayAmount = data.amount;
    var payType = data.payType;
    var orderId = data.orderId;
    var paymentPattern = data.paymentPattern;
    var $paymentInput = $(page).find("input[name='payAmount']");
    var $hasPayAmount = $(page).find(".hasPayAmount");

    if (payType == 2) {
        $(page).find("div.title").text("微信退款")
    } else if (payType == 3) {
        $(page).find("div.title").text("支付宝退款")
    } else if (payType == 12) {
        $(page).find("div.title").text("云闪付退款")
    }

    $paymentInput.val(hasPayAmount);
    $hasPayAmount.text(mpos.formatPrice(hasPayAmount));
    mpos.checkInputValue($paymentInput, InputType.Amount);
    //加载金额选择项
    mpos.loadPaymentAmountSelect(page, function (amount) {
        var oldAmount = $.trim($paymentInput.val());
        if (oldAmount == "") {
            oldAmount = 0;
        } else {
            oldAmount = Number(oldAmount);
        }
        $paymentInput.val(mpos.priceFixed(oldAmount + amount));
    });
    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var amount = $.trim($paymentInput.val());
            if (amount == "") {
                mpos.alert("请输入退款金额");
                return;
            }
            amount = parseFloat(amount);
            if (amount == 0) {
                mpos.alert("退款金额不能为零");
                return;
            }

            if (amount > hasPayAmount) {
                mpos.alert("退款金额不能大于已付金额");
                return;
            }

            mpos.clearSettlePaymentItem({
                OrderId: orderId,
                PaymentId: paymentId,
                Amount: amount
            }, function (data) {
                mpos.dialog.close(data);
            })
        }
    });
});

/**
 移动银行结账对话框
 */
mpos.dialogController(mpos.dialogPage.iBoxPayPay, function (page, data) {
    var settleData = data.settle;
    var paymentPattern = data.paymentPattern;
    var $paymentInput = $(page).find("input[name='payAmount']");
    var $totalObligationAmount = $(page).find(".totalObligationAmount"); //待收
    var $selectPaymentType = $(page).find(".select-payment-type"); //拉卡拉付款选择

    $totalObligationAmount.text(mpos.formatPrice(settleData.TotalObligationAmount));
    $paymentInput.val(settleData.TotalObligationAmount);
    $(page).find(">div.title").text(paymentPattern.PaymentPatternName);
    if (paymentPattern.IsAllowNegative != 0) {
        mpos.checkInputValue($paymentInput, InputType.NegativeAmount);
    } else {
        mpos.checkInputValue($paymentInput, InputType.Amount);
    }

    //当不是拉卡拉时，不显示付款选择
    if (mpos.deviceFactory.deviceType != DeviceType.LklPayDevice) {
        $selectPaymentType.remove();
    } else {
        if (!mpos.shopConfig.EnabledLakalaScanPay) { //没有启用时也不显示
            $selectPaymentType.remove();
        }
    }

    //加载金额选择项
    mpos.loadPaymentAmountSelect(page, function (amount) {
        var oldAmount = $.trim($paymentInput.val());
        if (oldAmount == "") {
            oldAmount = 0;
        } else {
            oldAmount = Number(oldAmount);
        }
        $paymentInput.val(mpos.priceFixed(oldAmount + amount));
    });
    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var amount = $paymentInput.val();
            if (amount == "") {
                mpos.alert("请输入金额");
                return;
            }
            amount = parseFloat(amount);
            if (amount <= 0) {
                mpos.alert("付款金额不能小于等于0");
                return;
            }
            if (amount > settleData.TotalObligationAmount) {
                mpos.alert("付款金额不能大于待收金额");
                return;
            }

            //if (amount < 10 || amount > 10000) {
            //    mpos.alert("付款金额必需在10元至10000元之前");
            //    return;
            //}
            var paymentType = 1;
            if (mpos.deviceFactory.deviceType == DeviceType.LklPayDevice && mpos.shopConfig.EnabledLakalaScanPay) {
                paymentType = $(page).find("input[name='selectPaymentType']:checked").val();
            }

            mpos.post(mpos.api.createBoxPay, {
                ConsumptionId: settleData.Consumption.ConsumptionId,
                PaymentPatternId: paymentPattern.PaymentPatternId,
                PaymentType: paymentType,
                Amount: amount,
            }, function (config) {
                if (config == null || typeof config != 'object') {
                    return;
                }
                if (mpos.deviceFactory.deviceType == DeviceType.IboxPayDevice) {
                    if (config.BoxConfig == null || typeof config.BoxConfig != 'object' ||
                        typeof config.BoxConfig.ApiKey != 'string' || config.BoxConfig.ApiKey == "" ||
                        typeof config.BoxConfig.AppCode != 'string' || config.BoxConfig.AppCode == "" ||
                        typeof config.BoxConfig.Md5Salt != 'string' || config.BoxConfig.Md5Salt == "") {
                        mpos.alert("未配置付款信息");
                        return;
                    }
                }
                if (config.OrderNo != "") {
                    mpos.showLoading();
                    mpos.isPaying = true;
                    var cfg = {
                        OrderNo: config.OrderNo,
                        PayAmount: config.PayAmount,
                        BoxConfig: config.BoxConfig,
                        PaymentType: paymentType
                    };
                    var payId = config.OnlineBankPayId;
                    cfg.PayType = 1;
                    mpos.deviceFactory.payOrder(cfg, function (result) {
                        mpos.hideLoading();
                        mpos.isPaying = false;
                        $(page).find(".btn-repeal").show();
                        var cbOrderNo = result.CbOrderNo;
                        var usedPaymentType = result.PaymentType;
                        mpos.post(mpos.api.updateBoxPay, {
                            PaymentPatternId: paymentPattern.PaymentPatternId,
                            OnlineBankPayId: payId,
                            IsOk: true,
                            TradeNo: cbOrderNo,
                            ErrMessage: "",
                            UsedPaymentType: usedPaymentType
                        }, function () {
                            mpos.dialog.close(true);
                        }, {
                            timeout: Config.importantBLTimeout
                        });
                    }, function (err) {
                        mpos.hideLoading();
                        mpos.isPaying = false;
                        mpos.post(mpos.api.updateBoxPay, {
                            PaymentPatternId: paymentPattern.PaymentPatternId,
                            OnlineBankPayId: payId,
                            IsOk: false,
                            TradeNo: "",
                            ErrMessage: err,
                        }, function () {

                        }, {
                            timeout: Config.importantBLTimeout
                        });
                        mpos.alert(err);
                    })
                }
            });
        }
    });
});

/**
 团购券付款
 */
mpos.dialogController(mpos.dialogPage.grouponPay, function (page, data) {
    var $page = $(page);
    var settleData = data.settle;
    var paymentPattern = data.paymentPattern;
    var $tabAuto = $page.find(".tab_auto");
    var $tabManual = $page.find(".tab_manual");
    var $autoVerify = $page.find(".auto_verify");
    var $currentUseTicket = $page.find(".current_use_ticket");
    var paymentPatternId = paymentPattern.PaymentPatternId;
    var currentGrouponCode = "";
    var IsPayToOrder = data.IsPayToOrder;
    var needRefresh = false;
    var rms_group_id = 0;
    var verify_token = '';  // 抖音券自动验券返回参数，用券时要传入
    var encrypted_codes = [];  // 抖音券自动验券返回参数，用券时要传入
    var minConsume = 0;   // 票券最少可用数量
    var maxConsume = 0;   // 票券最多可用数量
    $page.find(">div.title").text(paymentPattern.PaymentPatternName);
    $page.find(".app-submit").on("click", function (e) {
        mpos.dialog.close(needRefresh);
    });

    $page.find("input[name='payAutoAmount']").hide();
    var groupTicketTotal = 0;  // 使用券的数量
    $page.find(".dish-operation .ticket-total").text(groupTicketTotal);

    var manualSelectedClass = 'manual-selected';
    /**
     Tab切换 到 自动
     */
    $tabAuto.on("click", function (e) {
        $(e.currentTarget).parent().removeClass(manualSelectedClass);
    });

    /**
     Tab切换 到 手动
     */
    $tabManual.on("click", function (e) {
        $(e.currentTarget).parent().addClass(manualSelectedClass);
    });

    /**
     自动验证的确定
     */
    $page.find("#btnValidate").on("click", function (e) {
        if ($("#btnValidate").hasClass("reset")) {
            resetAuto();
            return;
        }
        var code = $autoVerify.find("input[name='autoGrouponCode']").val();
        code = $.trim(code);
        if (code.length < 0) {
            mpos.alert("请输入团购券号!");
            return;
        }
        checkAutoCode(code);
    });

    var loopTimes = 0;

    /**
     * 检查自动验券
     * */
    function checkAutoCode(code) {
        loopTimes += 1;
        if (loopTimes > 2) {
            loopTimes = 0;
            return;
        }
        mpos.post(mpos.api.checkGrouponCode, {
            PaymentPatternId: paymentPatternId,
            Code: code,
            OrderId: settleData.EnterOrder.Order.OrderId
        }, function (r) {
            currentGrouponCode = code;
            var msg = r.dealTitle;
            rms_group_id = r.rms_group_id;
            verify_token = r.verify_token || '';
            encrypted_codes = r.encrypted_codes || [];
            minConsume = r.minConsume || 0;   // 票券最少可用数量
            maxConsume = r.count || 0;   // 票券最多可用数量
            setAutoVertify();

            $page.find(".grouponDetail").empty().removeClass("nd")
                .append("<div>券：" + code + "</div>")
                .append("<div>" + msg + "</div>")
                .append("<div>票券最少可用" + minConsume + "张, 最多可用" + maxConsume + "张</div>");
            $page.find("#btnAutoOk").prop("disabled", false);
        });
    }

    /**
     设置为已验证过的控件状态
     */
    function setAutoVertify() {
        $page.find("#btnAutoOk").prop("disabled", true);
        $autoVerify.find("input[name='autoGrouponCode']").prop("disabled", false);
        $page.find("#btnValidate").text("重置");
        $page.find("#btnValidate").addClass("reset");
        $page.find("#btnScanQr").prop("disabled", false);
        groupTicketTotal = minConsume;  // 使用券的数量
        $page.find(".dish-operation .ticket-total").text(groupTicketTotal);
    }

    /**
     重置自动验证
     */
    function resetAuto() {
        $page.find("#btnAutoOk").prop("disabled", true);
        $autoVerify.find("input[name='autoGrouponCode']").prop("disabled", false);
        $page.find("#btnValidate").text("验证");
        $page.find("#btnValidate").removeClass("reset");
        $page.find(".grouponDetail").empty().addClass("nd");
        $page.find("#btnScanQr").prop("disabled", false);
        currentGrouponCode = "";
        groupTicketTotal = 0;  // 使用券的数量
        minConsume = 0;
        maxConsume = 0;
        $page.find(".dish-operation .ticket-total").text(groupTicketTotal);
    }

    /**
     手动验证的确定
     */
    $page.find("#btnManualOk").on("click", function (e) {
        var amount = getPayAmount();
        if (amount == 0) {
            return;
        }
        var code = $.trim($page.find("input[name='manualGrouponCode']").val());
        if (code == "") {
            mpos.alert("请输入团购券号");
            return;
        }
        mpos.settlePayment({
            // 付款方式ID
            PaymentPatternId: paymentPattern.PaymentPatternId,
            // 订单ID
            OrderId: settleData.EnterOrder.Order.OrderId,
            // 付款金额
            Amount: amount,
            // 备注
            Remark: code,
            IsPayToOrder: IsPayToOrder
        }, function (settle) {
            needRefresh = true;
            $currentUseTicket.append("<li><span>券：" + code + "</span><span>" + mpos.formatPrice(amount) + "</span></li>");
            settleData = mpos.fixSettleInfo(settle);
            initPayAmount();
            $page.find("input[name='manualGrouponCode']").val("");
        });
    });

    /**
     * 修改票券数量
     * */
    $page.find(".dish-operation").on("click", function (e) {
        e.stopPropagation();
        if (e.target.tagName != "BUTTON" || groupTicketTotal == 0) {
            return;
        }
        var target = $(e.target);
        var $parent = target.parents(".dish-operation");
        var $dishNum = $parent.find('.num');
        var isIncrease = target.hasClass("increase"); //标识点+号还是-号

        if (isIncrease) {
            if (groupTicketTotal + 1 <= maxConsume) {
                groupTicketTotal += 1;  // 使用券的数量
                $dishNum.text(groupTicketTotal);
            }
        } else {
            if (groupTicketTotal - 1 >= minConsume) {
                groupTicketTotal -= 1;  // 使用券的数量
                $dishNum.text(groupTicketTotal);
            }
        }
    });

    /**
     * 使用券
     */
    $page.find("#btnAutoOk").on("click", function (e) {
        if (currentGrouponCode == "" || groupTicketTotal == 0) {
            return;
        }
        //var amount = getPayAmount();
        //if (amount == 0) {
        //    return;
        //}
        mpos.showLoading();
        mpos.post(mpos.api.useGrouponCode, {
            // 付款方式ID
            PaymentPatternId: paymentPattern.PaymentPatternId,
            // 订单ID
            OrderId: settleData.EnterOrder.Order.OrderId,
            //券号
            Code: currentGrouponCode,
            rms_group_id: rms_group_id,
            verify_token: verify_token,
            encrypted_codes: encrypted_codes,
            ticket_num: groupTicketTotal
            //// 付款金额
            //Amount: amount,
        }, function (re) {
            mpos.hideLoading();
            needRefresh = true;
            $currentUseTicket.append("<li><span>券：" + currentGrouponCode + "</span><span class='amount textEllipsis'>" + mpos.formatPrice(re.Amount) + "</span></li>");
            resetAuto();
            settleData = mpos.fixSettleInfo(re.Settle);
            initPayAmount();
            if (re.AutoAddDishErrMsg) {
              mpos.alert(re.AutoAddDishErrMsg);
            }
        },
            {
                blFailed: function () {
                    mpos.hideLoading();
                }
            });
    });


    //扫码事件
    $page.find("#btnScanQr").on("click", function () {
        mpos.scanQR(function (result) {
          result = typeof jsonModelScanResult == "object" ? jsonModelScanResult : result;
          if (result.cancelled == true) {
            return;
          }
          var barCode = result.text;
          $autoVerify.find("input[name='autoGrouponCode']").val(barCode);
          checkAutoCode(barCode);
        }, function (err) {
            mpos.alert("扫码错误!");
        });

    });


    /**
     获取付款金额
     */
    function getPayAmount() {
        var amount = parseFloat($page.find("input[name='" + ($tabAuto.parent().hasClass(manualSelectedClass) ? 'payManualAmount' : 'payAutoAmount') + "']").val()) || 0;

        if (amount == 0) {
            mpos.alert("请输入金额");
        } else if (amount < 0) {
            amount = 0;
            mpos.alert("付款金额不能小于0");
        }
        if (amount > settleData.TotalObligationAmount) {
            amount = 0;
            mpos.alert("付款金额不能大于待收金额");
        }

        return amount;
    }

    /**
     初始化付款金额
     */
    function initPayAmount() {
        //$page.find("input[name='payAutoAmount']").val(settleData.TotalObligationAmount);
        $page.find("input[name='payManualAmount']").val(settleData.TotalObligationAmount);
    }

    /**
     默认禁用
     */
    $page.find("#btnAutoOk").prop("disabled", true);
    initPayAmount();
});

/**
 输入团购验证码
 */
mpos.dialogController(mpos.dialogPage.inputGrouponCode, function (page, data) {
    var $page = $(page);
    var imageUrl = data.ImageUrl;
    var paymentPatternId = data.PaymentPatternId;
    var $img = $page.find("#imgCode");
    var $inputCode = $page.find("input[name='txtCode']");
    $img.on("error", function () {
        mpos.alert("加载验证码失败，请检查网络是否正常！");
    });

    $img.attr("src", decodeURIComponent(imageUrl + "?t=" + new Date().getTime()));

    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var code = $.trim($inputCode.val());
            if (code == "") {
                mpos.alert("请输入验证码");
                return;
            }
            mpos.post(mpos.api.loginGroupon, {
                PaymentPatternId: paymentPatternId,
                Code: code
            }, function (r) {
                if (r.IsLogin) {
                    mpos.dialog.close(true);
                } else {
                    mpos.alert(r.Message);
                }
            });
        }
    });

    /**
     点击图片
     */
    $img.parent().on("click", function (e) {
        mpos.post(mpos.api.checkGrouponIsLogin, {
            PaymentPatternId: paymentPatternId
        }, function (r) {
            if (r.IsLogin) {
                mpos.dialog.close(true);
            } else {
                $img.attr("src", decodeURIComponent(r.CaptchaPath + "?t=" + new Date().getTime()));
            }
        });
    });

});

/**
 * 固定面额抵扣票券结账对话框
 */
mpos.dialogController(mpos.dialogPage.fixedTicketPay, function (page, data) {
    var settleData = data.settle;
    var paymentPattern = data.paymentPattern;
    var usedTicketCount = getUsedFixedTicketCount(data.usedFixedTickets);  // 获取已使用票券数量数组
    var maxTicketCount = (paymentPattern.FixedTicketNumber || 1) - usedTicketCount; // 票券最多使用数量
    var IsPayToOrder = data.IsPayToOrder;
    var $totalObligationAmount = $(page).find(".totalObligationAmount"); //待收
    var $receivableAmount = $(page).find(".receivableAmount"); // 收款金额
    var $ticketCount = $(page).find("input[name='ticketCount']");  // 使用票券数量
    var $realAmount = $(page).find(".real-amount"); // 营收金额
    var $noRealAmount = $(page).find(".no-real-amount"); // 非营收金额
    $totalObligationAmount.text(mpos.formatPrice(settleData.TotalObligationAmount));
    $(page).find(">div.title").text(paymentPattern.PaymentPatternName);  // 弹窗title

    if (maxTicketCount < 0) {
        maxTicketCount = 0;
        $ticketCount.val(0);
    }

    /**
     * 获取固定面额票券已使用的票券信息
     * @param {Object} pid PaymentPatternId
     */
    function getUsedFixedTicketCount(useTickets) {
        var usedCount = 0;
        if (useTickets && useTickets.length > 0) {
            for (var i = 0; i < useTickets.length; i++) {
                usedCount += useTickets[i].FixedTicketNumber;
            }
        }
        return usedCount;
    }

    // 渲染金额显示
    function onInputAmountChange() {
        var ticketCount = $ticketCount.val().trim();
        if (ticketCount == "") {
            return;
        }

        ticketCount = parseInt(ticketCount);
        var denominationAmount = paymentPattern.DenominationAmount;
        var realAmount = paymentPattern.RealAmount;
        var amount = denominationAmount * ticketCount;
        if (denominationAmount == 0) {
            $realAmount.text('0');
            $noRealAmount.text('0');
            $receivableAmount.val(amount.toFixed(2));
        } else {
            // 抵扣总金额大于待收金额，就以待收金额为准
            if (amount > settleData.TotalObligationAmount) {
                amount = settleData.TotalObligationAmount
            }
            var realAmountValue = (
                (parseInt(amount / denominationAmount) * realAmount)
                + ((ticketCount * denominationAmount) > amount ? ((amount - parseInt(amount / denominationAmount) * denominationAmount) * (realAmount / denominationAmount)) : 0)
            )
            var noRealAmountValue = (amount - realAmountValue).toFixed(2);
            $realAmount.text(realAmountValue.toFixed(2));
            $noRealAmount.text(noRealAmountValue);
            $receivableAmount.val(amount.toFixed(2));
        }
    }

    // 初始化金额显示
    onInputAmountChange();

    // 减少票券数量
    $(page).find('.reduce-btn').on('click', function (e) {
        e.stopPropagation();
        if (maxTicketCount == 0) {
            mpos.alert('票券可用数量已用完')
            return;
        }
        var count = parseInt($ticketCount.val());
        if (count > 1) {
            count -= 1;
            $ticketCount.val(count);
            onInputAmountChange();
        } else {
            mpos.alert('最少使用一张')
        }
    });

    // 增加票券数量
    $(page).find('.add-btn').on('click', function (e) {
        e.stopPropagation();
        if (maxTicketCount == 0) {
            mpos.alert('票券可用数量已用完')
            return;
        }
        var count = parseInt($ticketCount.val());
        if (count < maxTicketCount) {
            if (count * paymentPattern.DenominationAmount < settleData.TotalObligationAmount) {
                count += 1;
                $ticketCount.val(count);
                onInputAmountChange();
            } else {
                mpos.alert(count + '张票券足够抵扣待收金额');
            }
        } else {
            mpos.alert('最多使用' + maxTicketCount + '张');
        }
    });

    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            if (maxTicketCount == 0) {
                mpos.alert('票券可用数量已用完')
                return;
            }
            var ticketCount = $ticketCount.val();
            var amount = $receivableAmount.val().trim();
            if (ticketCount == "" || parseInt(ticketCount) == 0) {
                mpos.alert("请输入抵扣票券数量");
                return;
            }
            amount = parseFloat(amount);
            ticketCount = parseInt(ticketCount);
            var realAmount = parseFloat($realAmount.text());
            if (amount == 0) {
                mpos.alert("收款金额不能为零");
                return;
            }

            mpos.settlePayment({
                // 付款方式ID
                PaymentPatternId: paymentPattern.PaymentPatternId,
                // 订单ID
                OrderId: settleData.EnterOrder.Order.OrderId,
                // 付款金额
                Amount: amount,
                // 实收金额
                SaleIncomeAmount: realAmount,
                // 使用票券数量
                FixedTicketCount: ticketCount,
                // 备注
                Remark: '',
                IsPayToOrder: IsPayToOrder
            }, function (data) {
                mpos.dialog.close(true);
            });
        }
    });

});

/*
 茶芥选择
 */
mpos.dialogController(mpos.dialogPage.teaSelect, function (page, data) {
    var SELECTED_CLASS = "selected";

    var teas = data.Teas;
    var snacks = data.Snacks;

    var selectedTeas = [];//选中的茶
    var selectedSnacks = [];//选中的芥

    var teaList = $(page).find(".tea-list");
    var teaTitle = teaList.find(".teafee-title").remove();
    var snackList = $(page).find(".snack-list");
    var snackTitle = snackList.find(".teafee-title").remove();
    var $snackItem = snackList.find(".snack-item").remove();

    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close({
                status: false
            });
        } else {
            mpos.dialog.close({
                status: true,
                selectedTeas: selectedTeas,
                selectedSnacks: selectedSnacks
            });
        }
    });

    LoadTeaAndSnack();

    /*
     加载茶和芥
     */
    function LoadTeaAndSnack() {
        teaList.empty().append(teaTitle);
        snackList.empty().append(snackTitle);
        if (teas.length == 0) {
            teaList.remove();
        }
        if (snacks.length == 0) {
            snackList.remove();
        }

        //加载茶
        var fragment = $(document.createDocumentFragment());
        teas.forEach(function (tea) {
            var dish = mpos.GetBaseDishInfo(tea.DishId);
            var span = $("<span class='textEllipsis'/>")
                .text(dish.Dish.DishName)
                .data("dish_id", tea.DishId)
                .data("unit_id", tea.UnitId);

            if (tea.IsDefault) {
                span.addClass(SELECTED_CLASS);
                selectedTeas.push({
                    DishId: tea.DishId,
                    UnitId: tea.UnitId,
                });
            }
            fragment.append(span);
        });
        teaList.append(fragment);
        fragment = null;

        //加载芥
        fragment = $(document.createDocumentFragment());
        snacks.forEach(function (snack) {
            var dish = mpos.GetBaseDishInfo(snack.DishId);
            var $snackCopy = $snackItem.clone();
            $snackCopy.data("dish_id", snack.DishId).data("unit_id", snack.UnitId);
            $snackCopy.find('.snack-name').text(dish.Dish.DishName);
            if (snack.IsDefault) {
                var dishNum = snack.StartOrderNum || 1;
                $snackCopy.find('.num').text(dishNum);
                $snackCopy.find('.num').addClass("more");
                $snackCopy.addClass(SELECTED_CLASS);
                selectedSnacks.push({
                    DishId: snack.DishId,
                    UnitId: snack.UnitId,
                    DishNum: dishNum
                });
            }
            fragment.append($snackCopy);
        });
        snackList.append(fragment);
        fragment = null;

        //茶事件
        teaList.find("span[data-dish_id]").on("click", function (e) {
            var $target = $(e.currentTarget);
            var dishId = $target.data("dish_id");
            var unitId = $target.data("unit_id");
            if ($target.hasClass(SELECTED_CLASS)) {
                for (var i = 0; i < selectedTeas.length; i++) {
                    if (selectedTeas[i].DishId == dishId && selectedTeas[i].UnitId == unitId) {
                        selectedTeas.splice(i, 1);
                        break;
                    }
                }
                $target.removeClass(SELECTED_CLASS);
            } else {
                selectedTeas.push({
                    DishId: dishId,
                    UnitId: unitId,
                });
                $target.addClass(SELECTED_CLASS);
            }
        });

        //芥事件
        snackList.find(".snack-name").on("click", function (e) {
            e.stopPropagation();
            var $target = $(e.currentTarget);
            var $parent = $target.parent();
            var dishId = $parent.data("dish_id");
            var unitId = $parent.data("unit_id");
            if ($parent.hasClass(SELECTED_CLASS)) {
                // 查询当前芥在选中的下标
                var delIndex = selectedSnacks.findIndex(function (s) {
                    return s.DishId == dishId && s.UnitId == unitId;
                });
                if (delIndex != -1) {
                    if (selectedSnacks[delIndex].DishNum > 1) {
                        $parent.find('.num').removeClass("more");
                    }
                    $parent.find('.num').text('');
                    selectedSnacks.splice(delIndex, 1);
                    $parent.removeClass(SELECTED_CLASS);
                }
            } else {
                // 查询芥的信息
                var snackData = snacks.find(function (s) {
                    return s.DishId == dishId && s.UnitId == unitId
                });
                var dishNum = snackData.StartOrderNum || 1;
                selectedSnacks.push({
                    DishId: dishId,
                    UnitId: unitId,
                    DishNum: dishNum
                });
                $parent.find('.num').text(dishNum);
                if (dishNum > 1) {
                    $parent.find('.num').addClass("more");
                }
                $parent.addClass(SELECTED_CLASS);
            }
        });

        snackList.find(".dish-operation").on("click", function (e) {
            e.stopPropagation();
            if (e.target.tagName != "BUTTON") {
                return;
            }
            var target = $(e.target);
            var $parent = target.parents(".snack-item");
            var dishId = $parent.data("dish_id");
            var unitId = $parent.data("unit_id");
            var $dishNum = $parent.find('.num');
            var isIncrease = target.hasClass("increase"); //标识点+号还是-号
            // 查询当前芥在选中的下标
            var snackIndex = selectedSnacks.findIndex(function (s) {
                return s.DishId == dishId && s.UnitId == unitId;
            });
            if (isIncrease) {
                // 加芥
                if (snackIndex == -1) {
                    var snackData = snacks.find(function (s) {
                        return s.DishId == dishId && s.UnitId == unitId
                    })
                    var dishNum = snackData.StartOrderNum || 1;
                    selectedSnacks.push({
                        DishId: dishId,
                        UnitId: unitId,
                        DishNum: dishNum
                    });
                    $dishNum.text(dishNum);
                    if (dishNum > 1) {
                        $dishNum.addClass("more");
                    }
                    $parent.addClass(SELECTED_CLASS);
                } else {
                    selectedSnacks[snackIndex].DishNum = selectedSnacks[snackIndex].DishNum + 1;
                    $dishNum.text(selectedSnacks[snackIndex].DishNum);
                    $dishNum.addClass("more");
                }

            } else {
                // 减芥
                if (snackIndex == -1) {
                    return null;
                }
                var newNum = selectedSnacks[snackIndex].DishNum - 1;
                if (newNum < 1) {
                    $dishNum.text('');
                    selectedSnacks.splice(snackIndex, 1);
                    $parent.removeClass(SELECTED_CLASS);
                } else {
                    selectedSnacks[snackIndex].DishNum = newNum;
                    $dishNum.text(newNum);
                    if (newNum == 1) {
                        $dishNum.removeClass("more");
                    }
                }
            }
        });

    }
});

/**
 * 授权界面
 */
mpos.dialogController(mpos.dialogPage.userAuth, function (dialogPage, data) {
    var errMsg = data.errMsg;
    $(dialogPage).find("input[name=username]").val(mpos.localStorage.UserName || "");
    //if (mpos.isDebug){
    //    $(dialogPage).find("input[name=username]").val("");
    //    $(dialogPage).find("input[name=password]").val("");
    //}
    
    if (typeof errMsg == 'string' && errMsg.trim().length > 0) {
        $(dialogPage).find(".error-message").text(errMsg);
    } else {
        $(dialogPage).find(".error-message").remove();
    }
    
    $(dialogPage).find(".button.ok").on("click", function() {
        var username = $(dialogPage).find("input[name=username]").val().trim(),
            password = $(dialogPage).find("input[name=password]").val();
        if (username == null || username.length == 0) {
            mpos.alert("用户名不能为空!");
            return;
        }
        
        mpos.dialog.close({user: username, pwd: password});
        
    });
    $(dialogPage).find(".button.cancel").on("click", function(){
        mpos.dialog.close();
    });
});


/**
 * 授权解锁餐台界面
 */
mpos.dialogController(mpos.dialogPage.authUnlockTable, function (dialogPage, data) {
    var errMsg = data.errMsg; 
    if (typeof errMsg == 'string' || errMsg.trim().length > 0) {
        $(dialogPage).find(".error-message").text(errMsg);
    }  
    
    $(dialogPage).find(".button.ok").on("click", function() { 
        mpos.dialog.close(true); 
    });
    $(dialogPage).find(".button.cancel").on("click", function(){
        mpos.dialog.close();
    });
});

/**
 * 整单折扣 
 */
mpos.dialogController(mpos.dialogPage.wholeDiscount, function (page, data) {
    var settleData = data.settle;
    var isRate = data.isRate;
    var reasons = [];
    var shopConfig;
    var $discountValue = $(page).find("input[name='discountValue']");
    var $discountItem = $(page).find(".discount-list>li").remove();
    var $reasonItem = $(page).find(".reason-list>li").remove();
    
    if (isRate) {
        $(page).find(">.title").text("设置比例折扣");
    } else {
        $(page).find(">.title").text("设置整单折扣");
    }
    mpos.checkInputValue($discountValue, InputType.Num0To100);
    //加载折扣
    loadOftenDiscounts();

    //加载原因
    mpos.getReason(ReasonType.Discount, loadReason);
    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            var dishDiscount = $discountValue.val();

            if (dishDiscount == "") {
                mpos.alert("请输入折扣");
                return;
            }

            var re = /^[1-9]+[0-9]*]*$/;
            if (!re.test(dishDiscount)) {
                mpos.alert("折扣必需为0~100间的整数");
                return;
            }

            dishDiscount = parseInt(dishDiscount);

            if (dishDiscount < 0 || dishDiscount > 100) {
                mpos.alert("折扣必需为0~100间的整数");
                return;
            }

            var reasonId = $(page).find("input[name='selectReason']").filter(function () { return this.checked }).val();
            if (reasonId == undefined || reasonId == null) {
                if (shopConfig.DiscountRequire) {
                    mpos.alert("请选择折扣原因");
                    return;
                }
                reasonId = 0;
            }
            mpos.post(mpos.api.applyDiscount, {
                OrderId: settleData.EnterOrder.Order.OrderId,
                Discount: dishDiscount,
                IsRateDiscount: isRate,
                ReasonId: reasonId,
            }, function (data) {
                mpos.dialog.close(true);
            });
        }
    });

    /*
    加载原因
    */
    function loadReason(data) {
        mpos.getReasonConfirm(function(config) {
            reasons = data.ReasonList;
            shopConfig = config;
            var fragment = $(document.createDocumentFragment());
            $.each(reasons, function (index, item) {
                var reasonItem = $reasonItem.clone();
                reasonItem.find("input").val(item.ReasonId);
                reasonItem.find("span").text(item.ReasonText);
                fragment.append(reasonItem);
            });
            $(page).find(".reasonContainer").empty().append(fragment);
        });
    }

    /*
    加载常用折扣
    */
    function loadOftenDiscounts() {
        mpos.getOftenDiscounts(function(discounts){
            var fragment = $(document.createDocumentFragment());
            $.each(discounts, function (index, item) {
                var discountItem = $discountItem.clone();
                discountItem.find("input").val(item);
                discountItem.find("span").text(item);
                fragment.append(discountItem);
            });
            $(page).find(".commonDiscountList").empty().append(fragment);
            //折扣点击事件
            $(page).find("input[name='selectDiscount']").on("click", function (e) {
                $("input[name='discountValue']").val(e.currentTarget.value);
            });
        });
    }
});
/**
 * author: wang.p   2021-09-06
 * description: 存酒管理
 * */

mpos.controller(mpos.page.fetchWines, function (page, pageData) {
  var $page = $(page);
  var winesId = pageData.winesId;
  var winesPlaceData = pageData.winesPlaceData || []; // 存酒位置数组
  var winesData = null; // 记录存酒的详情数据

  var $fetchDetail = $page.find('.fetch-detail');
  var $fetchListNode = $page.find('.app-content ul');
  var $winesNode = $fetchListNode.find("li").remove();

  function goBackFun () {
    mpos.load(mpos.page.saveWinesManage);
  }

   //返回
  this.onBackKeyDown = goBackFun;
  $page.find("#goBack").on("click", goBackFun);

  $page.on("appShow", function () {
    //是否显示登录
    if (mpos.currentUser == null) {
      mpos.showDialog(mpos.dialogPage.login, function (status) {
        if (status) {
          //加载数据
          loadFetchWines();
        }
      });
    } else {
      //加载数据
      loadFetchWines();
    }
  });

  /**
   * 请求存酒数据
   * */
  function loadFetchWines () {
    // 加载存酒详情数据
    mpos.get(mpos.api.getSaveWineDetail, {StorageSaveId: winesId}, function (res) {
      winesData = res.Save;
      initWinesList(res)
    });
  }

  // 获取存酒位置信息
  function getPositionName (positionId) {
    var place = winesPlaceData.find(function(item) {
      return item.StoragePositionId == positionId;
    });
    return  place ? place.DisplayName : '';
  }

  /**
   * 渲染存酒列表
   * */
  function initWinesList (data) {
    var detailData = data.Save.MainStorage;  // 基本信息
    var saveList = data.Save.Details;  // 存酒的记录

    // 详情数据
    $fetchDetail.find('.StorageSaveSerial').text(detailData.StorageSaveSerial);
    $fetchDetail.find('.CustomerName').text(detailData.CustomerName)
    $fetchDetail.find('.Mobile').text(detailData.Mobile)
    $fetchDetail.find('.StorageStatus').text(SaveWinesStorageStatusEnum[detailData.StorageStatus])

    // 清空ul
    $fetchListNode.empty();
    var fragment = $(document.createDocumentFragment());
    saveList.forEach(function(item) {
      var $node = $winesNode.clone();
      $node.data('SaveDetailId', item.SaveDetailId)
      $node.find('.DishName').text(item.DishName);
      $node.find('.SaveNum').text(item.SaveNum);
      $node.find('.LeftNum').text(item.LeftNum);
      $node.find('.PositionId').text(getPositionName(item.PositionId));
      $node.find('.PositionId').data('PositionId', item.PositionId);
      $node.find('input[name=fetchNum]').val(0);
      fragment.append($node);
    })
    $fetchListNode.append(fragment);

    // 取酒数量事件
    $fetchListNode.find('input[name=fetchNum]').on("click", function () {
      var $total = $(this);
      var total = $total.val();
      var maxTotal = $total.parent().parent().find('.max-num').text();
      mpos.showDialog(mpos.dialogPage.fetchWinesNumber, {
        total: total,
        maxTotal: maxTotal
      }, function (res) {
        if (res.status) {
          $total.val(res.total);
        }
      });
    });
  }


  $page.find('.app-submit').on('click', function (e) {
    var operationType = $(e.currentTarget).data("operation");
    if (operationType == 2) {
      mpos.load(mpos.page.saveWinesManage);
    } else {
      var mobile = '';
      if (winesData.MainStorage && winesData.MainStorage.Mobile){
        mobile = winesData.MainStorage.Mobile
      } else {
        mpos.alert('缺少存酒人手机号');
        return;
      }

      // 遍历出取酒的信息
      var fetchList = [];
      var $nodeList = $page.find('ul li');
      for(var i=0;i < $nodeList.length; i++) {
        var $tempNode = $($nodeList[i]);
        var saveDetailId = $tempNode.data('SaveDetailId');
        var maxNum = $tempNode.find('.max-num').text();
        var fetchNum = $tempNode.find('input').val();
        if (!fetchNum || Number(fetchNum) === 0) {
          continue;
        }
        var orderName = $tempNode.find('.order-name').text();
        if (!InputType[InputType.Num1To999].test(fetchNum)) {
          mpos.alert(orderName + "输入的数量不正确");
          return;
        }
        fetchNum = Number(fetchNum)
        if (fetchNum > Number(maxNum)) {
          mpos.alert(orderName + "取酒最大数量为"+maxNum);
          return;
        }
        fetchList.push({
          SaveDetailId: saveDetailId,
          DishName: orderName,
          FetchNum: fetchNum
        });
      }

      if (fetchList.length === 0) {
        mpos.alert('请输入取酒数量');
        return;
      }
      var addFetchData = {
        "StorageSaveId": winesData.MainStorage.StorageSaveId,
        "FetchUserName": winesData.MainStorage.CustomerName,
        "FetchRemark": "",
        "FetchDetails": fetchList,
        "PrintBillId": mpos.fetchWinesBillId()  // 将取酒打印格式ID传入后端，获取打印的格式信息
      }

      mpos.showDialog(mpos.dialogPage.fetchWinesRemark, {mobile: mobile}, function (res) {
        if (res.status === true) {
          addFetchData.FetchRemark = res.remark;
          mpos.post(mpos.api.addFetchWine, addFetchData, function (res) {
            if (res) {
              fetchPrint(res.printData);
              goBackFun();
            } else {
              mpos.alert('保存失败，请重试')
            }
          });
        }
      });
    }
  })

  // 取酒打印
  function fetchPrint (printData) {
    try {
      //打印
      if (printData != undefined && printData.length > 0) {
        $.each(printData, function (idx, item) {
          for (var i = 0; i < mpos.fetchWinesBillNumber(); i++) { //打印多份
            var print = mpos.addPrintEmptyLine(item);
            mpos.deviceFactory.printTicket(print, null, function (err) {
              //打印
              mpos.alert(err);
            });
          }
        });
      }
    } catch (e) {

    }
  }

});


/**
 取酒备注
 */
mpos.dialogController(mpos.dialogPage.fetchWinesRemark, function (page, data) {
  var $page = $(page);
  var mobile = data.mobile;
  var $remark = $page.find(".remark");
  var $sendCodeBtn = $page.find(".send-code");
  var $fetchNum = $page.find('input[name=fetchNum]');
  var timerCode = null; // 定时器
  var timerValue = 60;  // 倒计时

  var isFetchWineValidSms = mpos.shopConfig.IsFetchWineValidSms;  // 是否取酒是发生验证码

  if (isFetchWineValidSms == 1) {
    $page.find('.fetch-code').removeClass('nd');
  }

  //确定和取消事件
  $page.find(".app-submit").on("click", function (e) {
    var operationType = $(e.currentTarget).data("operation");
    if (operationType == 2) {
      mpos.dialog.close({
        status: false
      });
    } else {
      if (isFetchWineValidSms == 1) {
        var codeValue = $.trim($fetchNum.val());
        if (!codeValue || codeValue.length < 4) {
          mpos.alert('验证码输入有误');
          return;
        }

        mpos.get(mpos.api.ValidFetchSms, {mobile: mobile, code: codeValue}, function (res) {
          if (res == 'ok') {
            dialogClose();
          } else {
            mpos.alert('验证码输入有误');
          }
        });
      } else {
        dialogClose();
      }
    }
  });

  function dialogClose () {
    var remark = $.trim($remark.val());
    mpos.dialog.close({
      status: true,
      remark: remark
    });
  }

  // 发送验证码
  $sendCodeBtn.on('click', function(){
    if ($(this).text() !== '发送') {
      return;
    }
    fetchSendCode();

  });

  // 发送短信
  function fetchSendCode () {
    mpos.get(mpos.api.SendFetchValidSms, {mobile: mobile}, function (res) {
      if (res == 'ok') {
        $sendCodeBtn.text(timerValue);
        startTimer();
      } else {
        mpos.alert('验证码发送失败');
      }
    });
  }

  function startTimer () {
    if (timerCode) {
      clearTimeout(timerCode);
    }
    timerCode = setTimeout(timerCodeFunc, 1000)
  }

  function timerCodeFunc () {
    timerValue--;
    if (timerValue >= 0) {
      $sendCodeBtn.text(timerValue);
      startTimer();
    } else {
      timerValue = 60;
      $sendCodeBtn.text('发送');
    }
  }

  $remark.focus(function(){
    $(this).addClass('focus-bg-color');
  });
  $remark.blur(function(){
    $(this).removeClass('focus-bg-color');
  });

  // 如果启用取酒验证码，就自动发生验证码
  if (isFetchWineValidSms == 1) {
    fetchSendCode();
  }
});


/**
 取酒数量
 */
mpos.dialogController(mpos.dialogPage.fetchWinesNumber, function (page, data) {
  var $page = $(page);
  var total = data && data.total != '' ? data.total : 1;
  var maxTotal = data && data.maxTotal != '' ? Number(data.maxTotal) : 0;
  var $winesNum = $page.find("input[name=winesNum]");
  $winesNum.val(total);
  mpos.checkInputValue($winesNum, InputType.MaxInteger);

  //确定和取消事件
  $page.find(".app-submit").on("click", function (e) {
    var operationType = $(e.currentTarget).data("operation");
    if (operationType == 2) {
      mpos.dialog.close({
        status: false
      });
    } else {
      var total = Number($.trim($winesNum.val()));
      if (maxTotal > 0 && maxTotal < total) {
        mpos.alert('取酒最大数不能超过'+maxTotal);
        return;
      }

      mpos.dialog.close({
        status: true,
        total: total
      });
    }
  });

  $winesNum.focus(function(){
    $(this).addClass('focus-bg-color');
  });
  $winesNum.blur(function(){
    $(this).removeClass('focus-bg-color');
  });

  // 显示修改数量时，延迟获取输入框焦点
  setTimeout(function(){
    $winesNum.focus();
  }, 200);

});


/**
 * 餐台首页
 * @todo: 需要补充逻辑
 * 默认根据是否登录，未登录则弹出登录界面，登录之后开始刷新基础数据
 */
mpos.controller(mpos.page.home, function (page) {
    var currentStatus = 0;
    var currentFloorId = 0;
    var tableList = null;
    //var me = this;
    var $page = $(page);

    //分批加载餐台
    var batchTimes = 0;  //加载批次数
    var batchAppendCount = 30; //分批加载时每次加载数量
    var batchTime = null; //分批加载餐台计时器

    //是否开启收银模式
    var isCashMode = mpos.localStorage.CashMode || false;

    //后台循环获取消息条数的setInterval
    var fetchMessageInterval = null;
    var clearTableLockTimeout = null;

    var fetchMessageIntervalTimeout = 20000;
    var clearTableLockIntervalTimeout = 3000;

    var tableHash = null;

    //this.transition = "instant";

    var $diningTableTemplate = $page.find(".app-list>.diningtable").remove();
    var $filterStatusItem = $page.find("#tableStatusSelect>li").remove();
    var $filterFloorItem = $page.find("#floorSelect>li").remove();
    var $filterFloorFixedItem = $page.find("#floorFilterFixed>li").remove();
    var $tableCellWidth = 0;  // 桌台列宽，只有超过114才生效

    //过滤餐台部分处理
    var diningTableFilterSection = $page.find('.diningtable-filter-section');
    diningTableFilterSection.find('input[name="cashMode"').prop('checked', isCashMode);
    toggleCashModeDisplay();

    /**
     * 根据收银模式显示界面
     */
    function toggleCashModeDisplay() {
        if (isCashMode) {
            diningTableFilterSection.find('.filter-title').eq(1).hide();
            diningTableFilterSection.find('#tableStatusSelect').hide();
        } else {
            diningTableFilterSection.find('.filter-title').eq(1).show();
            diningTableFilterSection.find('#tableStatusSelect').show();
        }
    }

    /**
     * 检查餐台过滤图标状态
     */
    function checkTableFilterIcon() {
        if (currentFloorId !== 0 || (!isCashMode && currentStatus !== 0)) {
            $page.find(".app-topbar .table-filter").addClass('selected');
        } else {
            $page.find(".app-topbar .table-filter").removeClass('selected');
        }
    }

    diningTableFilterSection.find('input[name="cashMode"').on('click', function (e) {
        var checked = $(this).prop("checked");
        mpos.localStorage.CashMode = checked;
        isCashMode = checked;
        toggleCashModeDisplay();
        e.stopPropagation();
    });
    diningTableFilterSection.show = function () {
        checkTableFilterIcon();
        diningTableFilterSection.addClass('show');
        setTimeout(function () {
            diningTableFilterSection.addClass('animation');
        }, 10);
    };
    diningTableFilterSection.hide = function () {
        checkTableFilterIcon();
        //防止点击穿透
        setTimeout(function () {
            diningTableFilterSection.removeClass('show').removeClass('animation');
        }, 0);
    };
    diningTableFilterSection.on('click', function (e) {
        e.stopPropagation();
        diningTableFilterSection.hide();
    });
    diningTableFilterSection.find('section').on('click', function (e) {
        e.stopPropagation();
    });

    /**
     * back键时检测是否餐台过滤弹出
     * @returns {boolean}
     */
    this.onBackKeyDown = function () {
        if (diningTableFilterSection.hasClass('show')) {
            diningTableFilterSection.hide();
            return false;
        }
        return true;
    };
 
    /**
     * 初始载入时的动作，获取数据，开始定时器等
     */
    function initHome() {  
        //刷新餐台数据
        refreshTable();
        //加载楼层
        loadFloors();
        //清理餐台锁
        mpos.post(mpos.api.forceUnLockTable, null, null, {
            hideLoading: true
        });

        //加载消息
        fetchMessageInterval = setTimeout(fetchNewMessageCount, 0);

        $(page).find('input[name="searchDiningTable"]').focus(function(){
            $(this).addClass('focus-bg-color');
        });
        $(page).find('input[name="searchDiningTable"]').blur(function(){
            $(this).removeClass('focus-bg-color');
        });

        // 商米v2使用android7版本，导致莫名的花屏，界面动画，花屏既可以取消， 自动获取焦点，促使页面刷新
        var bodyElement = document.getElementsByTagName('body');
        if (bodyElement && $(bodyElement[0]).hasClass('app-android-7')) {
            setTimeout(function () {
                $(page).find('input[name="searchDiningTable"]').focus();
            }, 300)
            setTimeout(function() {
                $(page).find('input[name="searchDiningTable"]').blur();
            }, 400)
        }
    }

    //判断需要刷新餐台
    $page.on("appShow", function () {
        // 显示餐台区域列表
        setFloorMenu();
        
        if (mpos.isNeedReloadTable) {
            refreshTable();
            mpos.isNeedReloadTable = false;
        }
    });
    //清理后台请求， 如消息循环获取
    $page.on("appDestroy", function () {

        if (fetchMessageInterval)
            clearInterval(fetchMessageInterval);
        if (clearTableLockTimeout)
            clearTimeout(clearTableLockTimeout);

        if (tableRefreshTimeout)
            clearTimeout(tableRefreshTimeout);
    });

    //抽屉账户界面
    $page.find(".app-topbar .slide-user").on("click", function () {
        mpos.slidePage.show();
    });

    // 判断是否启用系统默认键盘
    if (mpos.localStorage.enableSystemKeyboard) {
      $(page).find('input[name="searchDiningTable"]').bind('input porpertychange', function(obj){
        var searchReg = $(this).val().trim().toLowerCase();
        if (!Array.isArray(tableList)) return ;

        if (searchReg === '') {
          searchTableForLocal();
        } else {
          var resultArray = tableList.filter(function (item) {
            var result = item.TableName.toLowerCase().indexOf(searchReg) !== -1 || item.TableSerial.toLowerCase().indexOf(searchReg) !== -1;
            return result;
          });
          searchTableForLocal(resultArray);
        }
      })
    } else {
      mpos.KbInstance.register({
        el:       $(page).find('input[name="searchDiningTable"]'),
        callback: function (searchReg) {
          var displayStr = null;
          if (!Array.isArray(tableList)) return displayStr;

          if (searchReg === null) {
            searchTableForLocal();
          } else {
            var resultArray = tableList.filter(function (item) {
              var result = searchReg.test(item.TableName) || searchReg.test(item.TableSerial);
              if (displayStr === null && result) {
                displayStr = RegExp.$1;
              }
              return result;
            });

            searchTableForLocal(resultArray);
          }

          return displayStr;
        }
      });
    }

    $page.find(".app-topbar").on("click", function (e) {
        diningTableFilterSection.hide();
    });

    var messageBadge = $page.find(".message-badge");

    //消息按钮
    $page.find(".app-topbar .message-badge").on("click", function () {
        mpos.load(mpos.page.messageList);
    });

    $page.on(mpos.event.messageCountChanged, function (e, count) {
        clearTimeout(fetchMessageInterval);
        if (count == 0) {
            messageBadge.empty();
        } else {
            messageBadge.html("<span class='number'>" + count + "</span>");
        }
        fetchMessageInterval = setTimeout(fetchNewMessageCount, fetchMessageIntervalTimeout);
    });

    $page.find(".app-topbar .table-filter").on("click", function (e) {
        diningTableFilterSection.show();
        e.stopPropagation();
    });

    //刷新
    $page.find(".app-topbar .refresh_table").on("click", function (e) {
        refreshTable();
    });

    //餐台筛选重置
    diningTableFilterSection.find('.filter-reset').on('click', function (e) {
        e.stopPropagation();
        diningTableFilterSection.find('input[type="radio"][value="0"]').prop('checked', true);
        currentFloorId = 0;
        currentStatus = 0;
        refreshTable();
        diningTableFilterSection.hide();
        // 修改弹窗的过滤内容 
        $page.find('input[name="filterFloorFixed"][value="'+currentFloorId+'"]').prop('checked', true);
    });

    //餐台搜索
    diningTableFilterSection.find('.filter-ok').on('click', function (e) {
        e.stopPropagation();
        currentStatus = parseInt(diningTableFilterSection.find('input[name="filterStatus"]:checked').val()) || 0;
        currentFloorId = parseInt(diningTableFilterSection.find('input[name="filterFloor"]:checked').val()) || 0;
        // 修改弹窗的过滤内容 
        $page.find('input[name="filterFloorFixed"][value="'+currentFloorId+'"]').prop('checked', true);
        refreshTable();
        diningTableFilterSection.hide();
    });


    /**
     餐台状态
     */
    var tableStatusList = $page.find("#tableStatusSelect");
    var fragment = $(document.createDocumentFragment());
    [TableStatus.All, TableStatus.Empty, TableStatus.Taken, TableStatus.Reservation, TableStatus.Bill, TableStatus.CheckedOut].forEach(function (item) {
        var filterStatusItem = $filterStatusItem.clone();
        filterStatusItem.find('input').val(item);
        if (currentStatus === item) {
            filterStatusItem.find('input').prop('checked', true);
        }
        filterStatusItem.find('span').text(TableStatus[item]);
        fragment.append(filterStatusItem);
    });
    tableStatusList.append(fragment);
    fragment = null;

    /**
     定时解锁
     */
    function clearTableLock() {
        if (mpos.currentUser == null) {
            clearTableLockTimeout = setTimeout(clearTableLock, clearTableLockIntervalTimeout);
            return;
        }
        var currentPage = mpos.getCurrentPage();
        if (currentPage == undefined) {
            clearTableLockTimeout = setTimeout(clearTableLock, clearTableLockIntervalTimeout);
            return;
        }
        if (currentPage != mpos.page.settle
            && currentPage != mpos.page.memberInput
            && currentPage != mpos.page.tableTaken
            && currentPage != mpos.page.settleOperationMore
            && currentPage != mpos.page.weightdishes
            && currentPage != mpos.page.orderDishes
            && currentPage != mpos.page.orderMultiUnitDish
            && currentPage != mpos.page.allCookingForDishes
            && currentPage != mpos.page.orderDishForCooking
            && currentPage != mpos.page.orderDishForGroupPackage
            && currentPage != mpos.page.orderDishForNormalPackage
        ) { //当前页不为结账相关页面时，需要解锁
            if (mpos.openedPayTable) { //没有解锁过
                mpos.post(mpos.api.forceUnLockTable, null, function () {
                    mpos.openedPayTable = false; //标识已解锁过
                }, {
                    hideLoading: true,
                    error: function () {
                    },
                    blFailed: function () {
                    }
                });
            }
        } else { //如果是停到结账界面，检查是否被踢掉了
            //检查有没有被踢掉
            var wholeBillId = $(mpos.getCurrentPageDom()).data("whole_order_id");
            if (wholeBillId != undefined) {
                if (currentPage == mpos.page.settle) {
                    mpos.post(mpos.api.checkTableLockedForSettle, {
                        WholeOrderId: wholeBillId
                    }, function (err) {
                        if (err.length > 0) {
                            alert(err);
                            mpos.isNeedReloadTable = true;
                            //返回到餐台
                            mpos.back(mpos.page.home);
                        }
                    }, {
                        hideLoading: true,
                        error: function () {
                        },
                        blFailed: function () {
                        }
                    });
                } else if (currentPage == mpos.page.tableTaken) {
                  // 检测如果查看详情，不踢出  wang.p 2024-11-07
                  // console.log('开启多人查看详情，不踢出...');
                } else {
                    mpos.post(mpos.api.checkTableLockedForOrderDish, {
                        WholeOrderId: wholeBillId
                    }, function (err) {
                        if (err.length > 0) {
                            alert(err);
                            mpos.isNeedReloadTable = true;
                            //返回到餐台
                            mpos.back(mpos.page.home);
                        }
                    }, {
                        hideLoading: true,
                        error: function () {
                        },
                        blFailed: function () {
                        }
                    });
                }
            }
        }
        clearTableLockTimeout = setTimeout(clearTableLock, clearTableLockIntervalTimeout);
    }

    clearTableLockTimeout = setTimeout(clearTableLock, clearTableLockIntervalTimeout);

    /**
     定时获取消息数据
     */
    function fetchNewMessageCount() {
        mpos.post(mpos.api.getAllNewMessageCount, null, function (data) {
            if (data != undefined && data) {
                var count = data.ServiceCount + data.PaymentCount;
                if (count == 0) {
                    messageBadge.empty();
                } else {
                    messageBadge.html("<span class='number'>" + count + "</span>");
                }
                fetchMessageInterval = setTimeout(fetchNewMessageCount, fetchMessageIntervalTimeout);
            }
        }, {
            hideLoading: true,
            error: function () {
                fetchMessageInterval = setTimeout(fetchNewMessageCount, fetchMessageIntervalTimeout);
            },
            blFailed: function () {
                fetchMessageInterval = setTimeout(fetchNewMessageCount, fetchMessageIntervalTimeout);
            }
        });

    }

    /**
     刷新区域
     */
    function loadFloors() {
        mpos.post(mpos.api.loadFloors, function (data, status, xhr) {
            var floorList = $page.find("#floorSelect");
            var fragment = $(document.createDocumentFragment());
            [{ Id: 0, Name: '全部' }].concat(data).forEach(function (item) {
                var filterFloorItem = $filterFloorItem.clone();
                filterFloorItem.find('input').val(item.Id);
                if (item.Id === currentFloorId) {
                    filterFloorItem.find('input').prop('checked', true);
                }
                filterFloorItem.find('span').text(item.Name);
                fragment.append(filterFloorItem);
            });

            floorList.append(fragment);

            // 初始化顶部区域过滤
            initFloorFilterFixed(data);
        });
    }

    //处理界面刷新的逻辑
    var tableRefreshTimeout;

    /**
     * 开始定时刷餐台
     */
    function startRefreshTable() {
        clearTimeout(tableRefreshTimeout);
        tableRefreshTimeout = setTimeout(refreshTimeInterval, Config.refreshTableTimeInterval);
        /**
         * 定时刷餐台
         */
        function refreshTimeInterval() {
            //当前界面不在首页时不刷新
            if (mpos.hasDialog()
                || mpos.getCurrentPageDom() !== page
                || mpos.tableOperationPage.isShow
                || mpos.KbInstance.isKbShow()) {
                startRefreshTable();
                return;
            }
            refreshTable(true);
        }
    }


    $page.on('touchstart', startRefreshTable);

    /**
     * 刷新餐台，从数据库中获取, 根据hash值进行判断
     * @param isBackground 是否后台刷新
     */
    function refreshTable(isBackground) {
        mpos.post(mpos.api.showDiningTableList, { TableHash: tableHash }, function (data, status, xhr) {
            if (data.TableHash !== tableHash) {
                tableHash = data.TableHash;
                tableList = data.TableList;
                searchTableForLocal();
            } else if (!isBackground) {
                searchTableForLocal();
            }

            startRefreshTable();
        }, {
            hideLoading: true,
            error: function () {
                startRefreshTable();
            },
            blFailed: function () {
                startRefreshTable();
            }
        });
    }


    /**
     * 筛选餐台并显示
     * @param {Array} [dataSource]
     */
    function searchTableForLocal(dataSource) {
        if (!tableList) {
            return;
        }
        var tmpTableList = Array.isArray(dataSource) ? dataSource : tableList;
        tmpTableList = tmpTableList.filter(function (item) {
            if (currentFloorId != 0 && item.FloorSettingId != currentFloorId) {
                return false;
            }
            if (isCashMode) {
                if (item.TableStatus !== TableStatus.Taken && item.TableStatus !== TableStatus.Bill) {
                    return false;
                }
            } else {
                if (currentStatus != 0 && item.TableStatus != currentStatus) {
                    return false;
                }
            }

            return true;
        });

        //餐台数量小于50一次性加载，否则分批加载
        clearTimeout(batchTime); //清除分批加载餐台计时器
        batchTimes = 0;
        var listContainer = $page.find(".diningtable-list").empty();

        var tableListWidth = listContainer[0].offsetWidth - 9;  // 9是桌台列表两边间距6+3，因为右边留3px
        var tableCellCount = Math.floor(tableListWidth / 117);  // 117是桌台宽度114px+3px(右边margin-right)
        var cellWidth = Math.floor((tableListWidth - 117 * tableCellCount) / tableCellCount); // 计算剩余宽度平均分配到桌台宽度值
        if (cellWidth > 0) {
            $tableCellWidth = 114 + cellWidth;  // 114是桌台的宽度
        }
        if (tmpTableList.length > 50) {
            appendTableBatch();
            $page.find('.app-content')[0].scrollTop = 0;
        } else {
            var fragment = $(document.createDocumentFragment());
            tmpTableList.forEach(generateTable.bind(fragment));
            listContainer.append(fragment);
        }
        
        /**
         * 生成餐台并插入到对应的fragment
         * @param item 
         */
        function generateTable(item) {
            var diningTable = $diningTableTemplate.clone()
                .data("tablestatus", item.TableStatus)
                .data("order_id", item.DiningOrderId)
                .data("table_id", item.TableId);

            // 修改桌台列宽
            if ($tableCellWidth > 0) {
                diningTable.css('width',  $tableCellWidth+'px');
            }
            //处理团体台
            if (item.GroupSerial > 0) {
                diningTable.find(".diningtable-group").text("团" + item.GroupSerial + (item.IsMainTable == 1 ? "*" : ""));
            }

            diningTable.find(".diningtable-waiter").text(item.BookDetail ? '员工:'+item.BookDetail.BookSalesmanName : '');
            diningTable.find(".diningtable-number").text(item.TableName);
            diningTable.find(".diningtable-amount").text("￥"+Number(item.OrderAmount).toFixed(2));
            if (mpos.localStorage.enableDiningTableAmount === false) {
                diningTable.find(".diningtable-amount").addClass('nd');
            }

            // diningTable.tap(diningTableClick);  //导致触发两次事件
            diningTable.on('click',diningTableClick);
            this.append(diningTable);
        }

        /**
         *分批加载餐台
         */
        function appendTableBatch() {
            if (batchTimes < tmpTableList.length) {
                /*clearTimeout(batchTime);*/
                var fragment = $(document.createDocumentFragment());
                tmpTableList.slice(batchTimes, batchTimes + batchAppendCount).forEach(generateTable.bind(fragment));
                listContainer.append(fragment);
                batchTimes += batchAppendCount;
                batchTime = setTimeout(appendTableBatch, 100);
            }
        }

        /**
         * 餐台点击操作
         * @param {Event} e event object
         */
        function diningTableClick(e) {
            var orderId = $(e.currentTarget).data("order_id");
            var tableId = $(e.currentTarget).data("table_id");
            diningTableOperation(tableId, orderId);
        }
    }

    /**
     对餐台操作
     */
    function diningTableOperation(tableId, orderId) {
        var table = findTable(tableId, orderId);
        if (table == null) {
            return;
        }
        if (table.TableStatus == TableStatus.Empty //空台
            || table.TableStatus == TableStatus.Reservation //预订
        ) {
            if (table.BookDetail == null) {
                openTable(table);
            } else {
                //预订开台
                mpos.showDialog(mpos.dialogPage.openBookOrderTable, {
                    TableId: table.TableId,
                    TableName: table.TableName,
                    BookInfo: table.BookDetail
                }, function (status) {
                    if (status.Status == 1) { //预订入座成功
                        if (status.DishCount > 0) { //进入点菜,把预订的菜带过去
                            var orderId = status.OrderId;
                            var bookOrderId = status.BookOrderId;
                            doOrderDishes([orderId], bookOrderId);
                            mpos.openedPayTable = true;
                        }
                        refreshTable();
                    } else if (status.Status == 2) { //开台
                        openTable(table);
                    }
                });
            }
        } else if (table.TableStatus == TableStatus.Taken) { //占用
            if (isCashMode) {
                mpos.jumpToSettlePage(orderId, "home");
            } else {
                beginTableOperation(table);
            }
        } else if (table.TableStatus == TableStatus.Bill) { //预结
            if (isCashMode) {
                mpos.jumpToSettlePage(orderId, "home");
            } else {
                beginTableOperation(table);
            }
        } else if (table.TableStatus == TableStatus.CheckedOut) { //脏台
            mpos.dialog({
                title: "提醒",
                text: "确认要清台吗？",
                okButton: "是",
                cancelButton: "否"
            }, function (status) {
                if (status) {
                    mpos.post(mpos.api.cleanUpTable, {
                        TableId: table.TableId,
                        OrderId: table.OrderId
                    }, function () {
                        refreshTable();
                    });
                }
            });
        }
    }

    /**
     从缓存在查找指定的餐台
     */
    function findTable(tableId, orderId) {
        if (tableList == undefined || tableList == null) {
            return null;
        } else {
            for (var i = 0; i < tableList.length; i++) {
                if (tableList[i].DiningOrderId == orderId && tableList[i].TableId == tableId) {
                    return tableList[i];
                }
            }
            return null;
        }
    }

    // /**
    //  获取餐台
    //  优化获取有开台的餐台
    //  */
    // function findTableByTableId(tableId) {
    //     var tables = [];
    //     if (tableList == undefined || tableList == null) {
    //         return null;
    //     } else {
    //         for (var i = 0; i < tableList.length; i++) {
    //             if (tableList[i].TableId == tableId) {
    //                 tables.push(tableList[i]);
    //             }
    //         }
    //     }
    //     if (tables.length == 0) {
    //         return null;
    //     }
    //
    //     if (tables.length == 1) {
    //         return tables[0];
    //     }
    //     for (var i = 0; i < tables.length; i++) {
    //         if (tables[i].DiningOrderId > 0 && tables[i].VirtualTableSerial == 0) {
    //             return tables[i];
    //         }
    //     }
    //     for (var i = 0; i < tables.length; i++) {
    //         if (tables[i].DiningOrderId > 0) {
    //             return tables[i];
    //         }
    //     }
    //
    //     return tables[0];
    // }

    /**
     根据整单ID获取订单
     */
    function getOrderIdsByWholeBillId(wholeBillId) {
        var orderIds = [];
        if (tableList == undefined || tableList == null) {
            return orderIds;
        } else {
            for (var i = 0; i < tableList.length; i++) {
                if (tableList[i].WholeBillId == wholeBillId && tableList[i].WholeBillId > 0 && tableList[i].DiningOrderId > 0) {
                    orderIds.push(tableList[i].DiningOrderId);
                }
            }
        }
        return orderIds;
    }

    /**
     * 开台
     */
    function openTable(table) {
        mpos.showDialog(mpos.dialogPage.openTable, {
            "Table": table,
        }, function (orderId) {
            // 开启快速预订时，刷新桌台，更新快速预订桌台状态
            if (orderId == -99 && mpos.localStorage.enableOpenBookTable) {
                refreshTable();
                return;
            }

            if (orderId) {
                refreshTable();
                //点菜
                doOrderDishes([orderId], 0);
            }
        });
    }

    /**
     * 锁台并点菜
     * @param {Array} orderIds
     * @param {Number} bookOrderId
     */
    function doOrderDishes(orderIds, bookOrderId) {
        mpos.post(mpos.api.loadOrderDishDatas, {
            OrderIds: JSON.stringify(orderIds),
            BookOrderId: bookOrderId,
            NeedClearOrderDish: true,
            EnabledMutilOrderDish: mpos.localStorage.enableMutilOrderDish == true ? 1 : 2
        }, function (data) {
            mpos.load(mpos.page.orderDishes, {
                OrderIds: orderIds,
                DishData: data,
            });
            mpos.openedPayTable = true;
        }, {
            blFailed: function(err) {
                showUnlockTable(err, orderIds);
                return false;   
            }
        });
    }

    /**
     * 开始餐台操作
     * @param {Object} table
     */
    function beginTableOperation(table) {
        var orderId = table.DiningOrderId;
        mpos.tableOperationPage.show({
            OrderDish: true,//order.OrderStatus == DiningOrderStatus.Take,
            OrderDishForGroup: true,//(order.OrderStatus == DiningOrderStatus.Take && order.GroupSerial > 0),
            TakeAllDish: true,
            TakeTypeDish: true,
            OrderDetail: true, //order.OrderStatus == DiningOrderStatus.Take,
            WeightDish: true,
            PrintTableBill: true,
            PreBilledOrder: table.TableStatus != TableStatus.Bill,
            Settle: true,
            ModifyTableHeader: true,
            DeleteOrder: true,
            SwapTable: table.TableStatus == TableStatus.Taken,
            AddTableOrder: table.TableStatus == TableStatus.Taken,
            ChangeDishTable: true,
            CutTable: table.VirtualTableSerial == 0,
            PayToOrderData: mpos.isPayToOrderModel(),
            PushFood: true,   // 催菜功能
        }, function (status) {
            if (typeof status == "object") {
                var op = status.op;
                switch (op) {
                    case TableOperationType.SwapTable: //换台
                        if (table.TableStatus != TableStatus.Taken) {
                            mpos.alert("只有“占用”状态的餐台才能换台");
                            return;
                        }
                        mpos.showDialog(mpos.dialogPage.changeOrderTable, {
                            OrderId: orderId,
                            TableId: table.TableId   // 原桌台ID
                        }, function (status) {
                            if (status) {
                                refreshTable();
                            }
                        });
                        break;
                    case TableOperationType.AddTableOrder: //加台
                        if (table.TableStatus != TableStatus.Taken) {
                            mpos.alert("只有“占用”状态的餐台才能加台");
                            return;
                        }
                        mpos.showDialog(mpos.dialogPage.addTableOrder, {
                            OrderId: orderId
                        }, function (status) {
                            if (status) {
                                refreshTable();
                            }
                        });
                        break;
                    case TableOperationType.ChangeDishTable: //菜品转台
                        mpos.showDialog(mpos.dialogPage.changeDishTable, {
                            OrderId: orderId
                        }, function (status) {
                            if (status) {
                                refreshTable();
                            }
                        });
                        break;
                    case TableOperationType.CutTable: //搭台
                        if (table.VirtualTableSerial > 0) {
                            mpos.alert("临时餐台不允许搭台！");
                            return;
                        }
                        mpos.showDialog(mpos.dialogPage.cutTable, {
                            Table: table
                        }, function (status) {
                            if (status) {
                                refreshTable();
                            }
                        });
                        break;
                    case TableOperationType.DeleteOrder: //销台
                        {
                            mpos.dialog({
                                title: "提醒",
                                text: "确认要撤销开台吗？",
                                okButton: "是",
                                cancelButton: "否"
                            }, function (status) {
                                if (status) {
                                    mpos.post(mpos.api.cancelTable, {
                                        OrderId: orderId
                                    }, function () {
                                        refreshTable();
                                    })
                                }
                            });
                        }
                        break;
                    case TableOperationType.OrderDish: //点菜
                        {
                            doOrderDishes([orderId], 0);
                        }
                        break;
                    case TableOperationType.OrderDishForGroup: //团体点菜
                        {
                            if (table.GroupSerial == 0) {
                                mpos.alert("非团体台，不能团体点单！");
                            }
                            else {
                                var orderIds = getOrderIdsByWholeBillId(table.WholeBillId);
                                if (orderIds.length > 0) {
                                    doOrderDishes(orderIds, 0);
                                }
                            }
                        }
                        break;
                    case TableOperationType.TakeAllDish: //整单起菜
                        {
                            var printSigleBill = mpos.printSigleBill();
                            var printTotalBill = mpos.printTotalBill();
                            mpos.post(mpos.api.takeOrderDishes, {
                                OrderId: orderId,
                                PrintTotalBill: printTotalBill == 1,
                                PrintSigleBill: printSigleBill == 1,
                                OrderDishId: 0,
                            }, function (r) {
                                //本地打印总单
                                if (r.TotalBillGrids != null && Array.isArray(r.TotalBillGrids)) {
                                    $.each(r.TotalBillGrids, function (index, item) {
                                        var printData = mpos.addPrintEmptyLine(item);
                                        mpos.deviceFactory.printTicket(printData, null, function (err) {
                                            //打印
                                            mpos.alert(err);
                                        });
                                    })
                                }
                                //本地打印分单
                                if (r.SigleBillGrids != null && Array.isArray(r.SigleBillGrids)) {
                                    $.each(r.SigleBillGrids, function (index, item) {
                                        var printData = mpos.addPrintEmptyLine(item);
                                        mpos.deviceFactory.printTicket(printData, null, function (err) {
                                            //打印
                                            mpos.alert(err);
                                        });
                                    })
                                }
                                mpos.alert("已整单" + mpos.shopConfig.TakeCalledDescption);
                            });
                        }
                        break;
                    case TableOperationType.TakeTypeDish: //类别点菜
                        {
                            mpos.showDialog(mpos.dialogPage.takeTypeDish, {
                                OrderId: orderId
                            }, function (data) {
                                //console.log(data.Status);

                                //if (data.Status) {
                                //    refreshTable();
                                //}
                            });
                        }
                        break;
                    case TableOperationType.OrderDetail: //详情
                        {
                            mpos.getSettleInfo(orderId, function (settle) {
                                /** 查看详情时不锁单  wang.p  2024-11-05 */
                                // 获取桌台订单详情
                                mpos.load(mpos.page.tableTaken, {
                                  "settle": settle
                                });

                                /** 查看详情时不锁单  wang.p  2024-11-05 */
                                // mpos.post(mpos.api.lockTableForSettle, {
                                //     WholeOrderId: settle.EnterOrder.Order.WholeBillId
                                // }, function (r) {
                                //     if (r != undefined) {
                                //         if (r != "") {
                                //             mpos.alert(r);
                                //         } else {
                                //             mpos.load(mpos.page.tableTaken, {
                                //                 "settle": settle
                                //             });
                                //             mpos.openedPayTable = true;  // 标识需要解锁
                                //         }
                                //     }
                                // });

                            });
                        }
                        break;
                    case TableOperationType.WeightDish: //称重
                        {
                            mpos.post(mpos.api.findNeedWeightDishes, {
                                DiningOrderId: orderId
                            }, function (r) {
                                if (r == undefined || r == null || r.length == 0) {
                                    mpos.alert("没有需要称重的商品");
                                    return;
                                }
                                mpos.pick(mpos.page.weightdishes, {
                                    OrderId: orderId,
                                    Dishes: r,
                                    "wholeBillId": table.WholeBillId
                                }, function (status) {
                                    if (status) {
                                        refreshTable();
                                    }
                                });
                                mpos.openedPayTable = true;
                            });
                        }
                        break;
                    case TableOperationType.PrintTableBill: //打印台单
                        {
                            var billId = mpos.tableBillId();
                            mpos.post(mpos.api.printTableBillByMPOS, {
                                OrderId: orderId,
                                BillId: billId,
                            }, function (r) {
                                if (r.IsLocalPrint) {
                                    if (r.PrintData != null && Array.isArray(r.PrintData) && billId > 0) {
                                        var printNum = mpos.tableBillNumber();
                                        for (var i = 0; i < printNum; i++) { //打印多份
                                            var printData = mpos.addPrintEmptyLine(r.PrintData);
                                            mpos.deviceFactory.printTicket(printData, null, function (err) {
                                                //打印
                                                mpos.alert(err);
                                            });
                                        }
                                    }
                                } else {
                                    mpos.alert("操作成功");
                                }
                            });
                        }
                        break;
                    case TableOperationType.PreBilledOrder: //预结
                        {
                            mpos.preBilledOrder(orderId, 1, function () {
                                //重新刷新
                                refreshTable();
                            });
                        }
                        break;
                    case TableOperationType.Settle: //结账
                        {
                            mpos.jumpToSettlePage(orderId, "home");
                        }
                        break;
                    case TableOperationType.ModifyTableHeader: //修改台头
                        {
                            if (table.TableStatus != TableStatus.Taken) {
                                mpos.alert("当前状态不能修改台头！");
                                return;
                            }
                            mpos.post(mpos.api.lockTableForSettle, //先锁住
                                {
                                    WholeOrderId: table.WholeBillId
                                },
                                function (r) {
                                    if (r != undefined) {
                                        if (r != "") {
                                            mpos.alert(r);
                                        } else {
                                            mpos.showDialog(mpos.dialogPage.modifyOpenTable, {
                                                OrderId: orderId
                                            }, function (data) {
                                                if (data.Status) {
                                                    refreshTable();
                                                }
                                                mpos.post(mpos.api.forceUnLockTable, null, null, {
                                                    hideLoading: true
                                                });
                                            });
                                            mpos.openedPayTable = true;
                                        }
                                    }
                                });
                        }
                        break;
                    case TableOperationType.PayToOrderData:   // 收款记录
                        {
                            mpos.load(mpos.page.payToOrdeDetails, {
                                OrderId: orderId
                            });
                        }
                        break;
                    case TableOperationType.PushFood: // 催菜
                        {
                          mpos.post(mpos.api.reminderWholeOrder, {OrderId: orderId}, function (r) {
                            if (r != undefined) {
                              if (r != "") {
                                mpos.alert(r);
                              } else {
                                mpos.alert("整单催菜成功！");
                              }
                            }
                          });
                        }
                        break;
                }
            }
        });
    }

    //是否显示登录
    if (mpos.currentUser == null) {
        mpos.showDialog(mpos.dialogPage.login, function (status) {
            if (status) {
                initHome();
            }
        });
    } else {
        initHome();
    }

    /**
     * 设置显示餐台区域列表
     */
    function setFloorMenu () {
        try {
            // 显示餐台区域列表
            if (mpos.localStorage.enableFloorMenu) {
                $page.find(".diningtable-content").addClass('floor-menu-fixed-content');
            } else {
                $page.find(".diningtable-content").removeClass('floor-menu-fixed-content');
            }
        } catch(e) {
            
        }
    }

    /**
     * 顶部餐台区域过滤
     */
    function initFloorFilterFixed (data) {
        var floorFixedList = $page.find("#floorFilterFixed");
        var fragment = $(document.createDocumentFragment());
        [{ Id: 0, Name: '全部' }].concat(data).forEach(function (item) {
            var filterFloorItem = $filterFloorFixedItem.clone();
            filterFloorItem.find('input').val(item.Id);
            if (item.Id === currentFloorId) {
                filterFloorItem.find('input').prop('checked', true);
            }
            filterFloorItem.find('span').text(item.Name);
            fragment.append(filterFloorItem);
        });

        floorFixedList.append(fragment);

        // 添加监听事件
        floorFixedList.find('li').on('click', function(e){
            e.stopPropagation();
            var value = $(this).find('input').val();
            currentFloorId = parseInt(value) == NaN ? value : parseInt(value);
            // 修改弹窗的过滤内容 
            diningTableFilterSection.find('input[name="filterFloor"][value="'+currentFloorId+'"]').prop('checked', true);
            refreshTable();
        })
    }

    /**
     * 提示解锁
     */
    function showUnlockTable (data, orderIds) {
        // 提示解锁
        mpos.showDialog(mpos.dialogPage.authUnlockTable, {
            errMsg: data.data
        }, function (result) {
            if (result) {
                mpos.post(mpos.api.UnLockTableByWholeOrderId, {wholeOrderId: orderIds[0]}, function() {
                    mpos.alert('解锁成功！');
                }, {
                    hideLoading: true
                });
            }
        }); 
    }
    
});

/**
 * Created by xeonwell on 2016/5/14.
 *
 * 虚拟键盘定义
 *
 */

/**
 * 键盘初始化参数
 * @typedef {Object} KBOptions
 * @property {HTMLElement|String|ZeptoCollection} parent - 键盘载入点，可以为DOM元素或字符串，不可为空
 * @property {HTMLElement|String|ZeptoCollection} [el] - 事件触发点
 * @property {String} [searchStr] - 搜索字符串
 * @property {Number} [kbMode] - 键盘模式， 0-数字，1-字母，默认为0，会从localstorage里获取保存的值
 * @property {Function} [callback] - 回调函数, 参数为搜索字符串callback(searchReg), 该回调函数必须返回搜索的结果字符串
 * @property {Boolean} [showResultLabel] - 是否显示键盘上的结果标签， 默认不显示
 * @property {Number} [debounceTime] - 搜索延时时间，单位毫秒，基于_.debounce实现
 */

(function () {
    /**
     * 替换处理
     */
    var replaceArray = [
        ['[ABC]', /[ABC]/i],
        ['[DEF]', /[DEF]/i],
        ['[GHI]', /[GHI]/i],
        ['[JKL]', /[JKL]/i],
        ['[MNO]', /[MNO]/i],
        ['[PQRS]', /[PQRS]/i],
        ['[TUV]', /[TUV]/i],
        ['[WXYZ]', /[WXYZ]/i]
    ];

    /**
     * 全键盘数字
     * @type {[*]}
     */
    var fullKBArray = ['1234567890', 'QWERTYUIOP', 'ASDFGHJKL', 'ZXCVBNM'];

    /**
     * 数字键盘和字母键盘
     */
    var KbModeNumber = 0, KbModeAlpha = 1, KbModeFull = 2;
    var inputRE = /INPUT/i;

    /** @namespace  mpos.localStorage.KbMode */
    mpos.registerStorageProperties('KbMode');

    /**
     * 虚拟键盘定义
     * <code>
     *      new mpos.Components.KeyBoard({
                parent: $(page).find('.diningtable-filter-section'),
                showResultLabel: true,
                callback: function (searchReg) {
                    var displayStr = null;
                    if (!Array.isArray(tableList)) return displayStr;

                    var resultArray = tableList.filter(function (item) {
                        var result = searchReg.test(item.TableName) || searchReg.test(item.TableSerial);
                        if (displayStr === null && result) {
                            displayStr = RegExp.$1;
                        }
                        return result;
                    });

                    searchTableForLocal(resultArray);

                    return displayStr;
                }
            });
     * </code>
     * @namespace mpos.Components.KeyBoard
     * @param {KBOptions} options
     * @constructor
     */
    function KeyBoard(options) {
        if (!options || typeof options !== 'object')
            throw TypeError("初始化键盘参数必须要输入");

        var context = this;

        /**
         * 是否输入框
         * @type {boolean}
         */
        this.isInput = false;

        /**
         * 显示的字符串
         * @type {String|string}
         */
        this.displayStr = '';

        /**
         * 搜索字符串， 根据显示字符串转换而成
         * @type {String}
         */
        this.searchStr = '';
        /**
         * 触发Dom
         * @type {null|ZeptoCollection}
         */
        this.el = null;

        /**
         * 搜索回调
         * @type {Function|undefined}
         */
        this.callback = typeof options.callback === 'function' ? options.callback.bind(this) : undefined;
        /**
         * 搜索延时
         * @type {Number|number}
         */
        var debounceTime = parseInt(options.debounceTime) || 150;
        /**
         * 搜索延时函数
         * @type {Function}
         */
        this.debounceFunction = null;
        if (debounceTime === 0) {
            this.debounceFunction = searchKeyword
        } else {
            this.debounceFunction = _.debounce(searchKeyword, debounceTime);
        }
        /**
         * 记录是否扫描枪扫码操作清空搜索框
         * */
        scanClear: false,  // true=扫码操作， false=非扫码即虚拟键盘

        /**
         * 键盘模式
         * @type {Number|number}
         */
        this.kbMode = parseInt(options.kbMode || mpos.localStorage.KbMode) || 0;
        // /**
        //  * 当前的操作, c->切换键盘， b->退格键
        //  * @type {undefined|String}
        //  */
        // this.action = undefined;
        // /**
        //  * 当前点击的字符
        //  * @type {undefined|String}
        //  */
        // this.searchChar = undefined;

        //generate DOM
        /**
         * keyboard container
         * @type {ZeptoCollection}
         */
        this.container = $('<div class="keyboard-container"></div>');
        /**
         * keyboard button section
         * @type {ZeptoCollection}
         */
        this.kbSection = generateKeyboard(this.kbMode);
        /**
         * result display label
         * @type {ZeptoCollection|null}
         */
        this.resultLabel = null;

        if (options.showResultLabel) {
            this.resultLabel = $('<div class="search-result"></div>');
            this.container.append(this.resultLabel);
        }
        this.container.append(this.kbSection);

        //event binding
        this.container.on('click', function (e) {
            buttonClick.call(context, e);
            e.stopPropagation();
        });

        //下面的代码为处理显示效果的
        // this.container.on('click', function (e) {
        //     e.stopPropagation();
        // });
        // this.container.on('touchstart', function (e) {
        //     buttonClick.call(context, e);
        //     e.stopPropagation();
        // });
        // this.container.on('touchend touchcancel', function (e) {
        //     var target = e.target;
        //     if (target.tagName.toUpperCase() === 'BUTTON') {
        //         $(target).removeClass('active');
        //     }
        //     e.stopPropagation();
        // });

        $(options.parent).append(this.container);
    }

    /**
     * 搜索字符串
     */
    function searchKeyword() {
        // mpos.log('search string: ' + this.searchStr);
        if (this.callback) {
            if (this.scanClear) {
              return;
            }
            var result = this.callback(this.searchStr.length > 0 ? new RegExp('(' + this.searchStr + ')', 'i') : null);
            //处理字符串显示
            if (typeof result === 'string') {
                this.displayStr = result.toLowerCase();
            } else {
                this.displayStr = this.searchStr.replace(/\[(\w)\w+\]/g, '$1').toLowerCase();
                // if (this.action === '<') {
                //     this.displayStr = this.displayStr.substr(0, this.displayStr.length - 1);
                // } else if (this.action === undefined && this.searchChar !== undefined) {
                //     this.displayStr += '' + (this.kbMode === KbModeAlpha ? this.searchChar.charAt(1).toLowerCase()
                //             : this.searchChar);
                // }
            }
            setDisplayLabel.call(this);
        }
    }

    /**
     * 显示结果
     */
    function setDisplayLabel() {
        if (this.el) {
            this.el[this.isInput ? 'val' : 'text'](this.displayStr);
        }

        if (this.resultLabel)
            this.resultLabel.text(this.displayStr);
    }

    /**
     * 生成键盘区域
     * @param kbMode
     * @return {ZeptoCollection}
     */
    function generateKeyboard(kbMode) {
        var kbSection = $('<div class="keyboard-section"></div>');
        var $btn = $('<button>&nbsp;</button>'); //空的button必须有个空格
        if (kbMode === KbModeNumber) {
            kbSection.addClass('nine');
            [1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(function (item) {
                kbSection.append($btn.clone().text(item).data('s', item));
            });
            kbSection.append($btn.clone().addClass('switch').text('ABC').data('action', '>'));
            kbSection.append($btn.clone().text(0).data('s', 0));
            kbSection.append($btn.clone().addClass('back').data('action', '<'));
        } else if (kbMode === KbModeAlpha) {
            kbSection.addClass('nine');
            kbSection.append($btn.clone().addClass('disabled'));
            replaceArray.forEach(function (key) {
                kbSection.append($btn.clone().text(key[0].replace(/\[|\]/g, '')).data('s', key[0]));
            });
            kbSection.append($btn.clone().addClass('switch').text('ABC').data('action', '>'));
            kbSection.append($btn.clone().addClass('disabled'));
            kbSection.append($btn.clone().addClass('back').data('action', '<'));
        } else if (kbMode === KbModeFull) {
            kbSection.addClass('full');
            fullKBArray.forEach(function (kbStr) {
                    var divC = $("<div class='kbRow'/>");
                    kbStr.split('').forEach(function (item) {
                        divC.append($btn.clone().text(item).data('s', item));
                    });
                    kbSection.append(divC);
                });

            kbSection.append($btn.clone().addClass('switch').text('123').data('action', '>'));
            kbSection.append($btn.clone().addClass('back').data('action', '<'));
        }

        return kbSection;
    }

    /**
     * 键盘按钮点击事件
     * @param e
     */
    function buttonClick(e) {
        var target = e.target;
        if (target.tagName.toUpperCase() !== 'BUTTON') return;
        target = $(target);
        var action = target.data('action');
        this.scanClear = false;  // 移除扫描枪记录，开启虚拟键盘操作记录
        // this.action = action;
        switch (action) {
            case  '>':
                this.kbMode = (this.kbMode + 1) % 3;
                this.kbSection.remove();
                this.kbSection = generateKeyboard(this.kbMode);
                this.container.append(this.kbSection);
                mpos.localStorage.KbMode = this.kbMode;
                return;
            case '<':
                if (this.searchStr.length == 0) return;
                // this.searchStr = transform(this.displayStr.substr(0, this.displayStr.length - 1));
                this.searchStr = this.searchStr.substr(0, this.searchStr.endsWith(']') ? this.searchStr.lastIndexOf('[') : this.searchStr.length - 1);
                this.debounceFunction.call(this);
                return;
            default:
                break;
        }

        var s = target.data('s');
        // this.searchChar = s;
        if (s !== undefined) {
            this.searchStr = this.searchStr + s;
            this.debounceFunction.call(this);
        }

        // this.action = undefined;
        // this.searchChar = undefined;
    }

    /**
     * 转换给定的字符为对应的正则表达式
     * @param {String} str
     * @returns {String}
     */
    function transform(str) {
        if (typeof str !== 'string') return str;
        if (/[a-z]/i.test(str)) {
            replaceArray.forEach(function (key) {
                str = str.replace(key[1], key[0]);
            });
        }

        return str;
    }

    KeyBoard.prototype = {
        reset: function (isScan) {
            // 记录是扫描枪扫码操作还是虚拟键盘操作
            this.scanClear = isScan ? true : false;
            this.displayStr = '';
            this.searchStr = '';
            setDisplayLabel.call(this);
        },
    };

    // /**
    //  * 移除键盘
    //  */
    // KeyBoard.prototype.remove = function () {
    //     this.container.remove();
    // };

    /**
     * 单例键盘所在page
     * @type {ZeptoCollection}
     */
    var kbPage = $('<div id="keyboard-page"></div>').on('click', function (e) {
        instance.hide();
        e.stopPropagation();
    });

    /**
     * 是否显示了通用键盘
     * @returns {boolean}
     */
    var isKbShow = function () {
        return kbPage.parent().length > 0;
    };

    /**
     * @name KBInstance
     * @property {Function} show
     * @property {Function} register
     * @property {Function} hide
     * @property {Function} isKbShow
     */
    /**
     * 单例键盘
     * @type {mpos.Components.KeyBoard|KBInstance}
     */
    var instance = new KeyBoard({
        parent: kbPage
    });

    instance.isKbShow = isKbShow;

    /**
     * 显示默认键盘
     * @param {KBOptions} options
     */
    instance.show = function (options) {
        instance.callback = options.callback;
        instance.el = $(options.el);
        if (instance.el.length > 0) {
            instance.isInput = inputRE.test(instance.el[0].tagName);
            instance.displayStr = instance.el[instance.isInput ? 'val' : 'text']().toLowerCase();
            instance.searchStr = transform(instance.displayStr);
        } else {
            instance.isInput = false;
            instance.displayStr = '';
            instance.searchStr = '';
        }
        instance.isInput = instance.el.length > 0 ? inputRE.test(instance.el[0].tagName) : false;
        instance.displayStr = instance.el[instance.isInput ? 'val' : 'text']().toLowerCase();
        instance.searchStr = transform(instance.displayStr);
        setDisplayLabel.call(instance);

        if (!isKbShow()) {
            kbPage.appendTo('body');
            setTimeout(function () {
                kbPage.addClass('animation');
            }, 10);
        }
    };

    /**
     * 注册某个元素以及callback
     * <code>
     mpos.KbInstance.register({
                el: $(page).find('input[name="searchDiningTable"]'),
                callback: function (searchReg) {
                    var displayStr = null;
                    if (!Array.isArray(tableList)) return displayStr;

                    var resultArray = tableList.filter(function (item) {
                        var result = searchReg.test(item.TableName) || searchReg.test(item.TableSerial);
                        if (displayStr === null && result) {
                            displayStr = RegExp.$1;
                        }
                        return result;
                    });

                    searchTableForLocal(resultArray);

                    return displayStr;
                }
            });
     * </code>
     * @param {KBOptions} options - {el: ZeptoCollection, callback: Function}
     */
    instance.register = function (options) {
        if (!options.el) return;
        var el = $(options.el);
        if (el.length == 0) return;
        if (inputRE.test(el[0].tagName)) {
            el.prop('readonly', true);
        }
        el.on('click', function (e) {
            instance.show({
                el: this,
                callback: options.callback
            });
        });
    };

    /**
     * 隐藏默认键盘
     */
    instance.hide = function () {
        kbPage.remove().removeClass('animation');
        //处理掉引用到的元素
        instance.el = null;
        instance.callback = undefined;
    };

    mpos.KbInstance = instance;


    mpos.Components.extend(KeyBoard);
})();

/**
 会员卡输入对话框
 */
mpos.controller(mpos.page.memberInput, function (page, data) {
    var currentMemberCard = data.MemberCard; //当前会员卡
    var hasReset = false;
    var settleData = data.Settle;
    var newMemberCard = null;
    var queryCards = []; //查询到的卡信息
    var consumptionId = data.ConsumptionId;
    var me = this;
    var searchMemberCarTimeout = 0;
    var $page = $(page);

    var $memberCard = $page.find("li.member-card").remove();

    $page.find("#memberCardDetail").hide();
    $page.find("#memberCardList").hide();

    //增加整单ID
    $page.data("whole_order_id", settleData.EnterOrder.Order.WholeBillId);

    //清理后台请求， 如消息循环获取
    $page.on("appDestroy", function () {
        if (searchMemberCarTimeout)
            clearTimeout(searchMemberCarTimeout);
    });

    //加载会员卡
    if (currentMemberCard != null) {
        mpos.post(mpos.api.getMemberByMemberCardId, {
            MemberCardId: currentMemberCard.MemberCardId
        }, function (data) {
            currentMemberCard = data;
            showMemberCardDetail(currentMemberCard);
        });
    }
    //查询会员
    /*****事件****/
    //查询
    function searchMemberCard(carNum) {
        if (currentMemberCard != null) {
            mpos.alert("请先重置会员卡");
            return;
        }
        var key = "";
        var onlySelectCardNum = false;
        if (carNum == undefined) {
            //查询
            key = $page.find("input[name='card']").val().trim();
            if (key == "") {
                mpos.alert("请输入查询条件");
                return;
            }
        } else {
            if (carNum != "") {
                key = carNum;
                onlySelectCardNum = true;
            } else {
                return;
            }
        }

        //$page.find("input[name='card']")[0].blur();

        mpos.post(mpos.api.searchMembers, {
            Keyword: key
        }, function (data) {
            var memberCardListContainer = $page.find("#memberCardList");
            queryCards = data;
            if (!$.isArray(data) || data.length == 0) {
                mpos.alert("未找到对应卡信息");
                return;
            }
            if (onlySelectCardNum && data.length) {
                data = data.filter(function (item) {
                    return item.CardNumber == key;
                });
            }
            if (data.length == 1) { //当找到一个时，直接显示
                newMemberCard = data[0];
                showMemberCardDetail(data[0]);
                memberCardListContainer.empty().hide();
            } else { //多个时，显示列表
                //循环显示会员卡
                var fragment = $(document.createDocumentFragment());
                $.each(data, function (idx, item) {
                    var memberCard = $memberCard.clone();
                    memberCard.find("input").val(item.MemberCardId).on("click", function (e) {
                        var value = e.currentTarget.value;
                        var card = null;
                        for (var i = 0; i < queryCards.length; i++) {
                            if (queryCards[i].MemberCardId == value) {
                                card = queryCards[i];
                                break;
                            }
                        }
                        if (card != null) {
                            newMemberCard = card;
                            $page.find("#memberCardList").hide();
                            showMemberCardDetail(card);
                        }
                    });
                    memberCard.find(".member-name").text(item.MemberName);
                    memberCard.find(".member-mobile").text(item.Mobile);
                    memberCard.find(".member-cardNO").text("NO." + item.MemberCardNo);
                    fragment.append(memberCard);
                });

                memberCardListContainer.empty().append(fragment).show();
            }
        });
    }
    
    //$page.find(".app-submit").on("click", searchMemberCard);
    $page.find(".member-search-form").on("submit", function () {
        searchMemberCard();
        document.activeElement.blur();
        return false;
    });
    $page.find("input[name=card]")
        .on("focus", function () {
            if ($page.find("#memberCardList>li").length > 0) {
                $page.find("#memberCardList").show();
            }
        });

    //返回事件
    $page.find("#backMember").on("click", function (e) {
        if (hasReset) { //重置过
            me.reply({
                MemberCard: null
            });
        } else { //没有重置过
            mpos.back();
        }
    });
    //扫码
    $page.find("#scanMember").on("click", function (e) {
        mpos.scanQR(function (result) {
            result = typeof jsonModelScanResult == "object" ?
                jsonModelScanResult : result;
            if (result.cancelled == true) {
                return;
            }
            //处理扫描得到的结果
            $page.find("input[name='card']").val(result.text);
            searchMemberCard();
        }, function (err) {
            mpos.alert("扫码错误!");
        });
    });
    //确定
    $page.find("#okMember").on("click", function (e) {
        if (hasReset) { //重置过
            if (newMemberCard != null) {
                setMemberCard(newMemberCard.MemberCardId, function () {
                    me.reply({
                        MemberCard: newMemberCard
                    });
                });
            } else {
                me.reply({
                    MemberCard: newMemberCard
                });
            }
        } else { //没有重置过
            if (newMemberCard != null) { //应用了新卡
                setMemberCard(newMemberCard.MemberCardId, function () {
                    me.reply({
                        MemberCard: newMemberCard
                    });
                });
            } else { //无变化
                mpos.back();
            }
        }
    });

    //重置
    $page.find("#resetMember").on("click", function (e) {
        if (currentMemberCard != null) {
            mpos.dialog({
                title: "提醒",
                text: "是否需要重置当前会员卡？",
                okButton: "是",
                cancelButton: "否"
            }, function (status) {
                if (status) {
                    setMemberCard(0, function () {
                        //这里重置
                        hasReset = true;
                        currentMemberCard = null;
                        showMemberCardDetail(null);
                    });
                }
            });
        }
    });
    /*****事件End****/

    /*
     使用会员卡
     memberCardId = 0 时，表示重置会员卡
     */
    function setMemberCard(memberCardId, callBack) {
        mpos.post(mpos.api.setMemberCard, {
            MemberCardId: memberCardId,
            ConsumptionId: consumptionId
        }, callBack);
    }

    //显示会员明细
    function showMemberCardDetail(card) {

        var cardContainer = $page.find("#memberCardDetail");
        if (card) {
            mpos.post(mpos.api.getMemberTicketCount, {
                ConsumptionId: consumptionId,
                MemberCardId: card.MemberCardId,
                MemberId: card.MemberId
            }, function (result) {
                var ticketCount = result.TicketCount;
                cardContainer.find(".member-name").text(card.MemberName);
                cardContainer.find(".member-mobile").text(card.Mobile);
                cardContainer.find(".member-actualMoney").text(mpos.formatPrice(card.ActualMoney));
                cardContainer.find(".member-score").text(card.Score);
                cardContainer.find(".member-ticketCount").text(ticketCount);
                cardContainer.find(".member-levelName").text(card.LevelName);
                cardContainer.find(".member-couponName").text(card.CouponName);
                cardContainer.find(".member-cardNO").text(card.MemberCardNo);

                cardContainer.show();
            });
        } else {
            cardContainer.hide();
        }
    }

    mpos.startSearchMagCard();

    /*
     获取磁条卡号
     */
    function getMagCardNum() {
        searchMemberCarTimeout = setTimeout(function () {
            mpos.getMagCardNum(function (num) {
                if (num.length > 0) {
                    if (num == "0") {
                        mpos.alert("请重刷!");
                    } else {
                        mpos.alert("卡号：" + num);
                        searchMemberCard(num);
                    }
                }
                if (!mpos.isStopSearchMagCard) {
                    getMagCardNum();
                }
            });
        }, 300);
    }

    if (mpos.deviceFactory.deviceType == DeviceType.LklPayDevice) {
        getMagCardNum();
    }
});
/**
 * Created by xeonwell on 2016/7/13.
 *
 */
mpos.controller(mpos.page.memberRecharge, function (page, memberCard) {
    var $page = $(page);
    var memberCardDetail = $page.find('#memberCardDetail');
    var memberCardList = $page.find('#memberCardList');
    var rechargeContainer = $page.find('.recharge-container');
    var paymentTypeList = $page.find('.payment-type-list');
    var $memberCardItem = memberCardList.find("li.member-card").remove();
    var $rechargeAmount = rechargeContainer.find("input[name='rechargeAmount']");
    var currentSelectedMemberCard = _.isEmpty(memberCard) ? null : memberCard;
    var queryCards = [];//查询到的卡信息
    var listPayments = []; //付款方式
    var presentInfo = {
        TicketStrategyId: 0,
        TicketTypeId: 0,
        TicketTypeName: "",
        TicketCount: 0,
        PresentAmount: 0,
        RechargeStrategyId: 0
    };

    /**
     * reset the form
     */
    function resetUI() {
        memberCardDetail.hide();
        memberCardList.hide().empty();
        rechargeContainer.hide();
        paymentTypeList.hide();
    }

    $.selectOnFocus(page);
    showPaymentList();
    registerRechargeEvent();
    resetUI();
    setPresentUI();

    var form = $page.find('.search-member-form');
    var memberCardInput = $page.find('input[name="member-card"]');

    if (currentSelectedMemberCard) {
        showMemberCardDetail(currentSelectedMemberCard);
    }

    //submit form
    form.on('submit', function () {
        var cardNum = memberCardInput.val().trim();
        if (cardNum.length === 0) {
            resetUI();
            return;
        }
        searchMemberCard(cardNum);

        return false;
    });

    //reset form
    $page.find('.app-button.reset').on('click', function () {
        if (currentSelectedMemberCard) {
            //reset
            mpos.replace(mpos.page.memberRecharge);
        } else {
            //search
            form.trigger('submit');
        }
    });

    //scan qr
    $page.find('.scan-QR').on('click', function () {
        mpos.scanQR(function (result) {
            if (result.cancelled == true) {
                return;
            }
            $page.find('input[name="member-card"]').val(result.text);
            form.trigger('submit');
        }, function (err) {
            mpos.alert("扫码错误!");
        });
    });

    /**
     * 根据参数查询会员卡信息
     * @param carNum
     */
    function searchMemberCard(carNum) {

        if (carNum === undefined)
            return;

        mpos.post(mpos.api.searchMembers, {
            Keyword: carNum
        }, function (data) {
            queryCards = data;
            if (!$.isArray(data) || data.length == 0) {
                mpos.alert("未找到对应卡信息");
                return;
            }

            if (data.length == 1) { //当找到一个时，直接显示
                currentSelectedMemberCard = data[0];
                showMemberCardDetail(data[0]);
                memberCardList.hide().empty();
            } else { //多个时，显示列表
                //循环显示会员卡
                var fragment = $(document.createDocumentFragment());
                $.each(data, function (idx, item) {
                    var memberCard = $memberCardItem.clone();
                    memberCard.find("input").val(item.MemberCardId).on("click", function (e) {
                        var value = e.currentTarget.value;
                        var card = null;
                        for (var i = 0; i < queryCards.length; i++) {
                            if (queryCards[i].MemberCardId == value) {
                                card = queryCards[i];
                                break;
                            }
                        }
                        if (card != null) {
                            currentSelectedMemberCard = card;
                            memberCardList.hide();
                            showMemberCardDetail(card);
                        }
                    });
                    memberCard.find(".member-name").text(item.MemberName);
                    memberCard.find(".member-mobile").text(item.Mobile);
                    memberCard.find(".member-cardNO").text("NO." + item.MemberCardNo);
                    fragment.append(memberCard);
                });

                memberCardList.empty().append(fragment).show();
            }
        });
    }

    /**
     * 显示会员明细
     * @param card
     */
    function showMemberCardDetail(card) {
        if (card) {
            mpos.post(mpos.api.getMemberTicketCount, {
                ///TODO: 处理下面的值
                // ConsumptionId: consumptionId,
                MemberCardId: card.MemberCardId,
                MemberId: card.MemberId
            }, function (result) {
                $page.find('.app-button.reset').val("重置");

                var ticketCount = result.TicketCount;
                memberCardDetail.find(".member-name").text(card.MemberName);
                memberCardDetail.find(".member-mobile").text(card.Mobile);
                memberCardDetail.find(".member-actualMoney").text(mpos.formatPrice(card.ActualMoney));
                memberCardDetail.find(".member-score").text(card.Score);
                memberCardDetail.find(".member-ticketCount").text(ticketCount);
                memberCardDetail.find(".member-levelName").text(card.LevelName);
                memberCardDetail.find(".member-couponName").text(card.CouponName);
                memberCardDetail.find(".member-cardNO").text(card.MemberCardNo);

                memberCardDetail.show();
                rechargeContainer.show();
                paymentTypeList.show();
            });
        } else {
            memberCardDetail.hide();
            rechargeContainer.hide();
            paymentTypeList.hide();
        }
    }

    /**
     * 显示付款方式
     * @param card
     */
    function showPaymentList() {
        mpos.post(mpos.api.getRechargePayments, {}, function (data) {
            $.each(data, function (idx, item) {
                var typeItem = $("<li class='textEllipsis' />").text(item.PaymentPatternName)
                    .addClass("payment-type-" + item.PaymentPatternType);
                if (item.PaymentPatternType == 4) {
                    if (item.ThirdPaymentType != BankPaymentType.NormalPay) {
                        typeItem.data("pattern_id", item.PaymentPatternId);
                    }
                } else {
                    typeItem.data("pattern_id", item.PaymentPatternId);
                }
                //添加class, 银行卡支付和第三方支付的扩展
                if (item.PaymentPatternType == 4 || item.PaymentPatternType == 128) {
                    typeItem.addClass("payment-type-" + item.PaymentPatternType + "-" + item.ThirdPaymentType);
                }
                paymentTypeList.append(typeItem);
            });
            listPayments = data;
            paymentTypeList.hide();
            //付款方式点击事件
            paymentTypeList.find("li[data-pattern_id]").on("click", function (e) {
                var pid = $(e.currentTarget).data("pattern_id");
                var paymentPattern = findPaymentPatternInfo(pid);
                if (paymentPattern != null) {
                    beginPay(paymentPattern);
                }
            });
        });
    }

    /*
     开始支付
     */
    function beginPay(paymentPattern) {

        var rechargeAmount = getRechargeAmount();
        if (rechargeAmount == -1) {
            return;
        }

        var rechargeData = getRechargeData(paymentPattern);
        var canPay = true;
        if (rechargeAmount == 0) { //现金可以充值0元
            if (paymentPattern.PaymentPatternType == 1) { //现金支付
                if (Number(rechargeData.PresentAmount) <= 0) {
                    mpos.alert("充值总金额必需大于0");
                    return;
                }
            }
            canPay = false;
        }
        if (!canPay) {
            return;
        }

        if (rechargeData.TicketStrategyId > 0
            && rechargeData.TicketTypeId > 0
            && rechargeData.TicketCount > 0
            ) {
            mpos.post(mpos.api.rechTicketTypeCount, {
                StrategyId: rechargeData.TicketStrategyId,
                TicketTypeId: rechargeData.TicketTypeId,
                Count: rechargeData.TicketCount
            }, function (re) {
                if (re) {
                    mpos.dialog({
                        title: "提醒",
                        text: presentInfo.TicketTypeName + "票券类型受到数量控制，本次充值不会赠送票券，是否继续充值？",
                        okButton: "是",
                        cancelButton: "否"
                    }, function (status) {
                        if (status) {
                            executePay(paymentPattern, rechargeData);
                        }
                    });
                } else {
                    executePay(paymentPattern, rechargeData);
                    return;
                }
            });
        }
        else {
            executePay(paymentPattern, rechargeData);
        }
    }

    /*
    执行充值
    */
    function executePay(paymentPattern, rechargeData) {
        if (paymentPattern.PaymentPatternType == 1) { //现金
            payForCash(paymentPattern);
        } else if (paymentPattern.PaymentPatternType == 2) { //会员卡
            mpos.alert("不能使用此付款方式");
        } else if (paymentPattern.PaymentPatternType == 4) { //银行卡
            if (paymentPattern.ThirdPaymentType != BankPaymentType.NormalPay) { //盒子支付
                if (paymentPattern.ThirdPaymentType == BankPaymentType.IBoxPay && DeviceType[mpos.deviceFactory.deviceType] != "3.1") {
                    mpos.alert("此设备不支持此付款方式");
                    return;
                }
                if (paymentPattern.ThirdPaymentType == BankPaymentType.Lakala && DeviceType[mpos.deviceFactory.deviceType] != "3.2") {
                    mpos.alert("此设备不支持此付款方式");
                    return;
                }
                if (paymentPattern.ThirdPaymentType == BankPaymentType.WangPos && DeviceType[mpos.deviceFactory.deviceType] != "3.3") {
                    mpos.alert("此设备不支持此付款方式");
                    return;
                }
                payForLkl(paymentPattern);
            } else {
                mpos.alert("不能使用此付款方式");
            }
        } else if (paymentPattern.PaymentPatternType == 8) { //挂账
            mpos.alert("不能使用此付款方式");
        } else if (paymentPattern.PaymentPatternType == 16) { //免单
            mpos.alert("不能使用此付款方式");
        } else if (paymentPattern.PaymentPatternType == 32) { //票券
            mpos.alert("不能使用此付款方式");
        } else if (paymentPattern.PaymentPatternType == 64) { //订金
            mpos.alert("不能使用此付款方式");
            return;
        } else if (paymentPattern.PaymentPatternType == 128) { //第三方支付
            // 支付宝和微信、云闪付
            if (paymentPattern.ThirdPaymentType == 1 || paymentPattern.ThirdPaymentType == 2 || paymentPattern.ThirdPaymentType == 12) {
                payForWxOrAliPay(paymentPattern);
            } else if (paymentPattern.ThirdPaymentType == 3 || paymentPattern.ThirdPaymentType == 4) { //糯米和美团
                mpos.alert("不能使用此付款方式");
            }
        }
    }

    /**
     * 获取付款信息
     * @param {Object} pid PaymentPatternId
     */
    function findPaymentPatternInfo(pid) {
        if (listPayments) {
            for (var i = 0; i < listPayments.length; i++) {
                if (listPayments[i].PaymentPatternId == pid) {
                    return listPayments[i];
                }
            }
        }
        return null;
    }

    /**
     * 格式化总额显示
     * @param amount 金额
     * @returns {string} 格式化结果
     */
    function formatRechargeTotal(amount) {
        return "总额" + mpos.formatPrice(amount);
    }

    /*
     设置输入金额事件
     */
    function registerRechargeEvent() {
        mpos.checkInputValue($rechargeAmount, InputType.Amount);
        mpos.checkInputValue(rechargeContainer.find("input[name='rechargeGiveAmount']"), InputType.Amount);
        $rechargeAmount.on("focus", function (ev) {
            presentInfo = {
                TicketStrategyId: 0,
                TicketTypeId: 0,
                TicketTypeName: "",
                TicketCount: 0,
                PresentAmount: 0,
            };
        });
        $rechargeAmount.on("blur", function (ev) {
            var rechargeAmount = getRechargeAmount();
            if (rechargeAmount == 0) { //人民币可以充0元，所以这里可以为0
                //重新构造赠送对象
                presentInfo = {
                    TicketStrategyId: 0,
                    TicketTypeId: 0,
                    TicketTypeName: "",
                    TicketCount: 0,
                    PresentAmount: 0,
                };
                setPresentUI();
                return;
            }
            $rechargeAmount.val(Number(rechargeAmount).toFixed(2));
            mpos.post(mpos.api.getRechargePresent, {
                Amount: rechargeAmount,
                CardId: currentSelectedMemberCard.MemberCardId
            }, function (data) {
                presentInfo = data;
                setPresentUI();
            });

        });

        rechargeContainer.find("input[name='rechargeGiveAmount']").on("keyup", function (ev) {
            if (rechargeContainer.find("input[name='checkGive']:checked").val() == "2") {
                return;
            }

            var rechargeAmount = getRechargeAmount();
            if (rechargeAmount < 0) {
                return;
            }
            var presentAmount = rechargeContainer.find("input[name='rechargeGiveAmount']").val().trim();
            if (presentAmount == "" || isNaN(presentAmount)) {
                presentAmount = 0;
            }
            rechargeContainer.find(".rechargeTotal").text(formatRechargeTotal(parseFloat(presentAmount) + parseFloat(rechargeAmount)));
        });

        rechargeContainer.find("input[name='checkGive']").on("click", function (ev) {
            var rechargeAmount = getRechargeAmount();

            var $target = $(ev.currentTarget);
            if ($target.val() == "2") {
                rechargeContainer.find("input[name='rechargeGiveAmount']").prop("readonly", true);
                rechargeContainer.find(".rechargeTotal").text(formatRechargeTotal(rechargeAmount));
            } else {
                var presentAmount = rechargeContainer.find("input[name='rechargeGiveAmount']").val().trim();
                if (presentAmount == "") {
                    presentAmount = 0;
                }
                presentAmount = parseFloat(presentAmount);

                if (presentAmount < 0) {
                    presentAmount = 0;
                }
                rechargeContainer.find("input[name='rechargeGiveAmount']").prop("readonly", false);
                rechargeContainer.find(".rechargeTotal").text(formatRechargeTotal(parseFloat(presentAmount) + parseFloat(rechargeAmount)));
            }
        });
    }

    /*
    设置赠送UI
    */
    function setPresentUI() {
        var rechargeAmount = getRechargeAmount();
        rechargeContainer.find("input[name='checkGive']").prop("checked", false);
        if (presentInfo.PresentAmount == 0 && (presentInfo.TicketTypeId > 0)) {
            rechargeContainer.find("input[name='checkGive'][value='2']").prop("checked", true);
            rechargeContainer.find("input[name='rechargeGiveAmount']").prop("readonly", true);
            rechargeContainer.find(".rechargeTotal").text(formatRechargeTotal(rechargeAmount));
            rechargeContainer.find("input[name='checkGive'][value='2']").prop("disabled", false);
        } else {
            rechargeContainer.find("input[name='checkGive'][value='1']").prop("checked", true);
            rechargeContainer.find(".rechargeTotal").text(formatRechargeTotal(parseFloat(presentInfo.PresentAmount) + parseFloat(rechargeAmount)));
            if (presentInfo.TicketTypeId == 0) { //没有票券，禁用选中票券
                rechargeContainer.find("input[name='checkGive'][value='2']").prop("disabled", true);
            } else {
                rechargeContainer.find("input[name='checkGive'][value='2']").prop("disabled", false);
            }
        }
        rechargeContainer.find("input[name='rechargeGiveAmount']").val(Number(presentInfo.PresentAmount).toFixed(2));
        rechargeContainer.find(".rechargeGiveTicket").text(presentInfo.TicketTypeName);
    }

    /*
     获取充值金额
     */
    function getRechargeAmount() {
        var rechargeAmount = $rechargeAmount.val().trim();
        if (rechargeAmount == "") {
            mpos.alert("请输入充值金额");
            return -1;
        }

        rechargeAmount = Number(parseFloat(rechargeAmount).toFixed(2));

        if (rechargeAmount < 0) {
            mpos.alert("充值金额不能小于0");
            return -1;
        }

        return rechargeAmount;
    }

    /*
     现金支付
     */
    function payForCash(paymentPattern) {
        mpos.showDialog(mpos.dialogPage.rechargeCashPay, {
            RechargeData: getRechargeData(paymentPattern),
        }, function (data) {
            rechargeResult(data);
        });
    }

    /*拉卡支付*/
    function payForLkl(paymentPattern) {
        mpos.showDialog(mpos.dialogPage.lklRechargePay, {
            RechargeData: getRechargeData(paymentPattern),
        }, function (data) {
            rechargeResult(data);
        });
    }

    /*微信支付支付*/
    function payForWxOrAliPay(paymentPattern) {
        mpos.showDialog(mpos.dialogPage.wxOrAliRechargePay, {
            RechargeData: getRechargeData(paymentPattern),
        }, function (data) {
            rechargeResult(data);
        });
    }

    /*
     获取充值数据
     */
    function getRechargeData(paymentPattern) {
        var rechargeAmount = getRechargeAmount();
        var presentAmount = 0;
        var presentType = rechargeContainer.find("input[name='checkGive']:checked").val();
        if (presentType == 1) {
            presentAmount = rechargeContainer.find("input[name='rechargeGiveAmount']").val().trim();
            if (presentAmount == "") {
                presentAmount = 0;
            }

            presentAmount = parseFloat(presentAmount);

            if (presentAmount < 0) {
                presentAmount = 0;
            }
            presentInfo.TicketStrategyId = 0;
            presentInfo.TicketTypeId = 0;
            presentInfo.TicketCount = 0;

        }

        return {
            // 充值金额
            Amount: rechargeAmount.toFixed(2),
            // 赠送金额
            PresentAmount: presentAmount.toFixed(2),

            // 赠送的票券方案ID
            TicketStrategyId: presentInfo.TicketStrategyId,

            // 赠送的票券ID
            TicketTypeId: presentInfo.TicketTypeId,

            // 赠送的票券数量
            TicketCount: presentInfo.TicketCount,

            //充值方案ID
            RechargeStrategyId: presentInfo.RechargeStrategyId,

            // 会员ID
            MemberId: currentSelectedMemberCard.MemberId,

            // 会员卡ID
            MemberCardId: currentSelectedMemberCard.MemberCardId,

            // 付款方式
            PaymentPatternId: paymentPattern.PaymentPatternId,

            // 赠送类型，1-充值赠送，2-票券赠送
            PresentType: presentType,

            //支付方式名称
            PaymentPatternName: paymentPattern.PaymentPatternName,
            Mobile: currentSelectedMemberCard.Mobile,
            MemberName: currentSelectedMemberCard.MemberName,
            MemberCardNo: currentSelectedMemberCard.MemberCardNo
        };
    }

    /*
     处理充值结果
     */
    function rechargeResult(data) {
        if (data != undefined && typeof data == "object") {
            if (data.Status == 1) { //充值成功
                mpos.alert("充值成功！");
                //打印
                var printNum = mpos.localStorage.RechargePrintNumber || 0;
                var printBills = data.PrintContent;
                if (Array.isArray(printBills) && printBills.length > 0) {
                    for (var i = 0; i < printNum; i++) { //打印多份
                        var printData = mpos.addPrintEmptyLine(printBills);
                        mpos.deviceFactory.printTicket(printData, null, function (err) {
                            mpos.alert(err);
                        });
                    }
                }
                mpos.replace(mpos.page.memberRecharge);
            } else if (data.Status == 2) { //充值失败，但钱已扣，可以在历史中重试或取消
                alert("充值金额已扣取，但充值失败，系统自动转跳到充值历史去处理");
                mpos.replace(mpos.page.rechargeList);
            } else { //充值失败
                mpos.alert(data.Message);
            }
        }
    }
});

/**
 现金充值对话框
 */
mpos.dialogController(mpos.dialogPage.rechargeCashPay, function (page, data) {
    var rechargeData = data.RechargeData;
    var $page = $(page);
    $page.find(">div.title").text(rechargeData.PaymentPatternName);
    $page.find(".rechargeAmount").text((parseFloat(rechargeData.Amount) + parseFloat(rechargeData.PresentAmount)).toFixed(2));
    $page.find(".payAmount").text(parseFloat(rechargeData.Amount).toFixed(2));
    //确定和取消事件
    $page.find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {
            mpos.post(mpos.api.rechargeNormalPay, {
                Amount: rechargeData.Amount,
                PresentAmount: rechargeData.PresentAmount,
                TicketStrategyId: rechargeData.TicketStrategyId,
                TicketTypeId: rechargeData.TicketTypeId,
                TicketCount: rechargeData.TicketCount,
                MemberId: rechargeData.MemberId,
                MemberCardId: rechargeData.MemberCardId,
                PaymentPatternId: rechargeData.PaymentPatternId,
                PresentType: rechargeData.PresentType,
                FormatMasterId: mpos.localStorage.RechargePrintId || 0,//打印格式ID
                Mobile: rechargeData.Mobile,
                MemberName: rechargeData.MemberName,
                MemberCardNo: rechargeData.MemberCardNo,
                RechargeStrategyId: rechargeData.RechargeStrategyId
            }, function (r) {
                mpos.dialog.close(r);
            });
        }
    });
});

/**
 微信或支付宝充值对话框
 */
mpos.dialogController(mpos.dialogPage.wxOrAliRechargePay, function (page, data) {
    var rechargeData = data.RechargeData;
    var $page = $(page);
    $page.find(">div.title").text(rechargeData.PaymentPatternName);
    $page.find(".rechargeAmount").text((parseFloat(rechargeData.Amount) + parseFloat(rechargeData.PresentAmount)).toFixed(2));
    $page.find(".payAmount").text(parseFloat(rechargeData.Amount).toFixed(2));

    var $payScan = $page.find(".pay-scan");
    var $payResultMsg = $page.find(".pay-result-msg");
    var currentRechargeId = 0;
    var setTimeoutVar = 0;
    var isPaying = false;
    var hasPay = false;
    var leftCloseSecond = 2;
    var setTimeoutCloseVar = null;
    var payResult = null;

    $payResultMsg.hide();

    /**
     扫描
     */
    $payScan.on("click", function (e) {
        mpos.scanQR(function (result) {
            result = typeof jsonModelScanResult == "object" ?
                jsonModelScanResult : result;
            if (result.cancelled == true) {
                return;
            }
            var barCode = result.text;
            $payResultMsg.show();
            $payResultMsg.text("正在支付......");
            mpos.post(mpos.api.beginWxOrAliRechargePay, {
                Amount: rechargeData.Amount,
                PresentAmount: rechargeData.PresentAmount,
                TicketStrategyId: rechargeData.TicketStrategyId,
                TicketTypeId: rechargeData.TicketTypeId,
                TicketCount: rechargeData.TicketCount,
                MemberId: rechargeData.MemberId,
                MemberCardId: rechargeData.MemberCardId,
                PaymentPatternId: rechargeData.PaymentPatternId,
                PresentType: rechargeData.PresentType,
                BarCode: barCode,
                Mobile: rechargeData.Mobile,
                MemberName: rechargeData.MemberName,
                MemberCardNo: rechargeData.MemberCardNo
            }, function (data) {
                if (data.RechargeId > 0) {
                    currentRechargeId = data.RechargeId;
                    beginPay();
                }
                else {
                    mpos.alert(data.Message);
                }
            });
        }, function (err) {
            mpos.alert("扫码错误!");
        });

    });

    //确定和取消事件
    $(page).find(".app-submit").on("click", function (e) {
        if (isPaying) {
            mpos.alert("正在充值，无法操作....");
            return;
        }
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            clearTimeout(setTimeoutVar);
            if (payResult != null) {
                mpos.dialog.close(payResult);
            } else {
                mpos.dialog.close(hasPay);
            }
        } else {
            clearTimeout(setTimeoutVar);
            if (payResult != null) {
                mpos.dialog.close(payResult);
            } else {
                mpos.dialog.close(hasPay);
            }
        }
    });

    /**
     开始付款
     */
    function beginPay() {
        isPaying = true;
        $payResultMsg.show();
        $payResultMsg.text("正在查询充值结果......");
        mpos.showLoading();
        setTimeoutVar = setTimeout(checkPayResult, 1500);
    }

    /**
     开始检查付款检查
     */
    function checkPayResult() {
        if (currentRechargeId > 0) {
            mpos.post(mpos.api.checkWxOrAliRechargePayResult, {
                RechargeId: currentRechargeId,
                FormatMasterId: mpos.localStorage.RechargePrintId || 0,//打印格式ID
            }, function (result) {
                if (result.PayStatus == OnlinePayStatus.PayStart) {
                    setTimeoutVar = setTimeout(checkPayResult, 1000);
                } else if (result.PayStatus == OnlinePayStatus.PayFail) {
                    clearTimeout(setTimeoutVar);
                    isPaying = false;
                    hasPay = true;
                    $payResultMsg.text("充值失败：" + result.Message);
                    payResult = result.Result;
                    mpos.hideLoading();
                    leftCloseSecond = -1;
                    autoClose();
                } else if (result.PayStatus == OnlinePayStatus.PaySuccess) {
                    clearTimeout(setTimeoutVar);
                    isPaying = false;
                    $payResultMsg.text("充值成功！");
                    mpos.hideLoading();
                    hasPay = true;
                    payResult = result.Result;
                    $payScan.hide();
                    leftCloseSecond = 2;
                    setTimeoutCloseVar = setTimeout(autoClose);
                } else if (result.PayStatus == OnlinePayStatus.PayCancel) {
                    clearTimeout(setTimeoutVar);
                    $payResultMsg.text("充值已取消！");
                    mpos.hideLoading();
                    isPaying = false;
                    hasPay = true;
                }
            });
        } else {
            clearTimeout(setTimeoutVar);
            isPaying = false;
            mpos.hideLoading();
        }
    }

    /**
     自动关闭
     */
    function autoClose() {
        if (leftCloseSecond <= 0) {
            clearTimeout(setTimeoutCloseVar);
            mpos.dialog.close(payResult);
            return;
        }
        $payResultMsg.text("充值成功！" + leftCloseSecond + "秒后自动关闭");
        leftCloseSecond -= 1;
        setTimeoutCloseVar = setTimeout(autoClose, 1000);
    }
});

/**
 拉卡拉充值对话框
 */
mpos.dialogController(mpos.dialogPage.lklRechargePay, function (page, data) {
    var rechargeData = data.RechargeData;
    var $page = $(page);
    $page.find(">div.title").text(rechargeData.PaymentPatternName);
    $page.find(".rechargeAmount").text((parseFloat(rechargeData.Amount) + parseFloat(rechargeData.PresentAmount)).toFixed(2));
    $page.find(".payAmount").text(parseFloat(rechargeData.Amount).toFixed(2));
    var $selectPaymentType = $page.find(".select-payment-type"); //拉卡拉付款选择
    //当不是拉卡拉时，不显示付款选择
    if (mpos.deviceFactory.deviceType != DeviceType.LklPayDevice) {
        mpos.alert("不支付此付款方式充值！");
        mpos.dialog.close(false);
        return;
    } else {
        if (!mpos.shopConfig.EnabledLakalaScanPay) { //没有启用时也不显示
            $selectPaymentType.remove();
        }
    }

    //确定和取消事件
    $page.find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close(false);
        } else {

            var paymentType = 1;
            if (mpos.deviceFactory.deviceType == DeviceType.LklPayDevice && mpos.shopConfig.EnabledLakalaScanPay) {
                paymentType = $page.find("input[name='selectPaymentType']:checked").val();
            }

            mpos.post(mpos.api.createLklRechargePay, {
                Amount: rechargeData.Amount,
                PresentAmount: rechargeData.PresentAmount,
                TicketStrategyId: rechargeData.TicketStrategyId,
                TicketTypeId: rechargeData.TicketTypeId,
                TicketCount: rechargeData.TicketCount,
                MemberId: rechargeData.MemberId,
                MemberCardId: rechargeData.MemberCardId,
                PaymentPatternId: rechargeData.PaymentPatternId,
                PresentType: rechargeData.PresentType,
                Mobile: rechargeData.Mobile,
                MemberName: rechargeData.MemberName,
                MemberCardNo: rechargeData.MemberCardNo
            }, function (config) {
                if (config == null || typeof config != 'object') {
                    return;
                }
                if (mpos.deviceFactory.deviceType == DeviceType.IboxPayDevice) {
                    mpos.alert("不支持的付款方式");
                    return;
                }
                if (config.OrderNo != "") {
                    mpos.showLoading();
                    mpos.isPaying = true;
                    var cfg = {
                        OrderNo: config.OrderNo,
                        PayAmount: config.PayAmount,
                        BoxConfig: config.BoxConfig,
                        PaymentType: paymentType
                    };
                    var rechargeId = config.RechargeId;
                    cfg.PayType = 1;
                    mpos.deviceFactory.payOrder(cfg, function (result) {
                        mpos.hideLoading();
                        mpos.isPaying = false;
                        $(page).find(".btn-repeal").show();
                        var cbOrderNo = result.CbOrderNo;
                        var usedPaymentType = result.PaymentType;
                        mpos.post(mpos.api.updateLklRechargePay, {
                            RechargeId: rechargeId,
                            IsOk: true,
                            TradeNo: cbOrderNo,
                            ErrMessage: "",
                            UsedPaymentType: usedPaymentType,
                            FormatMasterId: mpos.localStorage.RechargePrintId || 0,//打印格式
                        }, function (r) {
                            mpos.dialog.close(r.Result);
                        }, {
                            timeout: Config.importantBLTimeout
                        });
                    }, function (err) {
                        mpos.hideLoading();
                        mpos.isPaying = false;
                        mpos.post(mpos.api.updateLklRechargePay, {
                            RechargeId: rechargeId,
                            IsOk: false,
                            TradeNo: "",
                            ErrMessage: err,
                        }, function () {

                        }, {
                            timeout: Config.importantBLTimeout
                        });
                        mpos.alert(err);
                    })
                }
            });
        }
    });
});

/**
 * 消息列表页面
 * */
mpos.controller(mpos.page.messageList, function (page) {

    var currentMessageType = ConsumptionMessageType.Payment;
    var canLoadMore = true;
    var pageIndex = 1;
    var serviceMessageCount = 0;
    var paymentMessageCount = 0;
    var $list = $(page).find("ul.app-list.systemMessage-list");
    var $itemService = $list.find("li.service-list").remove();
    var $itemPayment = $list.find("li.payment-list").remove();
    var $loading = $(page).find(".scrollLoading").remove();
    $list.empty();
    //+++++++++++++++++++++++++++++++
    /*Tab标签切换事件*/
    //默认显示支付消息
    $(page).find("#tab-pay").addClass("message-current");
    var $tabPay = $(page).find("#tab-pay");
    var $tabCall = $(page).find("#tab-call");
    $(page).find(".message-action .app-button").on("click", function (e) {
        $(this).addClass("message-current");
        pageIndex = 1;
        if (e.currentTarget.id == "tab-pay") {
            $tabCall.removeClass("message-current");
            currentMessageType = ConsumptionMessageType.Payment;
        } else {
            $tabPay.removeClass("message-current");
            currentMessageType = ConsumptionMessageType.Service;
        }
        canLoadMore = true;
        $list.empty();
        loadNewMessageCount();
        getMessageList();
    });
    //+++++++++++++++++++++++++++++++

    loadNewMessageCount();
    getMessageList();
    /*
    加载新消息条数
    */
    function loadNewMessageCount() {
        mpos.post(mpos.api.getAllNewMessageCount, null, function (data) {
            if (data != undefined && data) {
                paymentMessageCount = data.PaymentCount;
                serviceMessageCount = data.ServiceCount;
                refreshNewMessageCount();
            }
        }, {
            hideLoading: true,
            error: function () { },
            blFailed: function () { }
        });
    }

    /*
    刷新新消息个数
    */
    function refreshNewMessageCount() {
        if (serviceMessageCount == 0) {
            $tabCall.find(".message-count").empty().hide();
        } else {
            $tabCall.find(".message-count").text("(" + serviceMessageCount + ")").show();
        }
        if (paymentMessageCount == 0) {
            $tabPay.find(".message-count").empty().hide();
        } else {
            $tabPay.find(".message-count").text("(" + paymentMessageCount + ")").show();
        }
        mpos.triggerEvent(mpos.event.messageCountChanged, serviceMessageCount + paymentMessageCount);
    }

    /**
    * 从服务端获取账单列表
    */
    function getMessageList() {
        mpos.infiniteScroll($list, {
            loading: $loading
        }, function (callback) {
            if (!canLoadMore)
                return null;

            mpos.post(mpos.api.findConsumptionMessages, {
                ConsumptionMessageType: currentMessageType,
                PageSize: Config.DefaultPageSize,
                PageIndex: pageIndex++
            }, function (data) {
                if (!Array.isArray(data)) {
                    mpos.alert("返回数据格式不对");
                    canLoadMore = false;
                    return;
                }
                var list = [];
                canLoadMore = data.length == Config.DefaultPageSize;
                data.forEach(function (item, index) {
                    if (currentMessageType == ConsumptionMessageType.Payment) {
                        var paymentItem = $itemPayment.clone();
                        paymentItem.find(".diningtable-number").text(item.TableName);
                        paymentItem.find(".message-time").text(item.TimeDesc);
                        paymentItem.find(".message-context").text(item.Content);
                        paymentItem.data("o_id", item.OrderId);
                        paymentItem.data("m_id", item.MessageId);
                        paymentItem.data("r", item.IsReader ? 1 : 0);
                        paymentItem.find(".list-read").empty();
                        if (!item.IsReader) {
                            paymentItem.find(".list-read").html("<span class='is-read'></span>");
                        }
                        paymentItem.tap(function (e) {
                            var target = $(e.currentTarget);
                            var orderId = target.data("o_id");
                            var mid = target.data("m_id");
                            if (target.data("r") == 0) {
                                mpos.post(mpos.api.setMessageReader, {
                                    MessageId: mid
                                }, function () {
                                    if (paymentMessageCount > 0) {
                                        paymentMessageCount--;
                                        refreshNewMessageCount();
                                    }
                                    paymentItem.find(".list-read").empty();
                                    gotoSettle(orderId);
                                })
                            } else {
                                gotoSettle(orderId);
                            }
                        });
                        list.push(paymentItem);
                    } else {
                        var serviceItem = $itemService.clone();
                        serviceItem.find(".diningtable-number").text(item.TableName);
                        serviceItem.find(".message-time").text(item.TimeDesc);
                        serviceItem.find(".message-context").html('收到<span class="server-mark">' + item.Content + '</span>服务，请尽快处理！');
                        serviceItem.data("o_id", item.OrderId);
                        serviceItem.data("m_id", item.MessageId);
                        serviceItem.data("s", item.HasService ? 1 : 0);
                        serviceItem.data("r", item.IsReader ? 1 : 0);
                        serviceItem.data("j", item.NeedToJump ? 1 : 0);
                        serviceItem.find(".list-read").empty();
                        if (!item.IsReader) {
                            serviceItem.find(".list-read").html("<span class='is-read'></span>");
                        }
                        var messageright = serviceItem.find(".message-right");
                        if (item.HasService) {
                            messageright.empty();
                            messageright.html("<span class='server-status'>已服务</span><span class='server-staff textEllipsis'>" + item.ServiceUser + "</span>");
                        }
                        var serviceButton = messageright.find(".app-button.server-button");
                        serviceButton.tap(function (e) {
                            var parentContent = $(e.currentTarget).parents("li.service-list");
                            var rightContent = $(e.currentTarget).parent();
                            var jump = parentContent.data("j");
                            var orderId = parentContent.data("o_id");
                            var mid = parentContent.data("m_id");
                            var hasRead = parentContent.data("r");
                            if (parentContent.data("s") == 0) {//我来服务
                                mpos.post(mpos.api.setMessageToServiced, {
                                    MessageId: mid
                                }, function () {
                                    rightContent.html("<span class='server-status'>已服务</span><span class='server-staff textEllipsis'>" + mpos.currentUser.LoginName + "-" + mpos.currentUser.UserName + "</span>");
                                    parentContent.data("s", "1");
                                });
                                if (serviceMessageCount > 0) {
                                    serviceMessageCount--;
                                    refreshNewMessageCount();
                                }
                                if (hasRead == 0) {
                                    parentContent.find(".list-read").empty();
                                    parentContent.data("r","1");
                                }
                                if (jump == 1) {
                                    gotoSettle(orderId);
                                }
                            }
                            e.stopPropagation()
                        });
                        serviceItem.tap(function (e) {
                            var target = $(e.currentTarget);
                            var jump = target.data("j");
                            var orderId = target.data("o_id");
                            var mid = target.data("m_id");
                            var hasRead = target.data("r");
                            if (hasRead == 0) {
                                mpos.post(mpos.api.setMessageReader, {
                                    MessageId: mid
                                }, function () {
                                    target.find(".list-read").empty();
                                    if (serviceMessageCount > 0) {
                                        serviceMessageCount--;
                                        refreshNewMessageCount();
                                    }
                                    target.data("r","1");
                                    if (jump == 1) {
                                        gotoSettle(orderId);
                                    }
                                });
                            } else {
                                if (jump == 1) {
                                    gotoSettle(orderId);
                                }
                            }
                        });
                        list.push(serviceItem);
                    }
                });
                callback(list);

            }, {
                hideLoading: true
            });
        });
    }

    /*
    转跳到结账
    */
    function gotoSettle(orderId) {
        mpos.post(mpos.api.findDiningTable, {
            TableId: 0,
            OrderId: orderId
        }, function (data) {
            if (data == null || data == undefined) {
                mpos.alert("该餐台已结账");
            } else {
                mpos.jumpToSettlePage(orderId, "home");
            }
        });
    }
});

/**
 点菜数据操作对象
 */
mpos.OrderDishData = {
    createNew: function () {
        var orderDishData = {};
        /**
         订单ID集合
         */
        orderDishData.OrderIds = [];
        /**
         * 订单ID
         */
        orderDishData.OrderId = 0;

        /**
         * 餐台ID
         */
        orderDishData.TableId = 0;

        /**
         本次点菜的会话
         */
        orderDishData.SessionId = "";

        /**
         * 在线订单ID
         */
        orderDishData.OnlineOrderId = 0;

        /**
         * 是否为快餐点菜
         */
        orderDishData.IsSnackOrderDish = false;

        /**
         * 原始菜品数据
         */
        orderDishData.orderDishData = null;
        /**
         * 点菜配置
         */
        orderDishData.orderConfig = null;
        /**
         * 菜品数据
         */
        orderDishData.dishes = null;
        /**
         * 菜品类型
         */
        orderDishData.dishTypes = null;
        /**
         * 菜品大类
         */
        orderDishData.dishBigTypes = null;
        /**
         * 会员卡
         */
        orderDishData.memberCard = null;
        /**
         * 沽清菜品
         */
        orderDishData.saleOutDishes = null;
        /**
         * 沽清单位
         */
        orderDishData.saleOutUnits = null;
        /**
         * 做法
         */
        orderDishData.cookings = null;
        /**
         * 做法类型
         */
        orderDishData.cookingTypes = null;
        /**
         * 购车物中的菜品
         对象：
         {
            OrderDishId:0,//主键ID
            DishId:0, //菜品ID
            DishPortionsId:0, //单位ID
            DishPortions:"", //单位名称
            DishName:"", //菜品名称
            DishSaleAmount:0, //菜品金额
            DishNum:0, //菜品数量
            NormalDiscount:100,
            MemberDiscount:100,
            Discount:100,
            PriceType:1, //价格类型
            PriceOfferId:1,价格方案ID,
            SalePrice:10,//销售单价
            IsFreeDish:0,赠送类型
            MemberPrice:0, //会员价
            SpecialPrice:0, //特价
            DishPriceOrg:0, //原价
            DishPriceAdd:0,//加价
            CookingPrice:0,//做法加价
            TeaType:1,//茶芥类型
            OnlineOrderDishId:0,//线上菜品ID
            OnlineOrderId:0,//线上订单ID
            DishProperty:1, //菜品属性1-正常菜，2-套餐子菜，3-一品多吃主菜，4-一品多吃子菜，5-套餐主菜，
            KitchenRemark:1,厨房备注,
            ReplacePackageDishId:0,//套餐替换ID
            IsConfirmWeight:0,//称重，1-不需要称重，2-需称重，但未确认称重，3-已称重
            DiscountType:0,//折扣类型 0 - 系统折扣 2- 折扣方案 3- 整单折扣 4- 手动折扣  5- 比例折扣,
            DishRequestList:[
                 {
                    RequestId = 0,
                    RequestName = "",
                    RequestNum = 0,
                    RequestPrice = 0,
                 }
            ]
         }
         */
        orderDishData.ShoppingCarDishes = [];

        /**
         * 已点菜品，用于展示用
         * */
        orderDishData.AlreadyOrdered = [];

        /**
         * 点一个菜
         */
        orderDishData.orderOneDish = function (dish, dishNum, p) {
            if (dish == undefined || p == undefined) {
                return null;
            }
            var dishModel = {};

            dishModel.DishId = dish.Dish.DishId; //菜品ID
            dishModel.DishPortionsId = p.PortionsId; //单位ID
            dishModel.DishPortions = p.PortionsName; //单位名称
            dishModel.DishName = dish.Dish.DishName; //菜品名称
            dishModel.DishNum = dishNum; //菜品数量
            dishModel.IsTemporary = dish.Dish.IsTemporary || 0; //临时菜品标识
            dishModel.IsRandomPrice = dish.Dish.IsRandomPrice || 0; //时价菜品标识
            dishModel.NormalDiscount = p.Discount;
            dishModel.MemberDiscount = p.MemberDiscount;
            dishModel.Discount = p.Discount * p.MemberDiscount / 100;
            dishModel.PriceType = p.PriceType; //价格类型
            dishModel.PriceOfferId = p.CurrentSchemeId; //价格方案ID,
            dishModel.SalePrice = p.CurrentPrice; //销售单价
            dishModel.IsFreeDish = 0; //赠送类型,0非赠送，1-赠送，3-兑换
            dishModel.OperatorAuthorizer = 0; //操作授权人
            dishModel.AuthorizeTime = 0; //操作授权时间
            dishModel.OperationReasonId = 0; //操作原因
            dishModel.MemberPrice = p.MemberPrice; //会员价
            dishModel.SpecialPrice = p.SpecialPrice; //特价
            dishModel.DishPriceOrg = p.NormalPrice; //原价
            dishModel.DishPriceAdd = 0; //加价
            dishModel.CookingPrice = 0; //做法加价
            dishModel.TeaType = 0; //茶芥类型
            dishModel.OnlineOrderDishId = 0; //线上菜品ID
            dishModel.OnlineOrderId = 0; //线上订单ID
            dishModel.DishProperty = 1; //菜品属性1-正常菜，2-套餐子菜，3-一品多吃主菜，4-一品多吃子菜，5-套餐主菜，
            dishModel.IsMultiDish = 0; //菜品是否是一品多吃 1=是， 0=不是
            dishModel.IsMultiMainDish = 0; //菜品是否是一品多吃主菜 1=是， 0=不是
            dishModel.KitchenRemark = 0; //厨房备注,
            dishModel.ReplacePackageDishId = 0; //套餐替换ID
            dishModel.IsConfirmWeight = dish.Dish.IsConfirmWeight == 1 ? 2 : 1; //称重，1-不需要称重，2-需称重，但未确认称重，3-已称重
            dishModel.DishRequestList = [];
            dishModel.DiscountType = p.DiscountType;
            dishModel.DiscountSchemeId = 0;
            dishModel.MemberCouponOfferId = p.MemberSchemeId;
            dishModel.OperationAuthorizers = [];
            dishModel.BelongOrderDishId = 0;
            dishModel.PackageDishId = 0;
            dishModel.ReturnOrderDishId = 0;
            if (dishModel.MemberDiscount < 100 && !this.canRateDiscount(dishModel)) {
                dishModel.MemberDiscount = 100;
                dishModel.Discount = 100;
                dishModel.DiscountType = 0;
            }

            if (dishModel.MemberDiscount < 100) {
                dishModel.MemberCouponOfferId = p.MemberDiscountSchemeId;
            }

            if (dish.Dish.IsMultiDish == 1) {
                dishModel.DishProperty = OrderDishProperty.MultiDishMain;
                dishModel.IsMultiDish = dish.Dish.IsMultiDish; //菜品是否是一品多吃 1=是， 0=不是
                dishModel.IsMultiMainDish = dish.Dish.IsMultiMainDish; //菜品是否是一品多吃主菜 1=是， 0=不是
                orderDishData.DishProperty = OrderDishProperty.MultiDishMain;
            } else if (dish.Dish.DishProperty == 2) {
                orderDishData.DishProperty = 3;
            } else if (dish.Dish.DishProperty == 3) {
                orderDishData.DishProperty = 4;
            } else if (dish.Dish.PackageCategory > 0) {
                orderDishData.DishProperty = 5;
            }

            dishModel.OrderDishId = this.getMaxOrderDishId() + 1; //主键ID
            dishModel.DishSaleAmount = this.calculateDishSaleAmount(dishModel); //菜品金额

            return dishModel;
        };

        /**
         计算订单金额
         */
        orderDishData.calculateDishAmount = function (dishModel) {
            var me = this;
            var multiSubDishSaleAmount = 0; // 一品多吃子菜的价格
            dishModel.CookingPrice = Number(0.00);
            if (dishModel.DishRequestList && dishModel.DishRequestList.length > 0) {
                dishModel.DishRequestList.forEach(function (item) {
                    var c = me.getCookingById(item.RequestId);
                    // 一品多吃的做法数量不能跟着主菜数量变 dishModel.IsMultiDish != 1
                    if (c != null && c.IsRequestNumWithDish == 1 && dishModel.IsMultiDish != 1) {
                        // 做法数量可手输
                        if (c.IsRequestNum == 1) {
                          if (item.BaseRequestNum) {  // 做法基础数量
                            item.RequestNum = item.BaseRequestNum * dishModel.DishNum;
                          }
                        } else {
                          item.RequestNum = dishModel.DishNum;
                        }
                    }
                    dishModel.CookingPrice += Number((item.RequestNum * item.RequestPrice).toFixed(2));
                });
            }
            if (dishModel.DishProperty == OrderDishProperty.PackageDishMain) {
                // 套餐
                var subDishes = this.getPackageSubDishes(dishModel.OrderDishId);
                // 套餐子商品计算做法加价
                subDishes.forEach(function (sub) {
                    if (sub.DishRequestList && sub.DishRequestList.length > 0) {
                        sub.DishRequestList.forEach(function (item) {
                            var c = me.getCookingById(item.RequestId);
                            var requestNum = item.RequestNum;  // 做法数量
                            // 计算做法数量时，不进行修改，因为购物车循环计算价格时会对子商品进行计算此时会修改做法数量和价格
                            if (c != null && c.IsRequestNumWithDish == 1) {
                                // 做法数量可手输
                                if (c.IsRequestNum == 1) {
                                  if (item.BaseRequestNum) {  // 做法基础数量
                                    requestNum = item.BaseRequestNum * sub.DishNum;
                                  }
                                } else {
                                  requestNum = sub.DishNum;
                                }
                            }
                            // 套餐主菜中子商品做法加价
                            dishModel.CookingPrice += Number((requestNum * item.RequestPrice).toFixed(2));
                        });
                    }
                });
            } else if (dishModel.DishProperty == OrderDishProperty.MultiDishMain) {
                //一品多吃
                var subDishes = this.getMultiSubDishes(dishModel.OrderDishId);
                subDishes.forEach(function (item) {
                    multiSubDishSaleAmount += me.calculateDishSaleAmount(item);
                });
            }
            // 计算商品总价格
            dishModel.DishSaleAmount = this.calculateDishSaleAmount(dishModel) + multiSubDishSaleAmount; //菜品金额
        };

        /**
         计算购物车菜品金额
         */
        orderDishData.calculateShoppingCarDishAmount = function () {
            var me = this;
            this.ShoppingCarDishes.forEach(function (item) {
                me.calculateDishAmount(item);
            });
        };

        /**
         计算金额
         */
        orderDishData.calculateDishSaleAmount = function (dishModel) {
            var num = Number(dishModel.DishNum);
            if (dishModel.IsFreeDish == IsFreeDishType.Present) {
                return 0.00;
            }
            var price = Number(dishModel.SalePrice || 0);  // 存酒时没有价格所以为了兼容增加了0
            var money = price * Math.abs(num);
            var isConfirmWeightDish = dishModel.IsConfirmWeight == 2;
            if (isConfirmWeightDish) //称重菜
            {
                switch (this.orderConfig.WeightDishRoundRule) {
                    case 3: //到角
                        money = Math.ceil(money / 0.1) * 0.1;
                        break;
                    case 1: //到十元
                        money = Math.ceil(money / 10) * 10;
                        break;
                    case 2: //到元
                        money = Math.ceil(money / 1) * 1;
                        break;
                    case 0:
                    default:
                        break;
                }
            }

            money = (money * (num < 0 ? -1 : 1));
            var cookiePrice = Number(dishModel.CookingPrice);
            if (mpos.shopConfig.CookingNotUseCanRateDiscount) {
                //先除去会员折扣部分
                var discount = (dishModel.NormalDiscount);
                //是否为比例
                if (dishModel.DiscountType != 2 && dishModel.DiscountType != 5) {
                    cookiePrice = cookiePrice * discount / 100;
                }
            } else {
                cookiePrice = cookiePrice * dishModel.Discount / 100;
            }

            money = (money * dishModel.Discount / 100) + cookiePrice;

            return Number((money).toFixed(2));
        };

        /**
         是否允许比例折
         */
        orderDishData.canRateDiscount = function (dishModel) {
            var dish = this.getDish(dishModel.DishId);
            var rateDiscount = false;
            rateDiscount = dish.Dish.IsRateDiscount == 1;
            if (rateDiscount) {
                if (dishModel.PriceType == 2) { //特价方案是否允许比例折扣
                    var schemes = this.orderConfig.SpecialSchemeDiscount;
                    for (var i = 0; i < schemes.length; i++) {
                        if (schemes[i].Id == dishModel.PriceOfferId) {
                            return schemes[i].IsDiscount == 1;
                        }
                    }
                    return false;
                }
            }

            return rateDiscount;
        };

        /**
         检查菜品是否已沽清
         */
        orderDishData.checkIsSaleOut = function (dishId, unitId, dishNum) {
            var saleOutNum = this.getCanSaleDishNum(dishId);
            var dish = this.getDish(dishId);
            if (saleOutNum == -1) { //没有设置沽清
                return "";
            } else if (saleOutNum == 0) { //已卖完
                return dish.Dish.DishName + " 已经卖完";
            } else {
                var saleOutInfo = this.getDishSaleOutData(dishId, true);
                var num = dishNum * saleOutInfo["u_" + unitId];
                if (num > saleOutNum) {
                    return dish.Dish.DishName + " 销售数量不足";
                }
            }

            return "";
        };

        /**
         * 检查是否存在线上订单的菜品在购物车中
         */
        orderDishData.IsExistsOnlineOrderDish = function () {
            var exists = false;
            if (this.OnlineOrderId > 0) {
                for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                    if (this.ShoppingCarDishes[i].OnlineOrderId == this.OnlineOrderId) {
                        exists = true;
                        break;
                    }
                }
            }

            return exists;
        };

        /**
         *
         * 删除购物车内的菜品
         * @param orderDishIds
         */
        orderDishData.removeShopCartDishes = function (orderDishIds) {
            for (var j = 0; j < orderDishIds.length; j++) {
                for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                    if (this.ShoppingCarDishes[i].OrderDishId == orderDishIds[j]) {
                        this.ShoppingCarDishes.splice(i, 1);
                        break;
                    }
                }
            }
        };

        /**
         * 处理点菜的返回值
         * @param orderDishes
         */
        orderDishData.mergeShopCardDishes = function (orderDishes) {
            var newDishes = [];
            newDishes = this.ShoppingCarDishes.slice();
            var index = 0;
            for (var j = 0; j < orderDishes.length; j++) {
                var exists = false;
                for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                    if (this.ShoppingCarDishes[i].OrderDishId == orderDishes[j].OrderDishId) {
                        newDishes.splice(i, 1, orderDishes[j]);
                        if (orderDishes[j].IsMainPackage) { //处理套餐的插入
                            index = i;
                        } else {
                            index = 0;
                        }
                        exists = true;
                        break;
                    }
                }
                if (!exists) {
                    if (index == 0) {
                        newDishes.push(orderDishes[j]);
                    } else { //这里主要是处理套餐
                        newDishes.splice(index + 1, 0, orderDishes[j]);
                    }
                }
            }
            this.ShoppingCarDishes = newDishes.slice();
        };

        /**
         * 获取购物车中的点菜
         * （不包括茶和套餐子菜）
         * @param dishId
         * @param unitId
         * @return {Array} 菜品数组
         */
        orderDishData.getShoppingCarDish = function (dishId, unitId) {
            var orderDishes = [];
            if (unitId == undefined) {
                unitId = 0;
            }
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                if (this.ShoppingCarDishes[i].TeaType == OrderDishTeaType.Tea) { //茶不包括
                    continue;
                }
                if (this.ShoppingCarDishes[i].DishProperty == OrderDishProperty.PackageDishChild) { //套餐子菜不包括
                    continue;
                }
                if (this.ShoppingCarDishes[i].DishProperty == OrderDishProperty.MultiDishChild) { //一品多吃子菜不包括
                    continue;
                }
                if (this.ShoppingCarDishes[i].DishId == dishId) {
                    if (unitId > 0) {
                        if (unitId == this.ShoppingCarDishes[i].DishPortionsId) {
                            orderDishes.push(this.ShoppingCarDishes[i]);
                        }
                    } else {
                        orderDishes.push(this.ShoppingCarDishes[i]);
                    }
                }
            }

            return orderDishes;
        };

        /**
         获取最大点菜ID
         */
        orderDishData.getMaxOrderDishId = function () {
            if (this.ShoppingCarDishes.length == 0) {
                return 0;
            }
            var maxId = 0;
            this.ShoppingCarDishes.forEach(function (item) {
                if (typeof item.OrderDishId == 'string' && item.OrderDishId.length > 16) {
                    // 后端生成的 OrderDishId是字符串，长度超过js number 类型的最大长度，所以这里跳过
                } else if (item.OrderDishId > maxId) {
                    maxId = Number(item.OrderDishId || 0);
                } 
                
            });

            return maxId;
        }

        /**
         获取购物车菜品ID
         */
        orderDishData.getShoppingCardDishIds = function () {
            var dishIds = [];
            this.ShoppingCarDishes.forEach(function (item) {
                dishIds.push(item.DishId);
            });

            return dishIds;
        }

        /**
         获取购物车中的点菜
         */
        orderDishData.getShoppingCarDishByOrderDishId = function (orderDishId) {
            var orderDishes = [];
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                if (this.ShoppingCarDishes[i].OrderDishId == orderDishId) {
                    orderDishes.push(this.ShoppingCarDishes[i]);
                    break;
                }
            }
            if (orderDishes.length == 1) {
                return orderDishes[0];
            }

            return null;
        };

        /**
         * 获取购物车中的一品多吃的子菜
         * @orderDishId
         * @packageDishId  主菜ID
         */
        orderDishData.getShoppingCarMultiSubDishByOrderDishId = function (orderDishId, packageDishId) {
            var orderDishes = [];
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                if (this.ShoppingCarDishes[i].BelongOrderDishId == orderDishId && this.ShoppingCarDishes[i].PackageDishId == packageDishId) {
                    orderDishes.push(this.ShoppingCarDishes[i]);
                }
            }
            return orderDishes || [];
        };

        /**
         获取购物车中的已下单的菜
         */
        orderDishData.getShoppingCarAlreadyDishByOrderDishId = function (orderDishId) {
            var orderDishes = [];
            for (var i = 0; i < this.AlreadyOrdered.length; i++) {
                if (this.AlreadyOrdered[i].OrderDishId == orderDishId) {
                    orderDishes.push(this.AlreadyOrdered[i]);
                    break;
                }
            }
            if (orderDishes.length == 1) {
                return orderDishes[0];
            }

            return null;
        };


        /**
         获取套餐子菜
         */
        orderDishData.getPackageSubDishes = function (orderDishId) {
            var orderDishes = [];
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                if (this.ShoppingCarDishes[i].DishProperty == OrderDishProperty.PackageDishChild &&
                  this.ShoppingCarDishes[i].BelongOrderDishId == orderDishId) {
                    orderDishes.push(this.ShoppingCarDishes[i]);
                }
            }

            return orderDishes;
        };

        /**
         获取一品多吃子菜
         */
        orderDishData.getMultiSubDishes = function (orderDishId) {
            var orderDishes = [];
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                if (this.ShoppingCarDishes[i].DishProperty == OrderDishProperty.MultiDishChild &&
                  this.ShoppingCarDishes[i].BelongOrderDishId == orderDishId) {
                    orderDishes.push(this.ShoppingCarDishes[i]);
                }
            }

            return orderDishes;
        };

        /**
         获取菜品价格
         */
        orderDishData.getDishPrice = function (dish) {
            var units = dish.Units;
            for (var i = 0; i < units.length; i++) {
                if (units[i].IsDefault) {
                    return units[i].CurrentPrice;
                }
            }

            return units[0].CurrentPrice;
        };

        /**
         * 查找购物车中的商品不在销售方案中
         * */
        orderDishData.invalidDishFromShoppingCar = function () {
            var invalidDish = null;
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                var tempDish = this.ShoppingCarDishes[i];
                if (tempDish.DishProperty == OrderDishProperty.PackageDishChild || tempDish.DishProperty == OrderDishProperty.MultiDishChild) {
                    continue;
                }
                var dish = this.dishes.find(function (item, index) {
                    return item.Dish.DishId == tempDish['DishId'];
                });
                if (dish == null) {
                    invalidDish = tempDish;
                    break;
                }
            }
            if (invalidDish) {
                var logContent = {
                    ErrorName: 'MPOS前端日志.',
                    Dish: invalidDish,
                    DishList: this.dishes
                };

                mpos.post(mpos.api.SaveJsLog, {
                    ErrorMsg: JSON.stringify(logContent),
                    LogType: 0,
                }, function (res) {
                    console.log(res);
                });

                mpos.alert(invalidDish.DishName + ' 已停售，请移除购物车中该商品');
            }
            return invalidDish;
        };

        /**
         获取菜品
         */
        orderDishData.getDish = function (dishId) {
            var dish = this.dishes.filter(function (item, index) {
                return item.Dish.DishId == dishId;

            });
            if (dish == null || dish.length == 0) {
                //mpos.alert("未找到菜品");
                return null;
            }
            return dish[0];
        };

        /**
         获取菜品
         */
        orderDishData.getDishBySerial = function (dishSerial) {
            var dish = this.dishes.filter(function (item, index) {
                return item.Dish.DishSerial == dishSerial;

            });
            if (dish == null || dish.length == 0) {
                //mpos.alert("未找到菜品");
                return null;
            }
            return dish[0];
        };

        /**
         获取单位
         */
        orderDishData.getUnit = function (baseDish, unitId) {
            var units = baseDish.Units.filter(function (item, index) {
                return item.PortionsId == unitId;
            });
            if (units == null || units.length == 0) {
                return null;
            }
            return units[0];
        }

        /**
         从基础资料中获取菜品
         */
        orderDishData.getFromBaseDish = function (dishId) {
            var dish = mpos.BaseData.Dishes[dishId];
            if (dish == undefined) {
                return null;
            }
            return dish;
        };

        /**
         获取菜品类型
         */
        orderDishData.getDishType = function (dishTypeId) {
            var dishType = this.dishTypes.filter(function (item, index) {
                return item.DishTypeId == dishTypeId;

            });
            if (dishType == null || dishType.length == 0) {
                mpos.alert("未找到商品类别");
                return null;
            }
            return dishType[0];
        };

        /**
         获取做品做法
         */
        orderDishData.getDishCookings = function (dishId) {
            var dish = this.getDish(dishId);
            if (dish != null) {
                if (dish.DishCookings.length == 0) {
                    return null;
                } else {
                    var dc = [];
                    for (var i = 0; i < this.cookings.length; i++) {
                        for (var j = 0; j < dish.DishCookings.length; j++) {
                            if (this.cookings[i].RequestId == dish.DishCookings[j]) {
                                dc.push(this.cookings[i]);
                            }
                        }
                    }

                    return dc;
                }
            }
            return null;
        };

        /**
         获取菜品沽清信息
         @param {Number} dishId 菜品ID
         @param {Boolean} [getAllUnitRate] 是否获取所有单位的扣减比例，默认为false
         */
        orderDishData.getDishSaleOutData = function (dishId, getAllUnitRate) {
            if (getAllUnitRate == undefined) {
                getAllUnitRate = false;
            }
            var saleOutValue = {};
            if (!this.saleOutDishes) {
                return null;
            }
            var saleOutDish = this.saleOutDishes.filter(function (item, index) {
                return item.DishId == dishId;

            });
            //没有沽清数据
            if (saleOutDish == null || saleOutDish.length == 0) {
                return null;
            }
            //有沽清数据
            var _saleoutdish = saleOutDish[0];
            if (_saleoutdish.SaleOutType == DishSaleOutType.SaleOut) { //绝对沽清了
                var dish = this.getDish(dishId);
                if (!dish) {
                    return null;
                }
                saleOutValue["u_0"] = 0;
                for (var i = 0; i < dish.Units.length; i++) {
                    saleOutValue["u_" + dish.Units[i].PortionsId] = 0;
                }
            } else { //数量沽清
                var dish = this.getDish(dishId);
                if (!dish) {
                    return null;
                }
                saleOutValue["u_0"] = _saleoutdish.Num; //表示总共可扣多少

                if (_saleoutdish.IsWeight == 1 && dish.Dish.IsConfirmWeight) { //称重菜算一份
                    if (getAllUnitRate) {
                        for (var i = 0; i < dish.Units.length; i++) {
                            saleOutValue["u_" + dish.Units[i].PortionsId] = 1; //每份扣减的比例
                        }
                    }
                } else if (_saleoutdish.IsPortions == 1) { //多份量沽清
                    if (getAllUnitRate && this.saleOutUnits) {
                        for (var i = 0; i < this.saleOutUnits.length; i++) {
                            if (this.saleOutUnits[i].DishId == dishId) { //增加单位的沽清信息
                                saleOutValue["u_" + this.saleOutUnits[i].DishPortionsId] = this.saleOutUnits[i].Num; //每份扣减的比例
                            }
                        }
                    }
                } else {
                    if (getAllUnitRate) {
                        for (var i = 0; i < dish.Units.length; i++) {
                            saleOutValue["u_" + dish.Units[i].PortionsId] = 1; //每份扣减的比例
                        }
                    }
                }
            }

            return saleOutValue;
        };

        /**
         获取可以卖的菜品的数量
         返回说明：
         -1表示没有沽清设置
         0表示沽清了
         大于0表示可用数量
         */
        orderDishData.getCanSaleDishNum = function (dishId) {
            var saleOutInfo = this.getDishSaleOutData(dishId, true);
            if (saleOutInfo == null) {
                return -1;
            }
            if (saleOutInfo["u_0"] == 0) {
                return 0;
            }
            var num = saleOutInfo["u_0"];
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                if (this.ShoppingCarDishes[i].TeaType == OrderDishTeaType.Tea) { //茶不沽清
                    continue;
                }
                if (this.ShoppingCarDishes[i].DishId == dishId) { //得到沽清数量
                    if (saleOutInfo["u_" + this.ShoppingCarDishes[i].DishPortionsId]) {
                        num -= (saleOutInfo["u_" + this.ShoppingCarDishes[i].DishPortionsId] * this.ShoppingCarDishes[i].DishNum).toFixed(4);
                    }
                }
            }

            return num <= 0 ? 0 : parseFloat(num.toFixed(4));
        };

        /**
         获取已点菜数量
         @param {Number} dishId
         */
        orderDishData.getHasSelectDishNum = function (dishId) {
            var dishNum = 0;
            var dishTypeNum = 0;
            var dish = this.getDish(dishId);
            if (!dish) return null;
            var totalCostPrice = 0;
            var totalPrice = 0;
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                if (this.ShoppingCarDishes[i].DishProperty == OrderDishProperty.PackageDishChild) {
                    // 套餐子菜
                    continue;
                } else if (this.ShoppingCarDishes[i].DishProperty == OrderDishProperty.MultiDishChild) {
                    // 一品多吃子菜
                    continue;
                }
                var shoppingCarDish = this.getDish(this.ShoppingCarDishes[i].DishId);
                // 开启了大类筛选时，显示的分类不一定能找到对应菜品
                if (shoppingCarDish) {
                    if (this.ShoppingCarDishes[i].TeaType == OrderDishTeaType.Tea) {
                        if (dish.Dish.DishTypeId == shoppingCarDish.Dish.DishTypeId) {
                            dishTypeNum += this.ShoppingCarDishes[i].DishNum;
                        }
                        continue;
                    }
                    if (this.ShoppingCarDishes[i].DishId == dishId) {
                        dishNum += this.ShoppingCarDishes[i].DishNum;
                        var costPrice = this.getEstimatedCostPrice(dish, this.ShoppingCarDishes[i].DishPortionsId);
                        if (costPrice > 0) {
                            totalCostPrice += (this.ShoppingCarDishes[i].SalePrice - costPrice);
                            totalPrice += this.ShoppingCarDishes[i].SalePrice;
                        }
                    }
                    if (dish.Dish.DishTypeId == shoppingCarDish.Dish.DishTypeId) {
                        dishTypeNum += this.ShoppingCarDishes[i].DishNum;
                    }
                }
            }

            return {
                "DishNums": dishNum.toFixed(4),
                "EstimatedCostRate": (totalPrice > 0 && totalCostPrice > 0) ? (((totalCostPrice / totalPrice) * 100).toFixed(2) + "%") : "-",
                "DishTypeId": dish.Dish.DishTypeId,
                "DishTypeNum": Number(dishTypeNum).toFixed(4),
            };
        };

        /**
         * 获取菜预估成本金额
         * @param {any} dishId
         * @param {any} unitId
         */
        orderDishData.getEstimatedCostPrice = function (dish, unitId) {
            var units = dish.Units.filter(function (item, index) {
                return item.PortionsId == unitId;
            });
            if (units == null || units.length == 0) {
                return -1;
            }
            return units[0].EstimatedCost;
        }

        /**
         * 获取购物车菜品数量
         */
        orderDishData.getShopCartDishNum = function () {
            var dishNum = 0;
            var totalConsumptionAmt = 0;
            var totalCostPrice = 0;
            var totalPrice = 0;
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                if (this.ShoppingCarDishes[i].DishProperty == OrderDishProperty.PackageDishChild) {
                    // 套餐子菜数量不统计
                    continue;
                }
                if (this.ShoppingCarDishes[i].DishProperty == OrderDishProperty.MultiDishChild) {
                    // 一品多吃子菜数量不统计
                    continue;
                }
                var dish = this.getDish(this.ShoppingCarDishes[i].DishId);
                // 开启了大类筛选时，购物车中的数据和切换的大类数据，不一定一直，所有，找不到菜品也正常
                if (!dish && mpos.localStorage.enableBigDishTypes) {
                    dishNum += this.ShoppingCarDishes[i].DishNum;
                } else {
                    dishNum += this.ShoppingCarDishes[i].DishNum;
                    var costPrice = this.getEstimatedCostPrice(dish, this.ShoppingCarDishes[i].DishPortionsId);
                    if (costPrice > 0) {
                        totalCostPrice += (this.ShoppingCarDishes[i].SalePrice - costPrice);
                        totalPrice += this.ShoppingCarDishes[i].SalePrice;
                    }
                }
            }

            return {
                "DishNums": dishNum.toFixed(4),
                "EstimatedCostRate": (totalPrice > 0 && totalCostPrice > 0) ? (((totalCostPrice / totalPrice) * 100).toFixed(2) + "%") : "-",
            };
        };

        /**
         获取购物车菜品金额
         */
        orderDishData.getShoppingCarDishAmount = function () {
            var dishAmount = Number(0.00);
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                var dish = this.ShoppingCarDishes[i];
                //不是套餐子菜、一品多吃子菜时
                if (dish.DishProperty != OrderDishProperty.PackageDishChild &&
                  dish.DishProperty != OrderDishProperty.MultiDishChild) {
                    dishAmount += Number(dish.DishSaleAmount);
                }
            }
            return Number(dishAmount).toFixed(2);
        };

        /**
         获取已点特价菜品数量
         @exOrderDishId 需要排队的订单ID
         */
        orderDishData.getShppingCarSpecialDishNum = function (exOrderDishId) {
            var dishNum = Number(0.00);
            var exid = exOrderDishId == undefined ? 0 : exOrderDishId;
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                var dish = this.ShoppingCarDishes[i];
                //不是套餐子菜、一品多吃子菜时
                if (dish.DishProperty != OrderDishProperty.PackageDishChild &&
                  dish.DishProperty != OrderDishProperty.MultiDishChild &&
                  dish.OrderDishId != exid && dish.PriceType == OrderDishPriceType.Special) {
                    dishNum += Number(dish.DishNum);
                }
            }
            return Number(dishNum.toFixed(4));
        };

        /**
         把做法分组
         @param {Array} cookingIds
         */
        orderDishData.groupCookings = function (cookingIds) {
            var ct = {};
            for (var i = 0; i < cookingIds.length; i++) {
                var c = this.getCookingById(cookingIds[i]);
                var key = "c_" + c.RequestTypeId;
                if (ct[key] == undefined) {
                    var requestType = this.getCookingTypeById(c.RequestTypeId);
                    ct[key] = {
                        RequestTypeId: c.RequestTypeId,
                        RequestName: requestType.Name,
                        Cookings: []
                    };
                }
                ct[key].Cookings.push({
                    CookingName: c.RequestName,
                    RequestPrice: c.RequestPrice,
                    RequestId: c.RequestId
                });
            }

            return ct;
        };

        /**
         把做法分组，并按做法类型排序
         @param {Array} cookingIds  []
         @return Array 返回排序的分类数组
         */
        orderDishData.getGroupCookingsSort = function (cookingIds) {
          var ct = {};
          for (var i = 0; i < cookingIds.length; i++) {
            var c = this.getCookingById(cookingIds[i]);
            var key = "c_" + c.RequestTypeId;
            if (ct[key] == undefined) {
              var requestType = this.getCookingTypeById(c.RequestTypeId);
              ct[key] = {
                TypeKey: key,
                RequestTypeId: c.RequestTypeId,
                RequestName: requestType.Name,
                SortIndex: requestType.SortIndex,
                Cookings: []
              };
            }
            ct[key].Cookings.push({
              CookingName: c.RequestName,
              RequestPrice: c.RequestPrice,
              RequestId: c.RequestId
            });
          }

          var typeSort = [];
          for (var typeKey in ct) {
            typeSort.push(ct[typeKey]);
          }
          typeSort.sort(function(a,b) {
            return a.SortIndex - b.SortIndex;
          })

          return typeSort;
        };

        /**
         通过做法ID获取做法
         @param {Number} cookingId
         */
        orderDishData.getCookingById = function (cookingId) {
            for (var i = 0; i < this.cookings.length; i++) {
                if (this.cookings[i].RequestId == cookingId) {
                    return this.cookings[i];
                }
            }

            return null;
        };

        /**
         通过做法类型ID获取做法类型
         */
        orderDishData.getCookingTypeById = function (cookingTypeId) {
            for (var i = 0; i < this.cookingTypes.length; i++) {
                if (this.cookingTypes[i].RequestTypeId == cookingTypeId) {
                    return this.cookingTypes[i];
                }
            }

            return null;
        };

        /**
         添加菜品到购物车
         @dishData : {
         DishId: 0, //必填
         UnitId: 0, //必填
         DishNum:1, //必填
         DishName: '',//可空
         DishPrice: 0, //可空
         Cookings: [], //可空
         SubDishes:[] //可空
         }
         * @param dishData
         * @param callback
         */
        orderDishData.addDishToShoppingCar = function (dishData, callback) {
            var me = this;
            var dishNum = dishData.DishNum;
            var teaType = dishData.TeaType == undefined ? OrderDishTeaType.Normal : dishData.TeaType;
            if (dishData.DishNum > 0) { //加菜
                if (teaType != OrderDishTeaType.Tea) { //茶不检测沽清
                    var dish = this.getDish(dishData.DishId);
                    if (dish != null) { //这里有可能是空，因为套餐子菜可以不在销售方案中
                        var dishName = dish.Dish.DishName;
                        if (dishData.DishName != undefined) {
                            dishName = dishData.DishName;
                        }
                        if (!this.CheckHasSaleOut(dishData.DishId, dishName, dishData.UnitId, dishNum)) {
                            return;
                        }
                    }

                    //判断子菜是否沽清
                    if (dishData.SubDishes != undefined && dishData.SubDishes.length > 0) {
                        for (var i = 0; i < dishData.SubDishes.length; i++) {
                            dish = this.getDish(dishData.SubDishes[i].DishId);
                            if (dish != null) {
                                dishName = dish.Dish.DishName;
                                if (!this.CheckHasSaleOut(dishData.SubDishes[i].DishId, dishName, dishData.SubDishes[i].UnitId, dishData.SubDishes[i].DishNum)) {
                                    return;
                                }
                            }
                        }
                    }
                }
                //获取菜品基础数据
                var dish = this.getDish(dishData.DishId);
                var p = null;
                for (var i = 0; i < dish.Units.length; i++) {
                    if (dish.Units[i].PortionsId == dishData.UnitId) {
                        p = dish.Units[i];
                        break;
                    }
                }
                var dishes = [];

                var dishModel = this.orderOneDish(dish, dishData.DishNum, p);
                if (dishModel == null) {
                    return;
                }
                dishModel.TeaType = teaType;
                var isOriginalPrice = dishData.IsOriginalPrice != undefined && dishData.IsOriginalPrice ? true : false;
                //特价判断数量
                if (!isOriginalPrice &&
                    dish.Dish.IsTemporary != 1 &&
                    dish.Dish.IsRandomPrice != 1 &&
                    teaType != OrderDishTeaType.Tea &&
                    teaType != OrderDishTeaType.Snack &&
                    dishModel.PriceType == OrderDishPriceType.Special
                ) {
                    var specialNum = me.getShppingCarSpecialDishNum();
                    if (me.orderConfig.CurrentSpecialNum + dishData.DishNum + specialNum > me.orderConfig.SpecialNumPreOrder) {
                        mpos.dialog({
                            title: "提醒",
                            text: "特价菜每桌只允许点" + me.orderConfig.SpecialNumPreOrder + "个，超出部分将按原价计算",
                            okButton: "是",
                            cancelButton: "否"
                        }, function (status) {
                            if (!status) {
                                if (callback) {
                                    callback();
                                }
                                return;
                            }
                            dishModel.SalePrice = dishModel.DishPriceOrg; //原价点取
                            dishModel.PriceType = OrderDishPriceType.Normal;
                            dishModel.PriceOfferId = p.NormalSchemeId;
                            handleDishModel();
                        });
                    } else {
                        handleDishModel();
                    }
                } else {
                    handleDishModel();
                }
            }

            function handleDishModel() {
                if (isOriginalPrice) { //原价点取
                    dishModel.SalePrice = dishModel.DishPriceOrg; //原价点取
                    dishModel.PriceType = OrderDishPriceType.Normal;
                    dishModel.PriceOfferId = p.NormalSchemeId;
                }

                //处理做法
                me.handleCookings(dishModel, dishData.Cookings);

                //处理特殊菜品
                if (dishModel.TeaType == OrderDishTeaType.Normal) {
                    if (dish.Dish.IsTemporary == 1) { //临时菜
                        dishModel.MemberPrice = dishData.DishPrice; //会员价
                        dishModel.SpecialPrice = dishData.DishPrice; //特价
                        dishModel.DishPriceOrg = dishData.DishPrice; //原价
                        dishModel.SalePrice = dishData.DishPrice;
                        dishModel.PriceType = OrderDishPriceType.Manual;
                        dishModel.DishName = dishData.DishName;
                        dishModel.PriceOfferId = 0;
                    } else if (dish.Dish.IsRandomPrice == 1) { //时价菜
                        dishModel.MemberPrice = dishData.DishPrice; //会员价
                        dishModel.SpecialPrice = dishData.DishPrice; //特价
                        dishModel.DishPriceOrg = dishData.DishPrice; //原价
                        dishModel.SalePrice = dishData.DishPrice;
                        dishModel.PriceType = OrderDishPriceType.Manual;
                        dishModel.PriceOfferId = 0;
                    }
                }

                // 此处要区分一品多吃和套餐子菜
                var subDishes = [];
                if (dishData.SubDishes != undefined && dishData.SubDishes.length > 0) {
                    subDishes = me.orderSubDishes(dishModel, dishData.SubDishes);
                }

                dishes.push(dishModel);
                if (subDishes.length > 0) {
                    dishes = dishes.concat(subDishes);
                }

                me.mergeShopCardDishes(dishes);
                me.calculateShoppingCarDishAmount();

                if (callback) {
                    callback();
                }
            }
        };

        /**
         处理做法
         */
        orderDishData.handleCookings = function (dishModel, cookings) {
            //处理做法
            dishModel.DishRequestList = [];
            if (cookings != undefined && dishModel != undefined) {
                cookings.forEach(function (item) {
                    var cooking = {};
                    cooking.RequestId = item.CookingId;
                    cooking.RequestName = item.CookingName;
                    cooking.RequestNum = item.Num;
                    cooking.RequestPrice = item.CookingPrice;
                    cooking.BaseRequestNum = item.BaseRequestNum || item.Num;
                    dishModel.DishRequestList.push(cooking);
                });
            }
        }

        /**
         点套餐子菜/一品多吃子菜
         */
        orderDishData.orderSubDishes = function (mainDishModel, subDishes) {
            var me = this;
            if (subDishes == undefined ||
                subDishes == null ||
                subDishes.length == 0) {
                return;
            }
            var subDishModels = [];
            var addPrice = 0.00;
            var cookingPrice = 0.00;
            // 要区分套餐和一品多吃   IsMultiDish = 1 表示一品多吃， 就要将其修改为一品多吃对应属性
            var mainDishProperty = mainDishModel.IsMultiDish == 1 ? OrderDishProperty.MultiDishMain : OrderDishProperty.PackageDishMain
            var subDishProperty = mainDishModel.IsMultiDish == 1 ? OrderDishProperty.MultiDishChild : OrderDishProperty.PackageDishChild

            subDishes.forEach(function (item) {
                // 以前是从基础数据中获取菜品信息，但获取的菜品价格有误，实际价格在进入餐台后的接口中
                // 所以先从dishes中获取
                var baseDish = me.getDish(item.DishId);
                if (!baseDish) {
                    baseDish = me.getFromBaseDish(item.DishId);
                }
                var units = baseDish.Units.filter(function (u, index) {
                    return u.PortionsId == item.UnitId;
                });
                if (units == null || units.length == 0) {
                    return;
                }
                // 重新复制单位的对象信息，注释掉以前从me.getFromBaseDish中获取价格 wang.p  2022-05-09
                // NormalPrice 销售方案菜品价格，没有销售方案取基础数据，并且NormalPrice赋值BasePrice   wang.p 2024-12-31
                var unit = JSON.parse(JSON.stringify(units[0]));
                // unit.CurrentPrice = unit.BasePrice;
                // unit.MemberDiscount = 100;
                // unit.Discount = 100;
                // unit.DiscountType = 0;
                // unit.PriceType = 0;
                // unit.MemberPrice = unit.BasePrice;
                // unit.SpecialPrice = unit.BasePrice;
                unit.NormalPrice = unit.NormalPrice || unit.BasePrice;
                unit.SpecialSchemeId = 0;
                unit.CurrentSchemeId = 0;

                var subOrderDishInfo = me.orderOneDish(baseDish, item.DishNum, unit);
                subOrderDishInfo.DishPriceAdd = item.AddPrice;
                subOrderDishInfo.BelongOrderDishId = mainDishModel.OrderDishId;
                subOrderDishInfo.DishProperty = subDishProperty;
                subOrderDishInfo.PackageDishId = item.PackageDishId;
                subOrderDishInfo.ReplacePackageDishId = item.ReplacePackageDishId;
                if (mainDishModel.IsMultiDish == 1) {
                    // 一品多吃，子菜数量不能随主菜变
                    subOrderDishInfo.DishNum = subOrderDishInfo.DishNum;
                } else {
                    subOrderDishInfo.DishNum = mainDishModel.DishNum * subOrderDishInfo.DishNum;
                }

                subOrderDishInfo.Discount = mainDishModel.Discount;
                subOrderDishInfo.NormalDiscount = mainDishModel.NormalDiscount;
                subOrderDishInfo.MemberDiscount = mainDishModel.MemberDiscount;
                subOrderDishInfo.IsFreeDish = mainDishModel.IsFreeDish;
                subOrderDishInfo.PriceType = mainDishModel.PriceType;
                subOrderDishInfo.DiscountType = mainDishModel.DiscountType;

                //处理做法
                me.handleCookings(subOrderDishInfo, item.Cookings);

                subDishModels.push(subOrderDishInfo);

                addPrice += Number(item.AddPrice);
                cookingPrice += Number(subOrderDishInfo.CookingPrice);

            });

            //处理主菜金额
            mainDishModel.DishProperty = mainDishProperty;
            mainDishModel.SalePrice += addPrice;
            mainDishModel.DishPriceOrg += addPrice;
            mainDishModel.MemberPrice += addPrice;
            mainDishModel.SpecialPrice += addPrice;
            mainDishModel.CookingPrice = cookingPrice;

            return subDishModels;
        }

        /**
         点茶芥到购物车
         */
        orderDishData.addTeaAndSnackToShoppingCar = function (dishDatas, callback) {
            if (dishDatas.length == 0) {
                return;
            }
            var me = this;
            dishDatas.forEach(function (item) {
                var dish = {};
                dish.TeaType = item.TeaType;
                dish.DishId = item.DishId; //必填
                dish.UnitId = item.UnitId; //必填
                dish.DishNum = item.TeaType == OrderDishTeaType.Tea ? me.orderConfig.PeopleNum : (item.DishNum || 1); //必填
                dish.DishName = ""; //可空
                dish.Cookings = []; //可空
                me.addDishToShoppingCar(dish);
            });
            if (callback) {
                callback();
            }
        };

        /**
         * 刷新改茶的数量
         */
        orderDishData.refreshTeaNum = function () {
            var isExists = false;
            var dishIds = [];
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                var item = this.ShoppingCarDishes[i];
                if (item.TeaType == OrderDishTeaType.Tea) {
                    this.ShoppingCarDishes[i].DishNum = Number(this.orderConfig.PeopleNum);
                    dishIds.push(this.ShoppingCarDishes[i].DishId);
                    isExists = true;
                }
            }
            if (isExists) {
                this.calculateShoppingCarDishAmount();
            }

            return dishIds;
        }

        /**
         是否存在茶
         */
        orderDishData.ExistsTea = function () {
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                var item = this.ShoppingCarDishes[i];
                if (item.TeaType == OrderDishTeaType.Tea) {
                    return true;
                }
            }

            return false;
        };

        /**
       是否存在芥
       */
        orderDishData.ExistsSnack = function () {
            for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                var item = this.ShoppingCarDishes[i];
                if (item.TeaType == OrderDishTeaType.Snack) {
                    return true;
                }
            }

            return false;
        };

        /**
         修改购物车中的菜品，不包括套餐
         */
        orderDishData.changeOrderDishInfoForShoppingCar = function (dishData, callback) {
            var me = this;
            var orderDishId = dishData.OrderDishId;
            var hasOrderDish = this.getShoppingCarDishByOrderDishId(orderDishId);
            if (hasOrderDish == null) {
                return;
            }
            var baseDish = this.getDish(hasOrderDish.DishId);
            var unit = this.getUnit(baseDish, dishData.UnitId);

            if (baseDish.Dish.IsTemporary == 1) //临时菜的修改
            {
                if (hasOrderDish.TeaType == OrderDishTeaType.Normal) {
                    hasOrderDish.DishName = dishData.DishName;
                    hasOrderDish.MemberPrice = dishData.DishPrice; //会员价
                    hasOrderDish.SpecialPrice = dishData.DishPrice; //特价
                    hasOrderDish.DishPriceOrg = dishData.DishPrice; //原价
                    hasOrderDish.SalePrice = dishData.DishPrice;
                }
            } else if (baseDish.Dish.IsRandomPrice == 1) //时价菜
            {
                if (hasOrderDish.TeaType == OrderDishTeaType.Normal) {
                    hasOrderDish.MemberPrice = dishData.DishPrice; //会员价
                    hasOrderDish.SpecialPrice = dishData.DishPrice; //特价
                    hasOrderDish.DishPriceOrg = dishData.DishPrice; //原价
                    hasOrderDish.DishPortionsId = dishData.UnitId; //单位ID
                    hasOrderDish.DishPortions = unit.PortionsName; //单位名称
                    hasOrderDish.SalePrice = dishData.DishPrice;
                }
            } else //普通菜修改
            {
                if (hasOrderDish.DishPortionsId != dishData.UnitId) //修改了单位，需要重新取价
                {
                    var bakDish = $.deepClone(hasOrderDish); //备份需要修改的菜品
                    var dishUnit = me.getUnit(baseDish, dishData.UnitId);
                    //点一个新菜
                    var newOrderDish = me.orderOneDish(baseDish, bakDish.DishNum, dishUnit);
                    newOrderDish.OrderDishId = bakDish.OrderDishId;
                    Object.assign(hasOrderDish, newOrderDish);
                    if (newOrderDish.PriceType == OrderDishPriceType.Special) {
                        var specialNum = me.getShppingCarSpecialDishNum(bakDish.OrderDishId);
                        if (me.orderConfig.CurrentSpecialNum + bakDish.DishNum + specialNum > me.orderConfig.SpecialNumPreOrder) {
                            mpos.dialog({
                                title: "提醒",
                                text: "特价菜每桌只允许点" + me.orderConfig.SpecialNumPreOrder + "个，超出部分将按原价计算",
                                okButton: "是",
                                cancelButton: "否"
                            }, function (status) {
                                if (!status) {
                                    return;
                                }
                                hasOrderDish.SalePrice = newOrderDish.DishPriceOrg; //原价点取
                                hasOrderDish.PriceType = OrderDishPriceType.Normal;
                                hasOrderDish.PriceOfferId = p.NormalSchemeId;
                            });
                        }
                    }

                    hasOrderDish.DiscountSchemeId = bakDish.DiscountSchemeId;
                    hasOrderDish.NormalDiscount = bakDish.NormalDiscount;
                    hasOrderDish.MemberDiscount = 100;
                    hasOrderDish.MemberCouponOfferId = 0;
                    if (hasOrderDish.NormalDiscount < 100) {
                        if (dishUnit.IsDoubleDiscount) {
                            hasOrderDish.MemberDiscount = newOrderDish.MemberDiscount;
                            hasOrderDish.MemberCouponOfferId = dishUnit.MemberDiscountSchemeId;
                        }
                    } else {
                        hasOrderDish.MemberDiscount = newOrderDish.MemberDiscount;
                        hasOrderDish.MemberCouponOfferId = dishUnit.MemberDiscountSchemeId;
                    }
                    hasOrderDish.Discount = hasOrderDish.MemberDiscount * hasOrderDish.NormalDiscount / 100;
                    if (me.memberCard == null) {
                        hasOrderDish.MemberCouponOfferId = 0;
                    }
                }
            }
            me.handleCookings(hasOrderDish, dishData.Cookings);
            me.calculateShoppingCarDishAmount();
            if (callback) {
                callback();
            }
        };

        /**
         * 修改套餐子菜信息
         */
        orderDishData.changePackageDishesForShoppingCar = function (dishData, callback) {
            var me = this;
            var orderDishId = dishData.OrderDishId;
            var subDishes = dishData.SubDishes;
            var removeSubDishes = me.getPackageSubDishes(orderDishId);
            var mainDishModel = me.getShoppingCarDishByOrderDishId(orderDishId);
            var addPrice = 0.00;
            var removeSubOrderDishId = [];

            removeSubDishes.forEach(function (item) {
                addPrice += Number(item.DishPriceAdd);
                removeSubOrderDishId.push(item.OrderDishId);
            });

            me.removeShopCartDishes(removeSubOrderDishId);

            mainDishModel.SalePrice -= addPrice;
            mainDishModel.DishPriceOrg -= addPrice;
            mainDishModel.MemberPrice -= addPrice;
            mainDishModel.SpecialPrice -= addPrice;

            var newSubDishes = me.orderSubDishes(mainDishModel, subDishes);
            var dishModels = [];
            dishModels.push(mainDishModel);
            dishModels = dishModels.concat(newSubDishes);

            me.mergeShopCardDishes(dishModels);

            me.calculateShoppingCarDishAmount();
            if (callback) {
                callback();
            }
        }

        /**
         * 修改一品多吃信息
         */
        orderDishData.changeMultiDishesForShoppingCar = function (dishData, callback) {
            var me = this;
            var orderDishId = dishData.OrderDishId;
            var subDishes = dishData.SubDishes;
            var removeSubDishes = me.getMultiSubDishes(orderDishId);
            var mainDishModel = me.getShoppingCarDishByOrderDishId(orderDishId);
            // var salePrice = dishData.DishPrice;  // 主菜价格*数量
            var removeSubOrderDishId = [];
            removeSubDishes.forEach(function (item) {
                removeSubOrderDishId.push(item.OrderDishId);
            });
            me.removeShopCartDishes(removeSubOrderDishId);

            mainDishModel.DishNum = dishData.DishNum;  // 修改数量
            // mainDishModel.SalePrice = salePrice;
            // mainDishModel.DishPriceOrg = salePrice;
            // mainDishModel.MemberPrice = salePrice;
            // mainDishModel.SpecialPrice = salePrice;

            // 查询一品多吃子菜
            var newSubDishes = me.orderSubDishes(mainDishModel, subDishes);
            var dishModels = [];
            dishModels.push(mainDishModel);
            if (newSubDishes) {
                dishModels = dishModels.concat(newSubDishes);
            }

            me.mergeShopCardDishes(dishModels);

            // 修改做法
            me.handleCookings(mainDishModel, dishData.Cookings);
            me.calculateShoppingCarDishAmount();
            if (callback) {
                callback();
            }
        }

        /**
         加菜或减菜
         */
        orderDishData.increaseShoppingCarDishNum = function (orderDishId, dishNum, callback) {
            var me = this;
            var hasOrderDish = this.getShoppingCarDishByOrderDishId(orderDishId);
            if (hasOrderDish == null) {
                return;
            }

            if (hasOrderDish.IsFreeDish == IsFreeDishType.TicketExchange) {
                mpos.alert("已兑换的商品不能修改数量");
                return;
            }

            if (hasOrderDish.DishProperty == OrderDishProperty.PackageDishChild) {
                mpos.alert("套餐的商品不能设置数量！");
                return;
            }

            if (hasOrderDish.DishProperty == OrderDishProperty.MultiDishChild) {
                mpos.alert("一品多吃的子商品不能设置数量！");
                return;
            }

            if (hasOrderDish.TeaType == OrderDishTeaType.Tea) {
                mpos.alert("茶位不能修改数量");
                return;
            }

            if (dishNum > 0) { //加菜时需要检查沽清
                if (!this.CheckHasSaleOut(hasOrderDish.DishId, hasOrderDish.DishName, hasOrderDish.DishPortionsId, dishNum)) {
                    return;
                }
            }
            if (hasOrderDish.DishNum + dishNum <= 0) {
                var deleteOrderDishIds = [hasOrderDish.OrderDishId];
                var subDishes = [];
                // 判断是套餐还是一品多吃
                if (hasOrderDish.DishProperty == OrderDishProperty.MultiDishMain) {
                    subDishes = me.getMultiSubDishes(hasOrderDish.OrderDishId);
                } else {
                    subDishes = me.getPackageSubDishes(hasOrderDish.OrderDishId);
                }
                for (var i = 0; i < subDishes.length; i++) {
                    deleteOrderDishIds.push(subDishes[i].OrderDishId);
                }
                me.removeShopCartDishes(deleteOrderDishIds);
                if (me.OnlineOrderId > 0 && !me.IsSnackOrderDish && !me.IsExistsOnlineOrderDish()) {
                    alert(" 提醒：当前导入订单的商品已全部删除，订单恢复至未使用状态");
                    me.OnlineOrderId = 0;
                }

                if (callback) {
                    callback();
                }
            } else {
                var specialNum = me.getShppingCarSpecialDishNum();
                if (hasOrderDish.PriceType == OrderDishPriceType.Special &&
                    (me.orderConfig.CurrentSpecialNum + specialNum + dishNum > me.orderConfig.SpecialNumPreOrder)) { //超时特价数量
                    mpos.dialog({
                        title: "提醒",
                        text: "特价菜每桌只允许点" + me.orderConfig.SpecialNumPreOrder + "个，超出部分将按原价计算",
                        okButton: "是",
                        cancelButton: "否"
                    }, function (status) {
                        if (!status) {
                            return;
                        }
                        var orderDish = hasOrderDish;
                        var dish = {
                            DishId: orderDish.DishId,
                            UnitId: orderDish.DishPortionsId,
                            OrderId: me.OrderId,
                            TeaType: orderDish.TeaType,
                            DishNum: dishNum,
                            IsOriginalPrice: true,
                            DishName: orderDish.DishName,
                            DishPrice: orderDish.SalePrice,
                            Cookings: [], //做法不复制过来
                            SubDishes: hasOrderDish.IsMainPackage ? me.createNewSubDishes(hasOrderDish.OrderDishId, dishNum) : []
                        };
                        me.addDishToShoppingCar(dish, callback);
                    });
                } else { //没有，直接+或-
                    var subDishes = [];
                    if (hasOrderDish.DishProperty == OrderDishProperty.MultiDishMain) {
                        // 加减一品多吃时，子菜数量不能变化，只变动主菜
                        // subDishes = me.getMultiSubDishes(hasOrderDish.OrderDishId);
                    } else {
                        subDishes = me.getPackageSubDishes(hasOrderDish.OrderDishId);
                    }
                    var oldNum = hasOrderDish.DishNum;
                    if (oldNum + dishNum > 999.9999) {
                        mpos.alert("商品数量不能大于999.9999");
                        return;
                    }
                    hasOrderDish.DishNum += dishNum;

                    subDishes.forEach(function (item) {
                        item.DishNum = parseFloat(((item.DishNum / oldNum) * hasOrderDish.DishNum).toFixed(4));
                    });
                    me.calculateShoppingCarDishAmount();
                    if (callback) {
                        callback();
                    }
                }
            }
        };

        /**
         * 创建新一套餐子菜信息
         * 用于超时特价数量时重新点取
         */
        orderDishData.createNewSubDishes = function (orderDishId, num) {
            var newSubDishes = [];
            /**TODO: 这里没有区分套餐、一品多吃，一品多吃的子菜不随主菜数量翻倍*/
            var subDishes = this.getPackageSubDishes(orderDishId);
            var mainDish = this.getShoppingCarDishByOrderDishId(orderDishId);
            for (var i = 0; i < subDishes.length; i++) {
                var dish = subDishes[i];
                newSubDishes.push({
                    DishId: dish.DishId,
                    UnitId: dish.DishPortionsId,
                    DishNum: (dish.DishNum / mainDish.DishNum) * num,
                    PackageDishId: dish.PackageDishId,
                    ReplacePackageDishId: dish.ReplacePackageDishId,
                    AddPrice: dish.DishPriceAdd,
                    Cookings: []
                });
            }

            return newSubDishes;
        }

        /**
         获取做法的描述
         */
        orderDishData.getShoppingCarDishCookingDesc = function (dishRequestList, splitStr) {
            if (splitStr == undefined) {
                splitStr = "、";
            }
            var desc = "";
            if (dishRequestList && dishRequestList.length > 0) {
                for (var i = 0; i < dishRequestList.length; i++) {
                    if (desc != "") {
                        desc += splitStr;
                    }
                    var price = '';
                    if (Number(dishRequestList[i].RequestPrice) > 0) {
                        price = "￥" + dishRequestList[i].RequestPrice
                    }
                    if (dishRequestList[i].RequestNum <= 1) {
                        desc += dishRequestList[i].RequestName + price;
                    } else {
                        desc += dishRequestList[i].RequestName + price + "×" + parseFloat(dishRequestList[i].RequestNum);
                    }
                }
            }

            return desc;
        };

        /**
         叫起
         */
        orderDishData.setOrderDishHangUpDish = function (orderDishIds, callback) {
            var me = this;
            var flag = 4;
            orderDishIds.forEach(function (item) {
                var orderDish = me.getShoppingCarDishByOrderDishId(item);
                orderDish.KitchenRemark = orderDish.KitchenRemark == flag ? 0 : flag;
                if (orderDish.DishProperty == OrderDishProperty.PackageDishMain) {
                    var subDishes = me.getPackageSubDishes(item);
                    subDishes.forEach(function (sub) { //设置子菜的属性
                        sub.KitchenRemark = sub.KitchenRemark == flag ? 0 : flag;
                    });
                }
            });

            if (callback) {
                callback();
            }
        }

        /**
         修改菜品数量
         */
        orderDishData.changeOrderDishNumShoppingCar = function (orderDishId, callback) {
            var me = this;
            var orderDishInfo = me.getShoppingCarDishByOrderDishId(orderDishId);
            mpos.showDialog(mpos.dialogPage.changeDishNum, {
                DishNum: orderDishInfo.DishNum,
                DishName: orderDishInfo.DishName
            },
                function (status) {
                    if (status.status) {
                        var num = status.num;
                        var dishNum = Number(Number(num).toFixed(4));
                        if (dishNum > 0) {
                            if (!me.CheckHasSaleOut(orderDishInfo.DishId, orderDishInfo.DishName, orderDishInfo.DishPortionsId, dishNum - orderDishInfo.DishNum)) {
                                return;
                            }
                        }

                        if (dishNum < 0) {
                            return;
                        }
                        if (orderDishInfo.IsFreeDish == IsFreeDishType.TicketExchange) {
                            mpos.alert("已兑换的商品不能修改数量");
                            return;
                        }

                        if (orderDishInfo.DishProperty == OrderDishProperty.PackageDishChild) {
                            mpos.alert("套餐的商品不能设置数量！");
                            return;
                        }
                        if (orderDishInfo.DishProperty == OrderDishProperty.MultiDishChild) {
                            mpos.alert("一品多吃的子商品数量设置请点击修改！");
                            return;
                        }

                        if (orderDishInfo.TeaType == OrderDishTeaType.Tea) {
                            mpos.alert("茶位不能修改数量");
                            return;
                        }

                        if (dishNum > 999.9999) {
                            mpos.alert("商品数量不能大于999.9999");
                            return;
                        }

                        //if (dishNum < 0.0001) {
                        //    mpos.alert("商品数量不能小于0.0001");
                        //    return;
                        //}

                        if (orderDishInfo.PriceType == OrderDishPriceType.Special) {
                            var specialNum = me.getShppingCarSpecialDishNum(orderDishInfo.OrderDishId);
                            if (me.orderConfig.CurrentSpecialNum + dishNum + specialNum > me.orderConfig.SpecialNumPreOrder) {
                                mpos.alert("点取数量超出特价商品数量，请重新点单！");
                                return;
                            }
                        }
                        if (dishNum == 0) {
                            me.increaseShoppingCarDishNum(orderDishId, -orderDishInfo.DishNum, callback);
                        } else {
                            var oldNum = orderDishInfo.DishNum;
                            orderDishInfo.DishNum = dishNum;  // 修改主商品数量
                            if (orderDishInfo.DishProperty == OrderDishProperty.PackageDishMain) {
                                var subDishes = me.getPackageSubDishes(orderDishInfo.OrderDishId);
                                subDishes.forEach(function (item) { //设置子菜的属性
                                    item.DishNum = parseFloat(((item.DishNum / oldNum) * orderDishInfo.DishNum).toFixed(4));
                                });
                            } else if (orderDishInfo.DishProperty == OrderDishProperty.MultiDishMain) {
                                // var subDishes = me.getMultiSubDishes(orderDishInfo.OrderDishId);
                                // subDishes.forEach(function (item) { //设置子菜的属性
                                //     item.DishNum = parseFloat(((item.DishNum / oldNum) * orderDishInfo.DishNum).toFixed(4));
                                // });
                            }
                            me.calculateShoppingCarDishAmount();
                            if (callback) {
                                callback();
                            }
                        }
                    }
                });
        };

        /**
         检查是否沽清
         */
        orderDishData.CheckHasSaleOut = function (dishId, dishName, unitId, dishNum) {
            var saleOutNum = this.getCanSaleDishNum(dishId);
            if (saleOutNum == 0) { //已卖完
                mpos.alert(dishName + " 已经卖完");
                return false;
            }
            //检查是否已沽清了
            var checkMsg = this.checkIsSaleOut(dishId, unitId, dishNum);
            if (checkMsg != "") {
                mpos.alert(checkMsg);
                return false;
            }

            return true;
        };

        /*
        应用所有做法
        */
        orderDishData.applyAllCookies = function (cookies) {
            if (cookies && cookies.length > 0) {
                var hasHandCookie = [];  // 先缓存所有手写做法
                for (var i = 0; i < cookies.length; i++) {
                    if (cookies[i].CookingId <= 0) {
                        hasHandCookie.push(cookies[i]); 
                    }
                }
                for (var i = 0; i < this.ShoppingCarDishes.length; i++) {
                    var cardDish = this.ShoppingCarDishes[i];
                    if (cardDish.DishProperty == 5) { //套餐主菜跳过
                        continue;
                    }
                    var dish = this.getDish(cardDish.DishId);
                    if (dish == null) {
                        continue;
                    }
                    //if (dish.Dish.IsTemporary == 1) { //临时菜
                    //    continue;
                    //}
                    // 添加整单做法中手写做法
                    if (hasHandCookie.length > 0) {
                        // 查找出菜品已有的手写做法中最小的ID
                        var minCookingId = 0;
                        for (var j = 0; j < cardDish.DishRequestList.length; j++) {
                            if (cardDish.DishRequestList[j].RequestId < minCookingId) {
                                minCookingId = cardDish.DishRequestList[j].RequestId; 
                            }
                        }
                        // 循环添加手写做法
                        for(var h=0;h<hasHandCookie.length;h++) {
                            minCookingId -= 1;
                            cardDish.DishRequestList.push({
                                RequestId: minCookingId,
                                RequestName: hasHandCookie[h].CookingName,
                                RequestPrice: hasHandCookie[h].CookingPrice,
                                RequestNum: hasHandCookie[h].Num,
                            })
                        }  
                    }
                    for (var j = 0; j < cookies.length; j++) {
                        if (cookies[j].CookingId <= 0) {
                            continue;
                        }
                        var hasExists = false;
                        for (var k = 0; k < cardDish.DishRequestList.length; k++) {
                            if (cardDish.DishRequestList[k].RequestId == cookies[j].CookingId) {
                                hasExists = true;
                                break;
                            }
                        }
                        if (!hasExists) {
                            cardDish.DishRequestList.push({
                                RequestId: cookies[j].CookingId,
                                RequestName: cookies[j].CookingName,
                                RequestPrice: cookies[j].CookingPrice,
                                RequestNum: cookies[j].Num,
                            });
                        }
                    }
                }

                this.calculateShoppingCarDishAmount();
            }
        }

        /**
         判断购物车中是否存在菜品
         */
        orderDishData.ExistsOrderDishes = function () {
            return this.ShoppingCarDishes != null && this.ShoppingCarDishes.length > 0;
        };

        /**
         * 是否正在下单，用于预防快速点击下单导致的重复下单缺陷
         * @type {boolean}
         */
        var isOrdering = false;
        /**
         下单
         */
        orderDishData.saveOrderDishes = function (isPrint, isHangUp, callback) {
            if (isOrdering) return;
            var me = this;
            isOrdering = true;
            if (!me.ExistsOrderDishes()) {
                mpos.alert("没有要下单的商品");
                isOrdering = false;
                return;
            }
            // 判断购物车中的商品是否在销售方案中
            var invalidDish = me.invalidDishFromShoppingCar();
            if (invalidDish) {
                isOrdering = false;
                return;
            }

            var tableBillId = mpos.tableBillId();

            if (me.orderConfig.WaiterModel == 3) { //当为一单一服务员时，弹出选择服务员
                mpos.showDialog(mpos.dialogPage.selectWaiter, {}, function (r) {
                    if (r.WaiterId > -1) {
                        _beginSaveOrderDishes(r.WaiterId);
                    }
                });
            } else {
                _beginSaveOrderDishes(0);
            }

            function _beginSaveOrderDishes(waiterId) {
                mpos.post(mpos.api.saveOrderDishes, {
                    Dishes: JSON.stringify(me.ShoppingCarDishes),
                    OrderIds: JSON.stringify(me.OrderIds),
                    TableBillId: tableBillId,
                    IsPrint: isPrint,
                    IsAllHangUp: isHangUp,
                    OnlineOrderId: me.OnlineOrderId,
                    WaiterId: waiterId,
                    SessionId: me.SessionId,
                }, function (r) {
                    if (r.Successed == 0) { //价格有变动了
                        alert(r.ErrorMsg);
                        callback(false, r.Dishes);
                        isOrdering = false;
                        return;
                    }
                    me.ShoppingCarDishes = [];
                    if (r.TableBills) { //台单
                        if (r.TableBills != null && Array.isArray(r.TableBills) && tableBillId > 0 && r.TableBills.length > 0) {
                            var printNum = mpos.tableBillNumber();
                            for (var j = 0; j < r.TableBills.length; j++) {
                                for (var i = 0; i < printNum; i++) { //打印多份
                                    var printData = mpos.addPrintEmptyLine(r.TableBills[j]);
                                    mpos.deviceFactory.printTicket(printData, null, function (err) {
                                        //打印
                                        mpos.alert(err);
                                    });
                                }
                            }
                        }
                    }
                    var printSigleBill = mpos.printSigleBill();
                    var printTotalBill = mpos.printTotalBill();
                    if (printTotalBill == 1 && r.TotalBills) { //总单
                        if (r.TotalBills != null && Array.isArray(r.TotalBills) && r.TotalBills.length > 0) {
                            $.each(r.TotalBills, function (index, item) {
                                var printData = mpos.addPrintEmptyLine(item);
                                mpos.deviceFactory.printTicket(printData, null, function (err) {
                                    //打印
                                    mpos.alert(err);
                                });
                            })
                        }
                    }

                    if (printSigleBill == 1 && r.SigleBills) { //分单
                        if (r.SigleBills != null && Array.isArray(r.SigleBills) && r.SigleBills.length > 0) {
                            $.each(r.SigleBills, function (index, item) {
                                var printData = mpos.addPrintEmptyLine(item);
                                mpos.deviceFactory.printTicket(printData, null, function (err) {
                                    //打印
                                    mpos.alert(err);
                                });
                            })
                        }
                    }
                    if (callback) {
                        callback();
                    }
                    isOrdering = false;
                }, {
                    error: function () {
                        isOrdering = false;
                        return true;
                    },
                    blFailed: function () {
                        isOrdering = false;
                        return true;
                    }
                });
            }
        };

        /*
         * 选台下单，保存订单信息
         * */
        orderDishData.changeTableSaveOrderDishes = function (isPrint, isHangUp, orderIds, callback) {
            if (isOrdering) return;
            var me = this;
            isOrdering = true;
            if (!me.ExistsOrderDishes()) {
                mpos.alert("没有要下单的商品");
                isOrdering = false;
                return;
            }
            var tableBillId = mpos.tableBillId();

            _beginSaveOrderDishes(0);

            function _beginSaveOrderDishes(waiterId) {
                mpos.post(mpos.api.saveOrderDishes, {
                    Dishes: JSON.stringify(me.ShoppingCarDishes),
                    OrderIds: JSON.stringify(orderIds),
                    TableBillId: tableBillId,
                    IsPrint: isPrint == 1 ? true : false,
                    IsAllHangUp: isHangUp,
                    OnlineOrderId: me.OnlineOrderId,
                    WaiterId: waiterId,
                    SessionId: me.SessionId,
                }, function (r) {
                    if (r.Successed == 0) { //价格有变动了
                        alert(r.ErrorMsg);
                        callback(false, r.Dishes);
                        isOrdering = false;
                        return;
                    }
                    me.ShoppingCarDishes = [];
                    if (r.TableBills) { //台单
                        if (r.TableBills != null && Array.isArray(r.TableBills) && tableBillId > 0 && r.TableBills.length > 0) {
                            var printNum = mpos.tableBillNumber();
                            for (var j = 0; j < r.TableBills.length; j++) {
                                for (var i = 0; i < printNum; i++) { //打印多份
                                    var printData = mpos.addPrintEmptyLine(r.TableBills[j]);
                                    mpos.deviceFactory.printTicket(printData, null, function (err) {
                                        //打印
                                        mpos.alert(err);
                                    });
                                }
                            }
                        }
                    }
                    var printSigleBill = mpos.printSigleBill();
                    var printTotalBill = mpos.printTotalBill();
                    if (printTotalBill == 1 && r.TotalBills) { //总单
                        if (r.TotalBills != null && Array.isArray(r.TotalBills) && r.TotalBills.length > 0) {
                            $.each(r.TotalBills, function (index, item) {
                                var printData = mpos.addPrintEmptyLine(item);
                                mpos.deviceFactory.printTicket(printData, null, function (err) {
                                    //打印
                                    mpos.alert(err);
                                });
                            })
                        }
                    }

                    if (printSigleBill == 1 && r.SigleBills) { //分单
                        if (r.SigleBills != null && Array.isArray(r.SigleBills) && r.SigleBills.length > 0) {
                            $.each(r.SigleBills, function (index, item) {
                                var printData = mpos.addPrintEmptyLine(item);
                                mpos.deviceFactory.printTicket(printData, null, function (err) {
                                    //打印
                                    mpos.alert(err);
                                });
                            })
                        }
                    }
                    if (callback) {
                        callback();
                    }
                    isOrdering = false;
                }, {
                    error: function () {
                        isOrdering = false;
                        return true;
                    },
                    blFailed: function () {
                        isOrdering = false;
                        return true;
                    }
                });
            }
        };

        /**
         存酒添加商品
         @dishData : {
         DishId: 0, //必填
         UnitId: 0, //必填
         DishNum:1, //必填
         DishName: '',//可空
         DishPrice: 0, //可空
         Cookings: [], //可空
         SubDishes:[] //可空
         }
         * @param dishData
         * @param callback
         */
        orderDishData.addSaveWinesDishToShoppingCar = function (dishData, callback) {
            var me = this;
            var teaType = dishData.TeaType == undefined ? OrderDishTeaType.Normal : dishData.TeaType;
            if (dishData.DishNum > 0) { //加菜
                //获取菜品基础数据
                var dish = this.getDish(dishData.DishId);
                var p = null;
                for (var i = 0; i < dish.Units.length; i++) {
                    if (dish.Units[i].PortionsId == dishData.UnitId) {
                        p = dish.Units[i];
                        break;
                    }
                }
                var dishes = [];
                var dishModel = this.orderOneDish(dish, dishData.DishNum, p);
                if (dishModel == null) {
                    return;
                }
                dishModel.TeaType = teaType;

                dishes.push(dishModel);

                me.mergeShopCardDishes(dishes);
                if (callback) {
                    callback();
                }
            }
        };

        /**
         * 存酒加菜或减菜
         */
        orderDishData.increaseSaveWinesShoppingCarDishNum = function (orderDishId, dishNum, callback) {
            var me = this;
            var hasOrderDish = this.getShoppingCarDishByOrderDishId(orderDishId);
            if (hasOrderDish == null) {
                return;
            }

            if (hasOrderDish.DishNum + dishNum <= 0) {
                var deleteOrderDishIds = [hasOrderDish.OrderDishId];
                var subDishes = me.getPackageSubDishes(hasOrderDish.OrderDishId);
                for (var i = 0; i < subDishes.length; i++) {
                    deleteOrderDishIds.push(subDishes[i].OrderDishId);
                }
                me.removeShopCartDishes(deleteOrderDishIds);
                if (callback) {
                    callback();
                }
            } else {
                //没有，直接+或-
                var subDishes = me.getPackageSubDishes(hasOrderDish.OrderDishId);
                var oldNum = hasOrderDish.DishNum;
                if (oldNum + dishNum > 99999.9999) {
                    mpos.alert("商品数量不能大于99999.9999");
                    return;
                }
                hasOrderDish.DishNum += dishNum;

                subDishes.forEach(function (item) {
                    item.DishNum = parseFloat(((item.DishNum / oldNum) * hasOrderDish.DishNum).toFixed(4));
                });
                if (callback) {
                    callback();
                }
            }
        };

        /**
         * 更新做法数量，
         * @cooking   做法
         * @oldNum    最开始的菜品数量
         * @dishNum   最新的菜品数量
         * @isSub     是否是子菜
         */
        orderDishData.getDishRequestList = function (cooking, oldNum, dishNum, isSub = false)  {
          var newRequestNum = cooking.RequestNum;
          if (cooking.IsRequestNumWithDish == 1 || isSub) {
                newRequestNum = Number((cooking.RequestNum / oldNum * dishNum).toFixed(4));
            }
            var copyObj = $.deepClone(cooking);
            copyObj.RequestNum = newRequestNum;

            return copyObj;
        };

        return orderDishData;
    },

    /*创建点套餐的操作对象*/
    createPackageOrderDish: function (packageDish, mainOrderDishId, orderDishData) {
        var operation = {};
        /**
         * 套餐信息
         */
        operation.packageDish = packageDish;
        /**
         * 已点子菜信息
         */
        operation.orderSubDishes = [];
        /**
         * 要修改的套餐ID
         */
        operation.orderDishId = mainOrderDishId;
        /**
         * 要修改的套餐ID
         */
        operation.orderDishData = orderDishData;

        /**
         * 添加子菜到已点子菜中
         */
        operation.addToSubDishes = function (pd, num) {
            if (num == undefined) {
                num = pd.DishNum;
            }
            if (this.checkHasOrderSubDish(pd.PackageDishId)) {
                return;
            }

            var cookings = [];
            this.orderSubDishes.push({
                DishId: pd.DishId,
                UnitId: pd.DishPortionsId,
                DishNum: num,
                PackageDishId: pd.PackageDishId,
                ReplacePackageDishId: 0,
                AddPrice: 0,
                Cookings: cookings
            });
        }

        /**
         *  检查套餐子菜是否在已点子菜中
         */
        operation.checkHasOrderSubDish = function (packageDishId) {
            var exists = false;
            for (var i = 0; i < this.orderSubDishes.length; i++) {
                if (this.orderSubDishes[i].PackageDishId == packageDishId) {
                    exists = true;
                    break;
                }
            }
            return exists;
        }

        /**
         *  检查套餐子菜是否在已点子菜中
         */
        operation.getHasOrderSubDish = function (packageDishId) {
            for (var i = 0; i < this.orderSubDishes.length; i++) {
                if (this.orderSubDishes[i].PackageDishId == packageDishId) {
                    return this.orderSubDishes[i];
                }
            }
            return null;
        }

        /**
         * 从已点子菜中移除
         */
        operation.removeSubDishes = function (packageDishId) {
            for (var i = 0; i < this.orderSubDishes.length; i++) {
                if (this.orderSubDishes[i].PackageDishId == packageDishId) {
                    this.orderSubDishes.splice(i, 1);
                    break;
                }
            }
        }

        /**
         * 修改菜品时，还原子菜
         */
        operation.restoreOrderDish = function (isGroup) {
            if (this.orderDishId > 0) {
                var subDishes = this.orderDishData.getPackageSubDishes(this.orderDishId);
                var mainDish = this.orderDishData.getShoppingCarDishByOrderDishId(this.orderDishId);
                for (var i = 0; i < subDishes.length; i++) {
                    var cookings = [];
                    if (subDishes[i].DishRequestList != null && subDishes[i].DishRequestList.length > 0) {
                        for (var j = 0; j < subDishes[i].DishRequestList.length; j++) {
                            var cooking = subDishes[i].DishRequestList[j];
                            cookings.push({
                                CookingId: cooking.RequestId,
                                CookingName: cooking.RequestName,
                                CookingPrice: cooking.RequestPrice,
                                Num: cooking.RequestNum
                            });
                        }
                    }
                    var dishNum = isGroup ? subDishes[i].DishNum / mainDish.DishNum : 0;
                    this.orderSubDishes.push({
                        DishId: subDishes[i].DishId,
                        UnitId: subDishes[i].DishPortionsId,
                        DishNum: dishNum,
                        PackageDishId: subDishes[i].PackageDishId,
                        ReplacePackageDishId: subDishes[i].ReplacePackageDishId,
                        AddPrice: isGroup ? subDishes[i].DishPriceAdd / subDishes[i].DishNum : subDishes[i].DishPriceAdd,
                        Cookings: cookings
                    });
                }
                if (!isGroup) { //如果是分组套餐无法按以下方法处理
                    //处理数量，因为这里的数量不是单位数量（单位数量是主菜为1时的子菜数量）
                    for (var j = 0; j < this.orderSubDishes.length; j++) {
                        for (var i = 0; i < this.packageDish.PackageDishList.length; i++) {
                            if (this.orderSubDishes[j].PackageDishId == this.packageDish.PackageDishList[i].PackageDish.PackageDishId) {
                                if (this.orderSubDishes[j].ReplacePackageDishId > 0) { //替换菜
                                    for (var k = 0; k < this.packageDish.DishPackageReplaceList.length; k++) {
                                        if (this.packageDish.DishPackageReplaceList[k].PackageDishReplaceId == this.orderSubDishes[j].ReplacePackageDishId) {
                                            //取单位数量
                                            this.orderSubDishes[j].DishNum = this.packageDish.DishPackageReplaceList[k].DishNum;
                                            break;
                                        }
                                    }
                                } else { //非替换菜
                                    this.orderSubDishes[j].DishNum = this.packageDish.PackageDishList[i].PackageDish.DishNum; //取单位数量
                                }
                                break;
                            }
                        }
                    }
                } else { //恢复加价
                    for (var j = 0; j < this.orderSubDishes.length; j++) {
                        for (var i = 0; i < this.packageDish.PackageDishList.length; i++) {
                            if (this.orderSubDishes[j].PackageDishId == this.packageDish.PackageDishList[i].PackageDish.PackageDishId) {
                                this.orderSubDishes[j].AddPrice = this.packageDish.PackageDishList[i].PackageDish.SubDishPrice; //取单位数量
                                break;
                            }
                        }
                    }
                }
            }
        };

        /**
         获取套餐分组
         */
        operation.getDishGroupById = function (gId) {
            for (var i = 0; i < this.packageDish.PackageGroupList.length; i++) {
                var groupDish = this.packageDish.PackageGroupList[i];
                if (groupDish.PackageGroup.DishPackageGroupId == gId) {
                    return groupDish
                }
            }
            return null;
        };

        /**
         获取套餐分组的已选数量
         */
        operation.getNotMustSelectDishNumByGroupId = function (gId) {
            var num = 0.00;
            var g = this.getDishGroupById(gId);
            for (var i = 0; i < g.PackageGroupNotMustDishList.length; i++) {
                for (var k = 0; k < this.orderSubDishes.length; k++) {
                    if (this.orderSubDishes[k].PackageDishId == g.PackageGroupNotMustDishList[i].PackageDish.PackageDishId) {
                        num += this.orderSubDishes[k].DishNum;
                    }
                }
            }
            return num;
        };

        return operation;
    }
};

/**
 点菜
 */
mpos.controller(mpos.page.orderDishes, function (page, pageData) {
    var $page = $(page);
    //参数处理
    var orderIds = pageData.OrderIds; //点菜订单ID
    if (!orderIds) {
        orderIds = [0];
    }
    var isSnack = false;
    var clearShoppingDishes = true;
    if (pageData.IsSnack != undefined) {
        isSnack = pageData.IsSnack;
        if (isSnack) { //快餐结账过来不需要清除购物车数据
            clearShoppingDishes = false;
        }
    }
    var wholeBillId = 0;
    // 锁台点单时，就已经请求了数据
    var dishData = pageData.DishData == undefined ? null : pageData.DishData;
    var debounceTimeout = null;  // 创建一个扫描枪防抖的搜索菜品对象
    var scanningGunValue = [];  // 扫描枪输入的内容
    var scanningGunListener = false;  // 是否开启了扫码枪监听

    //判断是否显示毛利率，显示就要调整相关容器padding-bottom的高度
    if (mpos.localStorage.enableEstimatedCost) {
        $page.find('.app-content-body').addClass('has-stimated-cost');
        // $page.find('.app-content-body>ul').css('padding-bottom', '90px');
        $page.find('.dish-search-list').addClass('estimated-cost-search');
    } else {
        $page.find('.app-content-body').removeClass('has-stimated-cost');
        // $page.find('.app-content-body>ul').css('padding-bottom', '60px');
        $page.find('.dish-search-list').removeClass('estimated-cost-search');
    }

    /*定义参数*/
    var bookOrderId = pageData.BookOrderId; //预订ID
    if (!bookOrderId) {
        bookOrderId = 0;
    }
    var selectedBigDishTypeId = 0; // 当前选中菜品大类ID， 0表示未有菜品大类选择

    var SELECT_TYPE_CLASS = "selected";

    /**
     *
     * @param tableId
     * @param orderId
     * @returns {*}
     */
    function getOrderDishDataByTableOrderId(tableId, orderId) {
        if (mpos.localStorage.LocalTableOrder) {
            var localOrder = JSON.parse(mpos.localStorage.LocalTableOrder);
            var result = null;
            if (localOrder[tableId] && localOrder[tableId][orderId]) {
                result = localOrder[tableId][orderId];
            }
            delete localOrder[tableId];
            mpos.localStorage.LocalTableOrder = JSON.stringify(localOrder)
            return result;
        }
        return null;
    }

    /**
     *
     * @param tableId
     * @param orderId
     * @param dishes
     */
    function saveOrderDishDataByTableOrderId(tableId, orderId, dishes) {
        var localOrder = mpos.localStorage.LocalTableOrder || {};
        if (typeof localOrder === 'string')
            localOrder = JSON.parse(localOrder)
        if (!localOrder[tableId])
            localOrder[tableId] = {}
        localOrder[tableId][orderId] = dishes;
        mpos.localStorage.LocalTableOrder = JSON.stringify(localOrder);
    }

    //点菜对象
    var orderDishData = mpos.OrderDishData.createNew();

    orderDishData.OrderId = orderIds[0];
    orderDishData.OrderIds = orderIds;

    var currentSelectedDishType = 0; //当前选中的菜品分类

    var shoppingCarContainer = $page.find(".shopping-car-container"); //购物车未下单列表

    var dishTypeContainer = $page.find(".dish-type-list");
    var dishContainer = $page.find(".app-content-body>ul.dish-list");
    // var searchInput = $page.find("input[name='searchDish']");
    var dishSearchContainer = $page.find('.app-content-body>.dish-search-list>.dish-list');

    var kb = {};
    // 判断是否启用系统默认键盘
    if (mpos.localStorage.enableSystemKeyboard) {
        kb.reset = function () { }; // 空方法，防止切换系统默认键盘时，调用自定义键盘的reset方法
        dishSearchContainer.css('padding-top', '47px');
        var searchDishResult = dishSearchContainer.parent().find('input[name="searchDishResult"]');
        searchDishResult.removeClass('nd');
        searchDishResult.bind('input porpertychange', function (obj) {
            var searchReg = $(this).val().trim().toLowerCase();
            var dishList = [];
            if (searchReg !== '') {
                for (var i = 0, j = 0; i < orderDishData.dishes.length; i++) {
                    var dish = orderDishData.dishes[i];
                    if (dish.Dish.DishSpell.toLowerCase().indexOf(searchReg) !== -1 ||
                        dish.Dish.DishSerial.toLowerCase().indexOf(searchReg) !== -1 ||
                        dish.Dish.DishName.toLowerCase().indexOf(searchReg) !== -1) {
                        //精确匹配的提前
                        if (dish.Dish.DishSpell.toLowerCase() == searchReg ||
                            dish.Dish.DishSerial.toLowerCase() == searchReg ||
                            dish.Dish.DishName.toLowerCase() == searchReg) {
                            dishList.unshift(dish);
                        } else {
                            dishList.push(dish);
                        }
                    }
                }

                if (dishList.length > Config.maxSearchDishDisplayLength) {
                    dishList = dishList.slice(0, Config.maxSearchDishDisplayLength);
                }
            }

            dishSearchContainer.empty().append(fragmentWithDishList(dishList));
            refreshUI();
        })

    } else {
        kb = new mpos.Components.KeyBoard({
            parent: dishSearchContainer.parent(),
            showResultLabel: true,
            callback: function (searchReg) {
                var displayStr = null;
                var dishList = [];
                if (searchReg !== null) {
                    for (var i = 0, j = 0; i < orderDishData.dishes.length; i++) {
                        var dish = orderDishData.dishes[i];
                        if (searchReg.test(dish.Dish.DishSpell) ||
                            searchReg.test(dish.Dish.DishSerial) ||
                            searchReg.test(dish.Dish.DishName)) {

                            var str = RegExp.$1.toLowerCase();
                            //精确匹配的提前
                            if (dish.Dish.DishSpell.toLowerCase() == str ||
                                dish.Dish.DishSerial.toLowerCase() == str ||
                                dish.Dish.DishName.toLowerCase() == str) {
                                dishList.unshift(dish);
                            } else {
                                dishList.push(dish);
                            }

                            if (displayStr === null) displayStr = str;
                            // j += 1;
                            // if (j > Config.maxSearchDishDisplayLength)
                            //     break;
                        }
                    }

                    if (dishList.length > Config.maxSearchDishDisplayLength) {
                        dishList = dishList.slice(0, Config.maxSearchDishDisplayLength);
                    }
                }

                dishSearchContainer.empty().append(fragmentWithDishList(dishList));
                refreshUI();

                return displayStr;
            }
        });
    }

    var goodsCar = $page.find(".goodsCar.app-button");

    var $dishTypeItem = dishTypeContainer.find("li").remove();
    var $dishItem = dishContainer.find("li").remove();
    var $shoppingCarItem = shoppingCarContainer.find("li.shopping-car-item").remove();
    var $shoppingCarAlreadyItem = shoppingCarContainer.find("li.already-dish-item").remove(); // 已下单菜品列表

    /** @namespace mpos.localStorage.OrderDishDisplayMode */
    mpos.registerStorageProperties('OrderDishDisplayMode');

    var displayMode = Number(mpos.localStorage.OrderDishDisplayMode) || 0; //记录分段控件列表和搜索的状态
    var orderSwitchMode = Number(mpos.localStorage.OrderSwitchMode) || 0; //记录分段控件未下单和已下单的状态

    //判断酒楼还是快餐模式
    var mposType = OrderPropertyType.Normal;
    if (!orderIds || (orderIds.length == 1 && orderIds[0] == 0)) {
        mposType = OrderPropertyType.Snack;
    } else if (isSnack) {
        mposType = OrderPropertyType.Snack;
    }

    // //分段控件
    setTopBarSwitch();

    /**
     * 切换显示界面为列表还是搜索
     */
    function switchDisplayUI() {
        if (displayMode === 0) {  // 显示列表、隐藏搜索
            dishSearchContainer.parent().addClass('nd');
            kb.reset();
            dishSearchContainer.empty();
            onScanningGunToKeydown(false); // 移除键盘监听事件

            if (mpos.localStorage.enableSystemKeyboard) {
                //系统键盘时，清空搜索输入框
                dishSearchContainer.parent().find('input[name="searchDishResult"]').val('');
            }
            dishTypeContainer.removeClass('nd');
            dishContainer.removeClass('nd');
        } else {  // 隐藏列表、显示搜索
            dishTypeContainer.addClass('nd');
            dishContainer.addClass('nd');
            dishSearchContainer.parent().removeClass('nd');
            onScanningGunToKeydown(true); // 添加键盘监听事件
        }
    }
    // 初始化界面显示列表还是搜索
    switchDisplayUI();

    if (mposType == OrderPropertyType.Snack) {
        $page.find(".app-topbar>.app-button.back").remove();
        //边栏
        $page.find(".app-topbar>.slide-user").on("click", function () {
            mpos.slidePage.show();
        });
        //remove .more
        $page.find(".more.app-button").remove();
        $page.find(".more-operation-list").remove();
        $page.find(".doOrderDish.app-button").text("付款");
    } else {
        $page.find(".all-hangup").text("整单" + mpos.shopConfig.WaitCallUpDescption);
        $page.find(".app-topbar>.slide-user").remove();

        if (mpos.isPayToOrderModel()) {
            $page.find(".more.app-button").remove();
            $page.find(".more-operation-list").remove();
            $page.find(".doOrderDish.app-button").text("付款");
        } else {
            $page.find(".doOrderDish.app-button").text("下单")
            $page.on("click", function () {
                $page.find(".more-operation-list:not(.nd)").addClass("nd");
            });
            /**
             * 更多按钮事件
             * 切换菜品更多操作界面的显示
             */
            $page.find(".more.app-button").on("click", function (e) {
                e.stopPropagation();
                $page.find(".footer .more-operation-list").toggleClass("nd");
            });

            /**
             * 更多操作操作
             */
            $page.find(".footer .more-operation-list li").on("click", function (e) {
                var $target = $(e.currentTarget);
                if ($target.hasClass("send-first")) { //先送
                    //封装先送订单
                    var saveDishes = function () {
                        orderDishData.saveOrderDishes(true, false, function (r, dishes) {
                            if (r != undefined && !r) {
                                bookOrderId = 0;
                                loadOrderDishDatas(false, function () {
                                    orderDishData.ShoppingCarDishes = dishes;
                                    refreshUI();
                                    refreshShoppingCarUI();
                                });

                            } else {
                                bookOrderId = 0;
                                loadOrderDishDatas(true, function () {
                                    refreshUI();
                                    refreshShoppingCarUI();
                                    if (isShoppingCarContainerDisplayed()) {
                                        hideShoppingCarContainer();
                                    }
                                });

                            }
                        });
                    }
                    //判断是否开启了先送确认提示开关
                    if (mpos.localStorage.enableSubmitOrderTips) {
                        mpos.dialog({
                            title: "提醒",
                            text: "是否确定先送？",
                            okButton: "是",
                            cancelButton: "否"
                        }, function (res) {
                            if (res === 'ok') {
                                saveDishes();
                            }
                        });
                    } else {
                        saveDishes();
                    }

                } else if ($target.hasClass("not-print")) {
                    //增加下单不打印提示
                    var saveDishes = function () {
                        orderDishData.saveOrderDishes(false, false, function (r, dishes) {
                            if (r != undefined && !r) {
                                bookOrderId = 0;
                                loadOrderDishDatas(false, function () {
                                    orderDishData.ShoppingCarDishes = dishes;
                                    refreshUI();
                                    refreshShoppingCarUI();
                                });
                                return;
                            }
                            mpos.back(mpos.page.home); //返回首页
                            mpos.removeFromStack();
                        });
                    }
                    //判断是否开启了先送确认提示开关
                    if (mpos.localStorage.enableSubmitOrderTips) {
                        mpos.dialog({
                            title: "提醒",
                            text: "是否下单不打印？",
                            okButton: "是",
                            cancelButton: "否"
                        }, function (res) {
                            if (res === 'ok') {
                                saveDishes();
                            }
                        });
                    } else {
                        saveDishes();
                    }

                } else if ($target.hasClass("all-hangup")) {  // 整单等叫
                    if (!orderDishData.ExistsOrderDishes()) {
                      mpos.alert('请选择下单商品');
                      return;
                    }

                    // 弹出选择整单等叫的窗口
                    mpos.showDialog(mpos.dialogPage.allHangupOrder, {
                      Dishes: orderDishData.ShoppingCarDishes
                    }, function (result) {
                      if (result && result.dishes && result.dishes.length > 0) {
                        orderDishData.setOrderDishHangUpDish(result.dishes, function () {
                          // 显示购物车，就要刷新UI
                          if (isShoppingCarContainerDisplayed()) {
                            refreshUI();
                            refreshShoppingCarUI();
                          }
                        });
                      }
                    });
                    // 取消整单等叫直接下单的操作，2025-05-23 wang.p
                    // orderDishData.saveOrderDishes(true, true, function (r, dishes) {
                    //     if (r != undefined && !r) {
                    //         bookOrderId = 0;
                    //         loadOrderDishDatas(false, function () {
                    //             orderDishData.ShoppingCarDishes = dishes;
                    //             refreshUI();
                    //             refreshShoppingCarUI();
                    //         });
                    //         return;
                    //     }
                    //     mpos.back(mpos.page.home); //返回首页
                    //     mpos.removeFromStack();
                    // });
                } else if ($target.hasClass("all-cookie")) { //整单做法
                    mpos.pick(mpos.page.allCookingForDishes, {
                        OrderDishData: orderDishData,
                        WholeBillId: wholeBillId,
                    }, function (data) {
                        refreshUI();
                        refreshShoppingCarUI();
                    });
                } else if ($target.hasClass("modify-table-header")) {
                    // 修改台头
                    mpos.showDialog(mpos.dialogPage.modifyOpenTable, {
                        OrderId: orderDishData.OrderId
                    }, function (data) {
                        if (data.Status) {
                            if (orderDishData.orderConfig.PeopleNum != data.PeopleNum) {
                                orderDishData.orderConfig.PeopleNum = data.PeopleNum;
                                var dishIds = orderDishData.refreshTeaNum();
                                if (dishIds.length > 0) {
                                    refreshUI(dishIds);
                                }
                            }
                        }
                    });
                } else if ($target.hasClass("choice-table-submit")) {
                    //TODO: 下单选台
                    if (!orderDishData.ExistsOrderDishes()) {
                        mpos.alert('请选择下单商品');
                        return;
                    }
                    //弹窗桌台选择
                    mpos.showDialog(mpos.dialogPage.changeOrderedTable, {
                        OrderId: orderIds,
                        TableId: orderDishData.TableId,
                        HasDishes: orderDishData.AlreadyOrdered && orderDishData.AlreadyOrdered.length > 0
                    }, function (result) {
                        if (result) {
                            var selectTable = result.table;
                            var isPrint = result.isPrint;
                            if (selectTable.TableStatus === TableStatus.Taken) {
                                //已开台，保存订单
                                orderDishData.changeTableSaveOrderDishes(isPrint, false, [selectTable.DiningOrderId], function (r, dishes) {
                                    if (r != undefined && !r) {
                                        bookOrderId = 0;
                                        loadOrderDishDatas(false, function () {
                                            orderDishData.ShoppingCarDishes = dishes;
                                            refreshUI();
                                            refreshShoppingCarUI();
                                        });

                                        return;
                                    }
                                    mpos.back(mpos.page.home); //返回首页
                                });
                            } else {
                                // 撤销开台
                                var cancelTableFunc = null;
                                // 原来的桌台如果没有已下单数据，开台后撤销原空台
                                if (!(orderDishData.AlreadyOrdered && orderDishData.AlreadyOrdered.length > 0)) {
                                    cancelTableFunc = function () {
                                        mpos.post(mpos.api.cancelTable, {
                                            OrderId: orderIds
                                        }, function () {
                                        })
                                    }
                                }
                                //未开台， 进行开台操作
                                openTable(selectTable, isPrint, cancelTableFunc);
                            }
                        }
                    });

                }
            });
        }
    }

    /**
     * 下单选台，选择未开台，进行开台操作
     */
    function openTable(table, isPrint, callback) {
        mpos.showDialog(mpos.dialogPage.openTable, {
            "Table": table,
        }, function (orderId) {
            if (orderId) {
                callback && callback();
                //下单
                orderDishData.changeTableSaveOrderDishes(isPrint, false, [orderId], function (r, dishes) {
                    if (r != undefined && !r) {
                        bookOrderId = 0;
                        loadOrderDishDatas(false, function () {
                            orderDishData.ShoppingCarDishes = dishes;
                            refreshUI();
                            refreshShoppingCarUI();
                        });
                        return;
                    }
                    mpos.back(mpos.page.home); //返回首页
                });
            }
        });
    }

    //是否显示登录
    if (mpos.currentUser == null) {
        mpos.showDialog(mpos.dialogPage.login, function (status) {
            if (status) {
                //加载点菜数据
                prepareLoadOrderDishDatas();
            }
        });
    } else {
        //加载点菜数据
        prepareLoadOrderDishDatas();
    }

    //缓存滚动位置
    var contentScrollOffset = 0;
    dishContainer.on("scroll", function (e) {
        contentScrollOffset = e.currentTarget.scrollTop;
    });
    //还原滚动条的位置
    $page.on("appLayout", function () {
        //mpos.log("app layout");
        if (contentScrollOffset > 0)
            dishContainer[0].scrollTop = contentScrollOffset;
    });

    /**
     * 返回上个界面
     */
    function backToPrev() {
        //购物车是否显示
        if (isShoppingCarContainerDisplayed()) {
            setTopBarSwitch();
            hideShoppingCarContainer();
            return;
        }
        //
        if (mposType != OrderPropertyType.Snack) {
            if (!mpos.isPayToOrderModel() && orderDishData.ExistsOrderDishes()) {
                mpos.dialog({
                    title: "提醒",
                    text: "存在未下单的商品，是否继续退出？点击“是”会自动暂存本次所点商品。",
                    okButton: "是",
                    cancelButton: "否"
                }, function (status) {
                    if (status) {
                        saveOrderDishDataByTableOrderId(orderDishData.TableId, orderDishData.OrderId, orderDishData.ShoppingCarDishes);
                        // 商米v2使用android7版本，导致莫名的花屏，界面动画，花屏既可以取消， 自动获取焦点，促使页面刷新
                        setTimeout(function(){
                            mpos.back(mpos.page.home); //返回首页
                        }, 100);
                    } else { }
                });
            } else {
                // 商米v2使用android7版本，导致莫名的花屏，界面动画，花屏既可以取消， 自动获取焦点，促使页面刷新
                setTimeout(function(){
                    mpos.back(mpos.page.home); //返回首页
                }, 100);
            }
        }
    }

    //返回
    this.onBackKeyDown = backToPrev;
    $page.find("#goBack").on("click", backToPrev);

    //扫码
    $page.find(".app-topbar .scan-QR").on("click", function () {
        beginScanQR();
    });

    /**
     * 页面显示
     * */
    $page.on("appShow", function () {
        if (mpos.isPayToOrderModel()) {
            if (orderDishData.ShoppingCarDishes.length == 0) {
                mpos.post(mpos.api.getPayToOrderDishes, {
                    OrderId: orderDishData.OrderId,
                }, function (dishes) {
                    orderDishData.ShoppingCarDishes = dishes;
                    refreshUI();
                    refreshShoppingCarUI();
                });
            }
        }
        // 判断如果是搜索，就添加键盘监听事件
        if (displayMode != 0) {
          onScanningGunToKeydown(true);
        }
    });

    /**
     * 页面隐藏
     * */
    $page.on("appHide", function () {
      // 判断如果是搜索，就删除键盘监听事件
      if (displayMode != 0) {
        onScanningGunToKeydown(false);
      }
    });

    /*
    开始扫码
    */
    function beginScanQR() {
        mpos.scanQR(function (result) {
            result = typeof jsonModelScanResult == "object" ?
                jsonModelScanResult : result;
            if (result.cancelled == true) {
                return;
            }
            var qrCode = result.text;
            if (qrCode.toUpperCase().indexOf("HTTP://") != -1) {
                if (orderDishData.OnlineOrderId > 0) {
                    if (isSnack) {
                        mpos.alert("此订单已导入过线上订单！");
                    } else {
                        mpos.alert("已经导入一个订单，请下单后再导新的订单！");
                    }
                    return;
                }
                mpos.post(mpos.api.importOnlineOrder, {
                    Url: qrCode,
                    OrderId: orderDishData.OrderId,
                    Dishes: JSON.stringify(orderDishData.ShoppingCarDishes),
                }, function (r) {
                    loadOrderDishDatas(false, function () {
                        orderDishData.ShoppingCarDishes = r.Dishes;
                        orderDishData.OnlineOrderId = r.OnlineOrderId; //标记为在线订单
                        refreshUI();
                        refreshShoppingCarUI();
                    });
                });
            } else { //点菜
                var dish = orderDishData.getDishBySerial(qrCode);
                if (dish == null) {
                    mpos.alert("商品不存在！");
                    // beginScanQR();   // wang.p 2025-06-19 防止找不到商品一直显示扫码
                } else {
                    beginOrderDish(dish.Dish.DishId, true);
                }
            }
        }, function (err) {
            mpos.alert("扫码错误!");
        });
    }

    /**
     * 酒楼模式下显示餐台名称和就餐人数
     * 同时判断酒楼模式下是否显示菜品大类
     * @param {} status  true=显示，false=隐藏
     */
    function showOrHideDiningTable (status) {
        if (mposType && mposType != OrderPropertyType.Snack) {
            var appContentHeader = $page.find(".app-content-header");
            var appContentBody = $page.find(".app-content-body");
            var enableBigDishTypes = mpos.localStorage.enableBigDishTypes;
            // var diningTable = $page.find(".dining-table");

            // 酒楼模式下显示就餐人和餐台，以及大类时，app-content-body的样式
            var styleClass = 'has-dining-table';
            if (enableBigDishTypes) {
                styleClass = 'has-dining-table-and-type-big';
            }
            if (status) {
                appContentHeader.removeClass('nd');
                appContentBody.addClass(styleClass);
                // diningTable.removeClass('nd');
                // dishTypeContainer.addClass('dining-table-top-22');
                // dishContainer.addClass('dining-table-top')
            } else {
                appContentHeader.addClass('nd');
                appContentBody.removeClass(styleClass);
                // diningTable.addClass('nd');
                // dishTypeContainer.removeClass('dining-table-top-22');
                // dishContainer.removeClass('dining-table-top')
            }
        }
    }

    /*
     * 隐藏和显示底部下单和更多按钮*/
    function showOrHideSubmitBtn(status) {
        if (status) {
            //隐藏
            $page.find(".doOrderDish.app-button").addClass('hide');
            $page.find(".more.app-button").addClass('hide');
        } else {
            //显示
            $page.find(".doOrderDish.app-button").removeClass('hide');
            $page.find(".more.app-button").removeClass('hide');
        }
    }

    /*
     * 显示头部分段控件
     * */
    function setTopBarSwitch(type) {
        $page.find('.app-topbar>.switch-display').empty(); //清空

        if (type && orderSwitchMode) {
            showOrHideSubmitBtn(true);
        } else {
            showOrHideSubmitBtn(false);
        }
        // 启用系统键盘，要隐藏搜索控件
        if (mpos.localStorage.enableSystemKeyboard) {
            //系统键盘时，搜索输入框隐藏，这里隐藏时再显示购物车已下单和未下单界面时，搜索框遮挡了界面
            if (type) {
                dishSearchContainer.parent().find('input[name="searchDishResult"]').addClass('nd');
            } else {
                dishSearchContainer.parent().find('input[name="searchDishResult"]').removeClass('nd');
            }
        }

        if (type) {
            //分段控件 显示点菜，和已点菜
            new mpos.Components.SegmentControl({
                parent: $page.find('.app-topbar>.switch-display'),
                data: ['未下单', '已下单'],
                debounceTime: 80,
                initIndex: orderSwitchMode,
                callback: function (index) {
                    mpos.localStorage.OrderSwitchMode = index;
                    orderSwitchMode = index;
                    showOrHideSubmitBtn(orderSwitchMode);
                    if (orderSwitchMode) {
                        //显示已下单菜品
                        refreshShoppingCarAlreadyOrdered();
                    } else {
                        //显示未下单菜品列表
                        refreshShoppingCarUI();
                    }
                }
            });
        } else {
            //分段控件
            new mpos.Components.SegmentControl({
                parent: $page.find('.app-topbar>.switch-display'),
                data: ['列表', '搜索'],
                debounceTime: 80,
                initIndex: displayMode,
                callback: function (index) {
                    mpos.localStorage.OrderDishDisplayMode = index;
                    displayMode = index;
                    switchDisplayUI();
                    showOrHideDiningTable(index != 1);
                }
            });
        }

        if (!type && orderSwitchMode == 0 && displayMode == 0) {
            showOrHideDiningTable(true);
        } else {
            showOrHideDiningTable(false);
        }

    }

    //购物车事件
    goodsCar.on("click", function () {
        if (orderDishData.ShoppingCarDishes.length == 0 && orderDishData.AlreadyOrdered.length == 0 && !isShoppingCarContainerDisplayed()) {
            return;
        }
        if (isShoppingCarContainerDisplayed()) {
            setTopBarSwitch(); //显示列表和搜索控件
            hideShoppingCarContainer();
        } else {
            setTopBarSwitch(1); //显示未下单和已下单控件
            if (orderSwitchMode) {
                //显示已下单菜品
                refreshShoppingCarAlreadyOrdered();
            } else {
                //显示未下单菜品列表
                refreshShoppingCarUI();
            }
            showShoppingCarContainer();

        }
    });

    /**
     * 下单/付款按钮事件
     */
    $page.find(".doOrderDish.app-button").on("click", function () {
        if (mposType != OrderPropertyType.Snack) {
            if (mpos.isPayToOrderModel()) {
                //快餐模式下结账
                if (!orderDishData.ExistsOrderDishes()) {
                    return;
                }

                // 判断购物车中的商品是否在销售方案中
                var invalidDish = orderDishData.invalidDishFromShoppingCar();
                if (invalidDish) {
                    return;
                }


                if (orderDishData.orderConfig.WaiterModel == 3) { //当为一单一服务员时，弹出选择服务员
                    mpos.showDialog(mpos.dialogPage.selectWaiter, {}, function (r) {
                        if (r.WaiterId > -1) {
                            var waiterId = r.WaiterId;
                            //跳转支付请求
                            paySettleToOrder(orderDishData.ShoppingCarDishes, orderIds[0], waiterId);
                            // mpos.post(mpos.api.getConsumptionPaySettle, {
                            //     OrderId: orderIds[0],
                            //     Dishes: JSON.stringify(orderDishData.ShoppingCarDishes),
                            //     WaiterId: waiterId
                            // }, function (data) {
                            //     mpos.load(mpos.page.settle, {
                            //         settle: mpos.fixSettleInfo(data),
                            //         from: "pay_to_order"
                            //     });
                            // });
                        }
                    });
                } else {
                    //跳转支付请求
                    paySettleToOrder(orderDishData.ShoppingCarDishes, orderIds[0], 0);
                    // mpos.post(mpos.api.getConsumptionPaySettle, {
                    //     OrderId: orderIds[0],
                    //     Dishes: JSON.stringify(orderDishData.ShoppingCarDishes),
                    //     WaiterId: 0
                    // }, function (data) {
                    //     mpos.load(mpos.page.settle, {
                    //         settle: mpos.fixSettleInfo(data),
                    //         from: "pay_to_order"
                    //     });
                    // });
                }

                return;
            }

            //非快餐模式下
            //封装下单函数
            var saveDishesFunc = function () {
                orderDishData.saveOrderDishes(true, false, function (r, dishes) {
                    if (r != undefined && !r) {
                        bookOrderId = 0;
                        loadOrderDishDatas(false, function () {
                            orderDishData.ShoppingCarDishes = dishes;
                            refreshUI();
                            refreshShoppingCarUI();
                        });

                        return;
                    }
                    mpos.isNeedReloadTable = true;  // 刷新home页，更新桌台显示的消费金额
                    //判断是否开启酒楼模式下单直接跳转结账界面
                    if (mpos.localStorage.enableToSettlePay) {
                        mpos.jumpToSettlePage(orderIds[0], 'home');
                    } else if (mpos.localStorage.enableKeepOrderDish) { 
                        // 开启了点餐完停留在点餐页面 
                        loadOrderDishDatas(false, function () {
                            orderDishData.ShoppingCarDishes = [];
                            refreshUI();
                            refreshShoppingCarUI();
                        });
                        // 查询订单详情
                        mpos.getSettleInfo(orderIds[0], function (settle) {
                            if (!settle) {
                                return;
                            } 
                            var orderData = settle.Orders.find(function(temp) {
                                return temp.Order.OrderId == orderIds[0]
                            });
                            if (orderData) {
                                orderDishData.AlreadyOrdered = orderData.Dishes;
                            }
                        });

                    } else {
                        mpos.back(mpos.page.home); //返回首页
                    }
                });
            }
            //点菜下单，判断是否开启了弹窗提示，弹窗提示是否确定下单
            if (mpos.localStorage.enableSubmitOrderTips) {
                mpos.dialog({
                    title: '提醒',
                    text: '是否确定下单？',
                    okButton: "是",
                    cancelButton: "否"
                }, function (res) {
                    if (res === 'ok') {
                        saveDishesFunc();
                    }
                });
            } else {
                saveDishesFunc();
            }
        } else {
            //快餐模式下结账
            if (!orderDishData.ExistsOrderDishes()) {
                return;
            }
            // 判断购物车中的商品是否在销售方案中
            var invalidDish = orderDishData.invalidDishFromShoppingCar();
            if (invalidDish) {
                return;
            }

            //跳转支付请求
            mpos.post(mpos.api.getSnackSettle, {
                OrderId: orderIds[0],
                Dishes: JSON.stringify(orderDishData.ShoppingCarDishes),
            }, function (data) {
                mpos.load(mpos.page.settle, {
                    settle: mpos.fixSettleInfo(data),
                    from: "snack_order_dish"
                });
            });
        }
    });

    /**
     * 先付款后下单接口增加一个赠送菜品的权限验证
     * @dishesData 菜品数据
     * @orderIdValue  订单ID
     * @waiterId  服务员ID
     * */
    function paySettleToOrder (dishesData, orderIdValue, waiterId) {
        //跳转支付请求
        mpos.post(mpos.api.getConsumptionPaySettle, {
            OrderId: orderIdValue,
            Dishes: JSON.stringify(dishesData),
            WaiterId: waiterId,
            IsUserAuth: 1,   // 增加先付款后下单时，判断未下单赠送的菜品是否有赠送权限， 1=验证，非1就不验证
        }, function (data) {
            mpos.load(mpos.page.settle, {
                settle: mpos.fixSettleInfo(data),
                from: "pay_to_order"
            });
        });
    }

    /**
     准备加载数据
     */
    function prepareLoadOrderDishDatas() {
        if (mposType == OrderPropertyType.Snack && orderIds[0] == 0) {
            mpos.post(mpos.api.createSnackOrder, null, function (r) {
                orderIds = [r.OrderId];
                orderDishData.OrderId = orderIds[0];
                orderDishData.OrderIds = orderIds;
                orderDishData.OnlineOrderId = r.OnlineOrderId; //快餐是实时导入，所以这里的ID并不是当时导入的ID，当为1时表示已导入，0表示未导入过
                loadOrderDishDatas(clearShoppingDishes);
            });
        } else {
            loadOrderDishDatas(clearShoppingDishes, function () {
                refreshUI();
                refreshShoppingCarUI();
            });
        }
    }

    /**
     加载本次点菜需要的数据
     */
    function loadOrderDishDatas(needClearOrderDish, callback) {

        if (dishData != null) { //如果从外部传进来的，则直接使用
            setDishData(dishData, true);
            dishData = null;
            if ((arguments.length > 1) && callback) {
                callback();
            }
            return;
        }
        var isClear = true;
        if (needClearOrderDish != undefined) {
            isClear = needClearOrderDish;
        }
        // 查询订单菜品数据
        mpos.post(mpos.api.loadOrderDishDatas, {
            OrderIds: JSON.stringify(orderIds),
            BookOrderId: bookOrderId,
            NeedClearOrderDish: isClear,
            EnabledMutilOrderDish: -1
        }, function (data) {
            setDishData(data, isClear);
            if ((arguments.length > 1) && callback) {
                callback();
            }
        });
    }

    /**
     设置数据和UI
     */
    function setDishData(data, isClear) {
        wholeBillId = data.Config.WholeBillId;
        //var t1 = new Date().getTime();
        if (!isSnack) {
            $page.data("whole_order_id", data.Config.WholeBillId); //设置被踢出检测
        }

        var dishTypes = [];
        for (var m = 0; m < mpos.BaseData.DishTypes.length; m++) {
            for (var i = 0; i < data.DishInfo.Dishes.length; i++) {
                var baseDish = mpos.BaseData.Dishes[data.DishInfo.Dishes[i].DishId];
                if (baseDish != undefined) {
                    if (baseDish.Dish.DishTypeId == mpos.BaseData.DishTypes[m].DishTypeId) {
                        dishTypes.push(mpos.BaseData.DishTypes[m]);
                        break;
                    }
                }
            }
        }
        /*
         * author： wang.p 2021-12-06
         * 记录选中的大类ID，目的是在大类切换时，通过大类ID过滤 orderDishData.dishTypes 和 orderDishData.dishes，来改变界面的渲染数据
         */
        selectedBigDishTypeId = 0;  // 设置大类默认选中全部

        orderDishData.dishTypes = dishTypes;
        orderDishData.IsSnackOrderDish = isSnack;
        orderDishData.orderConfig = data.Config;
        orderDishData.dishes = concatAndSortDishes(data.DishInfo.Dishes);  // 桌台展示的菜品数据，进行二次封装
        orderDishData.memberCard = data.MemberCard;
        orderDishData.saleOutDishes = data.DishInfo.SaleOutInfo.SaleOutDishes;   // 沽清的菜品
        orderDishData.saleOutUnits = data.DishInfo.SaleOutInfo.SaleOutPortionsDishes;  // 沽清的单位
        orderDishData.cookings = mpos.BaseData.Cookings;    // 菜品做法数组
        orderDishData.cookingTypes = mpos.BaseData.CookingTypes;  // 菜品做法类型
        orderDishData.ShoppingCarDishes = data.ShoppingCarDishes;  // 购物车菜品
        orderDishData.AlreadyOrdered = data.AlreadyOrdered;    // 已下单菜品
        orderDishData.TableId = data.TableId;   // 桌台ID
        if (orderDishData.ShoppingCarDishes == null || orderDishData.ShoppingCarDishes.length == 0) {
            var result = getOrderDishDataByTableOrderId(orderDishData.TableId, orderDishData.OrderId);
            if (result) {
                orderDishData.ShoppingCarDishes = result;
            }
        }

        if (isClear) {
            orderDishData.SessionId = mpos.genGUID();
        }
        //orderDishData.PackageDishes = mpos.BaseData.PackageDishes;
        //var t2 = new Date().getTime();
        //alert(t2 - t1);
        var teas = data.Teas;
        var snacks = data.Snacks;

        // 加载酒楼模式下，餐台名称和就餐人数
        if (mpos.localStorage.OrderPropertyType != OrderPropertyType.Snack) {
            var diningTable = $page.find(".dining-table");
            diningTable.find('.table-name span').text(orderDishData.orderConfig.TableName);
            diningTable.find('.people-number span').text(orderDishData.orderConfig.PeopleNum);

            // 判断是否显示菜品大类，同时判断是否存在大类数据
            if (mpos.localStorage.enableBigDishTypes) {
                var bigDishTypes = mpos.BaseData.BigDishType; // 大类基础数据
                // 通过菜品小类查找出对应的菜品大类数据
                var showBigDishTypes = [{DishTypeId: 0, DishTypeName: "全部", DishTypeSerial: "0"}];
                var tempBigDishTypesId = [];  // 保存大类的ID
                $.each(dishTypes, function (idx, smallType) {
                    var smallTypeId = smallType.DishTypeId;
                    for (var i = 0; i < bigDishTypes.length; i++) {
                        if (bigDishTypes[i].smallDishTypeIds.indexOf(smallTypeId) !== -1 && tempBigDishTypesId.indexOf(bigDishTypes[i].DishTypeId) === -1) {
                            showBigDishTypes.push(bigDishTypes[i]);
                            tempBigDishTypesId.push(bigDishTypes[i].DishTypeId);
                            break;
                        }
                    }
                })
                tempBigDishTypesId = null;
                orderDishData.dishBigTypes = showBigDishTypes;  // 赋值菜品大类
                setBigDishTypes(showBigDishTypes, orderDishData.dishTypes);
            }

        }

        loadDishTypes(); //加载菜品和类型
        loadDishes();

        selectTeas(teas, snacks); //加载茶芥

        setScrollData();
    }

    /**
     * 设置商品大类显示
     * @bigDishTypes   基础数据中菜品大类
     * @smallDishTypes  菜品小类
     * */
    function setBigDishTypes (showBigDishTypes, smallDishTypes) {
        // 判断是否显示菜品大类，同时判断是否存在大类数据
        if (mpos.localStorage.enableBigDishTypes) {
            // 通过菜品小类查找出对应的菜品大类数据
            var $dishTypeBigContent = $page.find(".dish-type-big-content");
            $dishTypeBigContent.removeClass('nd');
            // TODO: 设置菜品大类
            var $dishTypeBig = $dishTypeBigContent.find(".dish-type-big");
            var $bigItem = $dishTypeBig.find(".big-item").remove();
            $dishTypeBig.empty();
            var fragment = $(document.createDocumentFragment());
            if (showBigDishTypes && showBigDishTypes.length > 0) {
                $.each(showBigDishTypes, function (idx, item) {
                    var clone = $bigItem.clone();
                    if (idx === 0) {
                        // 默认选中第一个
                        clone.addClass(SELECT_TYPE_CLASS);
                        selectedBigDishTypeId = item.DishTypeId;  // 初始化大类选中
                    }
                    clone.text(item.DishTypeName);
                    clone.data("big_type_id", item.DishTypeId);
                    fragment.append(clone);
                });
            }
            $dishTypeBig.append(fragment);

            // 添加监听点击事件
            $dishTypeBig.find(".big-item").on('click', function(e) {
                // 移除之前的大类选中事件，添加当前点击选中
                var currentTarget = $(e.currentTarget);
                if (currentTarget.hasClass(SELECT_TYPE_CLASS))
                    return;

                selectedBigDishTypeId = Number(currentTarget.data("big_type_id"));  // 设置当前选中的大类ID
                $dishTypeBig.find("." + SELECT_TYPE_CLASS).removeClass(SELECT_TYPE_CLASS);
                currentTarget.addClass(SELECT_TYPE_CLASS);

                // 渲染小类，
                loadDishTypes(); //加载菜品和类型
                loadDishes();  // 加载菜品
                setScrollData();
            })
        }
    }

    /**
     * 通过大类获取小类和对应的菜品
     * @bigType  大类 0=全部或者不显示大类
     * */
    function getSmallDishTypesToBigType (bigType) {
        // 如果大类不是全部，就查找对应大类下对应小类中第一个小类
        if (bigType) {
            // 找出对应大类下包含的小类数据
            var tempAllSmallTypes = orderDishData.dishTypes;  // 临时保存对应的小类
            var currentBigDishType = orderDishData.dishBigTypes.find(function(item){
                return item.DishTypeId == bigType;
            });
            var showSmallTypes = [];
            if (currentBigDishType && currentBigDishType.smallDishTypeIds) {
                for(var i=0;i<currentBigDishType.smallDishTypeIds.length;i++) {
                    var tempTypeId = currentBigDishType.smallDishTypeIds[i];
                    var findSmallType = tempAllSmallTypes.find(function(item) {
                        return item.DishTypeId == tempTypeId
                    })
                    if (findSmallType) {
                        showSmallTypes.push(findSmallType);
                    }
                }
            }
            return showSmallTypes;

        } else {
            return orderDishData.dishTypes
        }

    }

    /**
     * 设置滚动所需要的数据及处理菜品列表滚动、菜品分类点击等事件
     */
    function setScrollData() {
        dishTypeContainer.find("li:first-of-type").addClass(SELECT_TYPE_CLASS);

        if (orderDishData.dishes.length > Config.maxDishLength) {
            //类型点击事件
            dishTypeContainer.find("li").on("click", function (e) {
                var currentTarget = $(e.currentTarget);
                if (currentTarget.hasClass(SELECT_TYPE_CLASS))
                    return;

                var typeId = currentTarget.data("type_id");
                loadDishes(typeId);
                dishTypeContainer.find("li." + SELECT_TYPE_CLASS).removeClass(SELECT_TYPE_CLASS);
                currentTarget.addClass(SELECT_TYPE_CLASS);
            });
            return;
        }

        var scrollData = [];

        //因为放入了分类信息，所以直接去分类所在位置即可
        dishContainer.find("li.dish-type").each(function () {
            scrollData.push(this.offsetTop);
        });

        if (scrollData.length <= 1)
            return;
        scrollData.push(Number.MAX_VALUE);

        /**
         * 滚动时判断滚动位置，切换菜品分类的显示
         * @param e Event
         */
        function scrollEvent(e) {
            //var scrollTop = e.currentTarget.scrollTop;
            for (var i = 0; i < scrollData.length - 1; i++) {
                if (i != currentSelectedDishType && contentScrollOffset >= scrollData[i] && contentScrollOffset < scrollData[i + 1]) {
                    currentSelectedDishType = i;
                    dishTypeContainer.find("li." + SELECT_TYPE_CLASS).removeClass(SELECT_TYPE_CLASS);
                    dishTypeContainer.find("li").eq(currentSelectedDishType).addClass(SELECT_TYPE_CLASS);
                    break;
                }
            }
        }

        dishContainer.on("scroll", scrollEvent);

        //类型点击事件
        dishTypeContainer.find("li").on("click", function (e) {
            var currentTarget = $(e.currentTarget);
            if (currentTarget.hasClass(SELECT_TYPE_CLASS))
                return;

            dishContainer.off("scroll", scrollEvent);

            //找到分类的位置并滚动过去
            //目前没有使用动画
            var typeId = currentTarget.data("type_id");
            for (var i = 0; i < orderDishData.dishTypes.length; i++) {
                if (orderDishData.dishTypes[i].DishTypeId == typeId) {
                    currentSelectedDishType = i;
                    dishContainer[0].scrollTop = scrollData[currentSelectedDishType];
                    break;
                }
            }

            dishTypeContainer.find("li." + SELECT_TYPE_CLASS).removeClass(SELECT_TYPE_CLASS);
            currentTarget.addClass(SELECT_TYPE_CLASS);

            //即时附上事件，将会触发，导致最后的分类如果不满一页，无法第一次选中
            setTimeout(function () {
                dishContainer.on("scroll", scrollEvent);
            }, 100);
        });

    }

    /**
     * 组织成点菜的数据
     * 根据菜品分类排序菜品
     * @param dishList 原始菜品列表
     */
    function concatAndSortDishes(dishList) {
        if (dishList.constructor != Array || dishList.length == 0)
            return [];

        var result = [];

        dishList.forEach(function (item) {
            var dish = {};
            var baseDish = mpos.BaseData.Dishes[item.DishId];
            if (baseDish != undefined) {
                dish.Units = [];
                dish.Dish = {
                    DishId: baseDish.Dish.DishId,
                    DishName: baseDish.Dish.DishName,
                    IsTemporary: baseDish.Dish.IsTemporary,
                    IsRandomPrice: baseDish.Dish.IsRandomPrice,
                    DishProperty: baseDish.Dish.DishProperty,
                    DishSerial: baseDish.Dish.DishSerial,
                    DishTypeId: baseDish.Dish.DishTypeId,
                    DishSpell: baseDish.Dish.DishSpell,
                    IsConfirmWeight: baseDish.Dish.IsConfirmWeight == 1,
                    PackageCategory: baseDish.Dish.PackageCategory,
                    IsRateDiscount: baseDish.Dish.IsRateDiscount,
                    IsModifyNum: baseDish.Dish.IsModifyNum,
                    IsMultiDish: baseDish.Dish.IsMultiDish, //  一品多吃菜类型，  1-一品多吃主菜
                    IsMultiMainDish: baseDish.Dish.IsMultiMainDish, //  一品多吃主菜，  1-是主菜
                };
                dish.DishCookings = baseDish.DishCookings;
                if (item.Units && item.Units.length > 0) {
                    item.Units.forEach(function (item) {
                        for (var i = 0; i < baseDish.Units.length; i++) {
                            if (baseDish.Units[i].PortionsId == item.PortionsId) {
                                item.PortionsName = baseDish.Units[i].PortionsName;
                                item.IsDefault = baseDish.Units[i].IsDefault;
                                item.EstimatedCost = baseDish.Units[i].EstimatedCost;
                                dish.Units.push(item);
                            }
                        }
                    });
                }

                result.push(dish);

            }
        });

        return result;
    }


    /**
     * 刷新UI
     */
    function refreshUI(dishIds) {
        if (dishIds != undefined) {
            dishIds.forEach(function (dishId) {
                var itemDom = $page.find("li[data-dish_id='" + dishId + "']");
                //刷新已点数量
                refreshDishShowUI(dishId, itemDom);
            });
        } else {
            orderDishData.ShoppingCarDishes.forEach(function (item) {
                var itemDom = $page.find("li[data-dish_id='" + item.DishId + "']");
                //刷新已点数量
                refreshDishShowUI(item.DishId, itemDom);
            });
        }

        refreshShoppingCarInfo();
    }

    /**
     刷新购物车内的菜品金额
     */
    function refreshShoppingCarInfo() {
        var data = orderDishData.getShopCartDishNum();
        var dishNum = data.DishNums;
        var estimatedCostRate = data.EstimatedCostRate;
        var goodsCarDishCount = goodsCar.find(".goods-car-dish-count");
        if (dishNum > 0) {
            goodsCarDishCount.attr('style', 'display:inline');
            goodsCarDishCount.text(parseFloat(dishNum));
        } else {
            goodsCarDishCount.attr('style', '');
        }
        var dishAmt = orderDishData.getShoppingCarDishAmount();
        var consumPrePerson = mpos.formatPrice(dishAmt / orderDishData.orderConfig.PeopleNum);
        $page.find(".footer").find(".estimated_cost_total_rate").html("整单毛利率:<span>" + estimatedCostRate + "</span>");
        $page.find(".footer").find(".consum_pre_person").html("人均消费:<span>" + consumPrePerson + "</span>");
        goodsCar.find(".goods-car-dish-amount").text(mpos.formatPrice(dishAmt));

        if (mpos.localStorage.enableEstimatedCost) {
            $page.find(".footer").find(".estimated_cost_total").addClass("estimated_show");
        } else {
            $page.find(".footer").find(".estimated_cost_total").removeClass("estimated_show");
        }
    }

    /**
     刷新点菜情况
     */
    function refreshDishShowUI(dishId, itemDom) {
        var dishItem = itemDom;

        /***********沽清处理************/
        refreshDishSaleoutShowUI(dishId, itemDom);
        /***********已点数量处理************/
        var info = orderDishData.getHasSelectDishNum(dishId);
        if (!info) {
            return;
        }
        //if (saleOutNum == 0) {
        //    dishItem.find(".increase").hide();
        //} else {
        //    dishItem.find(".increase").show();
        //}
        if (dishItem != undefined && dishItem.length > 0) {
            var numComponent = dishItem.find(".num");
            var estimatedCostComponent = dishItem.find(".estimated_cost");

            if (info.DishNums > 0) {
                numComponent.text(parseFloat(info.DishNums));
                if (info.DishNums > 1) {
                    numComponent.addClass("more");
                } else {
                    numComponent.removeClass("more");
                }
                //添加预估毛利率
                if (info.EstimatedCostRate && info.EstimatedCostRate.length > 0) {
                    estimatedCostComponent.text("毛利率:" + info.EstimatedCostRate).addClass("more");
                } else {
                    estimatedCostComponent.text("").addClass("more");
                }

            } else {
                numComponent.text("").removeClass("more");
                estimatedCostComponent.text("").removeClass("more");
            }

            //判断是否要显示毛利率
            if (mpos.localStorage.enableEstimatedCost) {
                estimatedCostComponent.addClass("estimated_show");
            } else {
                estimatedCostComponent.removeClass("estimated_show");
            }
        }

        var dishTypeItem = $page.find("li[data-type_id='" + info.DishTypeId + "']");
        if (dishTypeItem != undefined && dishTypeItem.length > 0) {
            if (info.DishTypeNum > 0) {
                dishTypeItem.find(".dish-count").show();
                dishTypeItem.find(".dish-count").text(parseFloat(info.DishTypeNum));
            } else {
                dishTypeItem.find(".dish-count").hide();
            }
        }
    }

    /**
     * 刷新沽清数据
     */
    function refreshDishSaleoutShowUI(dishId, itemDom) {
        /***********沽清处理************/
        var saleOutNum = orderDishData.getCanSaleDishNum(dishId);
        var $saleout = itemDom.find(".sale-out");
        if (saleOutNum == -1) { //没有设置沽清
            $saleout.remove();
        } else if (saleOutNum == 0) { //已卖完
            $saleout.text("沽");
        } else {
            $saleout.text(saleOutNum);
        }
    }

    /**
     加载菜品和菜品类型
     */
    function loadDishTypes() {
        dishTypeContainer.empty();
        var me = this;
        var fragment = $(document.createDocumentFragment());
        // 商品大类不为0，就要显示当前大类下的小类
        if (mpos.localStorage.OrderPropertyType != OrderPropertyType.Snack && selectedBigDishTypeId && selectedBigDishTypeId != 0) {
            // 查找大类下对应的小类
            var currentBigDishType = mpos.BaseData.BigDishType.find(function(item){return item.DishTypeId == selectedBigDishTypeId});
            if (currentBigDishType && currentBigDishType.smallDishTypeIds && currentBigDishType.smallDishTypeIds.length > 0) {
                // 获取大类下对应的小类
                var showDishTypes = getSmallDishTypesToBigType(selectedBigDishTypeId);
                $.each(showDishTypes, function (idx, item) {
                    if (currentBigDishType.smallDishTypeIds.indexOf(item.DishTypeId) !== -1) {
                        var clone = $dishTypeItem.clone();
                        clone.removeClass(SELECT_TYPE_CLASS);
                        clone.find(".dish-type-name").text(item.DishTypeName);
                        clone.data("type_id", item.DishTypeId);
                        clone.find(".dish-count").hide();
                        fragment.append(clone);
                    }
                });
            }
        } else {
            $.each(orderDishData.dishTypes, function (idx, item) {
                var clone = $dishTypeItem.clone();
                clone.removeClass(SELECT_TYPE_CLASS);
                clone.find(".dish-type-name").text(item.DishTypeName);
                clone.data("type_id", item.DishTypeId);
                clone.find(".dish-count").hide();
                fragment.append(clone);
            });
        }

        dishTypeContainer.append(fragment);
    }

    /**
     * 加载菜品
     * @param dishTypeId dish type id
     */
    function loadDishes(dishTypeId) {

        dishContainer.empty();
        if (orderDishData.dishTypes.length == 0)
            return;

        //写入菜品，需要判断是否菜品数量>200
        var dishList = [];

        var typeId;
        if (orderDishData.dishes.length > Config.maxDishLength || dishTypeId != undefined) {
            if (!dishTypeId && selectedBigDishTypeId) {
                // 商品大类选中了，就要先获取大类下面对应的小类，来展示
                var showDishTypes = getSmallDishTypesToBigType(selectedBigDishTypeId);
                typeId = dishTypeId || showDishTypes[0].DishTypeId;
            } else {
                typeId = dishTypeId || orderDishData.dishTypes[0].DishTypeId
            }

            // 通过类别过滤菜品信息
            dishList = orderDishData.dishes.filter(function (item) {
                return typeId == item.Dish.DishTypeId;
            });
        } else {
            dishList = orderDishData.dishes;
        }
        // 创建菜品列表组件元素
        var fragment = fragmentWithDishList(dishList);

        //处理菜品分类，插入到菜品列表中，滑动切换分类需要这个
        if (orderDishData.dishes.length <= Config.maxDishLength && dishTypeId == undefined) {
            typeId = 0;
            dishList.forEach(function (item) {
                if (item.Dish.DishTypeId != typeId) {
                    typeId = item.Dish.DishTypeId;
                    var dishType = orderDishData.dishTypes.find(function (t) {
                        return t.DishTypeId == typeId;
                    });
                    if (dishType) {
                        fragment.find("li[data-dish_id='" + item.Dish.DishId + "']")
                            .before($("<li class='dish-type' />")
                                .text(dishType.DishTypeName)
                                .data("typeId", dishType.DishTypeId));
                    }
                }
            });
        }
        dishContainer.append(fragment);

        dishContainer[0].scrollTop = 0;

        refreshUI();
    }

    /**
     * 根据菜品列表，生成document fragment
     * @param dishList
     */
    function fragmentWithDishList(dishList) {
        var fragment = $(document.createDocumentFragment());
        dishList.forEach(function (item) {
            if (item.Units.length == 0) {
                return;
            }
            // 一品多吃子菜，不显示
            if (item.Dish.IsMultiDish == 1 && item.Dish.IsMultiMainDish == 0) {
                return;
            }

            var dishItem = $dishItem.clone();
            dishItem.data("dish_id", item.Dish.DishId);
            var dishName = item.Dish.DishName;
            if (item.Units[0].PriceType == OrderDishPriceType.Special) {
                dishName = "(特)" + dishName;
            }
            if (item.Dish.IsTemporary == 1) {
                dishName = "(临)" + dishName;
            }
            // 一品多吃的表示
            if (item.Dish.IsMultiDish == 1) {
                dishItem.find(".multi-tag").text('多');
                dishItem.find(".multi-tag").removeClass('multi-tag-hide');
            }
            dishItem.find(".name").text(dishName);
            // 获取商品价格
            var priceText = mpos.formatPrice(orderDishData.getDishPrice(item));
            if (mpos.localStorage.enableUsedDefaultUnit) {
                var defaultUnit = item.Units.find(function(u) {
                    return u.IsDefault === true;
                })
                if (defaultUnit) {
                    priceText += '/'+defaultUnit.PortionsName;
                }
                if (item.Units.length > 1) {
                    dishItem.on('click', function (e) {
                        e.stopPropagation();
                        var target = $(e.target);
                        var dishId = target.parents("li").data("dish_id");
                        if (dishId) {
                            //多单位菜品显示单位和做法
                            orderDishForCooking(orderDishData.getDish(dishId));
                        }
                    })
                }
            }
            dishItem.find(".price").text(priceText);
            // 监听菜品加减事件
            dishItem.find(".dish-operation").on("click", function (e) {
                e.stopPropagation();
                if (e.target.tagName != "BUTTON")
                    return;

                var target = $(e.target);
                var dishId = target.parents("li").data("dish_id");
                var isIncrease = target.hasClass("increase"); //标识点+号还是-号
                //点菜事件
                beginOrderDish(dishId, isIncrease);
            });
            refreshDishSaleoutShowUI(item.Dish.DishId, dishItem);
            fragment.append(dishItem);
        });
        return fragment;
    }

    /**
     开始点菜
     @dishId ： 菜品ID
     @isIncrease : 是否加菜
     @isScan: 是否扫描枪加菜, 因为扫描枪扫码加菜时会触发键盘的删除按钮，导致搜索的菜品被清空
     */
    function beginOrderDish(dishId, isIncrease, isScan) {
        //reset keyboard
        kb.reset(isScan);
        var dish, hasOrderDishes;
        if (isIncrease) { //如果是加菜
            dish = orderDishData.getDish(dishId);
            if (!dish) {
                mpos.alert("该商品已停售");
                return;
            }
            // 这里防止加菜时提示Units报错  wang.p  2022-05-05
            if (!dish.Units || dish.Units.length == 0) {
                mpos.alert("抱歉，请点其他商品");
                return;
            }

            hasOrderDishes = orderDishData.getShoppingCarDish(dishId);
            var saleOutNum = orderDishData.getCanSaleDishNum(dishId);
            if (saleOutNum == 0) { //已卖完
                mpos.alert(dish.Dish.DishName + " 已经卖完");
                return;
            }

            var dishUnitId, dishType;
            if (dish.Dish.IsTemporary == 1 && dish.Dish.PackageCategory == 0) { //临时菜且非套餐,暂不支持临时套餐
                dishUnitId = dish.Units[0].PortionsId; //临时菜没有多单位
                if (hasOrderDishes.length > 0) { //继续搭配
                    orderDishForCooking(dish, function (r) {
                        refreshUI();
                        if (r != undefined && r != null) {
                            orderTempDish(r.dish, r.dish.Units[0].PortionsId);
                        }
                    });
                } else { //点临时菜
                    orderTempDish(dish, dishUnitId);
                }
            } else if (dish.Dish.IsRandomPrice == 1 && dish.Dish.IsMultiDish != 1) { //时价菜, 一品多吃的时价菜单独走
                if (dish.Units.length == 1) { //只有一个单位，且没有做法时，直接点菜
                    dishUnitId = dish.Units[0].PortionsId;
                    if (dish.DishCookings.length == 0) { //这里判断有菜品类型做法是否需要转到做法
                        dishType = orderDishData.getDishType(dish.Dish.DishTypeId);
                        if (orderDishData.orderConfig.ShowDishTypeCookingAfterOrderDish && dishType.DishTypeCookings.length > 0) {
                            orderDishForCooking(dish);
                            return;
                        }
                    } else {
                        if (orderDishData.orderConfig.ShowDishCookingAfterOrderDish) {
                            orderDishForCooking(dish);
                            return;
                        }
                    }
                    if (hasOrderDishes.length > 0) {
                        //直接加数量
                        orderDishData.increaseShoppingCarDishNum(hasOrderDishes[0].OrderDishId, 1, function () {
                            refreshUI();
                        });

                    } else {
                        mpos.showDialog(mpos.dialogPage.changeRandomPriceDishPrice, {
                            "Dish": dish,
                        }, function (status) {
                            if (status.status) {
                                if (dish.Dish.IsModifyNum == 1) {
                                    mpos.showDialog(mpos.dialogPage.changeDishNum, {
                                        DishNum: dishNum||1,
                                        DishName: dish.Dish.DishName
                                    },
                                        function (sta1) {
                                            if (sta1.status) {
                                                var num = sta1.num;
                                                dishNum = Number(Number(num).toFixed(4));
                                                if (dishNum > 0) {
                                                    orderDishData.addDishToShoppingCar({
                                                        DishId: dish.Dish.DishId,
                                                        UnitId: dishUnitId,
                                                        DishNum: dishNum,
                                                        DishName: "",
                                                        DishPrice: status.price
                                                    }, function () {
                                                        refreshUI();
                                                    });
                                                }
                                            }
                                        });
                                } else {
                                    orderDishData.addDishToShoppingCar({
                                        DishId: dish.Dish.DishId,
                                        UnitId: dishUnitId,
                                        DishNum: 1,
                                        DishName: "",
                                        DishPrice: status.price
                                    }, function () {
                                        refreshUI();
                                    });
                                }
                            }
                        });
                    }
                } else { //多单位或做法
                    // 多单位时，如果开启了显示默认单位，就直接对默认菜品进行加
                    orderDishUnitsUsedDefaultUnit(dish, hasOrderDishes);
                    // orderDishForCooking(dish);
                }
            } else if (dish.Dish.PackageCategory != 0) { //套餐
                if (hasOrderDishes.length == 0) { //购物车没有点此套餐时
                    if (dish.Dish.PackageCategory == 1) { //普通套餐
                        orderDishForNormalPackage(dish);
                    } else if (dish.Dish.PackageCategory == 2) { //分组套餐
                        orderDishForGroupPackage(dish);
                    }
                } else { //当有点此套餐时
                    var carDishIds = orderDishData.getShoppingCardDishIds();
                    orderDishForCooking(dish, function (r) {
                        if (r != undefined && r != null) { //继续搭配
                            if (r.dish.Dish.PackageCategory == 1) { //普通套餐
                                orderDishForNormalPackage(r.dish);
                            } else if (r.dish.Dish.PackageCategory == 2) { //分组套餐
                                orderDishForGroupPackage(r.dish);
                            }
                        } else {
                            refreshUI(carDishIds);
                        }
                    });
                }
            } else if (dish.Dish.IsMultiDish === 1) {
                // 一品多吃主菜
                if (hasOrderDishes.length == 0) { //购物车没有点此商品时
                    orderDishForMultiDishFunc(dish);
                } else { //当有点此套餐时
                    var carDishIds = orderDishData.getShoppingCardDishIds();
                    orderDishForCooking(dish, function (r) {
                        if (r != undefined && r != null) { //继续搭配
                            orderDishForMultiDishFunc(r.dish);
                        } else {
                            refreshUI(carDishIds);
                        }
                    });
                }

            } else { //普通菜
                if (dish.Units.length == 1) { //只有一个单位，且没有做法时，直接点菜
                    var dishNum = 1;
                    dishUnitId = dish.Units[0].PortionsId;
                    if (dish.DishCookings.length == 0) { //这里判断有菜品类型做法是否需要转到做法
                        dishType = orderDishData.getDishType(dish.Dish.DishTypeId);
                        if (orderDishData.orderConfig.ShowDishTypeCookingAfterOrderDish && dishType.DishTypeCookings.length > 0) {
                            orderDishForCooking(dish);
                            return;
                        }
                    } else {
                        if (orderDishData.orderConfig.ShowDishCookingAfterOrderDish) {
                            orderDishForCooking(dish);
                            return;
                        }
                    }
                    if (hasOrderDishes.length == 1) {
                        //直接加数量
                        orderDishData.increaseShoppingCarDishNum(hasOrderDishes[0].OrderDishId, dishNum, function () {
                            refreshUI();
                        });
                    } else if (hasOrderDishes.length > 1) { //继续搭配
                        orderDishForCooking(dish);
                    } else { //新点菜
                        if (dish.Dish.IsModifyNum == 1) {
                            mpos.showDialog(mpos.dialogPage.changeDishNum, {
                                DishNum: dishNum,
                                DishName: dish.Dish.DishName
                            },
                                function (status) {
                                    if (status.status) {
                                        var num = status.num;
                                        dishNum = Number(Number(num).toFixed(4));
                                        if (dishNum > 0) {
                                            orderDishData.addDishToShoppingCar({
                                                DishId: dish.Dish.DishId,
                                                UnitId: dishUnitId,
                                                DishNum: dishNum,
                                            }, function () {
                                                refreshUI();
                                            });
                                        }
                                    }
                                });
                        } else {
                            orderDishData.addDishToShoppingCar({
                                DishId: dish.Dish.DishId,
                                UnitId: dishUnitId,
                                DishNum: dishNum,
                            }, function () {
                                refreshUI();
                            });
                        }
                    }
                } else { //多单位或做法
                    // orderDishForCooking(dish);
                    // 多单位时，如果开启了显示默认单位，就直接对默认菜品进行加
                    orderDishUnitsUsedDefaultUnit(dish, hasOrderDishes);
                }
            }
        } else { //如果是减菜
            dish = orderDishData.getDish(dishId);
            hasOrderDishes = orderDishData.getShoppingCarDish(dishId);
            if (hasOrderDishes.length == 0) {
                return;
            }
            if (hasOrderDishes.length > 1) { //有继续搭配或多个临时菜时，需要走另外逻辑
                //继续搭配
                orderDishForCooking(dish);
            } else {
                var carDishIds = orderDishData.getShoppingCardDishIds();
                orderDishData.increaseShoppingCarDishNum(hasOrderDishes[0].OrderDishId, -1, function () {
                    refreshUI(carDishIds);
                });
            }
        }
    }

    /**
     * 有多单位，没有做法的点菜
     * @param dish
     */
    function orderMultiUnitDish(dish) {
        mpos.pick(mpos.page.orderMultiUnitDish, {
            Dish: dish,
            OrderDishData: orderDishData,
            WholeBillId: wholeBillId,
            OrderId: orderIds[0],
        }, function (data) {
            refreshUI();
        });
    }

    /**
     * 启用点菜列表显示默认单位，多单位菜品加菜直接进行默认单位加减
     * @dish   菜品
     * @hasOrderDishes   是否存在该菜品
     * @callback  回调函数
     * */
    function orderDishUnitsUsedDefaultUnit (dish, hasOrderDishes, callback) {
        // 多单位时，如果开启了显示默认单位，就直接对默认菜品进行加
        var isOrderDishForCooking = true; // 是否显示多单位或做法的弹窗流程
        if (mpos.localStorage.enableUsedDefaultUnit && dish.Units.length > 0) {
            var defaultUnit = dish.Units.find(function (u) {
                return u.IsDefault === true;
            });
            var dishUnitId = defaultUnit ? defaultUnit.PortionsId : 0;  // 默认单位ID
            var dishNum = 1;
            if (hasOrderDishes.length === 1) {
                var hasDefaultUnitDish = hasOrderDishes.find(function(hasDish) {
                    return hasDish.DishPortionsId === dishUnitId
                })
                // 多单位默认单位已添加菜品，直接增加数量
                if (hasDefaultUnitDish) {
                    isOrderDishForCooking = false;  // 停止走以前的多单位或做法的弹窗流程
                    orderDishData.increaseShoppingCarDishNum(hasDefaultUnitDish.OrderDishId, dishNum, function () {
                        refreshUI();
                    });
                }
            } else if (hasOrderDishes.length === 0){
                if (dishUnitId) {
                    isOrderDishForCooking = false;  // 停止走以前的多单位或做法的弹窗流程
                    // 添加默认菜品
                    var dishUnitId = defaultUnit.PortionsId;
                    if (dish.Dish.IsModifyNum == 1) {
                        mpos.showDialog(mpos.dialogPage.changeDishNum, {
                              DishNum: dishNum,
                              DishName: dish.Dish.DishName
                          },
                          function (status) {
                              if (status.status) {
                                  var num = status.num;
                                  dishNum = Number(Number(num).toFixed(4));
                                  if (dishNum > 0) {
                                      orderDishData.addDishToShoppingCar({
                                          DishId: dish.Dish.DishId,
                                          UnitId: dishUnitId,
                                          DishNum: dishNum,
                                      }, function () {
                                          refreshUI();
                                      });
                                  }
                              }
                          });
                    } else {
                        orderDishData.addDishToShoppingCar({
                            DishId: dish.Dish.DishId,
                            UnitId: dishUnitId,
                            DishNum: dishNum,
                        }, function () {
                            refreshUI();
                        });
                    }
                }
            }

        }
        if (isOrderDishForCooking){
            orderDishForCooking(dish);
        }
    }

    /**
     * 有做法的点菜或继续搭配的点菜
     * @param dish
     * @param callback
     */
    function orderDishForCooking(dish, callback) {
        var carDishIds = orderDishData.getShoppingCardDishIds();
        mpos.pick(mpos.page.orderDishForCooking, {
            Dish: dish,
            OrderDishData: orderDishData,
            WholeBillId: wholeBillId,
            OrderId: orderIds[0],
        }, function (data) {
            if (callback) {
                callback(data);
            } else {
                if (carDishIds.length == 0) {
                    refreshUI();
                } else {
                    refreshUI(carDishIds);
                    refreshUI();
                }
            }
        });
    }

    /**
     * 点一品多吃
     */
    function orderDishForMultiDishFunc(dish, callback) {
        mpos.pick(mpos.page.orderDishForMultiDish, {
            Dish: dish,
            OrderDishData: orderDishData,
            WholeBillId: wholeBillId,
            OrderId: orderIds[0],
        }, function (data) {
            refreshUI();
            if (callback) {
                callback();
            }
        });
    }

    /**
     * 点普通套餐
     */
    function orderDishForNormalPackage(dish, callback) {
        mpos.pick(mpos.page.orderDishForNormalPackage, {
            Dish: dish,
            OrderDishData: orderDishData,
            WholeBillId: wholeBillId,
            OrderId: orderIds[0],
        }, function (data) {
            if (data && data.OrderDishInfo != undefined) {
                orderDishData.addDishToShoppingCar(data.OrderDishInfo, function () {
                    refreshUI();
                });
            } else {
                refreshUI();
            }
            if (callback) {
                callback();
            }
        });
    }

    /**
     * 点分组套餐
     */
    function orderDishForGroupPackage(dish, callback) {
        mpos.pick(mpos.page.orderDishForGroupPackage, {
            Dish: dish,
            OrderDishData: orderDishData,
            WholeBillId: wholeBillId,
            OrderId: orderIds[0],
        }, function (data) {
            if (data && data.OrderDishInfo != undefined) {
                orderDishData.addDishToShoppingCar(data.OrderDishInfo, function () {
                    refreshUI();
                });
            } else {
                refreshUI();
            }

            if (callback) {
                callback();
            }
        });
    }

    /**
     * 点临时菜
     * @param dish
     * @param unitId
     */
    function orderTempDish(dish, unitId, callback) {
        mpos.showDialog(mpos.dialogPage.orderTempDish, {
            "Dish": dish,
            "OrderDishInfo": null
        }, function (status) {
            if (status.status) {
                var selectCooking = [];
                if ($.trim(status.cookingName).length > 0) {
                    selectCooking.push({
                        CookingId: 0,
                        CookingName: status.cookingName,
                        CookingPrice: 0,
                        Num: 1
                    });
                }
                orderDishData.addDishToShoppingCar({
                    DishId: dish.Dish.DishId,
                    UnitId: unitId,
                    DishNum: 1,
                    DishName: status.dishName,
                    DishPrice: status.price,
                    Cookings: selectCooking
                }, function () {
                    refreshUI();
                    if (callback) {
                        callback();
                    }
                });
            }
        });
    }

    /**
     * 刷新购物车UI中的菜品
     */
    function refreshShoppingCarUI() {
        shoppingCarContainer.empty();

        var fragment = $(document.createDocumentFragment());
        var sortNumber = 0;
        for (var i = 0; i < orderDishData.ShoppingCarDishes.length; i++) {
            var dish = orderDishData.ShoppingCarDishes[i];
            if (dish.DishProperty == OrderDishProperty.PackageDishChild) { //套餐子菜跳过
                continue;
            } else if (dish.DishProperty == OrderDishProperty.MultiDishChild) { //一品多吃子菜跳过
                continue;
            }
            sortNumber += 1;
            var item = $shoppingCarItem.clone(); //单个菜品列表
            item.find('.sort-number').html(sortNumber);
            item.data("order_dish_id", dish.OrderDishId);
            var dishName = dish.DishName;
            if (dish.IsFreeDish != 0) {
                dishName = (dish.IsFreeDish == 1 ? "(赠)" : "(券)") + dishName;
            }
            item.find(".name").text(dishName);
            item.find(".price").text(mpos.formatPrice(dish.DishSaleAmount));
            var detail = getOrderDishDetail(dish);
            item.find(".detail").text(detail);
            item.find(".num").text(dish.DishNum);
            if (dish.DishNum > 1) {
                item.find(".num").addClass("more");
            } else {
                item.find(".num").removeClass("more");
            }

            //点击得到操作ui
            item.on("click", function (e) {
                //判断显示已下单菜品，不进行展开
                if (orderSwitchMode) {
                    return;
                }

                if (e.target.tagName == "BUTTON")
                    return;

                if (mpos.Components.ShoppingDishOperation.has(this)) {
                    mpos.Components.ShoppingDishOperation.remove(this);
                    return;
                }

                var $currentTarget = $(e.currentTarget);
                var orderDishId = $currentTarget.data("order_dish_id");
                var orderDishInfo = orderDishData.getShoppingCarDishByOrderDishId(orderDishId);
                var baseDish = orderDishData.getDish(orderDishInfo.DishId);

                if (!baseDish) {
                    mpos.alert('该商品已停售，请先移除该商品')
                    return;
                }

                /**
                 * @type SDObject
                 */
                var options = {
                    parent: this,
                    callback: function (operationType) {
                        if (operationType == 1) { //叫起
                            orderDishData.setOrderDishHangUpDish([orderDishId], function () {
                                refreshUI();
                                refreshShoppingCarUI();
                            });
                        } else if (operationType == 2) { //数量
                            var carDishIds = orderDishData.getShoppingCardDishIds();
                            orderDishData.changeOrderDishNumShoppingCar(orderDishId, function () {
                                refreshUI(carDishIds);
                                refreshShoppingCarUI();
                            })
                        } else if (operationType == 3) { //修改
                            //开始修改
                            if (baseDish.Dish.PackageCategory > 0) { //修改套餐
                                if (baseDish.Dish.PackageCategory == 1) { //普通套餐
                                    mpos.pick(mpos.page.orderDishForNormalPackage, {
                                        Dish: baseDish,
                                        OrderDishData: orderDishData,
                                        WholeBillId: wholeBillId,
                                        OrderId: orderIds[0],
                                        OrderDishId: orderDishInfo.OrderDishId
                                    }, function (data) {
                                        if (data) {
                                            orderDishData.changePackageDishesForShoppingCar({
                                                OrderDishId: orderDishInfo.OrderDishId,
                                                OrderId: orderIds[0],
                                                SubDishes: data.OrderDishInfo.SubDishes
                                            }, function () {
                                                refreshUI();
                                                refreshShoppingCarUI();
                                            });
                                        }
                                    });
                                } else if (baseDish.Dish.PackageCategory == 2) { //分组套餐
                                    mpos.pick(mpos.page.orderDishForGroupPackage, {
                                        Dish: baseDish,
                                        OrderDishData: orderDishData,
                                        WholeBillId: wholeBillId,
                                        OrderId: orderIds[0],
                                        OrderDishId: orderDishInfo.OrderDishId
                                    }, function (data) {
                                        if (data) {
                                            orderDishData.changePackageDishesForShoppingCar({
                                                OrderDishId: orderDishInfo.OrderDishId,
                                                OrderId: orderIds[0],
                                                SubDishes: data.OrderDishInfo.SubDishes
                                            }, function () {
                                                refreshUI();
                                                refreshShoppingCarUI();
                                            });
                                        }
                                    });
                                }
                                return;
                            }
                            if (baseDish.Dish.IsMultiDish == 1) {  // IsMultiDish 判断是否是一品多吃
                                mpos.pick(mpos.page.orderDishForMultiDish, {
                                    Dish: baseDish,
                                    OrderDishData: orderDishData,
                                    WholeBillId: wholeBillId,
                                    OrderId: orderIds[0],
                                    OrderDishId: orderDishInfo.OrderDishId
                                }, function (data) {
                                    refreshUI();
                                    refreshShoppingCarUI();
                                });

                                return;
                            }

                            if (baseDish.Dish.IsTemporary == 1) { //临时菜修改
                                mpos.showDialog(mpos.dialogPage.orderTempDish, {
                                    "Dish": baseDish,
                                    "OrderDishInfo": orderDishInfo
                                }, function (status) {
                                    if (status.status) {
                                        var scookings = [];
                                        if ($.trim(status.cookingName).length > 0) {
                                            scookings.push({
                                                CookingId: 0,
                                                CookingName: status.cookingName,
                                                CookingPrice: 0,
                                                Num: 1
                                            });
                                        }
                                        orderDishData.changeOrderDishInfoForShoppingCar({
                                            OrderDishId: orderDishId,
                                            UnitId: orderDishInfo.DishPortionsId,
                                            DishName: status.dishName,
                                            DishPrice: status.price,
                                            Cookings: scookings
                                        }, function () {
                                            refreshUI();
                                            refreshShoppingCarUI();
                                        });
                                    }
                                });
                            } else { //其它菜品修改
                                mpos.pick(mpos.page.orderDishForCooking, {
                                    Dish: baseDish,
                                    OrderDishData: orderDishData,
                                    WholeBillId: wholeBillId,
                                    OrderId: orderIds[0],
                                    ModifyOrderDishId: orderDishId
                                }, function (data) {
                                    refreshUI();
                                    refreshShoppingCarUI();
                                });
                            }
                        } else if (operationType == 4) { //继续搭配
                            //继续搭配
                            mpos.pick(mpos.page.orderDishForCooking, {
                                Dish: baseDish,
                                OrderDishData: orderDishData,
                                WholeBillId: wholeBillId,
                                OrderId: orderIds[0],
                                ModifyOrderDishId: 0
                            }, function (data) {
                                var r = data;
                                if (baseDish.Dish.PackageCategory > 0) { //修改套餐
                                    if (r != undefined && r != null) { //继续搭配
                                        if (r.dish.Dish.PackageCategory == 1) { //普通套餐
                                            orderDishForNormalPackage(r.dish, function () {
                                                refreshUI();
                                                refreshShoppingCarUI();
                                            });
                                        } else if (r.dish.Dish.PackageCategory == 2) { //分组套餐
                                            orderDishForGroupPackage(r.dish, function () {
                                                refreshUI();
                                                refreshShoppingCarUI();
                                            });
                                        }
                                    } else {
                                        refreshUI();
                                        refreshShoppingCarUI();
                                    }
                                } else if (baseDish.Dish.IsTemporary == 1) { //临时菜且非套餐,暂不支持临时套餐
                                    if (r != undefined && r != null) {
                                        orderTempDish(r.dish, r.dish.Units[0].PortionsId, function () {
                                            refreshUI();
                                            refreshShoppingCarUI();
                                        });
                                    } else {
                                        refreshUI();
                                        refreshShoppingCarUI();
                                    }
                                } else if (baseDish.Dish.IsMultiDish == 1) {  // IsMultiDish 判断是否是一品多吃
                                    if (r != undefined && r != null) { //继续搭配
                                        orderDishForMultiDishFunc(r.dish, function () {
                                            refreshUI();
                                            refreshShoppingCarUI();
                                        });
                                    } else {
                                        refreshUI();
                                        refreshShoppingCarUI();
                                    }
                                } else {
                                    refreshUI();
                                    refreshShoppingCarUI();
                                }
                            });
                        }  else if (operationType == 5) { //赠送
                            var tempGiveDish = JSON.parse(JSON.stringify(orderDishInfo));
                            tempGiveDish.RealDishNum = orderDishInfo.DishNum;
                            mpos.giveDish(tempGiveDish, unSubmitGiveDish, true);
                        } else if (operationType == 6) {   /*取消赠送*/
                            unSubmitCancelGiveDish(orderDishInfo);
                        }
                    },
                    showJiaoqi: orderDishInfo.KitchenRemark < 4,
                    showNumber: orderDishInfo.TeaType != OrderDishTeaType.Tea,
                    showModify: (Array.isArray(baseDish.Units) ? baseDish.Units.length > 1 : false) || (Array.isArray(orderDishData.cookings) ? orderDishData.cookings.length > 0 : false),
                    showAddMore: true,
                    showGive: orderDishInfo.TeaType == OrderDishTeaType.Normal,
                    isFreeDish: orderDishInfo.IsFreeDish
                };


                new mpos.Components.ShoppingDishOperation(options);
            });

            //+、-事件
            item.find(".dish-operation").on("click", function (e) {
                e.stopPropagation();
                if (e.target.tagName != "BUTTON")
                    return;
                var target = $(e.target);
                var $li = target.parents("li");
                var orderDishId = $li.data("order_dish_id");
                var isIncrease = target.hasClass("increase"); //标识点+号还是-号
                var orderDish = orderDishData.getShoppingCarDishByOrderDishId(orderDishId);
                if (isIncrease) {
                    var saleOutNum = orderDishData.getCanSaleDishNum(orderDish.DishId);
                    if (saleOutNum == 0) { //已卖完
                        mpos.alert(orderDish.DishName + " 已经卖完");
                    }
                    orderDishData.increaseShoppingCarDishNum(orderDishId, 1, function () {
                        refreshUI();
                        orderDish = orderDishData.getShoppingCarDishByOrderDishId(orderDishId);
                        var _dishName = orderDish.DishName;
                        if (orderDish.IsFreeDish != 0) {
                            _dishName = (orderDish.IsFreeDish == 1 ? "(赠)" : "(券)") + _dishName;
                        }
                        $li.find(".name").text(_dishName);
                        $li.find(".price").text(mpos.formatPrice(orderDish.DishSaleAmount));
                        var detail = getOrderDishDetail(orderDish);
                        $li.find(".detail").text(detail);
                        $li.find(".num").text(orderDish.DishNum);
                        if (orderDish.DishNum > 1) {
                            $li.find(".num").addClass("more");
                        } else {
                            $li.find(".num").removeClass("more");
                        }
                        refreshShoppingCarUI();
                    });
                } else {
                    var carDishIds = orderDishData.getShoppingCardDishIds();
                    orderDishData.increaseShoppingCarDishNum(orderDishId, -1, function () {
                        refreshUI(carDishIds);
                        orderDish = orderDishData.getShoppingCarDishByOrderDishId(orderDishId);
                        if (orderDish == null) {
                            $li.remove();
                        } else {
                            var _dishName = orderDish.DishName;
                            if (orderDish.IsFreeDish != 0) {
                                _dishName = (orderDish.IsFreeDish == 1 ? "(赠)" : "(券)") + _dishName;
                            }
                            $li.find(".name").text(_dishName);
                            $li.find(".price").text(mpos.formatPrice(orderDish.DishSaleAmount));
                            var detail = getOrderDishDetail(orderDish);
                            $li.find(".detail").text(detail);
                            $li.find(".num").text(orderDish.DishNum);
                            if (orderDish.DishNum > 1) {
                                $li.find(".num").addClass("more");
                            } else {
                                $li.find(".num").removeClass("more");
                            }
                        }
                        refreshShoppingCarUI();
                    });
                }
            });

            fragment.append(item);
        }

        shoppingCarContainer.append(fragment);

        function getOrderDishDetail(orderDish) {
            var detail = "";
            if (orderDish.DishProperty == OrderDishProperty.PackageDishMain) { //套餐主菜
                if (orderDish.KitchenRemark == 4) {
                    detail += mpos.shopConfig.WaitCallUpDescption;
                }
                var subDishes = orderDishData.getPackageSubDishes(orderDish.OrderDishId);
                for (var j = 0; j < subDishes.length; j++) { //显示子菜
                    if (detail != "") {
                        detail += "、";
                    }
                    var subDish = subDishes[j];
                    detail += subDish.DishName + "*" + subDish.DishNum;
                    var cookingDesc = orderDishData.getShoppingCarDishCookingDesc(subDish.DishRequestList);
                    detail += "(" + subDish.DishPortions;
                    if (subDish.Discount < 100) {
                        detail += "、" + Number((subDish.Discount / 10).toFixed(2)) + "折";
                    }
                    if (cookingDesc != "") {
                        detail += "、" + cookingDesc;
                    }
                    detail += ")";
                }
            } else if (orderDish.DishProperty == OrderDishProperty.MultiDishMain) {  // 一品多吃主菜
                if (orderDish.KitchenRemark == 4) {
                    detail += mpos.shopConfig.WaitCallUpDescption;
                }
                // 主菜的做法显示
                var cookingDesc = orderDishData.getShoppingCarDishCookingDesc(orderDish.DishRequestList);
                if (cookingDesc != "") {
                    detail += "(" + cookingDesc + ")";
                }
                var subDishes = orderDishData.getMultiSubDishes(orderDish.OrderDishId);
                for (var j = 0; j < subDishes.length; j++) { //显示子菜
                    if (detail != "") {
                        detail += "、";
                    }
                    var subDish = subDishes[j];
                    detail += subDish.DishName + "*" + subDish.DishNum;
                    detail += "(" + subDish.DishPortions;
                    if (subDish.Discount < 100) {
                        detail += "、" + Number((subDish.Discount / 10).toFixed(2)) + "折";
                    }
                    detail += ")";
                }

            } else {
                if (orderDish.Discount < 100) {
                    detail += Number((orderDish.Discount / 10).toFixed(2)) + "折、";
                }
                if (orderDish.KitchenRemark == 4) {
                    detail += mpos.shopConfig.WaitCallUpDescption + "、";
                }
                detail += orderDish.DishPortions;
                var cookingDesc = orderDishData.getShoppingCarDishCookingDesc(orderDish.DishRequestList);
                if (cookingDesc != "") {
                    detail += "、" + cookingDesc;
                }
            }

            return detail;
        }
    }

    /*
     获取一个菜品
     */
    function findDishData(orderDishId) {
        for (var i = 0; i < orderDishData.AlreadyOrdered.length; i++) {
            if (orderDishData.AlreadyOrdered[i].OrderDishId == orderDishId) {
                return orderDishData.AlreadyOrdered[i];
            }
        }
        return null;
    }

    /**
     * 刷新购物车UI中已下单的菜品
     */
    function refreshShoppingCarAlreadyOrdered() {
        shoppingCarContainer.empty();

        var fragment = $(document.createDocumentFragment());
        //已下单菜品列表
        var alreadyOrderedList = orderDishData.AlreadyOrdered;

        //输入进入餐台的菜品
        $.each(alreadyOrderedList, function (idx, item) {
            var dishItem = $shoppingCarAlreadyItem.clone(); //单个菜品列表
            dishItem.find('.sort-number').html(idx + 1);
            dishItem.find('label.dish-selected').data("dishId", item.OrderDishId);
            dishItem.find(".dish-name").html(mpos.getDishTag(item) + item.DishName);
            dishItem.find(".dish-num").text("x" + item.DishNum);
            if (item.ReturnOrderDishId != 0) {
                dishItem.find(".dish-name").addClass('disabled');
            }
            // 显示划菜
            if (item.IsCrossDish) {
              dishItem.find(".dish-name").addClass('cross-dish')
            }
            if (item.DishProperty == OrderDishProperty.PackageDishChild) {
                dishItem.find(".dish-name").addClass('disabled');
                dishItem.find(".dish-amount").text("-");
            } else if (item.DishProperty == OrderDishProperty.MultiDishChild) {
                // 一品多吃子菜
                dishItem.find(".dish-name").addClass('disabled');
                dishItem.find(".dish-amount").text("-");
            } else {
                dishItem.find(".dish-amount").text(mpos.formatPrice(item.DishSaleAmount));
            }

            var cookies = "";
            var dishUnit = item.DishPortions;
            if (item.Discount < 100) {
                dishUnit += "/" + parseFloat((item.Discount / 10).toFixed(2)) + "折";
            }
            $.each(item.DishRequestList, function (idx, re) {
                cookies += re.RequestName + (Math.abs(re.RequestNum) == 1 ? "" : ("*" + re.RequestNum)) + "、"; //做法
            });

            if (cookies.length > 0) {
                dishItem.find(".detail").text(dishUnit + "/" + cookies.substr(0, cookies.length - 1));
            } else {
                dishItem.find(".detail").text(dishUnit);
            }
            dishItem.find(".order-date").text(item.OrderDate);
            // 菜品状态 KitchenRemark 厨房备注，0-无，1-已催菜 2-已起菜 4-叫起（支持位移运算，如2|4=6）
            if (item.KitchenRemarkDesc) {
              var statusBg = '';
              if ((item.KitchenRemark & KitchenRemarkEnum.TakeOut) == KitchenRemarkEnum.TakeOut) {
                // 起菜
              } else if ((item.KitchenRemark & KitchenRemarkEnum.QuickDish) == KitchenRemarkEnum.QuickDish){
                // 催菜
                statusBg = 'dish-status-red-bg';
              } else if ((item.KitchenRemark & KitchenRemarkEnum.Called) == KitchenRemarkEnum.Called) {
                // 等叫
                statusBg = 'dish-status-orange-bg';
              }
              var statusList = dishItem.find(".dish-status-list");
              var $dishStatus = statusList.find(".dish-status").remove();
              var descList = item.KitchenRemarkDesc.split('、');

              for(var i=0;i<descList.length;i++) {
                var statusNode = $dishStatus.clone();
                statusNode.text(descList[i]);
                statusNode.addClass('dish-status-show').addClass(statusBg);
                statusList.append(statusNode);
              }
            }
            fragment.append(dishItem);
        });

        /*****事件处理******/
        //菜品点击事件
        fragment.find("label.dish-selected").on("click", function (e) {
            var orderId = orderDishData.OrderId; //订单id
            var listItem = $(this).parents('li');
            if (mpos.Components.OrderedDishOperation.has(listItem)) {
                mpos.Components.OrderedDishOperation.remove(listItem);
                return;
            }

            var orderDishId = $(this).data("dishId");
            var dish = findDishData(orderDishId);
            var isSub = false;
            if (dish == null)
                return;
            //套餐子菜跳过
            if (dish.DishProperty == OrderDishProperty.PackageDishChild) {
                isSub = true;
            }
            //一品多吃子菜跳过
            if (dish.DishProperty == OrderDishProperty.MultiDishChild) {
                return;
            }

            //退完的菜不允许操作
            //if (dish.RealDishNum <= 0) {
            //    return;
            //}

            //只对非退的菜操作
            if (dish.ReturnOrderDishId != 0)
                return;

            // //预结不能操作
            // if (settleData.EnterOrder.Order.OrderStatus == 2) {
            //     mpos.alert("已预结，不能操作");
            //     return;
            // }

            /**
             * @type DOOptions
             */
            var options = {
                parent: $(this).parents('li'),
                callback: function (operation) {
                    switch (operation.operationType) {
                        case 1: //赠送
                            mpos.giveDish(dish, getAlreadyOrderedDishesFunc);
                            break;
                        case 2: //退菜
                            mpos.returndish(dish, getAlreadyOrderedDishesFunc);
                            break;
                        case 3: //折扣
                            mpos.discountDish(dish, getAlreadyOrderedDishesFunc);
                            break;
                        case 4: //取消赠送
                            mpos.cancelGiveDish(dish, getAlreadyOrderedDishesFunc);
                            break;
                        case 5: //修改单价
                            mpos.changeDishPrice(dish, getAlreadyOrderedDishesFunc);
                            break;
                        case 6: //起菜
                            mpos.qicai(dish, orderId, getAlreadyOrderedDishesFunc);
                            break;
                        case 7: //催菜
                            mpos.cuicai(dish, orderId, getAlreadyOrderedDishesFunc);
                            break;
                        case 8: //划菜
                            mpos.huacai(dish, orderId, getAlreadyOrderedDishesFunc);
                            break;
                        default:
                            break;
                    }
                },
                giveDish: -1,
                discountDish: false,
                returnDish: false,
                changeDishPrice: true,
                qicai: true,
                cuicai: true,
                huacai: true
            };
            if (dish.IsFreeDish == IsFreeDishType.None) {
                if (dish.TeTeaType != OrderDishTeaType.Tea && dish.RealDishNum > 0) {
                    options.giveDish = 1;
                }
                if (dish.RealDishNum > 0) {
                    options.discountDish = true;
                }
            } else if (dish.IsFreeDish == IsFreeDishType.Present) {
                if (dish.TeTeaType != OrderDishTeaType.Tea) {
                    options.giveDish = 0;
                }
                //options.changeDishPrice = false; //赠送后不能改价
            }
            if (dish.IsFreeDish == IsFreeDishType.None && dish.ReturnOrderDishId == 0 && dish.RealDishNum > 0) {
                options.returnDish = true;
            }
            if (dish.RealDishNum <= 0) { //退完了的不显示
                options.giveDish = -1;
                options.qicai = false;
                options.cuicai = false;
                options.huacai = false;
            }

            if (dish.IsFreeDish == IsFreeDishType.TicketExchange) { //兑换的不能改价
                options.changeDishPrice = false;
            }

            // 套餐子商品只能显示催菜
            if (isSub) {
              options.giveDish = -1;
              options.discountDish = false;
              options.returnDish = false;
              options.changeDishPrice = false;
              options.qicai = dish.RealDishNum <= 0 ? false : true;
              options.cuicai = dish.RealDishNum <= 0 ? false : true;
              options.huacai = dish.RealDishNum <= 0 ? false : true;
            }
            // 划菜不能进行起菜、催菜
            if (dish.IsCrossDish) {
              options.qicai = false;
              options.cuicai = false;
              options.huacai = false;
            }

            new mpos.Components.OrderedDishOperation(options);
        });

        shoppingCarContainer.append(fragment);
    }

    /**
     * 获取更新后已下单菜品*/
    function getAlreadyOrderedDishesFunc() {
        mpos.post(mpos.api.getAlreadyOrderedDishes, {
            DiningOrderId: orderDishData.OrderId
        }, function (r) {
            orderDishData.AlreadyOrdered = r;
            refreshShoppingCarAlreadyOrdered();
        });
    }


    /**
     * 获取订单详情
     * */
    function getOrderDishDetail(orderDish) {
        var detail = "";
        if (orderDish.DishProperty == 5) { //套餐主菜
            if (orderDish.KitchenRemark == 4) {
                detail += mpos.shopConfig.WaitCallUpDescption;
            }
            var subDishes = orderDishData.getPackageSubDishes(orderDish.OrderDishId);
            for (var j = 0; j < subDishes.length; j++) { //显示子菜
                if (detail != "") {
                    detail += "、";
                }
                var subDish = subDishes[j];
                detail += subDish.DishName + "*" + subDish.DishNum;
                var cookingDesc = orderDishData.getShoppingCarDishCookingDesc(subDish.DishRequestList);
                detail += "(" + subDish.DishPortions;
                if (subDish.Discount < 100) {
                    detail += "、" + Number((subDish.Discount / 10).toFixed(2)) + "折";
                }
                if (cookingDesc != "") {
                    detail += "、" + cookingDesc;
                }
                detail += ")";
            }
        } else {
            if (orderDish.Discount < 100) {
                detail += Number((orderDish.Discount / 10).toFixed(2)) + "折、";
            }
            if (orderDish.KitchenRemark == 4) {
                detail += mpos.shopConfig.WaitCallUpDescption + "、";
            }
            detail += orderDish.DishPortions;
            var cookingDesc = orderDishData.getShoppingCarDishCookingDesc(orderDish.DishRequestList);
            if (cookingDesc != "") {
                detail += "、" + cookingDesc;
            }
        }

        return detail;
    }

    /**
     弹出茶芥
     */
    function selectTeas(teas, snacks) {
        if ((teas != null && teas.length > 0) || (snacks != null && snacks.length > 0)) { //有茶芥
            var isAllDefault = true;
            for (var i = 0; i < teas.length; i++) {
                if (!teas[i].IsDefault) {
                    isAllDefault = false;
                    break;
                }
            }
            if (isAllDefault) {
                for (var i = 0; i < snacks.length; i++) {
                    if (!snacks[i].IsDefault) {
                        isAllDefault = false;
                    }
                }
            }
            var existsTea = orderDishData.ExistsTea();
            var existsSnack = orderDishData.ExistsSnack();
            var selectedTeaAndSnack = [];
            //如果全部都是默认，则自动点上茶芥
            if (isAllDefault) {
                if (!existsTea) {
                    for (var i = 0; i < teas.length; i++) {
                        selectedTeaAndSnack.push({
                            UnitId: teas[i].UnitId,
                            DishId: teas[i].DishId,
                            TeaType: OrderDishTeaType.Tea
                        });
                    }
                }
                if (!existsSnack) {
                    for (var i = 0; i < snacks.length; i++) {
                        selectedTeaAndSnack.push({
                            UnitId: snacks[i].UnitId,
                            DishId: snacks[i].DishId,
                            TeaType: OrderDishTeaType.Snack,
                            DishNum: snacks[i].StartOrderNum || 1
                        });
                    }
                }
                if (selectedTeaAndSnack.length > 0) {
                    orderDishData.addTeaAndSnackToShoppingCar(selectedTeaAndSnack, function () {
                        refreshUI();
                    });
                }
            } else { //弹出选则框
                if (existsTea && existsSnack) {
                    return;
                }
                mpos.showDialog(mpos.dialogPage.teaSelect, {
                    Teas: existsTea ? [] : teas,
                    Snacks: existsSnack ? [] : snacks
                }, function (r) {
                    if (r.status) {
                        if (!existsTea) {
                            for (var i = 0; i < r.selectedTeas.length; i++) {
                                selectedTeaAndSnack.push({
                                    UnitId: r.selectedTeas[i].UnitId,
                                    DishId: r.selectedTeas[i].DishId,
                                    TeaType: OrderDishTeaType.Tea
                                });
                            }
                        }
                        if (!existsSnack) {
                            for (var i = 0; i < r.selectedSnacks.length; i++) {
                                selectedTeaAndSnack.push({
                                    UnitId: r.selectedSnacks[i].UnitId,
                                    DishId: r.selectedSnacks[i].DishId,
                                    TeaType: OrderDishTeaType.Snack,
                                    DishNum: r.selectedSnacks[i].DishNum
                                });
                            }
                        }
                        if (selectedTeaAndSnack.length > 0) {
                            orderDishData.addTeaAndSnackToShoppingCar(selectedTeaAndSnack, function () {
                                refreshUI();
                            });
                        }
                    }
                });
            }
        }
    }

    /**
     * 动画显示购物车
     */
    function showShoppingCarContainer() {
        shoppingCarContainer.removeClass("nd");
        _.delay(function () {
            shoppingCarContainer.addClass("animation");
        }, 10);
    }

    /**
     * 动画隐藏购物车
     */
    function hideShoppingCarContainer() {
        shoppingCarContainer.removeClass("animation");
        _.delay(function () {
            shoppingCarContainer.addClass("nd");
        }, 200);
    }

    /**
     * 检测购物车是否显示
     */
    function isShoppingCarContainerDisplayed() {
        return !shoppingCarContainer.hasClass("nd");
    }

    /**
     * 未下单的菜品赠送
     * */
    function unSubmitGiveDish (giveData) {
        if (!giveData) {
            return ;
        }
        var orderDishId = giveData.OrderDishId;
        var dishNum = giveData.DishNum;  // 赠送的菜品数量
        // 查找出购物车中对应的菜品，进行数量的拆分
        var orderDishInfo = orderDishData.getShoppingCarDishByOrderDishId(orderDishId);
        var giveDishInfo = JSON.parse(JSON.stringify(orderDishInfo));  // 赠送的菜品
        var newOrderDishId = orderDishData.getMaxOrderDishId() + 1; //主键ID
        giveDishInfo.OrderDishId = newOrderDishId; //主键ID
        var oldNum = Number(giveDishInfo.DishNum);  // 原来的菜品数量
        giveDishInfo.DishNum = dishNum;
        giveDishInfo.IsFreeDish = 1;
        var refreshAmount = dishNum === orderDishInfo.DishNum;
        var subDishes = [];  // 子菜品

        // 商品做法数量修改
        if(giveDishInfo.DishRequestList && giveDishInfo.DishRequestList.length > 0) {
          var newDishRequestList = giveDishInfo.DishRequestList.map(function (item){
            return orderDishData.getDishRequestList(item, oldNum, giveDishInfo.DishNum);
          })
          giveDishInfo.DishRequestList = newDishRequestList;
        }

        if (giveDishInfo.DishProperty == OrderDishProperty.MultiDishMain) {  // 一品多吃赠送
          // 查找套餐子商品数组
          var tempSubDishes = orderDishData.getMultiSubDishes(orderDishId);
          // 修改套餐子菜数量
          tempSubDishes.forEach(function(item) {
            var oldSubNum = Number(item.DishNum.toFixed(4));  // 单份子菜品时数量，用来计算子菜做法的数量
            var subDishNum = Number(((item.DishNum / oldNum) * giveDishInfo.DishNum).toFixed(4));
            var tempSub = JSON.parse(JSON.stringify(item));
            tempSub.BelongOrderDishId = newOrderDishId;  // 关联的赠送的套餐主菜id
            tempSub.OrderDishId = newOrderDishId;  // 关联的赠送的套餐主菜id
            tempSub.IsFreeDish = 1;  // 赠送的标识
            tempSub.DishNum = subDishNum;
            tempSub.OldDishNum = subDishNum;  // 设置席(倍)数时，单桌的菜品数量
            tempSub.DishRequestList = item.DishRequestList && item.DishRequestList.map(function (item){
              return orderDishData.getDishRequestList(item, oldSubNum, subDishNum, true);
            })
            subDishes.push(tempSub)
          });

        } else if (giveDishInfo.DishProperty == OrderDishProperty.PackageDishMain) {  // 套餐
          // 查找套餐子商品数组
          var tempSubDishes = orderDishData.getPackageSubDishes(orderDishId);
          // 修改套餐子菜数量
          tempSubDishes.forEach(function(item) {
            var oldSubNum = Number(item.DishNum.toFixed(4));  // 单份子菜品时数量，用来计算子菜做法的数量
            var subDishNum = Number(((item.DishNum / oldNum) * giveDishInfo.DishNum).toFixed(4));
            var tempSub = JSON.parse(JSON.stringify(item));
            tempSub.BelongOrderDishId = newOrderDishId;  // 关联的赠送的套餐主菜id
            tempSub.OrderDishId = newOrderDishId;  // 关联的赠送的套餐主菜id
            tempSub.IsFreeDish = 1;  // 赠送的标识
            tempSub.DishNum = subDishNum;
            tempSub.OldDishNum = subDishNum;  // 设置席(倍)数时，单桌的菜品数量
            tempSub.DishRequestList = item.DishRequestList && item.DishRequestList.map(function (item){
              return orderDishData.getDishRequestList(item, oldSubNum, subDishNum, true);
            })
            subDishes.push(tempSub)
          });
        }

        orderDishData.ShoppingCarDishes.push(giveDishInfo);
        // 添加子菜品
        if (subDishes.length > 0) {
          subDishes.forEach(function (sub) {
            orderDishData.ShoppingCarDishes.push(sub);
          })
        }
        orderDishData.increaseShoppingCarDishNum(orderDishId, -dishNum, function () {
            if (refreshAmount) {
                orderDishData.calculateShoppingCarDishAmount();
            }
            // 刷新页面UI，和金额
            refreshUI();
            refreshShoppingCarUI();
        });

    }

    /**
     * 未下单的菜品取消赠送
     * */
    function unSubmitCancelGiveDish (cancelDish) {
        if (!cancelDish) {
            return;
        }
        var orderDishId = cancelDish.OrderDishId;

        var giveDishInfo = JSON.parse(JSON.stringify(cancelDish));  // 赠送的菜品
        var newOrderDishId = orderDishData.getMaxOrderDishId() + 1; //主键ID
        giveDishInfo.OrderDishId = newOrderDishId;
        giveDishInfo.IsFreeDish = 0;
        var subDishes = [];  // 子菜品
        // 查找出赠送的菜品信息
        if (cancelDish.DishProperty == OrderDishProperty.MultiDishMain) {  // 一品多吃
          // 查找子商品数组
          var tempSubDishes = orderDishData.getMultiSubDishes(orderDishId);
          // 修改套餐子菜数量
          tempSubDishes.forEach(function(item) {
            var tempSub = JSON.parse(JSON.stringify(item));
            tempSub.BelongOrderDishId = newOrderDishId;  // 关联的赠送的套餐主菜id
            tempSub.OrderDishId = newOrderDishId;  // 关联的赠送的套餐主菜id
            tempSub.IsFreeDish = 0;  // 赠送的标识
            subDishes.push(tempSub);
          });
        } else if (cancelDish.DishProperty == OrderDishProperty.PackageDishMain) {  // 套餐
          // 查找套餐子商品数组
          var tempSubDishes = orderDishData.getPackageSubDishes(orderDishId);
          // 修改套餐子菜数量
          tempSubDishes.forEach(function(item) {
            var tempSub = JSON.parse(JSON.stringify(item));
            tempSub.BelongOrderDishId = newOrderDishId;  // 关联的赠送的套餐主菜id
            tempSub.OrderDishId = newOrderDishId;  // 关联的赠送的套餐主菜id
            tempSub.IsFreeDish = 0;  // 赠送的标识
            subDishes.push(tempSub);
          });
        }

        orderDishData.ShoppingCarDishes.push(giveDishInfo);
        // 添加子菜品
        if (subDishes.length > 0) {
          subDishes.forEach(function (sub) {
            orderDishData.ShoppingCarDishes.push(sub);
          })
        }
        orderDishData.increaseShoppingCarDishNum(orderDishId, -cancelDish.DishNum, function () {
            orderDishData.calculateShoppingCarDishAmount();
            // 刷新页面UI，和金额
            refreshUI();
            refreshShoppingCarUI();
        });
    }

    /**
     * 使用扫描枪监听键盘事件
     * @status 是否开启键盘监听
     * */
    function onScanningGunToKeydown (status) {
      if (status) {
        if (!scanningGunListener) {
          scanningGunListener = true;
          document.addEventListener("keydown", scanningGunToDish);
        }
      } else {
        // 这里本应该先判断是否已经开键盘监听，暂时没有判断scanningGunListener值，一直都关闭键盘监听
        scanningGunListener = false;
        document.removeEventListener( "keydown", scanningGunToDish);
      }
    }

    /**
     * 扫描枪处理监听事件
     * */
    function scanningGunToDish (event) {
      // 放置输入框的系统键盘输入触发事件
      if (event.key == 'Process') {
        return;
      }
      // 扫码枪输入内容只能是字母和数字，没有使用正则是因为有些键时之母比如Tab
      var keyCodeList = [
        {type: 'A~Z', min: 65, max: 90},
        {type: '0~9', min: 48, max: 57},
        {type: '0~9', min: 96, max: 105},
      ]
      var hasKey = keyCodeList.find(function(item) {
        return item.min <= event.keyCode && item.max >=  event.keyCode;
      })
      if (hasKey) {
        scanningGunValue.push({value: event.key, times: new Date().getTime()});
        if (scanningGunValue.length < 2) {
          return;
        }
        if (debounceTimeout) {
          clearTimeout(debounceTimeout);
          debounceTimeout = null;
        }
        debounceTimeout = setTimeout(debounceSearchDish, 100)
      }
    }

    /**
     * 扫描枪搜索菜品
     * */
    function debounceSearchDish () {
      var isValidate = true;
      // 判断键盘输入的时间间隔必须小于50
      for(var i=1;i<scanningGunValue.length;i++) {
        if (scanningGunValue[i].times - scanningGunValue[i-1].times > 50) {
          isValidate = false;
          break;
        }
      }
      if (!isValidate) {
        scanningGunValue = [];
        return;
      }
      var scanningValues = [];
      for(var i=0;i<scanningGunValue.length;i++) {
        scanningValues.push(scanningGunValue[i]['value']);
      }

      var searchStr = scanningValues.join('').toLowerCase();
      scanningGunValue = [];
      dishSearchContainer.empty(); // 清空搜索列表
      // 判断是否启用系统默认键盘
      if (mpos.localStorage.enableSystemKeyboard) {
        //系统键盘时，清空搜索输入框
        dishSearchContainer.parent().find('input[name="searchDishResult"]').val('');
      }
      if (!searchStr || orderDishData.dishes.length == 0) {
        return;
      }
      var searchDishList = [];
      for (var i = 0, j = 0; i < orderDishData.dishes.length; i++) {
        var dish = orderDishData.dishes[i];
        //精确匹配的商品编码
        if (dish.Dish.DishSerial.toLowerCase() == searchStr) {
          searchDishList.push(dish);
          break;
        }
      }
      if (searchDishList.length > 0) {
        dishSearchContainer.append(fragmentWithDishList(searchDishList));  // 显示搜索列表
        beginOrderDish(searchDishList[0].Dish.DishId, true, true);
      }
    }

});

/**
 点时价菜改价对话框
 */
mpos.dialogController(mpos.dialogPage.changeRandomPriceDishPrice, function (page, data) {
    var $page = $(page);
    var dish = data.Dish;
    var $priceOrg = $page.find(".price-org"); //原价
    var $price = $page.find("input[name='price']"); //现价

    $priceOrg.text(mpos.formatPrice(dish.Units[0].CurrentPrice));

    $price.val(dish.Units[0].CurrentPrice);

    mpos.checkInputValue($price, InputType.Amount);

    $page.find(">div.title").text(dish.Dish.DishName);

    //确定和取消事件
    $page.find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close({
                status: false
            });
        } else {
            var amount = $.trim($price.val());
            if (amount == "") {
                mpos.alert("请输入价格");
                return;
            }
            amount = Number(amount);
            if (amount < 0) {
                mpos.alert("价格不能为负");
                return;
            }
            mpos.dialog.close({
                status: true,
                price: amount
            });
        }
    });
});

/**
 点临时菜对话框
 */
mpos.dialogController(mpos.dialogPage.orderTempDish, function (page, data) {
    var $page = $(page);
    var dish = data.Dish;
    var orderDishInfo = data.OrderDishInfo;
    var $dishName = $page.find("input[name='dishName']"); //名称
    var $price = $page.find("input[name='price']"); //价格
    var $cooking = $page.find("input[name='cooking']"); //做法

    if (orderDishInfo != null) { //修改菜品时
        $dishName.val(orderDishInfo.DishName);
        $price.val(orderDishInfo.SalePrice);
        if (orderDishInfo.DishRequestList && orderDishInfo.DishRequestList.length == 1) {
            $cooking.val(orderDishInfo.DishRequestList[0].RequestName);
        }
    } else {
        $dishName.val(dish.Dish.DishName);
        var defaultPrice = 0.00;
        // 取参考价
        if (dish.Units) {
          var defaultUnit= dish.Units.find(function (item) {
            return item.IsDefault;
          });
          if (!defaultUnit) {
            defaultUnit = dish.Units[0];
          }
          defaultPrice = defaultUnit ? defaultUnit.CurrentPrice : 0.00;
        }
        $price.val(defaultPrice);
    }

    mpos.checkInputValue($price, InputType.Amount);

    //title标题
    $page.find(">div.title").text(dish.Dish.DishName);

    //确定和取消事件
    $page.find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close({
                status: false
            });
        } else {
            var amount = $.trim($price.val());
            if (amount == "") {
                mpos.alert("请输入价格");
                return;
            }
            amount = Number(amount);
            if (amount < 0) {
                mpos.alert("价格不能为负");
                return;
            }
            var dishName = $.trim($dishName.val());
            if (dishName == "") {
                mpos.alert("请输入菜品名称");
                return;
            }
            var cookingName = $.trim($cooking.val());
            if (cookingName == null) {
                cookingName = "";
            }
            mpos.dialog.close({
                status: true,
                "price": amount,
                "dishName": dishName,
                "cookingName": cookingName
            });
        }
    });

});

/**
 修改数量
 */
mpos.dialogController(mpos.dialogPage.changeDishNum, function (page, data) {
    var $page = $(page);
    var $num = $page.find("input[name='dishNum']");
    $num.val(Number(data.DishNum));
    //监听键盘输入，输入0.时会有问题
    // mpos.checkInputValue($num, InputType.DishNum);

    $page.find(".title").text(data.DishName);

    //确定和取消事件
    $page.find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close({
                status: false
            });
        } else {

            var num = $.trim($num.val());
            if (num == "") {
                mpos.alert("输入的数量不正确");
                return;
            }
            if (!InputType[InputType.DishNum].test(num)) {
                mpos.alert("输入的数量不正确，小数点后最多3位");
                return;
            }
            num = Number(num);
            if (num < 0) {
                mpos.alert("数量不能小于0");
                return;
            }
            mpos.dialog.close({
                status: true,
                num: num
            });
        }
    });

    $num.focus(function(){
        $(this).addClass('focus-bg-color');
    });
    $num.blur(function(){
        $(this).removeClass('focus-bg-color');
    });

    // 显示修改数量时，延迟获取输入框焦点
    setTimeout(function(){
        $num.focus();
    }, 200);

    // 去掉自定义键盘，因为有些输入框需要输入小数点。
    // 判断是否启用系统默认键盘
    // if (mpos.localStorage.enableSystemKeyboard) {
    // } else {
    //     mpos.KbInstance.register({
    //         el: $page.find('input[name="dishNum"]'),
    //         callback: function (searchReg) {
    //         }
    //     });
    //     mpos.KbInstance.show({
    //         el: $page.find('input[name="dishNum"]'),
    //         callback: function (searchReg) {
    //         }
    //     });
    //     $num.addClass('focus-bg-color');
    // }

});



/**
 * Created by xeonwell on 2016/2/16.
 *
 * 有做法点菜
 */
mpos.controller(mpos.page.orderDishForCooking, function (page, data) {
    var dish = data.Dish;
    var modifyOrderDishId = 0;//要修改的购物车菜品ID
    var modifyOrderDishInfo = null;
    var dishId = dish.Dish.DishId;
    var orderDishData = data.OrderDishData;
    var orderId = data.OrderId;
    var wholeBillId = data.WholeBillId;
    var selectedCookings = []; //选中的做法
    var customCookings = [];  // 手写做法
    var hasOrderDishes = [];//已点菜品
    if (data.ModifyOrderDishId) { //获取要修改的菜品
        modifyOrderDishId = data.ModifyOrderDishId;
        modifyOrderDishInfo = orderDishData.getShoppingCarDishByOrderDishId(modifyOrderDishId);
    }

    $.selectOnFocus(page);
    var $page = $(page);
    $page.data("whole_order_id", wholeBillId); //设置被踢出检测


    var $hasOrderDish = $page.find(".has-order-dish");//已点菜品
    var $orderNewDish = $page.find(".order-new-dish");//点新菜

    var hasOrderDishContainer = $page.find(".order-dish-list");
    var $hasOrderDishItem = hasOrderDishContainer.find("li").remove();

    var dishContainer = $page.find(".dish-select");
    var $dishItem = dishContainer.find("li").remove();

    var cookingContainer = $page.find(".cooking-container");
    var $cookingItem = cookingContainer.find(".cooking-item").remove();

    var moreCookingContainer = $page.find(".more-cooking-container");
    var $moreCookingItem = moreCookingContainer.find(".cooking-item").remove();

    var $handCookieName = $page.find("input[name='hand_cookie_name']");
    var $handCookiePrice = $page.find("input[name='hand_cooke_price']");
    // 做法搜索的弹窗
    var $cookingSearchBtn = $page.find("button.cooking-search-btn");
    // 手写做法新增按钮 
    var $customCookingBtn = $page.find("button.custom-cooking-btn");
    var $customCookingList = $page.find(".custom-cooking-list");   // 手写做法的列表

    var me = this;
    var isRandomPrice = dish.Dish.IsRandomPrice == 1; //是否为时价菜
    //标题
    $page.find(".app-title").text(dish.Dish.DishName);

    //加载UI
    initUI();
    $.selectOnFocus(page);

    //返回事件
    function backToPrev() {
        me.reply();
    }
    this.onBackKeyDown = backToPrev;
    $page.find("#goBack").on("click", backToPrev);

    //提交
    $page.find(".ok.app-submit").on("click", function (e) {
        if ($orderNewDish.hasClass("nd")) {
            me.reply();
            return;
        }
        var unitId = $page.find("input[name='selectedUnit']:checked").val();
        var price = 0;
        if (isRandomPrice) {
            var $input = dishContainer.find("li[data-unit_id='" + unitId + "'] input[name='price']");
            price = parseFloat($.trim($input.val())).toFixed(2);
            if (isNaN(price)) {
                mpos.alert("请输入商品价格");
                return;
            }
        }
        
        //移除手写做法
        for (var i = 0; i < selectedCookings.length; i++) {
            if (selectedCookings[i].CookingId <= 0) {
                selectedCookings.splice(i, 1);
                break;
            }
        }
        // 添加手写做法
        if (customCookings.length > 0) {
            for(var i = 0; i < customCookings.length; i++) {
                selectedCookings.push(customCookings[i]);
            } 
        } 

        if (modifyOrderDishInfo != null) { //修改菜品
            orderDishData.changeOrderDishInfoForShoppingCar({
                OrderDishId: modifyOrderDishInfo.OrderDishId,
                UnitId: unitId,
                DishPrice: price,
                Cookings: selectedCookings
            }, function () {
                me.reply();
            });
        } else {
            if (dish.Dish.IsModifyNum == 1) {
                mpos.showDialog(mpos.dialogPage.changeDishNum, {
                    DishNum: 1,
                    DishName: dish.Dish.DishName
                },
                 function (status) {
                     if (status.status) {
                         var num = status.num;
                         var dishNum = Number(Number(num).toFixed(4));
                         if (dishNum > 0) {
                             orderDishData.addDishToShoppingCar({
                                 DishId: dish.Dish.DishId,
                                 UnitId: unitId,
                                 DishNum: dishNum,
                                 DishPrice: price,
                                 Cookings: selectedCookings
                             }, function () {
                                 me.reply();
                             });
                         }
                     }
                 });
            } else {
                orderDishData.addDishToShoppingCar({
                    DishId: dish.Dish.DishId,
                    UnitId: unitId,
                    DishNum: 1,
                    DishPrice: price,
                    Cookings: selectedCookings
                }, function () {
                    me.reply();
                });
            }
        }
    });

    /*
     加载菜品多单位
     */
    function loadDishUnit() {
        dishContainer.empty();
        var fragment = $(document.createDocumentFragment());
        for (var i = 0; i < dish.Units.length; i++) {
            var item = $dishItem.clone();
            var unit = dish.Units[i];
            item.data("unit_id", unit.PortionsId);

            if (isRandomPrice) {
                if (modifyOrderDishInfo != null) {//如果是修改已点菜品，只需要显示修改的单位价格
                    //显示已点时价菜的价格
                    if (unit.PortionsId == modifyOrderDishInfo.DishPortionsId) {
                        item.find(".price-input input").val(modifyOrderDishInfo.SalePrice);
                    } else {
                        item.find(".price-input input").val(unit.CurrentPrice);
                    }

                } else {
                    //var unitHasOrderDishes = orderDishData.getShoppingCarDish(dishId, unit.PortionsId);
                    //这里应该是有且只有一个
                    //if (unitHasOrderDishes.length == 1 && unitHasOrderDishes[0].DishNum > 0) {
                    //    //显示已点时价菜的价格
                    //    item.find(".price-input input").val(unitHasOrderDishes[0].SalePrice);
                    //} else {
                    //显示时价菜的价格
                    item.find(".price-input input").val(unit.CurrentPrice);
                    //}
                }
            } else {//隐藏时价菜
                item.find(".price-input").remove();
            }

            var checkBox = item.find("input[name='selectedUnit']");
            checkBox.val(unit.PortionsId);
            if (modifyOrderDishInfo != null) { //如果是修改，选中修改的菜品单位
                if (unit.PortionsId == modifyOrderDishInfo.DishPortionsId) {
                    checkBox.prop("checked", true);
                }
            } else { //否则，只显示默认单位
                if (unit.IsDefault) {
                    checkBox.prop("checked", true);
                }
            }
            item.find(".price").text("(" + mpos.formatPrice(unit.CurrentPrice) + ")");
            item.find(".name").text(unit.PortionsName);

            fragment.append(item);
        }

        dishContainer.append(fragment);
        fragment = null;

        //选中单位
        $page.find("input[name='selectedUnit']").on("click", function (e) {
            var $target = $(e.currentTarget);
            $page.find("input[name='selectedUnit']").prop("checked", false);
            $target.prop("checked", true);
        });
    }

    /*
     加载做法
     */
    function loadDishCooking() {
        cookingContainer.empty();
        var dishType = orderDishData.getDishType(dish.Dish.DishTypeId);
        var cookings = null;
        var hasMoreCookings = true; //是否显示更多做法
        if (dish.DishCookings.length > 0) { //有菜品关联做法时
            cookings = orderDishData.getGroupCookingsSort(dish.DishCookings);
        } else if (dishType.DishTypeCookings.length) { //有做法类型关联做法时
            cookings = orderDishData.getGroupCookingsSort(dishType.DishTypeCookings);
        } else { //都没有时，显示全部做法
            hasMoreCookings = false;
            //不显示专有做法
            cookingContainer.addClass("nd");
        }
        var scookings = [];
        if (hasMoreCookings) {
            var fragment = $(document.createDocumentFragment());
            for (var cookingGroup=0; cookingGroup < cookings.length; cookingGroup++) {
                var cookingItem = $cookingItem.clone();
                cookingItem.find(".cooking-type-name").text(cookings[cookingGroup].RequestName);
                var $list = cookingItem.find(".cooking-list");
                for (var j = 0; j < cookings[cookingGroup].Cookings.length; j++) {
                    var c = cookings[cookingGroup].Cookings[j];
                    var price = "";
                    if (c.RequestPrice > 0) {
                        price = "(+" + mpos.formatPrice(c.RequestPrice) + ")";
                    }
                    $list.append("<span data-c_id='" + c.RequestId + "' class='cooking-name textEllipsis'>" + c.CookingName + price + "</span>");
                    scookings.push(c.RequestId);
                }
                fragment.append(cookingItem);
            }

            cookingContainer.append(fragment);
            fragment = null;
        }
        //填充所有做法到更多
        var allCookingIds = [];
        for (var i = 0; i < orderDishData.cookings.length; i++) {
            if (scookings.findIndex(function (t) {
                return t == orderDishData.cookings[i].RequestId;
            }) == -1) {
                allCookingIds.push(orderDishData.cookings[i].RequestId);
            }
        }
        var allCookingGroup = orderDishData.getGroupCookingsSort(allCookingIds);
        moreCookingContainer.empty();
        var fragment = $(document.createDocumentFragment());
        for (var cookingGroup=0; cookingGroup<allCookingGroup.length; cookingGroup++) {
            var cookingItem = $moreCookingItem.clone();
            cookingItem.find(".cooking-type-name").text(allCookingGroup[cookingGroup].RequestName);
            var cookinglist = cookingItem.find(".cooking-list");
            for (var j = 0; j < allCookingGroup[cookingGroup].Cookings.length; j++) {
                var c = allCookingGroup[cookingGroup].Cookings[j];
                var price = "";
                if (c.RequestPrice > 0) {
                    price = "(+" + mpos.formatPrice(c.RequestPrice) + ")";
                }
                cookinglist.append("<span data-c_id='" + c.RequestId + "' class='cooking-name textEllipsis'>" + c.CookingName + price + "</span>");
            }
            if(cookings) {
                cookingItem.find(".cooking-type-name").addClass('collapse-cell');
                cookinglist.addClass('nd');
            }

            //if (hasMoreCookings) {
            //    cookingItem.addClass("nd");
            //}
            //cookingItem.on("click", function (e) {
            //    var $cookieTag = $(e.currentTarget);
            //    if ($target.hasClass("nd")) {
            //        $cookieTag.removeClass("nd");
            //    } else {
            //        $cookieTag.addClass("nd");
            //    }
            //});
            fragment.append(cookingItem);
        }

        moreCookingContainer.append(fragment);
        fragment = null;

        //选中修改菜品的做法
        if (modifyOrderDishInfo != null) { //取到修改的菜品的做法
            showSelectedCookingStatus(); // 渲染选中做法的状态
        }

        //做法选中事件
        cookingContainer.find("span[data-c_id]").on("click", function (e) {
            selectCooking(e);
        });
        //更多中的做法选中事件
        moreCookingContainer.find("span[data-c_id]").on("click", function (e) {
            selectCooking(e);
        });

        ////更多中的做法折叠和展开事件
        moreCookingContainer.find(".cooking-type-name").on("click", function (e) {
            //判断是否有折叠（collapse-cell）或者展开（expand-cell）的class
            if($(this).hasClass("collapse-cell")){
                $(this).removeClass('collapse-cell').addClass('expand-cell');
                var nextNode = $(this).next();
                if(nextNode && nextNode[0]) {
                    $(nextNode[0]).removeClass('nd');
                }
            }else if($(this).hasClass("expand-cell")){
                $(this).removeClass('expand-cell').addClass('collapse-cell');
                var nextNode = $(this).next();
                if(nextNode && nextNode[0]) {
                    $(nextNode[0]).addClass('nd');
                }
            }

        });
    }


    /**
     * 显示做法的选中状态
     * */
    function showSelectedCookingStatus ()  {
        // 加载手写做法
        initHandCookie(); 
        //选中修改菜品的做法
        for (var k = 0; k < selectedCookings.length; k++) {
            var allCookingTargets = $page.find("span[data-c_id='" + selectedCookings[k].CookingId + "']");
            for (var j = 0; j < allCookingTargets.length; j++) {
                $(allCookingTargets[j]).addClass("selected");
            }
        }
    }


    /*
     加载手写做法
    */
    function initHandCookie() {
        $customCookingList.empty();
        if (!customCookings || customCookings.length == 0) {
            return;
        }  
        for (var j = 0; j < customCookings.length; j++) {
            var c = customCookings[j];
            var price = "";
            if (c.CookingPrice > 0) {
                price = "(+" + mpos.formatPrice(c.CookingPrice) + ")";
            }
            $customCookingList.append("<span data-c_id='" + c.CookingId + "' class='cooking-name textEllipsis'><span class='delete-icon'>x</span>" + c.CookingName + price + "</span>");
        }
        //异常手写做法
        $customCookingList.find("span[data-c_id]").on("click", function (e) { 
            deleteCustomCooking(e);
        });
    }

    /**
     * 删除手写做法  
     */
    function deleteCustomCooking(e) {
        var $target = $(e.currentTarget);
        var cookingId = $target.data("c_id"); 
        for (var i = 0; i < customCookings.length; i++) {
            if (customCookings[i].CookingId == cookingId) {
                customCookings.splice(i, 1);
                break;
            }
        } 
        initHandCookie();
    }


    /*
     点击做法事件
     */
    function selectCooking(e) {
        var $target = $(e.currentTarget);
        var cookingId = $target.data("c_id");
        var cooking = orderDishData.getCookingById(cookingId);
        var cookingName = cooking.RequestName;
        var requestPrice = cooking.RequestPrice;
        var requestId = cooking.RequestId;

        if ($target.hasClass("selected")) {
            for (var i = 0; i < selectedCookings.length; i++) {
                if (selectedCookings[i].CookingId == requestId) {
                    selectedCookings.splice(i, 1);
                    break;
                }
            }
        } else {

            var cookingData = {
                CookingId: requestId,
                CookingName: cookingName,
                CookingPrice: requestPrice,
                Num: 1,
                BaseRequestNum: 1
            };
            if (cooking.IsRequestNum == 1) {
                // 判断做法是否支持即时录入数量
                mpos.showDialog(mpos.dialogPage.changeCookingNum, {CookingData: cookingData}, function (status) {
                    if (status.status) {
                        selectedCookings.push(status.data);
                    }
            	});
            } else {
                selectedCookings.push(cookingData);
        	}
        }
        //更新选中的样式
        var allCookingTargets = $page.find("span[data-c_id='" + cookingId + "']");
        var isSelected = $target.hasClass("selected");
        for (var j = 0; j < allCookingTargets.length; j++) {
            if (isSelected) {
                $(allCookingTargets[j]).removeClass("selected");
            } else {
                $(allCookingTargets[j]).addClass("selected");
            }
        }


    }

    /*
     加载已点菜品数据
     如果是修改已点菜品，不会执行此段逻辑
     */
    function loadHasOrderDishes(noDishClose) {
        hasOrderDishContainer.empty();
        hasOrderDishes = orderDishData.getShoppingCarDish(dishId);
        if (hasOrderDishes.length == 0) { //如果没有已点菜品
            if (dish.Dish.IsTemporary == 1 || (noDishClose != undefined && noDishClose)) {
                me.reply();
                return;
            }
            $hasOrderDish.addClass("nd");//已点菜品
            $orderNewDish.removeClass("nd");//点新菜
        }
        for (var i = 0; i < hasOrderDishes.length; i++) {
            var item = $hasOrderDishItem.clone();
            item.data("order_dish_id", hasOrderDishes[i].OrderDishId);
            item.find(".name").text("搭配" + (i + 1));
            item.find(".num").text(hasOrderDishes[i].DishNum);

            //显示明细
            if (hasOrderDishes[i].DishProperty == OrderDishProperty.PackageDishMain) {//套餐主菜
                var detail = "";
                if (hasOrderDishes[i].KitchenRemark == 4) {
                    detail +=  mpos.shopConfig.WaitCallUpDescption + "、";
                }
                var subDishes = orderDishData.getPackageSubDishes(hasOrderDishes[i].OrderDishId);
                for (var j = 0; j < subDishes.length; j++) { //显示子菜
                    if (detail != "") {
                        detail += "、";
                    }
                    var subDish = subDishes[j];
                    detail += subDish.DishName + "*" + subDish.DishNum;
                    var cookingDesc = orderDishData.getShoppingCarDishCookingDesc(subDish.DishRequestList);
                    detail += "(" + subDish.DishPortions;
                    if (subDish.Discount < 100) {
                        detail += "、" + parseFloat((subDish.Discount / 10).toFixed(2)) + "折";
                    }
                    if (cookingDesc != "") {
                        detail += "、" + cookingDesc;
                    }
                    detail += ")";
                }
                item.find(".detail").text(detail);
            } else if (hasOrderDishes[i].DishProperty == OrderDishProperty.MultiDishMain) {
                // 一品多吃
                var detail = "";
                if (hasOrderDishes[i].KitchenRemark == 4) {
                    detail +=  mpos.shopConfig.WaitCallUpDescption + "、";
                }
 				detail += hasOrderDishes[i].DishPortions;
                var cookingDesc = orderDishData.getShoppingCarDishCookingDesc(hasOrderDishes[i].DishRequestList);
                if (cookingDesc != "") {
                    detail += "(" + cookingDesc + ")";
                }
                var subDishes = orderDishData.getMultiSubDishes(hasOrderDishes[i].OrderDishId);
                for (var j = 0; j < subDishes.length; j++) { //显示子菜
                    if (detail != "") {
                        detail += "、";
                    }
                    var subDish = subDishes[j];
                    detail += subDish.DishName + "*" + subDish.DishNum;
                }
                item.find(".detail").text(detail);

            } else {
                var detail = "";
                if (dish != null && dish.Dish.IsTemporary == 1) { //临时菜显示名称和价格
                    detail += hasOrderDishes[i].DishName + "、" + mpos.formatPrice(hasOrderDishes[i].SalePrice);
                }

                if (detail != "") {
                    detail += "、";
                }
                if (hasOrderDishes[i].Discount < 100) {
                    detail += parseFloat((hasOrderDishes[i].Discount / 10).toFixed(2)) + "折、";
                }
                if (hasOrderDishes[i].KitchenRemark == 4) {
                    detail +=  mpos.shopConfig.WaitCallUpDescption + "、";
                }
				detail += hasOrderDishes[i].DishPortions;
                var cookingDesc = orderDishData.getShoppingCarDishCookingDesc(hasOrderDishes[i].DishRequestList);
                if (cookingDesc != "") {
                    detail += "、" + cookingDesc;
                }
                item.find(".detail").text(detail);
            }

            item.find(".detail").text(detail);
            item.find(".dish-operation").on("click", function (e) {
                if (e.target.tagName != "BUTTON")
                    return;
                var target = $(e.target);
                var orderDishId = target.parents("li").data("order_dish_id");
                var isIncrease = target.hasClass("increase"); //标识点+号还是-号
                var orderDish = orderDishData.getShoppingCarDishByOrderDishId(orderDishId);
                if (isIncrease) {
                    //var saleOutNum = orderDishData.getCanSaleDishNum(dishId);
                    //if (saleOutNum == 0) {//已卖完
                    //    mpos.alert(dish.DishName + " 已卖完了");
                    //    return;
                    //}
                    orderDishData.increaseShoppingCarDishNum(orderDishId, 1, function () {
                        loadHasOrderDishes(true);
                    });
                } else {
                    orderDishData.increaseShoppingCarDishNum(orderDishId, -1, function () {
                        loadHasOrderDishes(true);
                    });
                }
            });

            //修改菜品
            item.find(".modify").on("click", function (e) {
                var target = $(e.target);
                var orderDishId = target.parents("li").data("order_dish_id");
                var tmpOrderDishInfo = orderDishData.getShoppingCarDishByOrderDishId(orderDishId);
                //开始修改
                if (dish.Dish.IsTemporary == 1) { //临时菜修改
                    mpos.showDialog(mpos.dialogPage.orderTempDish, {
                        "Dish": dish,
                        "OrderDishInfo": tmpOrderDishInfo
                    }, function (status) {
                        if (status.status) {
                            var scookings = [];
                            if ($.trim(status.cookingName).length > 0) {
                                scookings.push({
                                    CookingId: 0,
                                    CookingName: status.cookingName,
                                    CookingPrice: 0,
                                    Num: 1
                                });
                            }
                            orderDishData.changeOrderDishInfoForShoppingCar({
                                OrderDishId: orderDishId,
                                UnitId: tmpOrderDishInfo.DishPortionsId,
                                DishName: status.dishName,
                                DishPrice: status.price,
                                Cookings: scookings
                            }, function () {
                                loadHasOrderDishes();
                            });
                        }
                        return;
                    });
                } else { //其它菜品修改
                    if (tmpOrderDishInfo.DishProperty == OrderDishProperty.PackageDishMain) {//如果是套餐修改
                        if (dish.Dish.PackageCategory == 1) { //普通套餐
                            mpos.pick(mpos.page.orderDishForNormalPackage, {
                                Dish: dish,
                                OrderDishData: orderDishData,
                                WholeBillId: wholeBillId,
                                OrderId: orderId,
                                OrderDishId: tmpOrderDishInfo.OrderDishId
                            }, function (data) {
                                if (data) {
                                    orderDishData.changePackageDishesForShoppingCar({
                                        OrderDishId: tmpOrderDishInfo.OrderDishId,
                                        OrderId: orderId,
                                        SubDishes: data.OrderDishInfo.SubDishes
                                    }, function () {
                                        loadHasOrderDishes();
                                    });
                                }
                            });
                        } else if (dish.Dish.PackageCategory == 2) { //分组套餐
                            mpos.pick(mpos.page.orderDishForGroupPackage, {
                                Dish: dish,
                                OrderDishData: orderDishData,
                                WholeBillId: wholeBillId,
                                OrderId: orderId,
                                OrderDishId: tmpOrderDishInfo.OrderDishId
                            }, function (data) {
                                if (data) {
                                    orderDishData.changePackageDishesForShoppingCar({
                                        OrderDishId: tmpOrderDishInfo.OrderDishId,
                                        OrderId: orderId,
                                        SubDishes: data.OrderDishInfo.SubDishes
                                    }, function () {
                                        loadHasOrderDishes();
                                    });
                                }
                            });
                        }
                    } else if (tmpOrderDishInfo.DishProperty == OrderDishProperty.MultiDishMain) {
                        // 一品多吃
                        mpos.pick(mpos.page.orderDishForMultiDish, {
                            Dish: dish,
                            OrderDishData: orderDishData,
                            WholeBillId: wholeBillId,
                            OrderId: orderId,
                            OrderDishId: tmpOrderDishInfo.OrderDishId
                        }, function (data) {
                            loadHasOrderDishes();
                        });

                    } else { //普通菜修改
                        mpos.pick(mpos.page.orderDishForCooking, {
                            Dish: dish,
                            OrderDishData: orderDishData,
                            WholeBillId: wholeBillId,
                            OrderId: orderId,
                            ModifyOrderDishId: orderDishId
                        }, function (data) {
                            loadHasOrderDishes();
                        });
                    }
                }
            });

            item.appendTo(hasOrderDishContainer);
        }
    }

    /**
     * 加载UI
     */
    function initUI() {

        //控制和显示继续点菜的内容
        hasOrderDishes = orderDishData.getShoppingCarDish(dishId);
        if (hasOrderDishes.length > 0) {
            $hasOrderDish.removeClass("nd");//已点菜品
            $orderNewDish.addClass("nd");//点新菜
            //继续搭配事件
            $page.find(".has-order-dish .continue").on("click", function (e) {
                var $target = $(e.currentTarget);
                $target.hide();
                if (dish.Dish.IsTemporary == 1) { //需要临时菜点菜
                    me.reply({
                        "dish": dish
                    });
                } else if (dish.Dish.PackageCategory != 0) { //套餐时
                    me.reply({
                        "dish": dish
                    });
                } else if (dish.Dish.IsMultiDish == 1) {
                    // 一品多吃
                    me.reply({
                        "dish": dish
                    });
                } else { //普通菜
                    $orderNewDish.removeClass("nd");//点新菜
                }
            });
        } else {
            $hasOrderDish.addClass("nd");//已点菜品
            $orderNewDish.removeClass("nd");//点新菜
        }

        //如果是修改菜品信息，则不显示已点菜品，并显示已点的做法
        if (modifyOrderDishId > 0) {
            $hasOrderDish.addClass("nd");//已点菜品
            $orderNewDish.removeClass("nd");//点新菜
        } else {//如果是修复菜品，则不显示已点菜品
            loadHasOrderDishes();
        }

        if (dish.Dish.IsTemporary == 0) { //非临时菜时加载继续点菜的内容
            //恢复已选中的做法到缓存中
            if (modifyOrderDishInfo != null) {
                for (var k = 0; k < modifyOrderDishInfo.DishRequestList.length; k++) {
                    if (modifyOrderDishInfo.DishRequestList[k].RequestId <= 0) {
                        customCookings.push({
                            CookingId: modifyOrderDishInfo.DishRequestList[k].RequestId,
                            CookingName: modifyOrderDishInfo.DishRequestList[k].RequestName,
                            CookingPrice: modifyOrderDishInfo.DishRequestList[k].RequestPrice,
                            Num: modifyOrderDishInfo.DishRequestList[k].RequestNum,
                        });
                    } else {
                        selectedCookings.push({
                            CookingId: modifyOrderDishInfo.DishRequestList[k].RequestId,
                            CookingName: modifyOrderDishInfo.DishRequestList[k].RequestName,
                            CookingPrice: modifyOrderDishInfo.DishRequestList[k].RequestPrice,
                            Num: modifyOrderDishInfo.DishRequestList[k].RequestNum,
                        });
                    }
                    
                }
            }

            //加载菜品多单位
            loadDishUnit();
            mpos.checkInputValue($handCookiePrice, InputType.Amount);
            //加载做法
            loadDishCooking();
        }
    }

    /**
     * 点击搜索做法按钮
     * */
    $cookingSearchBtn.on('click', function () {
        mpos.showDialog(mpos.dialogPage.cookingSearch, {
            Dish: dish,
            OrderDishData: orderDishData,
            CheckCookings: selectedCookings
        }, function (data) {
            if (data && data.length > 0) {
                selectedCookings = data;
                showSelectedCookingStatus();
            }
        });
    })

    
    /**
     * 点击添加手写做法按钮
     * */
    $customCookingBtn.on('click', function () { 
        //手写做法
        var handCookieName = $.trim($handCookieName.val());
        var handCookiePrice = $handCookiePrice.val(); 
        if (handCookieName == "") {
            mpos.alert("手写做法名称不能为空！");
            return;
        }

        if (handCookiePrice == "") {
            handCookiePrice = 0;
        }
        if (!mpos.isAmount(handCookiePrice)) {
            mpos.alert("手写做法价格输入错误");
            return;
        }
        handCookiePrice = Number(handCookiePrice);
        if (handCookiePrice < 0) {
            mpos.alert("手写做法价格不能小于0！");
            return;
        }
        // 遍历最小的ID
        var minCookingId = 0;
        if (customCookings.length > 0) {
            for(var i=0;i<customCookings.length;i++) {
                if (customCookings[i].CookingId < minCookingId) {
                    minCookingId = customCookings[i].CookingId;
                }
            }
        }

        customCookings.push({
            CookingId: (minCookingId - 1),
            CookingName: handCookieName,
            CookingPrice: handCookiePrice,
            Num: 1
        });

        // 重新渲染手写做法数组
        initHandCookie();
        // 清空手写输入内容
        $handCookieName.val('');
        $handCookiePrice.val(''); 
    })
});

/**
 * 点分组套餐
 */
mpos.controller(mpos.page.orderDishForGroupPackage, function (page, data) {
    var dish = data.Dish;
    var dishId = dish.Dish.DishId;
    var orderDishData = data.OrderDishData;
    var orderId = data.OrderId;
    var wholeBillId = data.WholeBillId;
    var orderDishId = 0; //修改的套餐ID
    if (data.OrderDishId != undefined) {
        orderDishId = data.OrderDishId;
    }
    var packageDishOperaion = null;//套餐操作对象

    $(page).data("whole_order_id", wholeBillId); //设置被踢出检测

    var $selectDishContainer = $(page).find(".select-dish-container"); //必选项容器
    var $itemTitle = $selectDishContainer.find(".dish-edit-list-title").remove();
    var $selectDishItems = $selectDishContainer.find(".items").remove();
    var $singleSelectItem = $selectDishItems.find(".single-select-item").remove();
    var $mutilSelectItem = $selectDishItems.find(".mutil-select-item").remove();
    var me = this;
    //标题
    $(page).find(".app-title").text(dish.Dish.DishName);

    //加载UI
    initData();

    //返回事件
    function backToPrev() {
        me.reply();
    }
    this.onBackKeyDown = backToPrev;
    $(page).find("#goBack").on("click", backToPrev);

    //提交
    $(page).find(".ok.app-submit").on("click", function (e) {
        var subDishes = $.deepClone(packageDishOperaion.orderSubDishes);
        var subDishesDict = {};  // 记录已选子菜字典
        $.each(subDishes, function (idx, item) {
            item.AddPrice = (item.AddPrice * item.DishNum).toFixed(2);
            subDishesDict[item.DishId+"_"+item.UnitId+"_"+item.PackageDishId] = item;
        });
        // 验证分组数量是否有效
        for (var i = 0; i < packageDishOperaion.packageDish.PackageGroupList.length; i++) {
          var groupDish = packageDishOperaion.packageDish.PackageGroupList[i];
          var maxCount = groupDish.PackageGroup.DishNum || 0;   // 分组最大可选数量
          var minCount = groupDish.PackageGroup.MinDishCount || 0;   // 分组最小可选数量
          var groupNotMustDishes = groupDish.PackageGroupNotMustDishList;  // 分组可选子菜
          var subTotal = 0;  // 分组下已选子菜总数量
          // 遍历计算出该分组下可选商品总数量
          $.each(groupNotMustDishes, function (idx, sub) {
            var tempSub = sub.PackageDish
            if (tempSub && subDishesDict[tempSub.DishId+"_"+tempSub.DishPortionsId+"_"+tempSub.PackageDishId]) {
              subTotal += subDishesDict[tempSub.DishId+"_"+tempSub.DishPortionsId+"_"+tempSub.PackageDishId]['DishNum'];
            }
          });
          // 验证分组最小数量
          if (minCount > 0 && minCount > subTotal) {
            mpos.alert("["+groupDish.PackageGroup.DishPackageGroupName+"]分组最少选"+minCount+"项");
            return;
          }
          // 验证分组最大数量
          if (maxCount > 0 && maxCount < subTotal) {
            mpos.alert("["+groupDish.PackageGroup.DishPackageGroupName+"]分组最多可选"+maxCount+"项");
            return;
          }
        }

        var orderDishInfo = {
            DishId: dish.Dish.DishId,
            UnitId: dish.Units[0].PortionsId,
            DishNum: 1,
            DishPrice: 0,
            SubDishes: subDishes
        };
        var isModified = false;
        if (orderDishId > 0) {
            isModified = true;
        }
        me.reply({
            OrderDishInfo: orderDishInfo,
            IsModified: isModified
        });
    });

    /**
    * 加载Data
    */
    function initData() {
        var r = mpos.GetPackageDishInfo(dishId);
        if (r == null) {
            mpos.alert("找不到套餐");
            mpos.back();
        }
        packageDishOperaion = mpos.OrderDishData.createPackageOrderDish(r, orderDishId, orderDishData);
        //如果是修改菜品，则还原子菜
        packageDishOperaion.restoreOrderDish(true);

        //必选菜加到子菜中
        for (var i = 0; i < packageDishOperaion.packageDish.PackageGroupList.length; i++) {
            var groupDish = packageDishOperaion.packageDish.PackageGroupList[i];
            for (var k = 0; k < groupDish.PackageGroupMustDishList.length; k++) {
                var pd = groupDish.PackageGroupMustDishList[k];
                if (orderDishId == 0) { //如果是新增套餐，添加到子菜集合中
                    packageDishOperaion.addToSubDishes(pd.PackageDish);
                }
            }
        }
        //加载UI
        initUI();
    }

    /**
     * 加载UI
     */
    function initUI() {
        $selectDishContainer.empty();
        for (var i = 0; i < packageDishOperaion.packageDish.PackageGroupList.length; i++) {
            var $titleClone = $itemTitle.clone();
            var groupDish = packageDishOperaion.packageDish.PackageGroupList[i];
            var title = groupDish.PackageGroup.DishPackageGroupName;
            var canSelectNum = groupDish.PackageGroup.DishNum;  // 最多可选数量
            var minSelectNum = groupDish.PackageGroup.MinDishCount || 0;  // 最少可选数量
            var strList = []
            if (minSelectNum > 0) {
              strList.push("最少选"+minSelectNum+"项");
            }
            if (canSelectNum > 0) {
              strList.push("最多可选" + canSelectNum + "项");
            }
            if (strList.length > 0) {
              title += "(" + strList.join(',') + ")"
            }
            $titleClone.text(title);
            $selectDishContainer.append($titleClone);
            var $itemCloneParent = $selectDishItems.clone().empty();
            $itemCloneParent.data("g_id", groupDish.PackageGroup.DishPackageGroupId);
            //增加必选
            for (var k = 0; k < groupDish.PackageGroupMustDishList.length; k++) {
                var $itemClone = $singleSelectItem.clone(); //必选的都为单选模板
                var pd = groupDish.PackageGroupMustDishList[k];
                $itemClone.data("p_id", pd.PackageDish.PackageDishId); //子菜的对应ID
                var pgDish = mpos.GetBaseDishInfo(pd.PackageDish.DishId);
                var name = pgDish.Dish.DishName;
                // 单位
                if (pd.PackageDish.DishPortionsId > 0 && pgDish.Units) {
                  var dishUnit = pgDish.Units.find(function(item) {
                    return item.PortionsId == pd.PackageDish.DishPortionsId;
                  });
                  if (dishUnit) {
                    name += "["+dishUnit['PortionsName']+"]";
                  }
                }
                if (pd.PackageDish.DishNum > 1) {
                    name += "*" + pd.PackageDish.DishNum;
                }
                $itemClone.find(".name").text(name);
                // 设置沽清状态
                refreshDishSaleoutShowUI(pd.PackageDish.DishId, $itemClone);
                var checkBoxItem = $itemClone.find("input[name='selectSubDish']");
                checkBoxItem.prop("checked", true);
                checkBoxItem.prop("disabled", true);

                //选做法
                $itemClone.on("click", function (e) {
                    var $currentTarget = $(e.currentTarget);
                    mpos.packageSubDishPage.show({
                        SubDishes: packageDishOperaion.orderSubDishes,
                        PackageDishId: $currentTarget.data("p_id"),
                        OrderDishData: orderDishData,
                        PackageDish: packageDishOperaion.packageDish
                    }, function () {
                        initUI();
                    });
                });
                $itemCloneParent.append($itemClone);
            }
            //增加可选
            for (var k = 0; k < groupDish.PackageGroupNotMustDishList.length; k++) {
                var $itemClone = null;
                var pd = groupDish.PackageGroupNotMustDishList[k];
                if (canSelectNum > 1) { //多选模板
                    $itemClone = $mutilSelectItem.clone();
                    $itemClone.data("p_id", pd.PackageDish.PackageDishId); //子菜的对应ID
                    $itemClone.data("is_single", 0);
                    var pgDish = mpos.GetBaseDishInfo(pd.PackageDish.DishId);
                    var name = pgDish.Dish.DishName;
                    // 单位
                    if (pd.PackageDish.DishPortionsId > 0 && pgDish.Units) {
                      var dishUnit = pgDish.Units.find(function(item) {
                        return item.PortionsId == pd.PackageDish.DishPortionsId;
                      });
                      if (dishUnit) {
                        name += "["+dishUnit['PortionsName']+"]";
                      }
                    }
                    if (pd.PackageDish.SubDishPrice > 0) {
                        name += "(+" + mpos.formatPrice(pd.PackageDish.SubDishPrice) + ")";
                    }
                    $itemClone.find(".name").text(name);
                    // 设置沽清状态
                    refreshDishSaleoutShowUI(pd.PackageDish.DishId, $itemClone);
                    var $num = $itemClone.find(".num");
                    $num.text("");
                    var hasorder = packageDishOperaion.getHasOrderSubDish(pd.PackageDish.PackageDishId);
                    if (hasorder != null) { //展示已选中的菜
                        $num.text(hasorder.DishNum);
                    }
                    //+ -事件和进去做法事件
                    $itemClone.on("click", function (e) {
                        if (e.target.tagName == "LI" || e.target.tagName == "P") { //进入选做法
                            var pid = 0;
                            if (e.target.tagName == "LI") {
                                pid = $(e.target).data("p_id");
                            } else {
                                pid = $(e.target).parents("li").data("p_id");
                            }
                            if (packageDishOperaion.checkHasOrderSubDish(pid)) {
                                //进入选做法界面
                                mpos.packageSubDishPage.show({
                                    SubDishes: packageDishOperaion.orderSubDishes,
                                    PackageDishId: pid,
                                    OrderDishData: orderDishData,
                                    PackageDish: packageDishOperaion.packageDish
                                }, function () { initUI(); });
                            }
                            return;
                        }
                        if (e.target.tagName != "BUTTON")
                            return;
                        var target = $(e.target);
                        var pid = target.parents("li").data("p_id");
                        var gid = target.parents("ul").data("g_id");
                        var group = packageDishOperaion.getDishGroupById(gid);  // 获取分组信息
                        var totalAllowNum = group.PackageGroup.DishNum; //总共可选数量
                        var isIncrease = target.hasClass("increase"); //标识点+号还是-号
                        //获取已点一个组的可选已点数量
                        var hasOrderNum = packageDishOperaion.getNotMustSelectDishNumByGroupId(gid);
                        var hasOrderDish = packageDishOperaion.getHasOrderSubDish(pid);
                        if (isIncrease) {  // 添加子商品
                          // 相同子商品再添加时，要判断是否开启相同子商品是否允许重复添加，
                          if (hasOrderDish && group.PackageGroup.OnlyOneForSameDish == 1) {
                            mpos.alert('该子商品最多可选1项');
                            return
                          }

                          var addNum = 1;
                            // 如果这个子菜之前没有加过，就要获取该子菜起点数量，然后再比较总共可选数量是否超了，不能默认就是数量1
                            if (!hasOrderDish) {
                                var willAddDish = packageDishOperaion.packageDish.PackageDishList.find(function(item) {
                                   return  item.PackageDish.PackageDishId == pid;
                                });
                                addNum = willAddDish.PackageDish.DishNum || 1;
                            }
                            if (hasOrderNum + addNum <= totalAllowNum) { //数量加1或点一个子菜
                                if (hasOrderDish != null) {
                                    hasOrderDish.DishNum += addNum;
                                } else { //增加一个数量
                                    for (var k = 0; k < packageDishOperaion.packageDish.PackageDishList.length; k++) {
                                        if (packageDishOperaion.packageDish.PackageDishList[k].PackageDish.PackageDishId == pid) {
                                            packageDishOperaion.addToSubDishes(packageDishOperaion.packageDish.PackageDishList[k].PackageDish, addNum);
                                            hasOrderDish = packageDishOperaion.getHasOrderSubDish(pid);
                                            hasOrderDish.AddPrice = packageDishOperaion.packageDish.PackageDishList[k].PackageDish.SubDishPrice;
                                            break;
                                        }
                                    }
                                }
                            }
                        } else {
                            if (hasOrderDish != null) {
                                // 查询子菜起点数量，数量和当前已有数量一样，就全部移除
                                var willAddDish = packageDishOperaion.packageDish.PackageDishList.find(function(item) {
                                    return  item.PackageDish.PackageDishId == pid;
                                });
                                if (willAddDish && willAddDish.PackageDish.DishNum === hasOrderDish.DishNum) {
                                    packageDishOperaion.removeSubDishes(pid);
                                } else {
                                    if (hasOrderDish.DishNum - 1 <= 0) {
                                        packageDishOperaion.removeSubDishes(pid);
                                    } else {
                                        hasOrderDish.DishNum -= 1;
                                    }
                                }
                            }
                        }
                        //重新获取并刷新
                        hasOrderDish = packageDishOperaion.getHasOrderSubDish(pid);
                        var $num = target.parents("li").find(".num");
                        if (hasOrderDish == null) {
                            $num.text("");
                        } else {
                            $num.text(hasOrderDish.DishNum);
                        }
                    });
                } else {//单选模板
                    $itemClone = $singleSelectItem.clone();
                    $itemClone.data("p_id", pd.PackageDish.PackageDishId); //子菜的对应ID
                    $itemClone.data("is_single", 1);
                    var pgDish = mpos.GetBaseDishInfo(pd.PackageDish.DishId);
                    var name = pgDish.Dish.DishName;
                    var num = pd.PackageDish.DishNum;
                    if (num > canSelectNum) {
                        continue;
                    }
                    // 单位
                    if (pd.PackageDish.DishPortionsId > 0 && pgDish.Units) {
                      var dishUnit = pgDish.Units.find(function(item) {
                        return item.PortionsId == pd.PackageDish.DishPortionsId;
                      });
                      if (dishUnit) {
                        name += "["+dishUnit['PortionsName']+"]";
                      }
                    }
                    if (num > 1) {
                        name += "*" + num;
                    }
                    if (pd.PackageDish.SubDishPrice > 0) {
                        name += "(+" + mpos.formatPrice(pd.PackageDish.SubDishPrice) + ")";
                    }
                    $itemClone.find(".name").text(name);
                    // 设置沽清状态
                    refreshDishSaleoutShowUI(pd.PackageDish.DishId, $itemClone);
                    var checkBoxItem = $itemClone.find("input[name='selectSubDish']");
                    //恢复原来选中的数据
                    if (packageDishOperaion.checkHasOrderSubDish(pd.PackageDish.PackageDishId)) {
                        checkBoxItem.prop("checked", true);
                    }
                    if (num > canSelectNum) { //当大于可选数量时，禁止选择
                        checkBoxItem.prop("disabled", true);
                        checkBoxItem.prop("checked", false);
                    }

                    //选做法
                    $itemClone.on("click", function (e) {
                        if (e.target.tagName == "INPUT") {
                            return;
                        }
                        var $currentTarget = $(e.currentTarget);
                        var selectSubDish = $currentTarget.find("input[name='selectSubDish']");
                        var checked = selectSubDish.prop("checked");
                        if (!checked) {
                            selectSubDish.trigger("click");
                            return;
                        }
                        //进入选做法界面
                        mpos.packageSubDishPage.show({
                            SubDishes: packageDishOperaion.orderSubDishes,
                            PackageDishId: $currentTarget.data("p_id"),
                            OrderDishData: orderDishData,
                            PackageDish: packageDishOperaion.packageDish
                        }, function () { initUI(); });
                    });

                    //选中可选菜
                    $itemClone.find("input[name='selectSubDish']").on("click", function (e) {
                        e.stopPropagation();
                        var $currentTarget = $(e.currentTarget);
                        var pid = $currentTarget.parent().data("p_id");
                        if ($currentTarget.prop("checked")) {
                            $.each($currentTarget.parents("ul").find("input[name='selectSubDish']:checked").not(":disabled"), function (index, item) {
                                packageDishOperaion.removeSubDishes($(item).parents("li").data("p_id"));
                            });
                            $currentTarget.parents("ul").find("input[name='selectSubDish']").not(":disabled").prop("checked", false);
                            $currentTarget.prop("checked", true);
                            for (var k = 0; k < packageDishOperaion.packageDish.PackageDishList.length; k++) {
                                if (packageDishOperaion.packageDish.PackageDishList[k].PackageDish.PackageDishId == pid) {
                                    // 默认设置的子菜数量
                                    var addNum = packageDishOperaion.packageDish.PackageDishList[k].PackageDish.DishNum || 1;
                                    packageDishOperaion.addToSubDishes(packageDishOperaion.packageDish.PackageDishList[k].PackageDish, addNum);
                                    var hasOrderDish = packageDishOperaion.getHasOrderSubDish(pid);
                                    hasOrderDish.AddPrice = packageDishOperaion.packageDish.PackageDishList[k].PackageDish.SubDishPrice;
                                    break;
                                }
                            }
                        } else {
                            packageDishOperaion.removeSubDishes(pid);
                        }
                    });
                }

                $itemCloneParent.append($itemClone);
            }
            $selectDishContainer.append($itemCloneParent);
        }
    }


    /**
     * 刷新沽清数据
     */
    function refreshDishSaleoutShowUI(dishId, itemDom) {
      /***********沽清处理************/
      var saleOutNum = orderDishData.getCanSaleDishNum(dishId);
      var $saleout = itemDom.find(".sale-out");
      if (saleOutNum == -1) { //没有设置沽清
        $saleout.remove();
      } else if (saleOutNum == 0) { //已卖完
        $saleout.text("沽");
        $saleout.addClass('sale-out-show');
      } else {
        $saleout.text(saleOutNum);
        $saleout.addClass('sale-out-show');
      }
    }

});

/**
 * author: wang.p 2022-04-28
 * 点一品多吃
 */
mpos.controller(mpos.page.orderDishForMultiDish, function (page, data) {
  var dish = data.Dish;
  var dishId = dish.Dish.DishId;
  var orderDishData = data.OrderDishData;
  var wholeBillId = data.WholeBillId;
  var orderDishId = 0; //修改的一品多吃的ID
  if (data.OrderDishId != undefined) {
    orderDishId = data.OrderDishId;
  }
  var packageDishOperaion = null;//一品多吃操作对象

  $(page).data("whole_order_id", wholeBillId); //设置被踢出检测

  var me = this;
  var $multiDishNum = $(page).find('input.multi-dish-num');  // 一品多吃主菜数量
  var $dishTotalPrice = $(page).find('.multi-dish-price'); // 价格显示
  var $multiSubDishList = $(page).find(".multi-sub-dish-list"); //子菜
  var $multiDishCookingList = $(page).find(".multi-dish-cooking-list"); //做法
  var $cookingTabList = $(page).find('.cooking-menu .tab-list'); //做法类别菜单
  var $filterMultiDishCookingList = $(page).find(".filter-multi-dish-cooking-list"); //过滤做法

  var $multiSubItem = $multiSubDishList.find(".multi-sub-item").remove();  // 子菜单个项
  var $multiCookingItem = $multiDishCookingList.find(".cooking-item").remove();  // 单个做法项
  var $filterMultiCookingItem = $filterMultiDishCookingList.find(".cooking-item").remove();  // 单个做法项
  var $cookingTab = $cookingTabList.find(".tab").remove();  // 做法类别项

  //标题
  $(page).find(".app-title").text(dish.Dish.DishName);

  //加载Data
  initData();

  //返回事件
  function backToPrev() {
    me.reply();
  }
  this.onBackKeyDown = backToPrev;
  $(page).find("#goBack").on("click", backToPrev);

  //提交
  $(page).find(".ok.app-submit").on("click", function (e) {
      // 菜品总价格
      var mainDishPrice = orderDishData.getDishPrice(dish); // 获取价格

      /// 做法
      var selectedCookings = [];
      if (packageDishOperaion.orderDishCookings.length > 0) {
        for (var i=0;i<packageDishOperaion.orderDishCookings.length;i++) {
          var tempCooking = packageDishOperaion.orderDishCookings[i];
          selectedCookings.push({
            CookingId: tempCooking['RequestId'],
            CookingName: tempCooking['CookingName'],
            CookingPrice: tempCooking['RequestPrice'],
            Num: tempCooking['CookingNum']
          });
        }
      }
      // 子菜
      var subDishList = [];
      if (packageDishOperaion.orderMultiSubDishList.length > 0) {
        for (var i=0;i<packageDishOperaion.orderMultiSubDishList.length;i++) {
          var tempSubDish = packageDishOperaion.orderMultiSubDishList[i];
          subDishList.push({
            AddPrice: 0,
            Cookings: [],
            DishId: tempSubDish.Dish.DishId,
            DishNum: tempSubDish.Dish.DishNum,
            PackageDishId: packageDishOperaion.dish.Dish.DishId,
            ReplacePackageDishId: 0,
            UnitId: tempSubDish.Units[0].PortionsId
          });
        }
      }

      var orderDishInfo = {
        DishId: dish.Dish.DishId,
        UnitId: dish.Units[0].PortionsId,
        DishNum: packageDishOperaion.dishNum,
      };

      if (orderDishId) { //修改菜品
        orderDishData.changeMultiDishesForShoppingCar({
          OrderDishId: orderDishId,
          UnitId: orderDishInfo.UnitId,
          DishNum: orderDishInfo.DishNum,
          DishPrice: mainDishPrice, // 获取价格,
          Cookings: selectedCookings,
          SubDishes: subDishList
        }, function () {
          me.reply();
        });
      } else {
          orderDishData.addDishToShoppingCar({
            DishId: orderDishInfo.DishId,
            UnitId: orderDishInfo.UnitId,
            DishNum: orderDishInfo.DishNum,
            DishPrice: mainDishPrice,
            Cookings: selectedCookings,
            SubDishes: subDishList
          }, function () {
            me.reply();
          });
      }

  });

  // 判断是否新建搭配菜品，自动弹出主菜的数量输入
  if (!orderDishId && packageDishOperaion) {
    // 自动调起主菜数量输入修改数量
    setTimeout(onClickMultiDishNum, 500);
  }

  /**
   * 调起修改主菜数量
   * */
  function onClickMultiDishNum () {
    if (packageDishOperaion) {
      // 自动调起主菜数量输入修改数量
      mpos.showDialog(mpos.dialogPage.changeDishNum, {
          DishNum: packageDishOperaion.dishNum,
          DishName: packageDishOperaion.dish.Dish.DishName
        },
        function (status) {
          if (status.status && Number(status.num) > 0) {
            var num = status.num;
            var dishNum = Number(num);
            if (dishNum > 0) {
              packageDishOperaion.dishNum = dishNum;
              $multiDishNum.val(dishNum);
              // 计算价格
              renderTotalPrice();
            }
          }
        });
    }
  }


  /**
   * 加载Data
   */
  function initData() {
    var mulitDishObj = mpos.GetMulitDishInfo(dishId);
    if (mulitDishObj == null) {
      mpos.alert("找不到该商品");
      mpos.back();
    }
    var multiSubDishList = [];  // 一品多吃的子菜集合
    // 查找一品多吃子菜对应的菜品数据
    if (mulitDishObj.MultiSubDishList && mulitDishObj.MultiSubDishList.length > 0) {
      for (var c=0;c<mulitDishObj.MultiSubDishList.length;c++){
        var multiChild = mulitDishObj.MultiSubDishList[c];
        var childDish = orderDishData.getDish(multiChild.DishId);
        if (childDish) {
          multiSubDishList.push(childDish);
        }
      }
    }

    var multiDishNum = 1; // 主菜数量
    // 封装做法类型的数组
    var dishType = orderDishData.getDishType(dish.Dish.DishTypeId);
    var cookings = null;
    var dishCookings = [];
    if (dish.DishCookings.length > 0) { //有菜品关联做法时
      cookings = orderDishData.getGroupCookingsSort(dish.DishCookings);
    } else if (dishType.DishTypeCookings.length) { //有做法类型关联做法时
      cookings = orderDishData.getGroupCookingsSort(dishType.DishTypeCookings);
    }
    var scookingIds = [];  // 记录做法ID
    if (cookings) {
      for(var i=0;i<cookings.length;i++) {
        dishCookings.push(cookings[i]);
        if (cookings[i].Cookings) {
          cookings[i].Cookings.forEach(function(item) {
            scookingIds.push (item.RequestId);
          });
        }
      }
      cookings = null;
    }

    var allCookingIds = [];
    // 填充所有做法到更多  这个是从多做法复制过来
    for (var i = 0; i < orderDishData.cookings.length; i++) {
      if (scookingIds.findIndex(function (t) {return t == orderDishData.cookings[i].RequestId;}) == -1) {
        allCookingIds.push(orderDishData.cookings[i].RequestId);
      }
    }
    scookingIds = null;
    var allCookingGroup = orderDishData.getGroupCookingsSort(allCookingIds);
    if (allCookingGroup) {
      for(var i=0;i<allCookingGroup.length;i++) {
        dishCookings.push(allCookingGroup[i]);
      }
    }

    var selectCookingList = [];   // 修改菜品时已选中的做法
    var selectSubDishList = [];   // 修改菜品时已选中的子菜
    // 购物车中获取该商品
    if (orderDishId) {
      var shopCarDish = orderDishData.getShoppingCarDishByOrderDishId(orderDishId);
      var shopCarMultiSubDishes = orderDishData.getShoppingCarMultiSubDishByOrderDishId(orderDishId, dish.Dish.DishId);
      multiDishNum = shopCarDish.DishNum;
      // 遍历购物车中一品多吃主菜已选的做法
      if (shopCarDish.DishRequestList) {
        var tempCookingList = [];
        dishCookings.forEach(function(item) {
          tempCookingList = tempCookingList.concat(item.Cookings);
        })
        // 遍历购物车中主商品已选中的做法
        for(var i=0;i<shopCarDish.DishRequestList.length;i++) {
          var tempSelectCooking = shopCarDish.DishRequestList[i];
          var cookingData = tempCookingList.find(function(item) {
            return item.RequestId == tempSelectCooking.RequestId;
          });
          if (cookingData) {
            // 封装已选中的做法
            selectCookingList.push({
              CookingName: cookingData['CookingName'],
              RequestId: cookingData['RequestId'],
              RequestPrice: cookingData['RequestPrice'],
              CookingNum: tempSelectCooking['RequestNum']
            })
          }
        }

        tempCookingList = null;
      }
      // 遍历购物车中已选中的一品多吃的子菜
      if (shopCarMultiSubDishes && shopCarMultiSubDishes.length > 0) {

        // 遍历购物车中主商品已选中的做法
        for(var i=0;i<shopCarMultiSubDishes.length;i++) {
          var tempSelectSub = shopCarMultiSubDishes[i];
          var subData = multiSubDishList.find(function(item) {
            return item.Dish.DishId == tempSelectSub['DishId'];
          });
          if (subData) {
            var newSub = JSON.parse(JSON.stringify(subData));
            newSub.Dish.DishNum = tempSelectSub['DishNum']
            // 封装已选中的子菜
            selectSubDishList.push(newSub)
          }
        }
      }
    }

    /**
     * 封装操作对象
     * */
    packageDishOperaion = {
      dish: dish,   // 操作的主菜对象
      multiSubDishList: multiSubDishList,   // 一品多吃的子菜集合
      dishNum: multiDishNum,   // 主菜数量
      dishCookings: dishCookings,   // 做法数组
      orderDishCookings: selectCookingList,  // 已选主菜做法
      orderMultiSubDishList: selectSubDishList, // 已选子菜
    }

    // 渲染单位和数量
    var priceText = mpos.formatPrice(orderDishData.getDishPrice(dish)); // 获取价格
    var defaultUnit = dish.Units[0];
    var unitName = defaultUnit.PortionsName + "(" +priceText+ ")";
    $(page).find('.multi-dish-unit .dish-unit').text(unitName);
    $(page).find('.multi-dish-unit .app-input').text(packageDishOperaion.dishNum);

    // 渲染主菜数量
    renderMultiDishNum();

    // 渲染子菜列表
    renderMultiSubDish();

    // 渲染做法
    renderCookingTypeList();

    // 渲染价格显示
    renderTotalPrice();

  }

  // 主菜数量设置
  function renderMultiDishNum () {
    $multiDishNum.val(packageDishOperaion.dishNum);
    $multiDishNum.on('click', function (e) {
      // 修改数量
      onClickMultiDishNum();
    })
  }

  // 渲染价格
  function renderTotalPrice () {
    // 菜品主菜价格*数量 + 子菜价格*数量 + 做法*数量 = 总价格
    var totalPrice = 0; // 总价格
    var totalPriceText = '';
    var dishPrice = orderDishData.getDishPrice(packageDishOperaion.dish);  // 主菜价格
    totalPrice += Number(dishPrice) * Number(packageDishOperaion.dishNum);
    totalPriceText += dishPrice +'x'+ packageDishOperaion.dishNum;
    // 子菜价格
    if (packageDishOperaion.orderMultiSubDishList.length > 0) {
      for (var i=0;i<packageDishOperaion.orderMultiSubDishList.length;i++) {
        var subDish = packageDishOperaion.orderMultiSubDishList[i];
        totalPrice += Number(orderDishData.getDishPrice(subDish)) * Number(subDish.Dish.DishNum);
        totalPriceText += '+'+ orderDishData.getDishPrice(subDish) +'x'+ subDish.Dish.DishNum;
      }
    }
    // 做法价格
    if (packageDishOperaion.orderDishCookings.length > 0) {
      for (var i=0;i<packageDishOperaion.orderDishCookings.length;i++) {
        var subDish = packageDishOperaion.orderDishCookings[i];
        totalPrice += Number(subDish.RequestPrice) * Number(subDish.CookingNum);
        totalPriceText += '+'+ subDish.RequestPrice +'x'+ subDish.CookingNum;
      }
    }
    if (totalPriceText) {
      totalPriceText += '=';
    }
    $dishTotalPrice.find('.price').text(totalPriceText);
    $dishTotalPrice.find('.price-total').text(totalPrice.toFixed(2));

  }

  // 渲染子菜
  function renderMultiSubDish () {
    //展示必选项
    $multiSubDishList.empty();
    var fragment = $(document.createDocumentFragment());
    for (var i = 0; i < packageDishOperaion.multiSubDishList.length; i++) {
      var subDish = packageDishOperaion.multiSubDishList[i];
      var unit = subDish.Units[0];
      var $subItem = $multiSubItem.clone();
      $subItem.data('dish-unit-id', subDish.Dish.DishId);  // 标识
      $subItem.find('.sub-name').text(subDish.Dish.DishName);
      $subItem.find('.sub-price').text(mpos.formatPrice(orderDishData.getDishPrice(subDish)));
      // 判断是否是修改，并判断是否选中该子菜
      if (orderDishId) {
        var checkedSub = packageDishOperaion.orderMultiSubDishList.find(function (item) {
          return item.Dish.DishId == subDish.Dish.DishId;
        })
        if (checkedSub) {
          $subItem.find('.sub-num').text(checkedSub.Dish.DishNum);
          $subItem.addClass('checked');
        }
      }

      $subItem.on("click", function (e) {
        var $currentTarget = $(e.currentTarget);
        var dishUnitId = $currentTarget.data('dish-unit-id');
        // 遍历出子菜是否添加
        onCheckedSubDish(dishUnitId, $currentTarget)

      });

      fragment.append($subItem);
    }
    $multiSubDishList.append(fragment);
    fragment = null;
  }

  /**
   * 子菜选中与取消操作
   * @dishUnitId  子菜ID和单位ID组合标识
   * @subNode  元素节点对象
   * */
  function onCheckedSubDish (dishUnitId, $subNode) {
    var subIndex = packageDishOperaion.orderMultiSubDishList.findIndex(function(item) {
      return item.Dish.DishId === dishUnitId
    });
    if (subIndex === -1) {
      // 未添加，要进行添加操作
      var subDish = packageDishOperaion.multiSubDishList.find(function(item) {
        return item.Dish.DishId === dishUnitId;
      });
      if (!subDish) {
        mpos.alert("子商品未找到");
        return;
      }
      // 修改数量
      mpos.showDialog(mpos.dialogPage.changeDishNum, {
          DishNum: 1,
          DishName: subDish.Dish.DishName
        },
        function (status) {
          if (status.status && Number(status.num) > 0) {
            var num = status.num;
            var dishNum = Number(num);
            if (dishNum > 0) {
              $subNode.addClass('checked');
              $subNode.find('.sub-num').text(dishNum);
              var newSub = JSON.parse(JSON.stringify(subDish));
              newSub.Dish.DishNum = dishNum
              packageDishOperaion.orderMultiSubDishList.push(newSub);
              // 计算价格
              renderTotalPrice();
            }
          }
        });
    } else {
      // 已添加，进行删除操作
      packageDishOperaion.orderMultiSubDishList.splice(subIndex, 1);
      $subNode.removeClass('checked');
      // 计算价格
      renderTotalPrice();
    }

  }

  /**
   * 渲染做法类别
   * */
  function renderCookingTypeList () {
    $cookingTabList.empty();
    if (packageDishOperaion.dishCookings.length > 0) {
      var fragment = $(document.createDocumentFragment());
      for (var i = 0; i < packageDishOperaion.dishCookings.length; i++) {
        var cookingData = packageDishOperaion.dishCookings[i];
        var $subItem = $cookingTab.clone();
        $subItem.data('cooking-type-id', cookingData.RequestTypeId);  // 标识
        $subItem.find('.cooking-name').text(cookingData.RequestName);
        $subItem.on("click", function (e) {
          var $currentTarget = $(e.currentTarget);
          setCookingTypeStyle($currentTarget);
          var cookingId = $currentTarget.data('cooking-type-id');
          // 遍历出子菜是否添加
          renderCookingList(Number(cookingId));
        });

        fragment.append($subItem);
      }
      $cookingTabList.append(fragment);
      fragment = null;

      var checkedCookingType = $cookingTabList.find('.checked');
      // 渲染第一个做法类型选中操作
      if (!checkedCookingType || checkedCookingType.length === 0) {
        setCookingTypeStyle($($cookingTabList.find('.tab')[0]));
        var firstCookingType = packageDishOperaion.dishCookings[0];
        renderCookingList(firstCookingType.RequestTypeId);
      }
    }
  }

  /**
   * 做法分类选中样式设置
   * */
  function setCookingTypeStyle ($cookingTypeNode) {
    var checkedCookingType = $cookingTabList.find('.checked');
    // 渲染第一个做法类型选中操作
    if (checkedCookingType && checkedCookingType.length > 0) {
      checkedCookingType.removeClass('checked');
    }
    $cookingTypeNode.addClass('checked')
  }

  /**
   * 渲染做法分类下的做法项
   * */
  function renderCookingList (cookingTypeId) {
    // 查询做法
    var cookingList = packageDishOperaion.dishCookings.find(function(item){return item.RequestTypeId === cookingTypeId})

    //展示必选项
    $multiDishCookingList.empty();
    if (cookingList) {
      var fragment = $(document.createDocumentFragment());
      for (var i = 0; i < cookingList.Cookings.length; i++) {
        var subDish = cookingList.Cookings[i];
        var $cookingItem = $multiCookingItem.clone();
        $cookingItem.data('cooking-id', subDish.RequestId);  // 标识
        $cookingItem.data('cooking-name', subDish.CookingName);  // 记录做法的名称
        $cookingItem.data('cooking-price', subDish.RequestPrice);  // 记录做法的价格
        $cookingItem.find('.cooking-name').text(subDish.CookingName);
        $cookingItem.find('.cooking-price').text(mpos.formatPrice(subDish.RequestPrice));
        // 判断做法是否选中
        var checkedCooking = packageDishOperaion.orderDishCookings.find(function(item) { return item.RequestId == subDish.RequestId;})
        if (checkedCooking) {
          $cookingItem.addClass('checked');
          $cookingItem.find('.cooking-num').text( checkedCooking.CookingNum);  // 记录做法的数量
        }

        $cookingItem.on("click", function (e) {
          var $currentTarget = $(e.currentTarget);
          var cookingId = $currentTarget.data('cooking-id');
          // 遍历出子菜是否添加
          onCheckedCooking(cookingId, $currentTarget)
        });

        fragment.append($cookingItem);
      }
      $multiDishCookingList.append(fragment);
      fragment = null;
    }
  }

  /**
   * 做法选择
   * @cookingId  做法ID组合标识
   * @subNode  元素节点对象
   * */
  function onCheckedCooking (cookingId, $subNode) {

    var cookingIndex = packageDishOperaion.orderDishCookings.findIndex(function(item) {return item.RequestId === cookingId});
    if (cookingIndex === -1) {
      var cookingName = $subNode.data('cooking-name');
      var cookingPrice = $subNode.data('cooking-price');
      // 修改数量
      mpos.showDialog(mpos.dialogPage.changeDishNum, {
          DishNum: 1,
          DishName: cookingName
        },
        function (status) {
          if (status.status && Number(status.num) > 0) {
            var num = status.num;
            var dishNum = Number(num);
            if (dishNum > 0) {
              $subNode.addClass('checked');
              $subNode.find('.cooking-num').text(dishNum);
              packageDishOperaion.orderDishCookings.push({
                CookingName: cookingName,
                RequestId: cookingId,
                RequestPrice: cookingPrice,
                CookingNum: dishNum,
              });
              // 计算价格
              renderTotalPrice();
            }
          }
        });
    } else {
      // 已添加，进行删除操作
      packageDishOperaion.orderDishCookings.splice(cookingIndex, 1);
      $subNode.removeClass('checked');

      // 计算价格
      renderTotalPrice();
    }

  }

  /**
   * 做法搜索事件
   * */
  $(page).find('button.search-btn').on('click', function(e){
    e.stopPropagation();
    // 获取
    var searchText = $(page).find('.search-cooking-content input').val().trim();

    if (searchText) {
      // 隐藏做法类别想
      $cookingTabList.addClass('content-hidden');
      $multiDishCookingList.addClass('content-hidden');

      var searchTextStr = searchText.toUpperCase();
      var filterCookings = [];
      // 查询做法
      if (packageDishOperaion.dishCookings.length > 0) {
        packageDishOperaion.dishCookings.forEach(function(item){
          for (var i = 0; i < item.Cookings.length; i++) {
            if (item.Cookings[i].CookingName.toUpperCase().indexOf(searchTextStr) != -1) {
              filterCookings.push(item.Cookings[i]);
            }
          }
        })
      }
      // 清空过滤项，
      $filterMultiDishCookingList.empty();
      $filterMultiDishCookingList.removeClass('content-hidden');  // 显示过滤的做法容器

      if (filterCookings.length > 0) {
        var fragment = $(document.createDocumentFragment());
        for (var i = 0; i < filterCookings.length; i++) {
          var subDish = filterCookings[i];
          var $cookingItem = $filterMultiCookingItem.clone();
          $cookingItem.data('cooking-id', subDish.RequestId);  // 标识
          $cookingItem.data('cooking-name', subDish.CookingName);  // 记录做法的名称
          $cookingItem.data('cooking-price', subDish.RequestPrice);  // 记录做法的价格
          $cookingItem.find('.cooking-name').text(subDish.CookingName);
          $cookingItem.find('.cooking-price').text(mpos.formatPrice(subDish.RequestPrice));
          // 判断做法是否选中
          var checkedCooking = packageDishOperaion.orderDishCookings.find(function(item) { return item.RequestId == subDish.RequestId;})
          if (checkedCooking) {
            $cookingItem.addClass('checked');
            $cookingItem.find('.cooking-num').text( checkedCooking.CookingNum);  // 记录做法的数量
          }

          $cookingItem.on("click", function (e) {
            var $currentTarget = $(e.currentTarget);
            var cookingId = $currentTarget.data('cooking-id');
            onCheckedCooking(cookingId, $currentTarget)
          });

          fragment.append($cookingItem);
        }
        $filterMultiDishCookingList.append(fragment);
        fragment = null;
      }

    } else {
      // 清除过滤操作
      $filterMultiDishCookingList.addClass('content-hidden');  // 显示过滤的做法容器
      $cookingTabList.removeClass('content-hidden');
      $multiDishCookingList.removeClass('content-hidden');

      // 渲染第一个做法类型选中操作
      renderCookingTypeList();
    }

  })

});

/**
 * 点普通套餐
 */
mpos.controller(mpos.page.orderDishForNormalPackage, function (page, data) {
    var dish = data.Dish;
    var dishId = dish.Dish.DishId;
    var orderDishData = data.OrderDishData;
    var orderId = data.OrderId;
    var wholeBillId = data.WholeBillId;
    var orderDishId = 0; //修改的套餐ID
    if (data.OrderDishId != undefined) {
        orderDishId = data.OrderDishId;
    }
    var packageDishOperaion = null;//套餐操作对象

    $(page).data("whole_order_id", wholeBillId); //设置被踢出检测

    var me = this;
    var mustSelectDishContainer = $(page).find(".must-select-dish-container"); //必选项容器
    var notMustSelectDishContainer = $(page).find(".not-must-select-dish-container");//可选项容器
    var mustSelectDishItems = mustSelectDishContainer.find(".items");
    var notMustSelectDishItems = notMustSelectDishContainer.find(".items");

    var $mustSelectDishItem = mustSelectDishItems.find("li").remove(); //必选项单项显示模板
    var $notMustSelectDishItem = notMustSelectDishItems.find("li").remove();//可选项单项显示模板

    //标题
    $(page).find(".app-title").text(dish.Dish.DishName);

    //加载Data
    initData();

    //返回事件
    function backToPrev() {
        me.reply();
    }
    this.onBackKeyDown = backToPrev;
    $(page).find("#goBack").on("click", backToPrev);

    //提交
    $(page).find(".ok.app-submit").on("click", function (e) {
        var orderDishInfo = {
            DishId: dish.Dish.DishId,
            UnitId: dish.Units[0].PortionsId,
            DishNum: 1,
            DishPrice: 0,
            SubDishes: packageDishOperaion.orderSubDishes
        };

        me.reply({
            OrderDishInfo: orderDishInfo,
            IsModified: orderDishId > 0
        });
    });

    /**
     * 加载Data
     */
    function initData() {
        var r = mpos.GetPackageDishInfo(dishId);
        if (r == null) {
            mpos.alert("找不到套餐");
            mpos.back();
        }
        packageDishOperaion = mpos.OrderDishData.createPackageOrderDish(r, orderDishId, orderDishData);
        //如果是修改菜品，则还原子菜
        packageDishOperaion.restoreOrderDish(false);

        //必选菜加到子菜中
        for (var i = 0; i < packageDishOperaion.packageDish.MustPackageDishList.length; i++) {
            var pd = packageDishOperaion.packageDish.MustPackageDishList[i];
            if (orderDishId == 0) { //如果是新增套餐，添加到子菜集合中
                packageDishOperaion.addToSubDishes(pd.PackageDish);
            }
        }
        //加载UI
        initUI();
    }

    /**
     * 加载UI
     */
    function initUI() {
        if (packageDishOperaion.packageDish.NotMustPackageDishList.length == 0) {
            notMustSelectDishContainer.remove();
        }
        //展示必选项
        mustSelectDishItems.empty();
        var fragment = $(document.createDocumentFragment());
        for (var i = 0; i < packageDishOperaion.packageDish.MustPackageDishList.length; i++) {
            var pd = packageDishOperaion.packageDish.MustPackageDishList[i];
            var mustSelectDishItem = $mustSelectDishItem.clone();
            var pgDish = mpos.GetBaseDishInfo(pd.PackageDish.DishId);
            mustSelectDishItem.data("p_id", pd.PackageDish.PackageDishId); //子菜的对应ID
            mustSelectDishItem.data("dish_id", pgDish.Dish.DishId);
            var orderSubDish = packageDishOperaion.getHasOrderSubDish(pd.PackageDish.PackageDishId);
            var dishNameText = pgDish.Dish.DishName;
            if (pgDish.Units && pgDish.Units[0]) {
              dishNameText += "["+pgDish.Units[0]['PortionsName']+"]"
            }
            if (orderSubDish.ReplacePackageDishId > 0) { //被替换了
                var dish = orderDishData.getDish(orderSubDish.DishId);
                if (dish != null) {
                    dishNameText = dish.Dish.DishName;
                    if (dish.Units && dish.Units[0]) {
                      dishNameText += "["+dish.Units[0]['PortionsName']+"]"
                    }
                }
            }
            // 设置显示的菜品名称
            mustSelectDishItem.find(".name").text(dishNameText);
            // 设置沽清状态
            refreshDishSaleoutShowUI(pd.PackageDish.DishId, mustSelectDishItem);

            if (pd.ReplacePackageDishList.length > 0) {
                mustSelectDishItem.addClass("exchange");
            }

            mustSelectDishItem.on("click", function (e) {
                var $currentTarget = $(e.currentTarget);
                mpos.packageSubDishPage.show({
                    SubDishes: packageDishOperaion.orderSubDishes,
                    PackageDishId: $currentTarget.data("p_id"),
                    OrderDishData: orderDishData,
                    PackageDish: packageDishOperaion.packageDish
                }, function () {
                    initUI();
                });
            });

            fragment.append(mustSelectDishItem);
        }
        mustSelectDishItems.append(fragment);
        fragment = null;

        //展示可选项
        notMustSelectDishItems.empty();
        fragment = $(document.createDocumentFragment());
        for (var i = 0; i < packageDishOperaion.packageDish.NotMustPackageDishList.length; i++) {
            var pd = packageDishOperaion.packageDish.NotMustPackageDishList[i];
            var notMustSelectDishItem = $notMustSelectDishItem.clone();
            var pgDish = mpos.GetBaseDishInfo(pd.PackageDish.DishId);
            notMustSelectDishItem.data("p_id", pd.PackageDish.PackageDishId); //子菜的对应ID
            notMustSelectDishItem.data("dish_id", pgDish.Dish.DishId);

            var dishName = pgDish.Dish.DishName;
            // 单位
            if (pd.PackageDish.DishPortionsId > 0 && pgDish.Units) {
              var dishUnit = pgDish.Units.find(function(item) {
                return item.PortionsId == pd.PackageDish.DishPortionsId;
              });
              if (dishUnit) {
                dishName += "[" + dishUnit.PortionsName + "]";
              }
            }
            if (pd.PackageDish.SubDishPrice > 0) { //加价
                dishName += "(+" + mpos.formatPrice(pd.PackageDish.SubDishPrice) + ")";
            }
            notMustSelectDishItem.find(".name").text(dishName);
            // 设置沽清状态
            refreshDishSaleoutShowUI(pd.PackageDish.DishId, notMustSelectDishItem);
            if (packageDishOperaion.checkHasOrderSubDish(pd.PackageDish.PackageDishId)) {
                notMustSelectDishItem.find("input[name='selectSubDish']").prop("checked", true);
            }
            notMustSelectDishItem.on("click", function (e) {
                if (e.target.tagName == "INPUT") {
                    return;
                }
                var $currentTarget = $(e.currentTarget);
                var selectSubDish = $currentTarget.find("input[name='selectSubDish']");
                var checked = selectSubDish.prop("checked");
                if (!checked) {
                    selectSubDish.trigger("click");
                    return;
                }
                //进入选做法界面
                mpos.packageSubDishPage.show({
                    SubDishes: packageDishOperaion.orderSubDishes,
                    PackageDishId: $currentTarget.data("p_id"),
                    OrderDishData: orderDishData,
                    PackageDish: packageDishOperaion.packageDish
                }, function () {
                    initUI();
                });
            });

            //选中可选菜
            notMustSelectDishItem.find("input[name='selectSubDish']").on("click", function (e) {
                e.stopPropagation();
                var $currentTarget = $(e.currentTarget);
                var pid = $currentTarget.parent().data("p_id");
                if (!$currentTarget.prop("checked")) {
                    packageDishOperaion.removeSubDishes(pid);
                } else {
                    for (var k = 0; k < packageDishOperaion.packageDish.NotMustPackageDishList.length; k++) {
                        if (packageDishOperaion.packageDish.NotMustPackageDishList[k].PackageDish.PackageDishId == pid) {
                            var packageDish = packageDishOperaion.packageDish.NotMustPackageDishList[k].PackageDish;
                            packageDishOperaion.addToSubDishes(packageDish);
                            var subDish = packageDishOperaion.getHasOrderSubDish(packageDish.PackageDishId);
                            subDish.AddPrice = packageDish.SubDishPrice;
                            break;
                        }
                    }
                }
            });

            fragment.append(notMustSelectDishItem);

        }
        notMustSelectDishItems.append(fragment);
        fragment = null;
    }

    /**
     * 刷新沽清数据
     */
    function refreshDishSaleoutShowUI(dishId, itemDom) {
      /***********沽清处理************/
      var saleOutNum = orderDishData.getCanSaleDishNum(dishId);
      var $saleout = itemDom.find(".sale-out");
      if (saleOutNum == -1) { //没有设置沽清
        $saleout.remove();
      } else if (saleOutNum == 0) { //已卖完
        $saleout.text("沽");
        $saleout.addClass('sale-out-show');
      } else {
        $saleout.text(saleOutNum);
        $saleout.addClass('sale-out-show');
      }
    }

});

/**
 * Created by xeonwell on 2016/1/27.
 * 套餐子菜、替换菜及做法界面
 */
mpos.packageSubDishPage = (function () {
    var packageSubdishPage = null;

    $(function () {
        packageSubdishPage = $('body>.package-subdish-page').remove();
    });

    /**
     * 根据传入的参数，修改套餐子菜或者替换菜及做法
     * @param {Object} options
     * @param {Function} callback
     */
    function show(options, callback) {
        if (packageSubdishPage == null || typeof options != 'object' || typeof callback != 'function')
            return;
        var page = packageSubdishPage.clone();

        //close
        page.find(".app-button.close").on("click", function () {
            hide();
        });
        $.selectOnFocus(page);
        //submit
        page.find(".app-button.app-submit").on("click", function () {
            var result = {};

            //手写做法
            var handCookieName = $.trim($handCookieName.val());
            var handCookiePrice = $handCookiePrice.val();
            //移除手写做法
            for (var i = 0; i < currentSubDish.Cookings.length; i++) {
                if (currentSubDish.Cookings[i].CookingId == 0) {
                    currentSubDish.Cookings.splice(i, 1);
                    break;
                }
            }

            if (handCookieName != "") {
                if (handCookiePrice == "") {
                    handCookiePrice = 0;
                }
                if (!mpos.isAmount(handCookiePrice)) {
                    mpos.alert("手写做法价格输入错误");
                    return;
                }
                handCookiePrice = Number(handCookiePrice);
                if (handCookiePrice < 0) {
                    mpos.alert("手写做法价格不能小于0！");
                    return;
                }
                currentSubDish.Cookings.push({
                    CookingId: 0,
                    CookingName: handCookieName,
                    CookingPrice: handCookiePrice,
                    Num: 1
                });
            }

            //循环修改原对象
            for (var i = 0; i < subDishes.length; i++) {
                for (var j = 0; j < orgSubDishes.length; j++) {
                    if (subDishes[i].PackageDishId == orgSubDishes[j].PackageDishId) {
                        orgSubDishes[j] = subDishes[i];
                        break;
                    }
                }
            }
            callback(result);
            hide();
        });

        // 处理生成逻辑
        var orgSubDishes = options.SubDishes;
        var subDishes = $.deepClone(orgSubDishes); //已选子菜的拷贝
        var packageDishId = options.PackageDishId; //套餐子菜ID
        var orderDishData = options.OrderDishData; //点菜对象
        var packageDish = options.PackageDish;
        var currentSubDish = null;//当前点的子菜信息

        var $subDishContainer = page.find(".sub-dish-container");
        var $subDishContainerUl = $subDishContainer.find("ul");
        var $subDishContainerItem = $subDishContainerUl.find("li").remove();

        var cookingContainer = page.find(".cooking-container");
        var $cookingItem = cookingContainer.find(".cooking-item").remove();

        var moreCookingContainer = page.find(".more-cooking-container");
        var $moreCookingItem = moreCookingContainer.find(".cooking-item").remove();

        var $handCookieName = page.find("input[name='hand_cookie_name']");
        var $handCookiePrice = page.find("input[name='hand_cooke_price']");

        var $cookingSearchBtn = page.find("button.cooking-search-btn");

        initUI();

        /**
         *  初始化UI显示
         */
        function initUI() {
            for (var i = 0; i < subDishes.length; i++) {
                if (subDishes[i].PackageDishId == packageDishId) {
                    currentSubDish = subDishes[i];
                    break;
                }
            }
            var dish = orderDishData.getDish(currentSubDish.DishId);

            //加载菜品选择
            var currentDishPackageInfo = null;
            for (var i = 0; i < packageDish.PackageDishList.length; i++) {
                if (packageDish.PackageDishList[i].PackageDish.PackageDishId == packageDishId) {
                    currentDishPackageInfo = packageDish.PackageDishList[i];
                    break;
                }
            }
            if (currentDishPackageInfo != null) {
                //if (currentDishPackageInfo.ReplacePackageDishList.length > 0) { //有替换菜品时
                //    $subDishContainer.removeClass("nd");
                //    loadReplaceDishes(currentDishPackageInfo); //加载替换菜品
                //} else {
                //    $subDishContainer.addClass("nd");
                //}
                loadReplaceDishes(currentDishPackageInfo); //加载替换菜品
            }

            //加载做法
            loadDishCooking(dish);
            initHandCookie();

            mpos.checkInputValue($handCookiePrice, InputType.Amount);
        }

        /*
          加载手写做法
         */
        function initHandCookie() {
            $.each(currentSubDish.Cookings, function (idx, item) {
                if (item.CookingId == 0) {
                    $handCookieName.val(item.CookingName);
                    $handCookiePrice.val(item.CookingPrice);
                }
            });
        }

        /**
         * 加载替换菜
         */
        function loadReplaceDishes(currentDishPackageInfo) {
            $subDishContainerUl.empty();

            //载替换菜
            for (var i = -1; i < currentDishPackageInfo.ReplacePackageDishList.length; i++) {
                var subDishItem = $subDishContainerItem.clone();
                var replaceId = 0, dish;
                if (i == -1) {//先加载原菜
                    dish = mpos.GetBaseDishInfo(currentDishPackageInfo.PackageDish.DishId);
                    subDishItem.find(".name").text(dish.Dish.DishName);
                    subDishItem.data("pid", currentDishPackageInfo.PackageDish.PackageDishId);
                    subDishItem.data("rid", 0);
                } else {
                    dish = mpos.GetBaseDishInfo(currentDishPackageInfo.ReplacePackageDishList[i].DishId);
                    var dishName = dish.Dish.DishName;
                    replaceId = currentDishPackageInfo.ReplacePackageDishList[i].PackageDishReplaceId;
                    subDishItem.data("pid", currentDishPackageInfo.PackageDish.PackageDishId);
                    subDishItem.data("rid", replaceId);
                    //格式化加价
                    if (currentDishPackageInfo.ReplacePackageDishList[i].PriceChanging > 0) {
                        dishName += "(+" + mpos.formatPrice(currentDishPackageInfo.ReplacePackageDishList[i].PriceChanging) + ")"
                    }
                    if (currentDishPackageInfo.ReplacePackageDishList[i].PriceChanging < 0) {
                        dishName += "(-" + mpos.formatPrice(Math.abs(currentDishPackageInfo.ReplacePackageDishList[i].PriceChanging)) + ")"
                    }
                    subDishItem.find(".name").text(dishName);
                }

                //选中当前的子菜
                if (currentSubDish.ReplacePackageDishId == replaceId) {
                    subDishItem.find("input[name='selectedDish']").prop("checked", true);
                }

                //点击事件
                subDishItem.on("click", function (e) {
                    var $currentTarget = $(e.currentTarget);
                    var $checkBox = $currentTarget.find("input[name='selectedDish']");

                    $subDishContainer.find("input[name='selectedDish']").prop("checked", false);
                    $checkBox.prop("checked", true);
                    var rid = $currentTarget.data("rid");
                    currentSubDish.ReplacePackageDishId = rid;
                    if (rid == 0) {
                        currentSubDish.AddPrice = 0;
                        currentSubDish.DishId = currentDishPackageInfo.PackageDish.DishId;
                        currentSubDish.UnitId = currentDishPackageInfo.PackageDish.DishPortionsId;
                        currentSubDish.DishNum = currentDishPackageInfo.PackageDish.DishNum;
                    } else {
                        var r_dish = getReplaceDish(rid);
                        currentSubDish.AddPrice = r_dish.PriceChanging;
                        currentSubDish.DishId = r_dish.DishId;
                        currentSubDish.UnitId = r_dish.DishPortionsId;
                        currentSubDish.DishNum = r_dish.DishNum;
                    }
                    //清空原做法
                    currentSubDish.Cookings = [];
                    //重新加载做法
                    var dish = orderDishData.getDish(currentSubDish.DishId);
                    loadDishCooking(dish);
                });

                subDishItem.find("input[name='selectedDish']").on("click", function () {
                    return;
                });
                $subDishContainerUl.append(subDishItem);

                //插入可替换描述
                if (i == -1 && currentDishPackageInfo.ReplacePackageDishList.length > 0) {
                    $subDishContainer.find(".replace-title").removeClass("nd");
                }
            }
        }

        /**
         * 获取替换菜信息
         */
        function getReplaceDish(rid) {
            if (rid == 0) {
                return null;
            }

            for (var i = 0; i < packageDish.DishPackageReplaceList.length; i++) {
                if (packageDish.DishPackageReplaceList[i].PackageDishReplaceId == rid) {
                    return packageDish.DishPackageReplaceList[i];
                }
            }

            return null;
        }

        /*
        加载做法
        */
        function loadDishCooking(dish) {
            cookingContainer.empty();
            var scookings = [];
            if (dish != null) { //当菜品不在销售方案时，这里为空
                var dishType = orderDishData.getDishType(dish.Dish.DishTypeId);
                var cookings = null;
                var hasMoreCookings = true; //是否显示更多做法
                if (dish.DishCookings.length > 0) { //有菜品关联做法时
                    cookings = orderDishData.getGroupCookingsSort(dish.DishCookings);
                } else if (dishType.DishTypeCookings.length > 0) { //有做法类型关联做法时
                    cookings = orderDishData.getGroupCookingsSort(dishType.DishTypeCookings);
                } else { //都没有时，显示全部做法
                    //不显示专有做法
                  hasMoreCookings = false;
                    cookingContainer.addClass("nd");
                }

                if (hasMoreCookings && cookings) {
                    var fragment = $(document.createDocumentFragment());
                    for (var cookingGroup=0; cookingGroup < cookings.length; cookingGroup++) {
                        var cookingItem = $cookingItem.clone();
                        cookingItem.find(".cooking-type-name").text(cookings[cookingGroup].RequestName);
                        var $list = cookingItem.find(".cooking-list");
                        for (var j = 0; j < cookings[cookingGroup].Cookings.length; j++) {
                            var c = cookings[cookingGroup].Cookings[j];
                            var price = "";
                            if (c.RequestPrice > 0) {
                                price = "(+" + mpos.formatPrice(c.RequestPrice) + ")";
                            }
                            $list.append("<span data-c_id='" + c.RequestId + "' class='cooking-name textEllipsis'>" + c.CookingName + price + "</span>");
                            scookings.push(c.RequestId);
                        }
                        fragment.append(cookingItem);
                    }
                    cookingContainer.removeClass("nd");
                    cookingContainer.append(fragment);
                    fragment = null;
                } else {
                    //page.find(".more-cookings").toggleClass("expand");
                }
            } else {
                //不显示专有做法
                cookingContainer.addClass("nd");
            }
            //填充所有做法到更多
            var allCookingIds = [];
            for (var i = 0; i < orderDishData.cookings.length; i++) {
                if (scookings.findIndex(function (t) {
                    return t == orderDishData.cookings[i].RequestId;
                }) == -1) {
                    allCookingIds.push(orderDishData.cookings[i].RequestId);
                }
            }
            var allCookingGroup = orderDishData.getGroupCookingsSort(allCookingIds);
            moreCookingContainer.empty();
            var fragment = $(document.createDocumentFragment());
            for (var cookingGroup = 0; cookingGroup < allCookingGroup.length; cookingGroup++) {
                var cookingItem = $moreCookingItem.clone();
                cookingItem.find(".cooking-type-name").text(allCookingGroup[cookingGroup].RequestName);
                var cookinglist = cookingItem.find(".cooking-list");
                for (var j = 0; j < allCookingGroup[cookingGroup].Cookings.length; j++) {
                    var c = allCookingGroup[cookingGroup].Cookings[j];
                    var price = "";
                    if (c.RequestPrice > 0) {
                        price = "(+" + mpos.formatPrice(c.RequestPrice) + ")";
                    }
                    cookinglist.append("<span data-c_id='" + c.RequestId + "' class='cooking-name textEllipsis'>" + c.CookingName + price + "</span>");
                }
                fragment.append(cookingItem);
            }

            moreCookingContainer.append(fragment);
            fragment = null;

            //恢复选中的做法
            if (currentSubDish.Cookings != null) { //取到修改的菜品的做法
                for (var k = 0; k < currentSubDish.Cookings.length; k++) {
                    var allCookingTargets = page.find("span[data-c_id='" + currentSubDish.Cookings[k].CookingId + "']");
                    for (var j = 0; j < allCookingTargets.length; j++) {
                        $(allCookingTargets[j]).addClass("selected");
                    }
                }
            }

            //做法选中事件
            cookingContainer.find("span[data-c_id]").on("click", function (e) {
                selectCooking(e);
            });
            //更多中的做法选中事件
            moreCookingContainer.find("span[data-c_id]").on("click", function (e) {
                selectCooking(e);
            });
        }

        // 渲染选中的做法状态
        function showSelectedCookingStatus () {
            //恢复选中的做法
            if (currentSubDish.Cookings != null) { //取到修改的菜品的做法
                for (var k = 0; k < currentSubDish.Cookings.length; k++) {
                    var allCookingTargets = page.find("span[data-c_id='" + currentSubDish.Cookings[k].CookingId + "']");
                    for (var j = 0; j < allCookingTargets.length; j++) {
                        $(allCookingTargets[j]).addClass("selected");
                    }
                }
            }
        }

        /*
         点击做法事件
         */
        function selectCooking(e) {
            var $target = $(e.currentTarget);
            var cookingId = $target.data("c_id");
            var cooking = orderDishData.getCookingById(cookingId);
            var cookingName = cooking.RequestName;
            var requestPrice = cooking.RequestPrice;
            var requestId = cooking.RequestId;
            if ($target.hasClass("selected")) {
                for (var i = 0; i < currentSubDish.Cookings.length; i++) {
                    if (currentSubDish.Cookings[i].CookingId == requestId) {
                        currentSubDish.Cookings.splice(i, 1);
                        break;
                    }
                }
            } else {
                var cookingData = {
                    CookingId: requestId,
                    CookingName: cookingName,
                    CookingPrice: requestPrice,
                    Num: 1,
                    BaseRequestNum: 1
                }
                if (cooking.IsRequestNum == 1) {
                    // 判断做法是否支持即时录入数量
                    mpos.showDialog(mpos.dialogPage.changeCookingNum, {CookingData: cookingData}, function (status) {
                        if (status.status) {
                            currentSubDish.Cookings.push(status.data);
                        }
                	});
                } else {
                    currentSubDish.Cookings.push(cookingData);
            	}
            }
            //更新选中的样式
            var allCookingTargets = page.find("span[data-c_id='" + cookingId + "']");
            var isSelected = $target.hasClass("selected");
            for (var j = 0; j < allCookingTargets.length; j++) {
                if (isSelected) {
                    $(allCookingTargets[j]).removeClass("selected");
                } else {
                    $(allCookingTargets[j]).addClass("selected");
                }
            }
        }

        /**
         * 点击搜索做法按钮
         * */
        $cookingSearchBtn.on('click', function () {
            var dish = orderDishData.getDish(currentSubDish.DishId);
            mpos.showDialog(mpos.dialogPage.cookingSearch, {
                Dish: dish,
                OrderDishData: orderDishData,
                CheckCookings: currentSubDish.Cookings || []
            }, function (data) {
                if (data && data.length > 0) {
                    currentSubDish.Cookings = data;
                    showSelectedCookingStatus();
                }
            });
        })

        //
        page.appendTo('body').addClass("show");
        _.delay(function () {
            page.addClass("animation");
        }, 10);
    }

    /**
     * 移除套餐子菜界面
     */
    function hide() {
        var page = $('body>.package-subdish-page');
        page.removeClass("animation");
        _.delay(function () {
            page.remove();
        }, 200);
    }

    return {
        show: show,
        hide: hide()
    }
})();

/**
 * 消息列表页面
 * */
mpos.controller(mpos.page.payToOrdeDetails, function (page, data) {
    var $list = $(page).find("ul.app-list.paytoorder-list");
    var $itemPayment = $list.find("li.payment-list").remove();
    var orderId = data.OrderId;
    var listData = [];
    $list.empty();
    getMessageList();


    /**
    * 从服务端获取账单列表
    */
    function getMessageList() {
        mpos.post(mpos.api.getPayToOrdeDetails, {
            OrderId: orderId
        }, function (data) {
            listData = data;
            data.forEach(function (p) {
                var paymentItem = $itemPayment.clone();
                paymentItem.find(".pay-serial-number").text(p.Serial);
                paymentItem.find(".pay-time").text(p.Time);
                paymentItem.find(".pay-dish-num").text(p.DishNum);
                paymentItem.find(".pay-pay-amount").text(p.Amount);
                paymentItem.find(".pay-payments").text(p.PaymentTypes);
                paymentItem.find(".pay-created-user").text(p.CreateBy);
                paymentItem.find(".pay-payments").text(p.PaymentTypes);
                paymentItem.find(".pay-status").text(p.StatusDesc);
                paymentItem.data("c_id", p.Id);
                $list.append(paymentItem);
            });

            $list.find(".pay-print").on("click", function (e) {
                var billId = mpos.localStorage.PreBilledOrderId;
                var printNum = mpos.cashOrderNumber();
                if (!billId) {
                    mpos.alert("没有设置打印格式，无法打印！");
                    return;
                }
                var $btn = $(e.currentTarget);
                var preConsumptionId = $btn.parents("li").data("c_id");
                if (preConsumptionId) {
                    mpos.dialog({
                        title: "提醒",
                        text: "确定要打印吗？",
                        okButton: "是",
                        cancelButton: "否"
                    }, function (res) {
                        if (res === 'ok') {
                            mpos.post(mpos.api.getPayToOrderPrintData, {
                                CashBillId: billId, //收银单ID
                                PreConsumptionId: preConsumptionId
                            }, function (re) {
                                //打印
                                var consumptionBill = re;
                                if (Array.isArray(consumptionBill) && consumptionBill.length > 0) {
                                    for (var i = 0; i < printNum; i++) { //打印多份
                                        var printData = mpos.addPrintEmptyLine(consumptionBill);
                                        mpos.deviceFactory.printTicket(printData, null, function (err) {
                                            mpos.alert(err);
                                        });
                                    }
                                } else {
                                    mpos.alert("返回数据格式不对!");
                                }
                            });
                        }
                    });
                }
            });
        });
    }
});

mpos.controller(mpos.page.printStyle, function(page) {
    //console.log(mpos.page.printStyle + " created.");

    $.selectOnFocus(page);
    var $page = $(page);

    var preBilledOrderId = mpos.preBilledOrderId() || 0;
    var preBilledOrderNumber = mpos.preBilledOrderNumber() || 1;
    var cashOrderId = mpos.localStorage.CashOrderId || 0;
    var cashOrderNumber = mpos.cashOrderNumber() || 1;
    var tableBillId = mpos.tableBillId() || 0;
    var tableBillNumber = mpos.tableBillNumber() || 1;
    var billHeadNumber = mpos.billHeadNumber() || 1;
    var billFootNumber = mpos.billFootNumber() || 1;
    var printTotalBill = mpos.printTotalBill() || 0;
    var printSigleBill = mpos.printSigleBill() || 0;

    var rechargePrintId = mpos.localStorage.RechargePrintId || 0;
    var rechargePrintNumber = mpos.localStorage.RechargePrintNumber || 1;

    var saveWinesPrintId = mpos.localStorage.SaveWinesPrintId || 0;  // 存酒打印格式ID
    var saveWinesPrintNumber = mpos.localStorage.SaveWinesPrintNumber || 1;  // 存酒打印数量
    var fetchWinesPrintId = mpos.localStorage.FetchWinesPrintId || 0;  // 取酒打印格式ID
    var fetchWinesPrintNumber = mpos.localStorage.FetchWinesPrintNumber || 1;  // 存酒打印数量

    var printerIP = mpos.localStorage.PrinterIP || "";
    var printerPort = mpos.localStorage.PrinterPort || 0;
    var preBilledOrderList = [],
        cashOrderList = [],
        tableBillList = [],
        rechargePrintList = [],
        saveWinesPrintList = [],   // 存酒打印格式数组
        fetchWinesPrintList = [];  // 取酒打印格式数组

    var $preBilledOrderSelect = $page.find('.printstyle-settings select[name=preBilledOrderId]');
    var $cashOrderSelect = $page.find('.printstyle-settings select[name=cashOrderId]');
    var $tableBillSelect = $page.find('.printstyle-settings select[name=tableBillId]');
    var $rechargePrintSelect = $page.find('.printstyle-settings select[name=rechargePrintId]');
    var $saveWinesPrintSelect = $page.find('.printstyle-settings select[name=saveWinesPrintId]');  // 存酒打印格式下拉组件
    var $fetchWinesPrintSelect = $page.find('.printstyle-settings select[name=fetchWinesPrintId]');  // 取酒打印格式下拉组件

    //处理模拟select的赋值
    function fakeSpanText() {
        var t = $(this);
        t.parent().find("span").text(this.options[this.selectedIndex].text);
    }
    $preBilledOrderSelect.on("change", fakeSpanText);
    $cashOrderSelect.on("change", fakeSpanText);
    $tableBillSelect.on("change", fakeSpanText);
    $rechargePrintSelect.on('change', fakeSpanText);
    $saveWinesPrintSelect.on('change', fakeSpanText);
    $fetchWinesPrintSelect.on('change', fakeSpanText);

    //初始赋值
    var $preBilledOrderNumber = $page.find('.printstyle-settings input[name=preBilledOrderNumber]');
    $preBilledOrderNumber.val(preBilledOrderNumber);
    mpos.checkInputValue($preBilledOrderNumber, InputType.Num0To100);
    var $cashOrderNumber = $page.find('.printstyle-settings input[name=cashOrderNumber]');
    $cashOrderNumber.val(cashOrderNumber);
    mpos.checkInputValue($cashOrderNumber, InputType.Num0To100);
    var $tableBillNumber = $page.find('.printstyle-settings input[name=tableBillNumber]');
    $tableBillNumber.val(tableBillNumber);
    mpos.checkInputValue($tableBillNumber, InputType.Num0To100);
    var $rechargePrintNumber = $page.find('.printstyle-settings input[name=rechargePrintNumber]');
    $rechargePrintNumber.val(rechargePrintNumber);
    mpos.checkInputValue($rechargePrintNumber, InputType.Num0To100);
    var $saveWinesPrintNumber = $page.find('.printstyle-settings input[name=saveWinesPrintNumber]');
    $saveWinesPrintNumber.val(saveWinesPrintNumber);
    mpos.checkInputValue($saveWinesPrintNumber, InputType.Num0To100);
    var $fetchWinesPrintNumber = $page.find('.printstyle-settings input[name=fetchWinesPrintNumber]');
    $fetchWinesPrintNumber.val(fetchWinesPrintNumber);
    mpos.checkInputValue($fetchWinesPrintNumber, InputType.Num0To100);

    var $billHeadNumber = $page.find('.printstyle-settings input[name=billHeadNumber]');
    $billHeadNumber.val(billHeadNumber);
    mpos.checkInputValue($billHeadNumber, InputType.Num0To100);
    var $billFootNumber = $page.find('.printstyle-settings input[name=billFootNumber]');
    $billFootNumber.val(billFootNumber);
    mpos.checkInputValue($billFootNumber, InputType.Num0To100);
    $page.find('.printstyle-settings input[name=printTotalBill]').prop("checked", !!(+printTotalBill));
    $page.find('.printstyle-settings input[name=printSigleBill]').prop("checked", !!(+printSigleBill));

    $page.find('.printstyle-settings input[name=printerIP]').val(printerIP);
    $page.find('.printstyle-settings input[name=printerPort]').val(printerPort);

    //打印测试
    $page.find('.printstyle-settings .print-test').on("click", function () {
        var printerIp = $page.find('.printstyle-settings input[name=printerIP]').val();
        var printerPort = parseInt($page.find('.printstyle-settings input[name=printerPort]').val()) || 0;
        if (printerPort == 0 || printerIp.trim().length == 0) {
            mpos.deviceFactory.printTest(function () { }, function (err) {
                mpos.alert(err);
            });
        } else {
            mpos.mposUtils.doPrint({
                printdata: [{
                    size: 1,
                    text: "打印测试0123456789",
                    type: 1
                }],
                ip: printerIp,
                port: printerPort,
                type: 0
            }, null, function (err) {
                mpos.alert("打印错误：" + err);
            });
        }
    });

    //back click event
    $page.on("appBeforeBack", function() {
        //存储数据
        mpos.preBilledOrderNumber(parseInt($page.find('.printstyle-settings input[name=preBilledOrderNumber]').val()) || 1);
        mpos.cashOrderNumber(parseInt($page.find('.printstyle-settings input[name=cashOrderNumber]').val()) || 1);
        mpos.preBilledOrderId(preBilledOrderList[$preBilledOrderSelect[0].selectedIndex].Id);
        mpos.localStorage.CashOrderId = cashOrderList[$cashOrderSelect[0].selectedIndex].Id;
        mpos.tableBillId(tableBillList[$tableBillSelect[0].selectedIndex].Id);
        mpos.tableBillNumber(parseInt($page.find('.printstyle-settings input[name=tableBillNumber]').val()) || 1);
        mpos.billHeadNumber(parseInt($page.find('.printstyle-settings input[name=billHeadNumber]').val()) || 1);
        mpos.billFootNumber(parseInt($page.find('.printstyle-settings input[name=billFootNumber]').val()) || 1);
        mpos.localStorage.RechargePrintId =  rechargePrintList[$rechargePrintSelect[0].selectedIndex].PrintFormatMasterId;
        mpos.localStorage.RechargePrintNumber = parseInt($page.find('.printstyle-settings input[name=rechargePrintNumber]').val()) || 1;
        mpos.localStorage.PrinterPort = parseInt($page.find('.printstyle-settings input[name=printerPort]').val()) || 0;
        mpos.localStorage.PrinterIP = $page.find('.printstyle-settings input[name=printerIP]').val().trim();
        var isPrintTotalBill = $page.find('.printstyle-settings input[name=printTotalBill]').prop("checked");
        mpos.printTotalBill(+isPrintTotalBill);
        var isPrintSigleBill = $page.find('.printstyle-settings input[name=printSigleBill]').prop("checked");
        mpos.printSigleBill(+isPrintSigleBill);
        mpos.saveWinesBillId(saveWinesPrintList[$saveWinesPrintSelect[0].selectedIndex].Id);
        mpos.saveWinesBillNumber(parseInt($saveWinesPrintNumber.val()) || 1);
        mpos.fetchWinesBillId(fetchWinesPrintList[$fetchWinesPrintSelect[0].selectedIndex].Id);
        mpos.fetchWinesBillNumber(parseInt($fetchWinesPrintNumber.val()) || 1);
    });

    // 查询打印单格式数据
    mpos.post(mpos.api.getPrintBillFormat, function(data) {
        if (!Array.isArray(data)) {
            mpos.alert("接口返回数据错误");
            return;
        }
        data.forEach(function(item, index) {
            //fake
            //if (typeof jsonModelPrintType == 'object')
            //item = jsonModelPrintType;

            if (item.BillTypeNo == PrtBillType.ReadyPayBill) {
                preBilledOrderList.push(item);
            } else if (item.BillTypeNo == PrtBillType.CashBill) {
                cashOrderList.push(item);
            } else if (item.BillTypeNo == PrtBillType.TableBill) {
                tableBillList.push(item);
            } else if (item.BillTypeNo == PrtBillType.SaveWinesBill) {
                saveWinesPrintList.push(item);
            } else if (item.BillTypeNo == PrtBillType.FetchWinesBill) {
                fetchWinesPrintList.push(item);
            }

        });

        preBilledOrderList.forEach(function(item, index) {
            var option = $('<option>').attr("value", item.Id).text(item.Name);
            if (item.Id == preBilledOrderId) {
                option.prop("selected", true);
                $preBilledOrderSelect.parent().find("span").text(item.Name);
            }
            option.appendTo($preBilledOrderSelect);
        });

        cashOrderList.forEach(function(item, index) {
            var option = $('<option>').attr("value", item.Id).text(item.Name);
            if (item.Id == cashOrderId) {
                option.prop("selected", true);
                $cashOrderSelect.parent().find("span").text(item.Name);
            }
            option.appendTo($cashOrderSelect);
        });

        tableBillList.forEach(function(item, index) {
            var option = $('<option>').attr("value", item.Id).text(item.Name);
            if (item.Id == tableBillId) {
                option.prop("selected", true);
                $tableBillSelect.parent().find("span").text(item.Name);
            }
            option.appendTo($tableBillSelect);
        });

        saveWinesPrintList.forEach(function(item, index) {
            var option = $('<option>').attr("value", item.Id).text(item.Name);
            if (item.Id == saveWinesPrintId) {
                option.prop("selected", true);
                $saveWinesPrintSelect.parent().find("span").text(item.Name);
            }
            option.appendTo($saveWinesPrintSelect);
        });

        fetchWinesPrintList.forEach(function(item, index) {
            var option = $('<option>').attr("value", item.Id).text(item.Name);
            if (item.Id == fetchWinesPrintId) {
                option.prop("selected", true);
                $fetchWinesPrintSelect.parent().find("span").text(item.Name);
            }
            option.appendTo($fetchWinesPrintSelect);
        });
    });

    // 查询充值打印格式
    mpos.post(mpos.api.getRechargePrintFormat, function (data) {
        if (!Array.isArray(data)) {
            mpos.alert("获取充值小票格式数据错误");
            return;
        }
        rechargePrintList = data;
        rechargePrintList.forEach(function (item, index) {
            var option = $('<option>').attr("value", item.PrintFormatMasterId).text(item.FormatName);
            if (item.PrintFormatMasterId == rechargePrintId) {
                option.prop("selected", true);
                $rechargePrintSelect.parent().find("span").text(item.FormatName);
            }
            option.appendTo($rechargePrintSelect);
        });
    });
});

/**
 * author: wang.p  2021-07-27
 * description: 催菜操作
 * 催菜功能暂时没有完成， 按钮显示在tableOperationPage.html，  开关控制homePage.js中   PushFood: false, 修改为true   2021-08-07  wang.p
 * */
mpos.controller(mpos.page.pushFood, function (page, obj) {
  var fmt = "yy-MM-dd HH:mm:ss";
  var settleData = [];
  var $pageDom = $(page);
  var $tableName = $pageDom.find(".table-name").remove();
  var $tableInfo = $pageDom.find(".table-info").remove();
  var $dishItem = $pageDom.find(".dish-item").remove();
  var $dishList = $pageDom.find(".table-dish-list").remove();
  var firstOrderStatus = 0;

  //返回事件
  function backToPrev() {
    mpos.back(mpos.page.home); //返回到首页
  }

  this.onBackKeyDown = backToPrev;
  $pageDom.find("#goBack").on("click", backToPrev);
  // 取消
  $pageDom.find("#pushCancelBtn").on("click", backToPrev);
  // 全选
  $pageDom.find("#pushCheckBtn").on("click", function () {
    $(".push-food-check-container").each(function(i){
      if(!$(this).hasClass('checked')) {
        $(this).addClass('checked')
      }
    });
  });
  // 催菜
  $pageDom.find("#pushFoodBtn").on("click", function () {
    var selectDishIds = [];
    $(".push-food-check-container.checked").each(function(i){
        selectDishIds.push($(this).data('dishId'));
    });
    // TODO: 请求催菜
  });

  /**
   * 显示金额及菜品
   * @param {Object} data
   * @param {Number} [status]
   * @param {XMLHttpRequest} [xhr]
   */
  function loadSettleCallBak(data, status, xhr) {
    settleData = data;
    if (firstOrderStatus == 0) {
      firstOrderStatus = settleData.EnterOrder.Order.OrderStatus;
    }
    //增加整单ID
    $pageDom.data("whole_order_id", settleData.EnterOrder.Order.WholeBillId);

    /*****循环输出餐台*****/
    // var dishAndOtherTable = "";

    $pageDom.find(".app-content").empty();
    var fragment = $(document.createDocumentFragment());

    var tableName = $tableName.clone();
    var tableInfo = $tableInfo.clone();
    var dishList = $dishList.clone();

    /****第一个餐台输入开始****/
    //餐台
    tableName.find(".name").text(settleData.EnterOrder.Table.TableName + (settleData.EnterOrder.Order.IsMain == 1 ? "(主)" : ""));
    //会员信息
    if (settleData.MemberCard != null) {
      $("<div class='member-name' />").text("会员：" + settleData.MemberCard.MemberName).appendTo(tableName);
    }

    //输出开台信息
    var openTableInfo = findOpenTableInfo(settleData.EnterOrder.Order.OrderId);
    tableInfo.find(".table-time").text("开台时间：" + (new Date(settleData.EnterOrder.Order.BeginTime)).formatDate(fmt));
    tableInfo.find(".table-people").text("人数：" + settleData.EnterOrder.Table.PeopleNum);
    tableInfo.find(".table-user").text("开台人：" + (openTableInfo == null ? "" : openTableInfo.OpenTableUser));
    tableInfo.find(".table-businesstimespan").text("市别：" + (openTableInfo == null ? "" : openTableInfo.BusinessTimeSpanName));

    //输入进入餐台的菜品
    $.each(settleData.EnterOrder.Dishes, function (idx, item) {
      var dishItem = $dishItem.clone();
      dishItem.find('label.dish-selected').data("dishId", item.OrderDishId);
      dishItem.find('.push-food-check-container').data('dishId', item.OrderDishId);
      dishItem.find(".dish-name").html(mpos.getDishTag(item) + item.DishName);
      dishItem.find(".dish-num").text("x" + item.DishNum);
      if (item.ReturnOrderDishId != 0) {
        dishItem.find(".dish-name").addClass('disabled');
      }
      if (item.DishProperty == OrderDishProperty.PackageDishChild) {
        dishItem.find(".dish-name").addClass('disabled');
        dishItem.find(".dish-amount").text("-");
      } else if (item.DishProperty == OrderDishProperty.MultiDishChild) {
        // 一品多吃子菜
        dishItem.find(".dish-name").addClass('disabled');
        dishItem.find(".dish-amount").text("-");
      } else {
        dishItem.find(".dish-amount").text(mpos.formatPrice(item.DishSaleAmount));
      }

      var cookies = "";
      var dishUnit = item.DishPortions;
      if (item.Discount < 100) {
        dishUnit += "/" + parseFloat((item.Discount / 10).toFixed(2)) + "折";
      }
      $.each(item.DishRequestList, function (idx, re) {
        cookies += re.RequestName + (Math.abs(re.RequestNum) == 1 ? "" : ("*" + re.RequestNum)) + "、"; //做法
      });

      if (cookies.length > 0) {
        dishItem.find(".dish-cookies").text(dishUnit + "/" + cookies.substr(0, cookies.length - 1));
      } else {
        dishItem.find(".dish-cookies").text(dishUnit);
      }
      dishList.append(dishItem);
    });

    fragment.append(tableName);
    fragment.append(tableInfo);
    fragment.append(dishList);

    /****第一个餐台输入End****/

    // //输出其它餐台及菜品
    // $.each(settleData.Orders, function (idx, order) {
    //   if (order.Order.OrderId == settleData.EnterOrder.Order.OrderId)
    //     return;
    //   tableInfo = $tableInfo.clone();
    //   tableName = $tableName.clone();
    //   dishList = $dishList.clone();
    //
    //   //餐台名称
    //   tableName.find(".name").text(order.Table.TableName + (order.Order.IsMain == 1 ? "(主)" : ""));
    //
    //   //输出开台信息
    //   var openTableInfo = findOpenTableInfo(order.Order.OrderId);
    //   tableInfo.find(".table-time").text("开台时间：" + (new Date(order.Order.BeginTime)).formatDate(fmt));
    //   tableInfo.find(".table-people").text("人数：" + order.Table.PeopleNum);
    //   tableInfo.find(".table-user").text("开台人：" + (openTableInfo == null ? "" : openTableInfo.OpenTableUser));
    //   tableInfo.find(".table-businesstimespan").text("市别：" + (openTableInfo == null ? "" : openTableInfo.BusinessTimeSpanName));
    //
    //   //输出菜品
    //   $.each(order.Dishes, function (index, item) {
    //     var dishItem = $dishItem.clone();
    //     dishItem.find('label.dish-selected').data("dishId", item.OrderDishId);
    //     dishItem.find('.push-food-checkbox').data("dishId", item.OrderDishId);
    //     dishItem.find(".dish-name").html(mpos.getDishTag(item) + item.DishName);
    //     dishItem.find(".dish-num").text("x" + item.DishNum);
    //     if (item.ReturnOrderDishId != 0) {
    //       dishItem.find(".dish-name").addClass('disabled');
    //     }
    //     if (item.DishProperty == OrderDishProperty.PackageDishChild) {
    //       dishItem.find(".dish-name").addClass('disabled');
    //       dishItem.find(".dish-amount").text("-");
    //     } else {
    //       dishItem.find(".dish-amount").text(mpos.formatPrice(item.DishSaleAmount));
    //     }
    //
    //     var cookies = "";
    //     var dishUnit = item.DishPortions;
    //     if (item.Discount < 100) {
    //       dishUnit += "/" + parseFloat((item.Discount / 10).toFixed(2)) + "折";
    //     }
    //     $.each(item.DishRequestList, function (idx, re) {
    //       cookies += re.RequestName + (Math.abs(re.RequestNum) == 1 ? "" : ("*" + re.RequestNum)) + "、"; //做法
    //     });
    //     if (cookies.length > 0) {
    //       dishItem.find(".dish-cookies").text(dishUnit + "/" + cookies.substr(0, cookies.length - 1));
    //     } else {
    //       dishItem.find(".dish-cookies").text(dishUnit);
    //     }
    //     dishList.append(dishItem);
    //
    //   });
    //
    //   fragment.append(tableName);
    //   fragment.append(tableInfo);
    //   fragment.append(dishList);
    // });
    //
    //
    // /*****循环输出餐台结束*****/

    /*****事件处理******/
    //菜品点击事件
    fragment.find(".table-dish-list .dish-selected").on("click", function (e) {
      e.stopPropagation();
      var checkContainer = $(this).find('.push-food-check-container');
      if (checkContainer.hasClass('checked')) {
        checkContainer.removeClass('checked');
      } else {
        checkContainer.addClass('checked');
      }
    });

    $pageDom.find(".app-content").append(fragment);
  }

  // /*
  //  获取一个菜品
  //  */
  // function findDishData(orderDishId) {
  //   for (var j = 0; j < settleData.Orders.length; j++) {
  //     for (var i = 0; i < settleData.Orders[j].Dishes.length; i++) {
  //       if (settleData.Orders[j].Dishes[i].OrderDishId == orderDishId) {
  //         return settleData.Orders[j].Dishes[i];
  //       }
  //     }
  //   }
  //   return null;
  // }

  /*
   获取开台信息
   * */
  function findOpenTableInfo(orderId) {
    if (settleData.OpenTableInfos) {
      for (var i = 0; i < settleData.OpenTableInfos.length; i++) {
        if (settleData.OpenTableInfos[i].OrderId == orderId) {
          return settleData.OpenTableInfos[i];
        }
      }
    }
    return null;
  }

  /**
   * 判断菜品数据是否存在，否则就请求数据
   * */
  if (obj.settle == undefined || obj.settle == null) {
    var orderId = obj.OrderId;
    mpos.getSettleInfo(orderId, loadSettleCallBak, {
      blFailed: function (data) {
        mpos.alert(data.data);
        mpos.back();
      }
    });
  } else {
    loadSettleCallBak(obj.settle);
  }
});

/**
 * Created by xeonwell on 2016/7/13.
 *
 */
mpos.controller(mpos.page.rechargeDetail, function (page, item) {
    var $page = $(page);
    var me = this;
    var fmt = "yy-MM-dd HH:mm:ss";
    var memRechargeRecordId = item.MemRechargeRecordId;
    var rechargeData = null;
    var rechargeNo = $page.find('.recharge-no');
    rechargeNo.hide();

    var rechargeAmount = $page.find('.recharge-amount');
    var rechargeGive = $page.find('.recharge-give');
    var rechargeStatus = $page.find('.recharge-status');
    var rechargePaymentType = $page.find('.recharge-payment-type');
    var rechargeOperator = $page.find('.recharge-operator');
    var rechargeTime = $page.find('.recharge-time');

    var memberName = $page.find('.member-name');
    var memberMobile = $page.find('.member-mobile');
    var memberCouponName = $page.find('.member-couponName');
    var memberCardNo = $page.find('.member-cardNO');

    initRechargeData();

    //退款
    $page.find('.recharge-refund').on('click', function () {
        //如果是拉卡拉
        if (rechargeData.IsLklPay) {
            mpos.post(mpos.api.lklRechargeReturnMoney, {
                RechargeId: memRechargeRecordId,
            }, function (config) {
                if (typeof config == "object") {
                    mpos.showLoading();
                    mpos.isPaying = true;
                    var cfg = {
                        OrderNo: config.OrderNo,
                        PayAmount: config.PayAmount,
                        BoxConfig: config.BoxConfig,
                        PaymentType: config.PaymentType,
                    };
                    cfg.PayType = 3;
                    cfg.CbOrderNo = config.TradeNo;
                    mpos.deviceFactory.payOrder(cfg, function (result) {
                        mpos.hideLoading();
                        mpos.isPaying = false;
                        var outTradeNo = result.OutTradeNo;
                        mpos.post(mpos.api.rechargeReturnMoney, {
                            RechargeId: memRechargeRecordId,
                            OutTradeNo: outTradeNo,
                        }, function () {
                            me.reply('1');
                        });
                    }, function (err) {
                        mpos.hideLoading();
                        mpos.isPaying = false;
                        mpos.alert("退款失败:" + err);
                    })
                }
            });
        } else {
            mpos.post(mpos.api.rechargeReturnMoney, {
                RechargeId: memRechargeRecordId,
                OutTradeNo: "",
            }, function () {
                me.reply('1');
            });
        }
    });

    //重试
    $page.find('.recharge-retry').on('click', function () {
        mpos.post(mpos.api.retryRecharge, {
            RechargeId: memRechargeRecordId,
            FormatMasterId: mpos.localStorage.RechargePrintId || 0,//打印格式
        }, function (r) {
            //打印
            var printNum = mpos.localStorage.RechargePrintNumber || 0;
            var printBills = r.PrintContent;
            if (Array.isArray(printBills) && printBills.length > 0) {
                for (var i = 0; i < printNum; i++) { //打印多份
                    var printData = mpos.addPrintEmptyLine(printBills);
                    mpos.deviceFactory.printTicket(printData, null, function (err) {
                        mpos.alert(err);
                    });
                }
            }
            me.reply('1');
        });
    });

    /*
    初始化显示
    */
    function initRechargeData() {
        mpos.post(mpos.api.getRechargeDetail, {
            RechargeId: memRechargeRecordId
        }, function (r) {
            rechargeData = r;
            rechargeAmount.text(mpos.formatPrice(r.TotalAmount));
            if (r.PresentType == 1) {
                rechargeGive.text("（赠送 " + mpos.formatPrice(r.PresentAmount) + "）");
            } else {
                rechargeGive.text("（赠送 票券）");
            }
            rechargeStatus.text("充值状态：" + r.RechargeStatusDes);
            rechargePaymentType.text(r.PaymentPatternName);
            rechargeOperator.text(r.CreatedBy);
            rechargeTime.text(r.CreatedOn);

            memberName.text(r.MemberName);
            memberMobile.text(r.Mobile);
            memberCouponName.text(r.CouponName);
            memberCardNo.text(r.MemberNumber);

            if (r.RechargeStatus == 2 || r.RechargeStatus == 4) {
                $page.find(".footer.clearfix").hide();
            }
        });
    }
});
/**
 * Created by xeonwell on 2016/7/13.
 */
mpos.controller(mpos.page.rechargeList, function (page) {
    var $page = $(page);

    var fmt = "yyyy-MM-dd",
        fmtTime = "HH:mm:ss";

    var pageIndex = 1;

    //list for operate
    var $list = $(page).find(".app-list.billOrder-list");
    //template
    var $item = $list.find("li.app-button").remove();
    //loading animation
    var $loading = $(page).find(".scrollLoading").remove();
    // can load more?
    var canLoadMore = true;

    var currentDate = new Date();
    var billDateLabel = $page.find("span.bill-date");
    var currentDayInput = $page.find('input[name=currentDay]');

    billDateLabel.text(currentDate.formatDate(fmt));
    currentDayInput.val(currentDate.formatDate(fmt)).on('change', function () {
        currentDate = new Date(this.value);
        resetConditions();
    });

    //前一天
    $page.find(".previous-day").on("click", function () {
        currentDate = currentDate.yesterday();
        currentDayInput.val(currentDate.formatDate(fmt));
        resetConditions();
    });

    //后一天
    $page.find(".next-day").on("click", function () {
        currentDate = currentDate.tomorrow();
        currentDayInput.val(currentDate.formatDate(fmt));
        resetConditions();
    });

    //get current date recharge list
    getRechargeList();

    /**
     * 重置条件并开始请求
     */
    function resetConditions() {
        billDateLabel.text(currentDate.formatDate(fmt));
        pageIndex = 1;
        canLoadMore = true;
        $list.empty();
        getRechargeList();
    }

    /**
     * 从服务端获取充值记录
     */
    function getRechargeList() {
        mpos.infiniteScroll($list, {
            loading: $loading
        }, function (callback) {
            if (!canLoadMore)
                return null;

            mpos.post(mpos.api.queryRecharges, {
                RechargeDate: currentDate.formatDate(fmt),
                PageSize: Config.DefaultPageSize,
                PageIndex: pageIndex++
            }, function (data) {
                if (!Array.isArray(data)) {
                    mpos.alert("返回数据格式不对");
                    canLoadMore = false;
                    return;
                }
                var list = [];
                canLoadMore = data.length == Config.DefaultPageSize;
                data.forEach(function (item, index) {

                    var $node = $item.clone();
                    $node.find(".billOrder-number").text(item.CreatedBy);
                    $node.find(".diningtable-number").text(item.RechargeStatusDes);
                    $node.find(".billOrder-time").text((new Date(item.CreatedOn)).formatDate(fmtTime));
                    $node.find(".billOrder-amount").text(mpos.formatPrice(item.TotalAmount));
                    $node.tap(function (e) {
                        mpos.pick(mpos.page.rechargeDetail, item, function (data) {
                            if (data == "1") {
                                //退款、重试之后，需要刷新单据
                                resetConditions();
                            }
                        });
                    });

                    list.push($node);
                });
                callback(list);

            }, {
                hideLoading: true
            });
        });
    }
});

/**
 * 选择酒水
 */
mpos.controller(mpos.page.saveWinesChoose, function (page, pageData) {
  var $page = $(page);
  //参数处理
  var winesData = pageData.winesData || {}
  var chooseData = winesData.Details || []; //点菜订单ID
  var isSnack = false;

  var SELECT_TYPE_CLASS = "selected";

  //点菜对象
  var orderDishData = mpos.OrderDishData.createNew();

  var currentSelectedDishType = 0; //当前选中的菜品分类

  var shoppingCarContainer = $page.find(".shopping-car-container"); //购物车未下单列表
  var dishTypeContainer = $page.find(".dish-type-list");
  var dishContainer = $page.find(".app-content>ul.dish-list");
  // var searchInput = $page.find("input[name='searchDish']");
  var dishSearchContainer = $page.find('.app-content>.dish-search-list>.dish-list');

  var $shoppingCarItem = shoppingCarContainer.find("li.shopping-car-item").remove();
  var goodsCar = $page.find(".goodsCar.app-button");
  var $dishTypeItem = dishTypeContainer.find("li").remove();
  var $dishItem = dishContainer.find("li").remove();


  var kb = {};
  // 判断是否启用系统默认键盘
  if (mpos.localStorage.enableSystemKeyboard) {
    kb.reset = function () { }; // 空方法，防止切换系统默认键盘时，调用自定义键盘的reset方法
    dishSearchContainer.css('padding-top', '47px');
    var searchDishResult = dishSearchContainer.parent().find('input[name="searchDishResult"]');
    searchDishResult.removeClass('nd');
    searchDishResult.bind('input porpertychange', function (obj) {
      var searchReg = $(this).val().trim().toLowerCase();
      var dishList = [];
      if (searchReg !== '') {
        for (var i = 0, j = 0; i < orderDishData.dishes.length; i++) {
          var dish = orderDishData.dishes[i];
          if (dish.Dish.DishSpell.toLowerCase().indexOf(searchReg) !== -1 ||
            dish.Dish.DishSerial.toLowerCase().indexOf(searchReg) !== -1 ||
            dish.Dish.DishName.toLowerCase().indexOf(searchReg) !== -1) {
            //精确匹配的提前
            if (dish.Dish.DishSpell.toLowerCase() == searchReg ||
              dish.Dish.DishSerial.toLowerCase() == searchReg ||
              dish.Dish.DishName.toLowerCase() == searchReg) {
              dishList.unshift(dish);
            } else {
              dishList.push(dish);
            }
          }
        }

        if (dishList.length > Config.maxSearchDishDisplayLength) {
          dishList = dishList.slice(0, Config.maxSearchDishDisplayLength);
        }
      }

      dishSearchContainer.empty().append(fragmentWithDishList(dishList));
      refreshUI();
    })

  } else {
    kb = new mpos.Components.KeyBoard({
      parent: dishSearchContainer.parent(),
      showResultLabel: true,
      callback: function (searchReg) {
        var displayStr = null;
        var dishList = [];
        if (searchReg !== null) {
          for (var i = 0, j = 0; i < orderDishData.dishes.length; i++) {
            var dish = orderDishData.dishes[i];
            if (searchReg.test(dish.Dish.DishSpell) ||
              searchReg.test(dish.Dish.DishSerial) ||
              searchReg.test(dish.Dish.DishName)) {

              var str = RegExp.$1.toLowerCase();
              //精确匹配的提前
              if (dish.Dish.DishSpell.toLowerCase() == str ||
                dish.Dish.DishSerial.toLowerCase() == str ||
                dish.Dish.DishName.toLowerCase() == str) {
                dishList.unshift(dish);
              } else {
                dishList.push(dish);
              }

              if (displayStr === null) displayStr = str;
              // j += 1;
              // if (j > Config.maxSearchDishDisplayLength)
              //     break;
            }
          }

          if (dishList.length > Config.maxSearchDishDisplayLength) {
            dishList = dishList.slice(0, Config.maxSearchDishDisplayLength);
          }
        }

        dishSearchContainer.empty().append(fragmentWithDishList(dishList));
        refreshUI();

        return displayStr;
      }
    });
  }

  /** @namespace mpos.localStorage.OrderDishDisplayMode */
  mpos.registerStorageProperties('OrderDishDisplayMode');

  var displayMode = 0; //记录分段控件列表和搜索的状态

  /**
   * 切换显示界面为列表还是搜索
   */
  function switchDisplayUI() {
    if (displayMode === 0) {
      dishSearchContainer.parent().addClass('nd');
      kb.reset();
      dishSearchContainer.empty();

      if (mpos.localStorage.enableSystemKeyboard) {
        //系统键盘时，清空搜索输入框
        dishSearchContainer.parent().find('input[name="searchDishResult"]').val('');
      }
      dishTypeContainer.removeClass('nd');
      dishContainer.removeClass('nd');
    } else {
      dishTypeContainer.addClass('nd');
      dishContainer.addClass('nd');
      dishSearchContainer.parent().removeClass('nd');
    }
  }

  // 分段控件
  setTopBarSwitch();
  switchDisplayUI();
  //加载点菜数据
  prepareLoadOrderDishDatas();

  //缓存滚动位置
  var contentScrollOffset = 0;
  dishContainer.on("scroll", function (e) {
    contentScrollOffset = e.currentTarget.scrollTop;
  });
  //还原滚动条的位置
  $page.on("appLayout", function () {
    if (contentScrollOffset > 0)
      dishContainer[0].scrollTop = contentScrollOffset;
  });

  //返回
  $page.find("#goBack").on("click", function (e) {

    mpos.load(mpos.page.saveWines, {winesData: winesData}); //返回首页
  });

  /*
   * 显示头部分段控件
   * */
  function setTopBarSwitch(type) {
    $page.find('.app-topbar>.switch-display').empty(); //清空

    //分段控件
    new mpos.Components.SegmentControl({
      parent: $page.find('.app-topbar>.switch-display'),
      data: ['列表', '搜索'],
      debounceTime: 80,
      initIndex: displayMode,
      callback: function (index) {
        displayMode = index;
        switchDisplayUI();
      }
    });

  }

  //购物车事件
  goodsCar.on("click", function () {
    if (orderDishData.ShoppingCarDishes.length == 0 && !isShoppingCarContainerDisplayed()) {
      return;
    }
    if (isShoppingCarContainerDisplayed()) {
      hideShoppingCarContainer();
    } else {
      refreshShoppingCarUI();
      showShoppingCarContainer();
    }
  });

  /**
   * 检测购物车是否显示
   */
  function isShoppingCarContainerDisplayed() {
    return !shoppingCarContainer.hasClass("nd");
  }

  //下单/付款按钮事件
  $page.find(".doOrderDish.app-button").on("click", function () {
    var dishes = [];
    // 将手动添加的存酒商品找出来， 通过判断DishId和UnitId
    var dishDict = {};
    if (chooseData && chooseData.length > 0) {
      chooseData.forEach(function (dish) {
        if(dish.DishId != 0 && dish.UnitId != 0) {
          dishDict[dish.DishId] = dish;
        } else {
          dishes.push(dish);
        }
      });
    }

    if (orderDishData.ShoppingCarDishes.length > 0) {
      orderDishData.ShoppingCarDishes.forEach(function (dish) {
        var findDish = dishDict[dish.DishId];
        dishes.push({
          DetailId: findDish ? findDish.DetailId : 0,   // 详细ID
          AssessPrice: 0,   /// 估价，没有默认0
          DishId: dish.DishId,
          DishName: dish.DishName,
          SaveNum: dish.DishNum,
          UnitName: dish.DishPortions,
          UnitId: dish.DishPortionsId,
          PositionId: findDish ? findDish.PositionId : 0,
          PositionName: findDish ? findDish.PositionName : ''   // 位置名称
        });
      });
    }
    dishDict = null;

    winesData.Details = dishes;

    mpos.load(mpos.page.saveWines, {winesData: winesData});
  });

  /**
   准备加载数据
   */
  function prepareLoadOrderDishDatas() {
    setDishData();
    refreshUI();
    refreshShoppingCarUI();
  }

  /**
   设置数据和UI
   */
  function setDishData() {
    var dishTypes = [];
    var dishKeys = Object.keys(mpos.BaseData.Dishes);

    for (var m = 0; m < mpos.BaseData.DishTypes.length; m++) {
      for (var i = 0; i < dishKeys.length; i++) {
        var baseDish = mpos.BaseData.Dishes[dishKeys[i]];
        if (baseDish != undefined) {
          if (baseDish.Dish.DishTypeId == mpos.BaseData.DishTypes[m].DishTypeId) {
            dishTypes.push(mpos.BaseData.DishTypes[m]);
            break;
          }
        }
      }
    }
    orderDishData.dishTypes = dishTypes;
    orderDishData.IsSnackOrderDish = isSnack;
    orderDishData.orderConfig = {};
    orderDishData.dishes = concatAndSortDishes();
    orderDishData.cookings = mpos.BaseData.Cookings;
    orderDishData.cookingTypes = mpos.BaseData.CookingTypes;
    orderDishData.ShoppingCarDishes = [];

    // 找出已选的菜品
    if (chooseData && chooseData.length > 0) {
      for (var i = 0; i < chooseData.length; i++) {
        // 判断菜品ID和单位ID不为空，就说明是菜单中的数据，否则就是手动添加的存酒商品
        if (chooseData[i]['DishId'] && chooseData[i]['DishId'] != 0 && chooseData[i]['UnitId'] && chooseData[i]['UnitId'] != 0) {
          var dishId = chooseData[i]['DishId'];
          var dishNum = chooseData[i]['SaveNum'];
          var dish = orderDishData.getDish(dishId);
          var dishUnitId = dish.Units[0].PortionsId;
          // 添加到购物车数据
          orderDishData.addSaveWinesDishToShoppingCar({
            DishId: dish.Dish.DishId,
            UnitId: dishUnitId,
            DishNum: dishNum,
          });
        }
      }
    }

    loadDishTypes(); //加载菜品和类型
    loadDishes();

    setScrollData();
  }

  /**
   * 设置滚动所需要的数据及处理菜品列表滚动、菜品分类点击等事件
   */
  function setScrollData() {
    dishTypeContainer.find("li:first-of-type").addClass(SELECT_TYPE_CLASS);

    if (orderDishData.dishes.length > Config.maxDishLength) {
      //类型点击事件
      dishTypeContainer.find("li").on("click", function (e) {
        var currentTarget = $(e.currentTarget);
        if (currentTarget.hasClass(SELECT_TYPE_CLASS))
          return;

        var typeId = currentTarget.data("type_id");
        loadDishes(typeId);
        dishTypeContainer.find("li." + SELECT_TYPE_CLASS).removeClass(SELECT_TYPE_CLASS);
        currentTarget.addClass(SELECT_TYPE_CLASS);
      });
      return;
    }

    var scrollData = [];

    //因为放入了分类信息，所以直接去分类所在位置即可
    dishContainer.find("li.dish-type").each(function () {
      scrollData.push(this.offsetTop);
    });

    if (scrollData.length <= 1)
      return;
    scrollData.push(Number.MAX_VALUE);

    /**
     * 滚动时判断滚动位置，切换菜品分类的显示
     * @param e Event
     */
    function scrollEvent(e) {
      //var scrollTop = e.currentTarget.scrollTop;
      for (var i = 0; i < scrollData.length - 1; i++) {
        if (i != currentSelectedDishType && contentScrollOffset >= scrollData[i] && contentScrollOffset < scrollData[i + 1]) {
          currentSelectedDishType = i;
          dishTypeContainer.find("li." + SELECT_TYPE_CLASS).removeClass(SELECT_TYPE_CLASS);
          dishTypeContainer.find("li").eq(currentSelectedDishType).addClass(SELECT_TYPE_CLASS);
          break;
        }
      }
    }

    dishContainer.on("scroll", scrollEvent);

    //类型点击事件
    dishTypeContainer.find("li").on("click", function (e) {
      var currentTarget = $(e.currentTarget);
      if (currentTarget.hasClass(SELECT_TYPE_CLASS))
        return;

      dishContainer.off("scroll", scrollEvent);

      //找到分类的位置并滚动过去
      //目前没有使用动画
      var typeId = currentTarget.data("type_id");
      for (var i = 0; i < orderDishData.dishTypes.length; i++) {
        if (orderDishData.dishTypes[i].DishTypeId == typeId) {
          currentSelectedDishType = i;
          dishContainer[0].scrollTop = scrollData[currentSelectedDishType];
          break;
        }
      }

      dishTypeContainer.find("li." + SELECT_TYPE_CLASS).removeClass(SELECT_TYPE_CLASS);
      currentTarget.addClass(SELECT_TYPE_CLASS);

      //即时附上事件，将会触发，导致最后的分类如果不满一页，无法第一次选中
      setTimeout(function () {
        dishContainer.on("scroll", scrollEvent);
      }, 100);
    });

  }

  /**
   * 组织成点菜的数据
   * 根据菜品分类排序菜品
   */
  function concatAndSortDishes() {

    var result = [];

    var dishTypeMap = {};
    orderDishData.dishTypes.forEach(function (item) {
      dishTypeMap[item.DishTypeId] = [];
    });
    var dishesKeys = Object.keys(mpos.BaseData.Dishes);
    dishesKeys.forEach(function (item) {
      var dish = {};
      var baseDish = mpos.BaseData.Dishes[item];
      if (baseDish != undefined) {
        dish.Units = baseDish.Units;
        dish.Dish = {
          DishId: baseDish.Dish.DishId,
          DishName: baseDish.Dish.DishName,
          IsTemporary: baseDish.Dish.IsTemporary,
          IsRandomPrice: baseDish.Dish.IsRandomPrice,
          DishProperty: baseDish.Dish.DishProperty,
          DishSerial: baseDish.Dish.DishSerial,
          DishTypeId: baseDish.Dish.DishTypeId,
          DishSpell: baseDish.Dish.DishSpell,
          IsConfirmWeight: baseDish.Dish.IsConfirmWeight == 1,
          PackageCategory: baseDish.Dish.PackageCategory,
          IsRateDiscount: baseDish.Dish.IsRateDiscount,
          IsModifyNum: baseDish.Dish.IsModifyNum,
          IsMultiDish: baseDish.Dish.IsMultiDish, //  一品多吃菜类型，  1-一品多吃主菜
          IsMultiMainDish: baseDish.Dish.IsMultiMainDish, //  一品多吃主菜，  1-是主菜
        };
        dish.DishCookings = baseDish.DishCookings;

        dishTypeMap[dish.Dish.DishTypeId].push(dish);
      }
    });

    orderDishData.dishTypes.forEach(function (item) {
      result = result.concat(dishTypeMap[item.DishTypeId]);
    });

    return result;
  }

  /**
   * 刷新UI
   */
  function refreshUI(dishIds) {
    if (dishIds != undefined) {
      dishIds.forEach(function (dishId) {
        var itemDom = $page.find("li[data-dish_id='" + dishId + "']");
        //刷新已点数量
        refreshDishShowUI(dishId, itemDom);
      });
    } else {
      orderDishData.ShoppingCarDishes.forEach(function (item) {
        var itemDom = $page.find("li[data-dish_id='" + item.DishId + "']");
        //刷新已点数量
        refreshDishShowUI(item.DishId, itemDom);
      });
    }

    refreshShoppingCarInfo();

  }

  /**
   刷新购物车内的菜品数量
   */
  function refreshShoppingCarInfo() {
    var data = orderDishData.getShopCartDishNum();
    var dishNum = data.DishNums;
    var goodsCarDishCount = goodsCar.find(".goods-car-dish-count");
    if (dishNum > 0) {
      goodsCarDishCount.attr('style', 'display:inline');
      goodsCarDishCount.text(parseFloat(dishNum));
    } else {
      goodsCarDishCount.attr('style', '');
    }
  }

  /**
   刷新点菜情况
   */
  function refreshDishShowUI(dishId, itemDom) {
    var dishItem = itemDom;

    /***********已点数量处理************/
    var info = orderDishData.getHasSelectDishNum(dishId);
    if (!info) {
      return;
    }

    if (dishItem != undefined && dishItem.length > 0) {
      var numComponent = dishItem.find(".num");

      if (info.DishNums > 0) {
        numComponent.text(parseFloat(info.DishNums));
        if (info.DishNums > 1) {
          numComponent.addClass("more");
        } else {
          numComponent.removeClass("more");
        }
      } else {
        numComponent.text("").removeClass("more");
      }

    }

    var dishTypeItem = $page.find("li[data-type_id='" + info.DishTypeId + "']");
    if (dishTypeItem != undefined && dishTypeItem.length > 0) {
      if (info.DishTypeNum > 0) {
        dishTypeItem.find(".dish-count").show();
        dishTypeItem.find(".dish-count").text(parseFloat(info.DishTypeNum));
      } else {
        dishTypeItem.find(".dish-count").hide();
      }
    }
  }

  /**
   * 刷新购物车UI中的菜品
   */
  function refreshShoppingCarUI() {
    shoppingCarContainer.empty();

    var fragment = $(document.createDocumentFragment());
    var sortNumber = 0;
    for (var i = 0; i < orderDishData.ShoppingCarDishes.length; i++) {
      var dish = orderDishData.ShoppingCarDishes[i];
      sortNumber += 1;
      var item = $shoppingCarItem.clone(); //单个菜品列表
      item.find('.sort-number').html(sortNumber);
      item.data("order_dish_id", dish.OrderDishId);
      var dishName = dish.DishName;
      item.find(".name").text(dishName);
      item.find(".num").text(dish.DishNum);
      //+、-事件
      item.find(".dish-operation").on("click", function (e) {
        e.stopPropagation();
        if (e.target.tagName != "BUTTON")
          return;
        var target = $(e.target);
        var $li = target.parents("li");
        var orderDishId = $li.data("order_dish_id");
        var isIncrease = target.hasClass("increase"); //标识点+号还是-号
        var orderDish = orderDishData.getShoppingCarDishByOrderDishId(orderDishId);
        if (isIncrease) {
          orderDishData.increaseSaveWinesShoppingCarDishNum(orderDishId, 1, function () {
            refreshUI();
            orderDish = orderDishData.getShoppingCarDishByOrderDishId(orderDishId);
            var _dishName = orderDish.DishName;
            $li.find(".name").text(_dishName);
            $li.find(".num").text(orderDish.DishNum);
          });
        } else {
          var carDishIds = orderDishData.getShoppingCardDishIds();
          orderDishData.increaseSaveWinesShoppingCarDishNum(orderDishId, -1, function () {
            refreshUI(carDishIds);
            orderDish = orderDishData.getShoppingCarDishByOrderDishId(orderDishId);
            if (orderDish == null) {
              $li.remove();
            } else {
              var _dishName = orderDish.DishName;
              $li.find(".name").text(_dishName);
              $li.find(".num").text(orderDish.DishNum);
            }
          });
        }
      });

      fragment.append(item);
    }

    shoppingCarContainer.append(fragment);

  }

  /**
   加载菜品和菜品类型
   */
  function loadDishTypes() {
    dishTypeContainer.empty();

    var fragment = $(document.createDocumentFragment());
    //菜品类型
    $.each(orderDishData.dishTypes, function (idx, item) {
      var clone = $dishTypeItem.clone();
      clone.removeClass(SELECT_TYPE_CLASS);
      clone.find(".dish-type-name").text(item.DishTypeName);
      clone.data("type_id", item.DishTypeId);
      clone.find(".dish-count").hide();
      fragment.append(clone);
    });
    dishTypeContainer.append(fragment);
  }

  /**
   * 加载菜品
   * @param dishTypeId dish type id
   */
  function loadDishes(dishTypeId) {

    dishContainer.empty();
    if (orderDishData.dishTypes.length == 0)
      return;

    //写入菜品，需要判断是否菜品数量>200
    var dishList = [];

    var typeId;
    if (orderDishData.dishes.length > Config.maxDishLength || dishTypeId != undefined) {
      typeId = dishTypeId || orderDishData.dishTypes[0].DishTypeId;
      dishList = orderDishData.dishes.filter(function (item) {
        return typeId == item.Dish.DishTypeId;
      });
    } else {
      dishList = orderDishData.dishes;
    }

    var fragment = fragmentWithDishList(dishList);

    //处理菜品分类，插入到菜品列表中，滑动切换分类需要这个
    if (orderDishData.dishes.length <= Config.maxDishLength && dishTypeId == undefined) {
      typeId = 0;
      dishList.forEach(function (item) {
        if (item.Dish.DishTypeId != typeId) {
          typeId = item.Dish.DishTypeId;
          var dishType = orderDishData.dishTypes.find(function (t) {
            return t.DishTypeId == typeId;
          });
          if (dishType) {
            fragment.find("li[data-dish_id='" + item.Dish.DishId + "']")
              .before($("<li class='dish-type' />")
                .text(dishType.DishTypeName)
                .data("typeId", dishType.DishTypeId));
          }
        }
      });
    }
    dishContainer.append(fragment);

    dishContainer[0].scrollTop = 0;

    refreshUI();
  }

  /**
   * 根据菜品列表，生成document fragment
   * @param dishList
   */
  function fragmentWithDishList(dishList) {
    var fragment = $(document.createDocumentFragment());
    dishList.forEach(function (item) {
      if (item.Units.length == 0) {
        return;
      }
      var dishItem = $dishItem.clone();
      dishItem.data("dish_id", item.Dish.DishId);
      var dishName = item.Dish.DishName;
      if (item.Units[0].PriceType == OrderDishPriceType.Special) {
        dishName = "(特)" + dishName;
      }
      if (item.Dish.IsTemporary == 1) {
        dishName = "(临)" + dishName;
      }
      dishItem.find(".name").text(dishName);
      dishItem.find(".price").text(mpos.formatPrice(orderDishData.getDishPrice(item)));

      dishItem.find(".dish-operation").on("click", function (e) {
        if (e.target.tagName != "BUTTON")
          return;

        var target = $(e.target);
        var dishId = target.parents("li").data("dish_id");
        var isIncrease = target.hasClass("increase"); //标识点+号还是-号
        //点菜事件
        beginOrderDish(dishId, isIncrease);
      });
      fragment.append(dishItem);
    });
    return fragment;
  }

  /**
   开始点菜
   @dishId ： 菜品ID
   @isIncrease : 是否加菜
   */
  function beginOrderDish(dishId, isIncrease) {
    //reset keyboard
    kb.reset();
    var dish, hasOrderDishes;
    if (isIncrease) { //如果是加菜
      dish = orderDishData.getDish(dishId);
      hasOrderDishes = orderDishData.getShoppingCarDish(dishId);

      var dishNum = 1;
      var dishUnitId = dish.Units[0].PortionsId;
      if (hasOrderDishes.length == 1) {
        //直接加数量
        orderDishData.increaseSaveWinesShoppingCarDishNum(hasOrderDishes[0].OrderDishId, dishNum, function () {
          refreshUI();
        });
      } else {
        orderDishData.addSaveWinesDishToShoppingCar({
          DishId: dish.Dish.DishId,
          UnitId: dishUnitId,
          DishNum: dishNum,
        }, function () {
          refreshUI();
        });
      }

    } else { //如果是减菜
      hasOrderDishes = orderDishData.getShoppingCarDish(dishId);
      if (hasOrderDishes.length == 0) {
        return;
      }

      var carDishIds = orderDishData.getShoppingCardDishIds();
      orderDishData.increaseSaveWinesShoppingCarDishNum(hasOrderDishes[0].OrderDishId, -1, function () {
        refreshUI(carDishIds);
      });
    }
  }

  /**
   * 动画显示购物车
   */
  function showShoppingCarContainer() {
    shoppingCarContainer.removeClass("nd");
    _.delay(function () {
      shoppingCarContainer.addClass("animation");
    }, 10);
  }

  /**
   * 动画隐藏购物车
   */
  function hideShoppingCarContainer() {
    shoppingCarContainer.removeClass("animation");
    _.delay(function () {
      shoppingCarContainer.addClass("nd");
    }, 200);
  }

});

/**
 * author: wang.p   2021-09-06
 * description: 存酒管理
 * */

// 创建存酒的对象
function createSaveWinesObj (data) {
  var winesObj = {
    StorageSaveId: 0,   //存酒ID
    Mobile: "",     // 手机号
    CustomerName: "",   // 客户名称
    MemberId: 0,   // 会员ID
    CardId: 0,   // 卡ID
    ExpiryDate: "",   // 过期时间
    Checked: false,   // 是否永久
    Remark: "",   // 备注
    /** {
        DetailId: 0,   // 详细ID
        AssessPrice: 0,   /// 估价，没有默认0
        DishId: 0,   // 菜品ID
        DishName: "",  // 菜品名称
        UnitId: 0,   // 单位ID
        UnitName: "",   // 单位名称
        SaveNum: 0,   // 存酒数量
        PositionId: 0,   // 位置ID
        PositionName: ""   // 位置名称
      }
    * */
    Details: []  // 存酒列表
  }

  if (data) {
    var keys = Object.keys(winesObj);
    keys.forEach(function (k) {
      var defaultValue = null;
      switch (typeof winesObj[k]) {
        case "string":
          defaultValue = ''
          break;
        case "boolean":
          defaultValue = ''
          break;
        case "number":
          defaultValue = ''
          break;
      }

      winesObj[k] = data[k] || defaultValue;
    })
    if (winesObj.ExpiryDate) {
      var tempDate = new Date(winesObj.ExpiryDate);
      winesObj.ExpiryDate = mpos.dateFormat(tempDate);
    }
  }

  return winesObj;
}

mpos.controller(mpos.page.saveWines, function (page, pageData) {
  var $page = $(page);
  // 尽量不用使用全局的winesData来保存，因为在修改位置和数量时，该数据不会更新，如果要保持一致，要使用获取数据的方法 getSaveWinesData
  var winesData = createSaveWinesObj(pageData.winesData);
  var chooseDishes = winesData.Details || [];
  var winesPlaceData = []; // 保存存酒的位置信息
  if (winesData.ExpiryDate === '') {
    var nowTime = new Date().getTime() + 30 * 24 * 60 * 60 * 1000;
    var tempDate = new Date(nowTime);
    winesData.ExpiryDate = mpos.dateFormat(tempDate);
  }

  var $mobile = $page.find('input[name=mobile]');
  var $mobileTips = $page.find('.mobile-tips');
  var $customer = $page.find('input[name=customer]');
  var $ExpiryDate = $page.find('input[name=ExpiryDate]');
  var $ExpiryDateSpan = $page.find('.date-container .date-text');
  var $chkExpire = $page.find('input[name=chkExpire]');
  var $remark = $page.find('.remark');
  var $ulNode = $page.find('.app-content .wines-list');
  var $liNode = $ulNode.find('li').remove();
  var timerTips = null; // 定时隐藏提示信息
  var $tipsContainer = $page.find('.app-content .tips-container');

  // 自动获取会员信息
  $page.find('input[name=chkAutoMember]').on('click', function(e){
    e.stopPropagation();
    var $checkBox = $(this);
    if ($checkBox.hasClass('checked')) {
      $checkBox.removeClass('checked');
    } else {
      $checkBox.addClass('checked');
      var value = $.trim($mobile.val());
      searchMemberInfo(value);
    }
  })

  // 有效期永久有效切换事件
  $page.find('input[name=chkExpire]').on('click', function(e){
    e.stopPropagation();
    var $checkBox = $(this);
    var checked = true;
    if ($checkBox.hasClass('checked')) {
      $checkBox.removeClass('checked');
      checked = false;
    } else {
      $checkBox.addClass('checked');
    }
    if ($checkBox.attr('name') === 'chkExpire') {
      if (checked) {
        var forever = '9999-12-30';
        $ExpiryDate.val(forever);
        $ExpiryDateSpan.text(forever);
        winesData.ExpiryDate = forever;
      } else {
        var nowTime = new Date().getTime() + 30 * 24 * 60 * 60 * 1000;
        var tempDate = mpos.dateFormat(new Date(nowTime));
        $ExpiryDate.val(tempDate);
        $ExpiryDateSpan.text(tempDate);
        winesData.ExpiryDate = tempDate;
      }
    }
  });

  // 返回上一个页面
  function backToPrev () {
    mpos.load(mpos.page.saveWinesManage);
  };

  // 返回
  this.onBackKeyDown = backToPrev;
  $page.find("#goBack").on("click", function(e) {
    e.stopPropagation();
    backToPrev();
  });

  $page.on("appShow", function () {
    // 获取存酒的位置信息
    mpos.get(mpos.api.getAllWinePosition, {}, function(res) {
      winesPlaceData = res || [];

      //加载数据
      loadSaveWinesInfo();
    });
  });

  // 获取存酒位置信息
  function getPositionName (positionId) {
    var place = winesPlaceData.find(function(item) {
      return item.StoragePositionId == positionId;
    });
    return  place ? place.DisplayName : '';
  }

  /**
   * 请求存酒数据
   * */
  function loadSaveWinesInfo () {
    $mobile.val(winesData.Mobile);
    $customer.val(winesData.CustomerName);
    $ExpiryDateSpan.text(winesData.ExpiryDate);
    $ExpiryDate.val(winesData.ExpiryDate);
    if (winesData.Checked) {
      $chkExpire.addClass('checked');
    }
    $remark.val(winesData.Remark);

    showUlNode();  // 渲染存酒的数据
  }

  // 渲染存酒的列表
  function showUlNode () {
    $ulNode.empty();
    if (chooseDishes && chooseDishes.length > 0) {
      $tipsContainer.addClass('nd');
      var fragment = $(document.createDocumentFragment());
      chooseDishes.forEach(function(item) {
        var $node = $liNode.clone();
        $node.data('DetailId', item.DetailId || 0);
        $node.attr('dish-id-value', item.DishId);
        $node.attr('unit-id-value', item.UnitId);
        $node.attr('unit-name-value', (item.UnitName || ''));
        $node.find('.dish-name').text(item.DishName);
        $node.find('input[name=total]').val(item.SaveNum);
        $node.find('input[name=place]').val(getPositionName(item.PositionId));
        $node.find('input[name=place]').data("PositionId", item.PositionId);
        $node.find('.delete-btn').on('click', function(e) {
          var $parentLI = $(this).parents('li');
          var dishName = $parentLI.find('.dish-name').text();
          var dishId = $parentLI.attr('value');
          mpos.dialog({
            title: "提醒",
            text: "是否删除" + dishName + "？",
            okButton: "是",
            cancelButton: "否"
          }, function (status) {
            if (status && status.toLowerCase() === 'ok') {
              $parentLI.remove();
              // 判断是否移除完数据，
              var childLi = $ulNode.find('li');
              if (!childLi || childLi.length === 0) {
                showTipsContainer();
              }
            }
          });
        });
        fragment.append($node);
      })
      $ulNode.append(fragment);
    } else {
      showTipsContainer();
    }

    // 显示提示添加存酒信息
    function showTipsContainer () {
      var cloneTipsContainer = $tipsContainer.clone();
      cloneTipsContainer.removeClass('nd');
      $ulNode.append(cloneTipsContainer);
    }

    /**
     *  输入存酒数量
     */
    $page.find("input[name=total]").on("click", function () {
      var $total = $(this);
      var total = $total.val();
      mpos.showDialog(mpos.dialogPage.saveWinesNumber, {
        total: total
      }, function (res) {
        if (res.status) {
          $total.val(res.total);
        }
      });
    });

    /**
     * 选择存酒位置
     */
    $page.find("input[name=place]").on("click", function () {
      var $place = $(this);
      var positionId = $place.data("PositionId");
      mpos.showDialog(mpos.dialogPage.saveWinesPlace, {
        placeData: winesPlaceData,
        positionId: positionId
      }, function (res) {
        if (res.status && res.place) {
          var placeData = res.place;
          $place.val(placeData.DisplayName);
          $place.data("PositionId", placeData.PositionId);
        }
      });
    });
  }

  /**
   * 获取数据
   * @filterNum  是否过滤掉数量为0的数据，默认过滤， true 不过滤
   * */
  function getSaveWinesData (filterNum) {

    var mobile = $mobile.val();
    var customer = $customer.val();
    var expiryDate = $ExpiryDate.val();
    var remark = $remark.val();
    var newWinesData = JSON.parse(JSON.stringify(winesData));
    newWinesData.Mobile = $.trim(mobile);
    newWinesData.CustomerName = $.trim(customer);
    newWinesData.ExpiryDate = $.trim(expiryDate);
    newWinesData.Remark = $.trim(remark);

    var winesList = [];
    var $liList = $page.find('li');
    if ($liList && $liList.length > 0) {
      for(var i=0;i<$liList.length;i++) {
        var $node = $($liList[i]);
        var detailId = $node.data('DetailId') || 0;
        var dishId = $node.attr('dish-id-value');
        var unitId = $node.attr('unit-id-value');
        var unitName = $node.attr('unit-name-value');
        var dishName = $node.find('.dish-name').text();
        var saveNum = $node.find('input[name=total]').val();
        var positionId = $node.find('input[name=place]').data("PositionId")

        if (!filterNum) {
          if (saveNum && Number(saveNum) > 0) {
            winesList.push({
              DetailId: detailId,   // 详细ID
              DishId: Number(dishId || 0),   // 菜品ID
              DishName: dishName,  // 菜品名称
              UnitId: Number(unitId || 0),   // 单位ID
              UnitName: unitName,   // 单位名称
              SaveNum: Number(saveNum),   // 存酒数量
              PositionId: Number(positionId || 0),   // 位置ID
            });
          }
        } else {
          winesList.push({
            DetailId: detailId,   // 详细ID
            DishId: Number(dishId || 0),   // 菜品ID
            DishName: dishName,  // 菜品名称
            UnitId: Number(unitId || 0),   // 单位ID
            UnitName: unitName,   // 单位名称
            SaveNum: Number(saveNum),   // 存酒数量
            PositionId: Number(positionId || 0),   // 位置ID
          });
        }
      }
    }
    newWinesData.Details = winesList;

    return newWinesData
  }

  // 添加存酒数据
  $page.find(".footer .get-btn").on("click", function () {
    mpos.showDialog(mpos.dialogPage.addSaveWinesInfo, {}, function (res) {
      if (res.status === 1) {
        // 手动添加商品
        winesData = getSaveWinesData();
        winesData.Details.push(res.winesData);
        chooseDishes = winesData.Details;
        showUlNode(); // 渲染数据
      } else if (res.status === 2) {
        // 手动选择商品
        var newWinesData = getSaveWinesData();
        mpos.load(mpos.page.saveWinesChoose, {winesData: newWinesData}); //返回首页
      }
    })

  });

  // 确定存酒
  $page.find(".footer .save-btn").on("click", function () {
    var saveWinesData = getSaveWinesData();
    if (!valiMobile(saveWinesData.Mobile)) {
      mpos.alert('手机号输入有误');
      return;
    }
    if (saveWinesData.CustomerName === '') {
      mpos.alert('客户姓名不能为空');
      return;
    }
    // 验证有效期必须大于今天
    if (!saveWinesData.ExpiryDate || new Date(saveWinesData.ExpiryDate).getTime() <= new Date().getTime()) {
      mpos.alert('有效期必须大于当天');
      return;
    }

    if (saveWinesData.Details.length === 0) {
      mpos.alert('请选择存酒信息');
      return ;
    }
    for(var i=0;i<saveWinesData.Details.length;i++) {
      if (!saveWinesData.Details[i].PositionId || saveWinesData.Details[i].PositionId == 0) {
        mpos.alert(saveWinesData.Details[i]['DishName'] + '未设置存酒位置');
        return ;
      }
    }

    if (saveWinesData.Details && saveWinesData.Details.length > 0) {
      saveWinesData.PrintBillId = mpos.saveWinesBillId();  // 将存酒打印格式ID传入后端，获取打印的格式信息
      mpos.post(mpos.api.addSaveWineStorage, saveWinesData , function(res) {
        if (res) {
          var printData = res.printData;
          try {
            //打印
            if (printData != undefined && printData.length > 0) {
              $.each(printData, function (idx, item) {
                for (var i = 0; i < mpos.saveWinesBillNumber(); i++) { //打印多份
                  var print = mpos.addPrintEmptyLine(item);
                  mpos.deviceFactory.printTicket(print, null, function (err) {
                    //打印
                    mpos.alert(err);
                  });
                }
              });
            }
          } catch (e) {

          }
          mpos.load(mpos.page.saveWinesManage); //返回首页
        } else {
          mpos.alert('保存失败，请重试')
        }
      });
    }
  })

  // 手机号正则验证
  function valiMobile (mobile) {
    return (/^1[3456789]\d{9}$/.test(mobile.trim()))
  }

  // 手机号输入框监听
  $mobile.on("input", function() {
    var chkAutoMember = $page.find('input[name=chkAutoMember]');
    if ($(chkAutoMember[0]).hasClass('checked')) {
      var value = $.trim($(this).val());
      searchMemberInfo(value);
    }
  });

  // 查询会员的信息
  function searchMemberInfo (mobile) {
    // 判断是否输入完整的手机号，验证是否自动获取会员信息
    if (valiMobile(mobile)) {
      mpos.get(mpos.api.getFindMember, {Mobile: mobile}, function(res) {
        if (res && res.MemberId) {
          var keys = Object.keys(res);
          keys.forEach(function(k){
            winesData[k] = res[k];
          });
          $customer.val(res.MemberName);
        } else {
          $customer.val('');
          showMobileTips('未查询到会员信息')
        }
      });
    }
  }
  // 展示提示信息
  function showMobileTips (tips) {
    $mobileTips.removeClass('nd');
    $mobileTips.text(tips);
    if (timerTips) {
      clearTimeout(timerTips);
    }
    timerTips = setTimeout(function(){
      $mobileTips.addClass('nd');
      timerTips = null;
    }, 3000)
  }

  $ExpiryDate.on('change', function () {
    var currentDate = new Date(this.value);
    var currentDateStr = mpos.dateFormat(currentDate);
    $(this).parent().find('.date-text').text(currentDateStr);
  });

});

/**
 添加存酒信息
 */
mpos.dialogController(mpos.dialogPage.addSaveWinesInfo, function (page, data) {
  var $page = $(page);
  var total = 1;
  var $inputNode = $page.find(".app-input")
  var $winesNum = $page.find("input[name=winesNum]");
  var $winesName = $page.find("input[name=winesName]");
  var $winesUnit = $page.find("input[name=winesUnit]");

  $winesNum.val(total);
  mpos.checkInputValue($winesNum, InputType.MaxNum);

  //确定和取消事件
  $page.find(".app-submit").on("click", function (e) {
    var operationType = $(e.currentTarget).data("operation");
    if (operationType == 2) {
      mpos.dialog.close({status: 0});
    } else {
      var total = $.trim($winesNum.val());

      var dishName = $.trim($winesName.val());
      var saveNum = $.trim($winesNum.val());
      var unitName = $.trim($winesUnit.val());
      if (!dishName || dishName === '') {
        mpos.alert('名称不能为空');
        return;
      }
      if (!unitName || unitName === '') {
        mpos.alert('单位不能为空');
        return;
      }

      var winesData = {
        DetailId: 0,   // 详细ID
        DishId: 0,   // 菜品ID
        DishName: dishName,  // 菜品名称
        UnitId: 0,   // 单位ID
        UnitName: unitName,   // 单位名称
        SaveNum: Number(saveNum || 0),   // 存酒数量
        PositionId: 0,   // 位置ID
      }
      mpos.dialog.close({
        status: 1,
        winesData: winesData
      });
    }
  });

  // 选择商品
  $page.find('.select-wines-btn').on("click", function (e) {
    e.stopPropagation();
    mpos.dialog.close({status: 2});
  })

  $inputNode.focus(function(){
    $(this).addClass('focus-bg-color');
  });
  $inputNode.blur(function(){
    $(this).removeClass('focus-bg-color');
  });

});


/**
 存酒数量
 */
mpos.dialogController(mpos.dialogPage.saveWinesNumber, function (page, data) {
  var $page = $(page);
  var total = data && data.total != '' ? data.total : 1;
  var $winesNum = $page.find("input[name=winesNum]");
  $winesNum.val(total);
  mpos.checkInputValue($winesNum, InputType.MaxNum);

  //确定和取消事件
  $page.find(".app-submit").on("click", function (e) {
    var operationType = $(e.currentTarget).data("operation");
    if (operationType == 2) {
      mpos.dialog.close({
        status: false
      });
    } else {
      var total = $.trim($winesNum.val());
      mpos.dialog.close({
        status: true,
        total: total
      });
    }
  });

  $winesNum.focus(function(){
    $(this).addClass('focus-bg-color');
  });
  $winesNum.blur(function(){
    $(this).removeClass('focus-bg-color');
  });

  // 显示修改数量时，延迟获取输入框焦点
  setTimeout(function(){
    $winesNum.focus();
  }, 200);

});

/**
 存酒位置
 */
mpos.dialogController(mpos.dialogPage.saveWinesPlace, function (page, data) {
  var $page = $(page);
  var placeData = data && data.placeData ? data.placeData : [];
  var positionId = data && data.positionId ? data.positionId : '';
  var $placeContainer = $page.find(".place-list");
  var $placeNode = $placeContainer.find(".place").remove();

  if (placeData && placeData.length > 0) {
    var fragment = $(document.createDocumentFragment());
    placeData.forEach(function(item) {
      var $node = $placeNode.clone();
      $node.text(item.DisplayName);
      $node.data('StoragePositionId', item.StoragePositionId);
      if (positionId === item.StoragePositionId) {
        $node.addClass('checked');
      }
      fragment.append($node);
    })
    $placeContainer.append(fragment);

    $placeContainer.find('.place').on('click', function () {
      var $node = $(this);
      if ($node.hasClass('checked')) {
        $node.removeClass('checked');
      } else {
        var $checkNode = $placeContainer.find('.checked');
        $checkNode.removeClass('checked');
        $node.addClass('checked');
      }
    })
  }

  //确定和取消事件
  $page.find(".app-submit").on("click", function (e) {
    var operationType = $(e.currentTarget).data("operation");
    if (operationType == 2) {
      mpos.dialog.close({
        status: false
      });
    } else {
      var $checkNode = $placeContainer.find('.checked');
      if ($checkNode && $checkNode.length > 0) {
        var newPlace = {
          DisplayName: $checkNode.text(),
          PositionId: $checkNode.data('StoragePositionId')
        } ;
        mpos.dialog.close({
          status: true,
          place: newPlace
        });
      } else {
        mpos.alert('请选择存酒位置');
      }
    }
  });

});



/**
 * author: wang.p   2021-09-06
 * description: 存酒管理
 * */

mpos.controller(mpos.page.saveWinesManage, function (page, pageData) {
  var $page = $(page);
  var statusList = [
    {value: 0, text: '全部'},
    {value: 1, text: '正常'},
    {value: 2, text: '已取完'},
    {value: 3, text: '已作废'},
    {value: 4, text: '已过期'}
  ];
  var winesPlaceData = []; // 缓存存酒位置数组信息

  var $StartDate = $page.find('.StartDate');
  var $EndDate = $page.find('.EndDate');
  var $StartDateSpan = $StartDate.parent().find('.date-text');
  var $EndDateSpan = $EndDate.parent().find('.date-text');
  var $statusSelect = $page.find('.save-wines-manage-form select[name=status]');
  var $winesManageListContainer = $page.find(".app-content .save-wines-manage-list");
  var $winesLiItem = $winesManageListContainer.find("li").remove();
  var $tipsContainer = $page.find('.tips-container');
  var $searchKeyWord = $page.find('.save-wines-manage-form input[name=searchKeyWord]')

  // 存酒日期默认显示近一个月
  var endDate = new Date();
  var startTimer = endDate.getTime() - 30 * 24 * 60 * 60 * 1000
  var startDate = new Date(startTimer);

  var startDateStr = mpos.dateFormat(startDate);
  var endDateStr = mpos.dateFormat(endDate);

  $StartDate.val(startDateStr);
  $EndDate.val(endDateStr);
  $StartDateSpan.text(startDateStr);
  $EndDateSpan.text(endDateStr);

  $StartDate.on('change', function () {
    var currentDate = new Date(this.value);
    var currentDateStr = mpos.dateFormat(currentDate);
    $StartDateSpan.text(currentDateStr);
  });
  $EndDate.on('change', function (value) {
    var currentDate = new Date(this.value);
    var currentDateStr = mpos.dateFormat(currentDate);
    $EndDateSpan.text(currentDateStr);
  });

  statusList.forEach(function(item, index) {
    var option = $('<option>').attr("value", item.value).text(item.text);
    if (item.value == statusList[0].value) {
      option.prop("selected", true);
      $statusSelect.parent().find("span").text(item.text);
    }
    option.appendTo($statusSelect);
  });

  // 态下拉事件
  $statusSelect.on("change", function () {
    var t = $(this);
    t.parent().find("span").text(this.options[this.selectedIndex].text);
  });

  // 点击查询
  $page.find('.save-wines-manage-form .search-btn').on('click', loadSaveWinesList);


  /**
   * 返回上个界面
   */
  function backToPrev() {
    var mposType = mpos.localStorage.OrderPropertyType || OrderPropertyType.Normal;
    if (mposType == OrderPropertyType.Normal) {
      mpos.load(mpos.page.home); //返回首页
      mpos.removeFromStack();
    } else {
      mpos.load(mpos.page.orderDishes); //返回点餐页面
      mpos.removeFromStack();
    }
  }

  // 关键字输入框获取焦点时选中全部
  $searchKeyWord.on('focus', function(){
    this.select();
  });


  //返回
  this.onBackKeyDown = backToPrev;
  $page.find("#goBack").on("click", backToPrev);

  $page.on("appShow", function () {
    //是否显示登录
    if (mpos.currentUser == null) {
      mpos.showDialog(mpos.dialogPage.login, function (status) {
        if (status) {
          //加载数据
          loadSaveWinesList();
        }
      });
    } else {
      //加载数据
      loadSaveWinesList();
    }
  });

  /**
   * 请求存酒数据
   * */
  function loadSaveWinesList () {
    // 获取查询条件
    var startDateStr = $StartDateSpan.text();
    var endDateStr = $EndDateSpan.text();
    var keyWord = $searchKeyWord.val();
    var status = statusList[$statusSelect[0].selectedIndex].value;
    var options = {
      BeginTime: startDateStr,
      EndTime: endDateStr,
      keyWord: keyWord.trim(),
      Status: status
    };

    mpos.post(mpos.api.getSaveWineList, options, function(res) {
      initWinesList(res);
    });

    // 获取存酒的位置信息
    if (!winesPlaceData || winesPlaceData.length === 0) {
      mpos.get(mpos.api.getAllWinePosition, {}, function (res) {
        winesPlaceData = res || [];
      });
    }
  }

  /**
   * 渲染存酒列表
   * */
  function initWinesList (data) {
    // 清空ul
    $winesManageListContainer.empty();

    if (!data || data.length === 0) {
      $tipsContainer.removeClass('nd');
      return ;
    } else {
      $tipsContainer.addClass('nd')
    }

    var fragment = $(document.createDocumentFragment());
    data.forEach(function(item, idx) {
      var $node = $winesLiItem.clone();
      $node.data('Id', item.Id)
      $node.find('.num').text(idx + 1);
      $node.find('.SerialNum').text(item.SerialNum);
      $node.find('.CustomerName').text(item.CustomerName);
      $node.find('.Mobile').text(item.Mobile);
      $node.find('.operation').on('click', function(e) {
        //TODO: 展示详情
        e.stopPropagation();
        var $liNode = $(this).parents('li');
        var winesId = $liNode.data('Id');
        $winesManageListContainer.find('.selected').removeClass('selected');  // 移除之前选中的样式
        if (winesId) {
          $liNode.addClass('selected');  // 添加选中的样式
          mpos.showDialog(mpos.dialogPage.saveWinesDetail, {
            winesId: winesId,
            winesPlaceData: winesPlaceData
          }, function (status) {
            if (status && status.data) {
              mpos.load(mpos.page.saveWines, {winesData: status.data});
            }
          });
        } else {
          mpos.alert('缺少数据唯一标识ID，请刷新重试')
        }
      })
      fragment.append($node);
    })
    $winesManageListContainer.append(fragment);

    $winesManageListContainer.find('li').on('click', function() {
      var currentNode = $(this);
      if (currentNode.hasClass('selected')) {
        currentNode.removeClass('selected');
      } else {
        $winesManageListContainer.find('.selected').removeClass('selected');
        currentNode.addClass('selected');
      }
    })
  }

  /**
   * 存酒事件
   * */
  $page.find('.save-btn').on('click', function() {
    // 获取是否有选中存酒单，有选中就修改，否则就存酒操作
    var selectedNode = $winesManageListContainer.find('.selected');
    if (selectedNode) {

    }
    mpos.load(mpos.page.saveWines);
  });

  /**
   * 取酒事件
   * */
  $page.find('.get-btn').on('click', function() {
    var selectedNode = $winesManageListContainer.find('.selected');
    if (selectedNode && selectedNode.length > 0) {
      var winesId = $(selectedNode[0]).data('Id');
      mpos.load(mpos.page.fetchWines, {winesId: winesId, winesPlaceData: winesPlaceData});
    } else {
      mpos.alert('请选择存酒记录')
    }
  });

});

/**
 * author: wang.p   2021-07-29
 * description: 沽清
 * */

mpos.controller(mpos.page.sellOut, function (page, pageData) {
  var $page = $(page);

  var SELECT_TYPE_CLASS = "selected";

  //点菜对象
  var orderDishData =  mpos.OrderDishData.createNew();

  var currentSelectedDishType = 0; //当前选中的菜品分类

  var dishTypeContainer = $page.find(".dish-type-list");
  var dishContainer = $page.find(".app-content>ul.dish-list");

  var $dishTypeItem = dishTypeContainer.find("li").remove();
  var $dishItem = dishContainer.find("li").remove();

  //缓存滚动位置
  var contentScrollOffset = 0;
  dishContainer.on("scroll", function (e) {
    contentScrollOffset = e.currentTarget.scrollTop;
  });
  //还原滚动条的位置
  $page.on("appLayout", function () {
    if (contentScrollOffset > 0)
      dishContainer[0].scrollTop = contentScrollOffset;
  });

  /**
   * 返回上个界面
   */
  function backToPrev() {
    var mposType = mpos.localStorage.OrderPropertyType || OrderPropertyType.Normal;
    if (mposType == OrderPropertyType.Normal) {
      mpos.load(mpos.page.home); //返回首页
      mpos.removeFromStack();
    } else {
      mpos.load(mpos.page.orderDishes); //返回点餐页面
      mpos.removeFromStack();
    }
  }

  //返回
  this.onBackKeyDown = backToPrev;
  $page.find("#goBack").on("click", backToPrev);

  $page.on("appShow", function () {
    //是否显示登录
    if (mpos.currentUser == null) {
      mpos.showDialog(mpos.dialogPage.login, function (status) {
        if (status) {
          //加载点菜数据
          loadOrderDishDatas();
        }
      });
    } else {
      //加载点菜数据
      loadOrderDishDatas();
    }
  });

  /**
   加载本次点菜需要的数据
   */
  function loadOrderDishDatas(callback) {
    mpos.get(mpos.api.getDishListForSaleOut, {}, function (data) {
      if (!data) {
        return;
      }
      // 封装数据
      var dishTypes = [];
      for (var m = 0; m < mpos.BaseData.DishTypes.length; m++) {
        for (var i = 0; i < data.DishInfo.Dishes.length; i++) {
          var baseDish = mpos.BaseData.Dishes[data.DishInfo.Dishes[i].DishId];
          if (baseDish != undefined) {
            if (baseDish.Dish.DishTypeId == mpos.BaseData.DishTypes[m].DishTypeId) {
              dishTypes.push(mpos.BaseData.DishTypes[m]);
              break;
            }
          }
        }
      }
      orderDishData.dishTypes = dishTypes;
      orderDishData.dishes = concatAndSortDishes(data.DishInfo.Dishes);
      orderDishData.saleOutDishes = data.DishInfo.SaleOutInfo.SaleOutDishes;   // 沽清的菜品
      orderDishData.saleOutUnits = data.DishInfo.SaleOutInfo.SaleOutPortionsDishes || [];  // 沽清的单位

      prepareLoadOrderDishDatas();
    });
  }

  /**
   * 组织成点菜的数据
   * 根据菜品分类排序菜品
   * @param dishList 原始菜品列表
   */
  function concatAndSortDishes(dishList) {
    if (!dishList || dishList.length == 0)
      return [];

    var result = [];
    var dishTypeMap = {};
    orderDishData.dishTypes.forEach(function (item) {
      dishTypeMap[item.DishTypeId] = [];
    });

    dishList.forEach(function (item) {
      var dish = {};
      var baseDish = mpos.BaseData.Dishes[item.DishId];
      if (baseDish != undefined) {
        dish.Units = [];
        dish.Dish = {
          DishId: baseDish.Dish.DishId,
          DishName: baseDish.Dish.DishName,
          IsTemporary: baseDish.Dish.IsTemporary,
          IsRandomPrice: baseDish.Dish.IsRandomPrice,
          DishProperty: baseDish.Dish.DishProperty,
          DishSerial: baseDish.Dish.DishSerial,
          DishTypeId: baseDish.Dish.DishTypeId,
          DishSpell: baseDish.Dish.DishSpell,
          IsConfirmWeight: baseDish.Dish.IsConfirmWeight == 1,
          PackageCategory: baseDish.Dish.PackageCategory,
          IsRateDiscount: baseDish.Dish.IsRateDiscount,
          IsModifyNum: baseDish.Dish.IsModifyNum,
          IsMultiDish: baseDish.Dish.IsMultiDish, //  一品多吃菜类型，  1-一品多吃主菜
          IsMultiMainDish: baseDish.Dish.IsMultiMainDish, //  一品多吃主菜，  1-是主菜
        };
        dish.DishCookings = baseDish.DishCookings;
        item.Units.forEach(function (item) {
          for (var i = 0; i < baseDish.Units.length; i++) {
            if (baseDish.Units[i].PortionsId == item.PortionsId) {
              item.PortionsName = baseDish.Units[i].PortionsName;
              item.IsDefault = baseDish.Units[i].IsDefault;
              item.EstimatedCost = baseDish.Units[i].EstimatedCost;
              dish.Units.push(item);
            }
          }
        });

        dishTypeMap[dish.Dish.DishTypeId].push(dish);
      }
    });

    orderDishData.dishTypes.forEach(function (item) {
      result = result.concat(dishTypeMap[item.DishTypeId]);
    });

    return result;
  }

  /**
   准备加载数据
   */
  function prepareLoadOrderDishDatas() {
    loadDishTypes(); //加载菜品和类型
    loadDishes();

    setScrollData();
  }

  /**
   * 设置滚动所需要的数据及处理菜品列表滚动、菜品分类点击等事件
   */
  function setScrollData() {
    dishTypeContainer.find("li:first-of-type").addClass(SELECT_TYPE_CLASS);

    if (orderDishData.dishes.length > Config.maxDishLength) {
      //类型点击事件
      dishTypeContainer.find("li").on("click", function (e) {
        var currentTarget = $(e.currentTarget);
        if (currentTarget.hasClass(SELECT_TYPE_CLASS))
          return;

        var typeId = currentTarget.data("type_id");
        loadDishes(typeId);
        dishTypeContainer.find("li." + SELECT_TYPE_CLASS).removeClass(SELECT_TYPE_CLASS);
        currentTarget.addClass(SELECT_TYPE_CLASS);
      });
      return;
    }

    var scrollData = [];

    //因为放入了分类信息，所以直接去分类所在位置即可
    dishContainer.find("li.dish-type").each(function () {
      scrollData.push(this.offsetTop);
    });

    if (scrollData.length <= 1)
      return;
    scrollData.push(Number.MAX_VALUE);

    /**
     * 滚动时判断滚动位置，切换菜品分类的显示
     * @param e Event
     */
    function scrollEvent(e) {
      //var scrollTop = e.currentTarget.scrollTop;
      for (var i = 0; i < scrollData.length - 1; i++) {
        if (i != currentSelectedDishType && contentScrollOffset >= scrollData[i] && contentScrollOffset < scrollData[i + 1]) {
          currentSelectedDishType = i;
          dishTypeContainer.find("li." + SELECT_TYPE_CLASS).removeClass(SELECT_TYPE_CLASS);
          dishTypeContainer.find("li").eq(currentSelectedDishType).addClass(SELECT_TYPE_CLASS);
          break;
        }
      }
    }

    dishContainer.on("scroll", scrollEvent);

    //类型点击事件
    dishTypeContainer.find("li").on("click", function (e) {
      var currentTarget = $(e.currentTarget);
      if (currentTarget.hasClass(SELECT_TYPE_CLASS))
        return;

      dishContainer.off("scroll", scrollEvent);

      //找到分类的位置并滚动过去
      //目前没有使用动画
      var typeId = currentTarget.data("type_id");
      for (var i = 0; i < orderDishData.dishTypes.length; i++) {
        if (orderDishData.dishTypes[i].DishTypeId == typeId) {
          currentSelectedDishType = i;
          dishContainer[0].scrollTop = scrollData[currentSelectedDishType];
          break;
        }
      }

      dishTypeContainer.find("li." + SELECT_TYPE_CLASS).removeClass(SELECT_TYPE_CLASS);
      currentTarget.addClass(SELECT_TYPE_CLASS);

      //即时附上事件，将会触发，导致最后的分类如果不满一页，无法第一次选中
      setTimeout(function () {
        dishContainer.on("scroll", scrollEvent);
      }, 100);
    });

  }

  /**
   * 组织成点菜的数据
   * 根据菜品分类排序菜品
   * @param dishList 原始菜品列表
   */
  function concatAndSortDishes(dishList) {
    if (dishList.constructor != Array || dishList.length == 0)
      return [];

    var result = [];

    var dishTypeMap = {};
    orderDishData.dishTypes.forEach(function (item) {
      dishTypeMap[item.DishTypeId] = [];
    });

    dishList.forEach(function (item) {
      var dish = {};
      var baseDish = mpos.BaseData.Dishes[item.DishId];
      if (baseDish != undefined) {
        dish.Units = [];
        dish.Dish = {
          DishId: baseDish.Dish.DishId,
          DishName: baseDish.Dish.DishName,
          IsTemporary: baseDish.Dish.IsTemporary,
          IsRandomPrice: baseDish.Dish.IsRandomPrice,
          DishProperty: baseDish.Dish.DishProperty,
          DishSerial: baseDish.Dish.DishSerial,
          DishTypeId: baseDish.Dish.DishTypeId,
          DishSpell: baseDish.Dish.DishSpell,
          IsConfirmWeight: baseDish.Dish.IsConfirmWeight == 1,
          PackageCategory: baseDish.Dish.PackageCategory,
          IsRateDiscount: baseDish.Dish.IsRateDiscount,
          IsModifyNum: baseDish.Dish.IsModifyNum,
          IsMultiDish: baseDish.Dish.IsMultiDish, //  一品多吃菜类型，  1-一品多吃主菜
          IsMultiMainDish: baseDish.Dish.IsMultiMainDish, //  一品多吃主菜，  1-是主菜
        };
        dish.DishCookings = baseDish.DishCookings;
        item.Units.forEach(function (item) {
          for (var i = 0; i < baseDish.Units.length; i++) {
            if (baseDish.Units[i].PortionsId == item.PortionsId) {
              item.PortionsName = baseDish.Units[i].PortionsName;
              item.IsDefault = baseDish.Units[i].IsDefault;
              item.EstimatedCost = baseDish.Units[i].EstimatedCost;
              dish.Units.push(item);
            }
          }
        });

        dishTypeMap[dish.Dish.DishTypeId].push(dish);
      }
    });

    orderDishData.dishTypes.forEach(function (item) {
      result = result.concat(dishTypeMap[item.DishTypeId]);
    });

    return result;
  }

  /**
   * 刷新沽清数据
   */
  function refreshDishSaleoutShowUI(dishId, itemDom) {
    /***********沽清处理************/
    var saleOutNum = orderDishData.getCanSaleDishNum(dishId);
    var $saleout = itemDom.find(".sale-out");
    var $sellOutBtn = itemDom.find('.sell-out-btn');
    if (saleOutNum == 0) { //已卖完
      $saleout.text("沽");
      $saleout.removeClass('nd');
      $sellOutBtn.text('取消沽清');
      $sellOutBtn.attr('value', 2);
      $sellOutBtn.addClass('cancel-sell-out');
    } else {
      $sellOutBtn.text('沽清');
      $sellOutBtn.attr('value', 1);
    }
  }

  /**
   加载菜品和菜品类型
   */
  function loadDishTypes() {
    dishTypeContainer.empty();

    var fragment = $(document.createDocumentFragment());
    //菜品类型
    $.each(orderDishData.dishTypes, function (idx, item) {
      var clone = $dishTypeItem.clone();
      clone.removeClass(SELECT_TYPE_CLASS);
      clone.find(".dish-type-name").text(item.DishTypeName);
      clone.data("type_id", item.DishTypeId);
      clone.find(".dish-count").hide();
      fragment.append(clone);
    });
    dishTypeContainer.append(fragment);
  }

  /**
   * 加载菜品
   * @param dishTypeId dish type id
   */
  function loadDishes(dishTypeId) {

    dishContainer.empty();
    if (orderDishData.dishTypes.length == 0)
      return;

    //写入菜品，需要判断是否菜品数量>200
    var dishList = [];

    var typeId;
    if (orderDishData.dishes.length > Config.maxDishLength || dishTypeId != undefined) {
      typeId = dishTypeId || orderDishData.dishTypes[0].DishTypeId;
      dishList = orderDishData.dishes.filter(function (item) {
        return typeId == item.Dish.DishTypeId;
      });
    } else {
      dishList = orderDishData.dishes;
    }

    var fragment = fragmentWithDishList(dishList);

    //处理菜品分类，插入到菜品列表中，滑动切换分类需要这个
    if (orderDishData.dishes.length <= Config.maxDishLength && dishTypeId == undefined) {
      typeId = 0;
      dishList.forEach(function (item) {
        if (item.Dish.DishTypeId != typeId) {
          typeId = item.Dish.DishTypeId;
          var dishType = orderDishData.dishTypes.find(function (t) {
            return t.DishTypeId == typeId;
          });
          if (dishType) {
            fragment.find("li[data-dish_id='" + item.Dish.DishId + "']")
              .before($("<li class='dish-type' />")
                .text(dishType.DishTypeName)
                .data("typeId", dishType.DishTypeId));
          }
        }
      });
    }
    dishContainer.append(fragment);

    dishContainer[0].scrollTop = 0;

  }

  /**
   * 根据菜品列表，生成document fragment
   * @param dishList
   */
  function fragmentWithDishList(dishList) {
    var fragment = $(document.createDocumentFragment());
    dishList.forEach(function (item) {
      if (item.Units.length == 0) {
        return;
      }
      var dishItem = $dishItem.clone();
      dishItem.data("dish_id", item.Dish.DishId);
      var dishName = item.Dish.DishName;
      if (item.Units[0].PriceType == OrderDishPriceType.Special) {
        dishName = "(特)" + dishName;
      }
      if (item.Dish.IsTemporary == 1) {
        dishName = "(临)" + dishName;
      }
      dishItem.find(".name").text(dishName);
      dishItem.find(".price").text(mpos.formatPrice(orderDishData.getDishPrice(item)));

      dishItem.find(".dish-operation").on("click", function (e) {
        if (e.target.tagName != "SPAN") {
          return;
        }
        var target = $(e.target);
        var parentObj = target.parents("li");
        var dishId = target.parents("li").data("dish_id");
        var isSellOut = target.attr("value");  // （1-沽清 2-取消沽清）
        requestSellOut(dishId, isSellOut, function(isSellOut, sellOutDishId) {
          var $saleout = parentObj.find(".sale-out");
          if (isSellOut == 1) {
            // 添加沽清成功后，将菜品加入估计里面
            var sellOutDish = orderDishData.saleOutDishes.find(function(sellDish) {return sellDish.DishId == sellOutDishId;} )
            if (!sellOutDish) {
              orderDishData.saleOutDishes.push({
                DishId: sellOutDishId,
                IsPortions: 0, // 多份量沽清
                IsWeight: 0,   // 称重菜算一份
                Num: 0,   // 每份扣减的比例
                SaleOutType: 1  // 绝对沽清了
              })
            }

            target.addClass('cancel-sell-out');
            target.attr('value', 2);
            target.text('取消沽清');
            $saleout.text("沽");
            $saleout.removeClass('nd');
          } else if (isSellOut == 2) {
            // 取消沽清后，将菜品冲沽清列表中去除
            var sellOutIndex = orderDishData.saleOutDishes.findIndex(function(sellDish) {return sellDish.DishId == sellOutDishId;} )
            if (sellOutIndex != -1) {
              orderDishData.saleOutDishes.splice(sellOutIndex, 1);
            }

            target.removeClass('cancel-sell-out');
            target.attr('value', 1);
            target.text('沽清');
            $saleout.addClass('nd');
          }

        });
      });
      // 设置沽清显示
      refreshDishSaleoutShowUI(item.Dish.DishId, dishItem);
      fragment.append(dishItem);
    });
    return fragment;
  }

  /**
   * 沽清操作
   * @dishId  菜品ID
   * @isSellOut   1=沽清，0=取消沽清
   * */
  function requestSellOut (dishId, isSellOut, callback) {
    if (isSellOut == 1 || isSellOut == 2) {
      mpos.post(mpos.api.dishSaleOut, {DishId: dishId, Type: isSellOut}, function (data) {
        if (data === 'ok') {
          callback && callback(isSellOut, dishId);
        }
      });
    }
  }


});

/**
 *设置
 */
mpos.controller(mpos.page.settingPage, function (page) {
    var animationInput = $(page).find("input[name='enablePageAnimation']"); //开启动画
    var submitTipInput = $(page).find("input[name='enableSubmitOrderTips']"); //开启下单确认提示
    var costInput = $(page).find("input[name='enableEstimatedCost']"); //开启毛利率显示
    var toSettlePay = $(page).find("input[name='enableToSettlePay']"); //酒楼模式点餐直接跳转结账界面
    var sysKeyboard = $(page).find("input[name='enableSystemKeyboard']"); //启用系统默认键盘
    var payToOrder = $(page).find("input[name='enablePayToOrder']"); //付款后下单
    var bigDishTypes = $(page).find("input[name='enableBigDishTypes']"); //酒楼模式下菜品大类显示
    var openBookTable = $(page).find("input[name='enableOpenBookTable']"); //酒楼模式下快速预订
    var usedDefaultUnit = $(page).find("input[name='enableUsedDefaultUnit']"); //点菜列表使用默认单位
    var diningTableAmount = $(page).find("input[name='enableDiningTableAmount']"); //开启餐台金额显示  界面显示时开启，但代码中是记录是否关闭，相反的操作

    var mutilOrderDish = $(page).find("input[name='enableMutilOrderDish']"); //允许同时对同一桌台点单
    var keepOrderDish = $(page).find("input[name='enableKeepOrderDish']"); // 点餐完停留在点餐页面
    var floorMenu = $(page).find("input[name='enableFloorMenu']"); // 显示餐台区域列表
    

    //设置开启动画状态
    if (!mpos.localStorage.isDisableAnimation) {
        animationInput.prop("checked", true);
    }
    animationInput.on("click", function () {
        var disabled = !animationInput.prop("checked");
        mpos.localStorage.isDisableAnimation = disabled;
        mpos.disablePageAnimation(disabled);
    });

    //设置下单确认提示
    if (mpos.localStorage.enableSubmitOrderTips) {
        submitTipInput.prop("checked", true);
    }
    submitTipInput.on("click", function () {
        var disabled = submitTipInput.prop("checked");
        mpos.localStorage.enableSubmitOrderTips = disabled;
    });

    //设置毛利率显示
    if (mpos.localStorage.enableEstimatedCost) {
        costInput.prop("checked", true);
    }
    costInput.on("click", function () {
        var disabled = costInput.prop("checked");
        mpos.localStorage.enableEstimatedCost = disabled;
    });
    //设置餐台金额显示
    if (mpos.localStorage.enableDiningTableAmount !== false) {
        diningTableAmount.prop("checked", true);
    }
    diningTableAmount.on("click", function () {
        var disabled = diningTableAmount.prop("checked");
        mpos.localStorage.enableDiningTableAmount = disabled;
    });

    //酒楼模式点餐直接跳转结账界面
    if (mpos.localStorage.enableToSettlePay) {
        toSettlePay.prop("checked", true);
    }
    toSettlePay.on("click", function () {
        var disabled = toSettlePay.prop("checked");
        mpos.localStorage.enableToSettlePay = disabled;
    });

    //酒楼模式点菜界面显示菜品大类
    if (mpos.localStorage.enableBigDishTypes) {
        bigDishTypes.prop("checked", true);
    }
    bigDishTypes.on("click", function () {
        var disabled = bigDishTypes.prop("checked");
        mpos.localStorage.enableBigDishTypes = disabled;
    });

    // 酒店模式下快速预订
    if (mpos.localStorage.enableOpenBookTable) {
        openBookTable.prop("checked", true);
    }
    openBookTable.on("click", function () {
        var disabled = openBookTable.prop("checked");
        mpos.localStorage.enableOpenBookTable = disabled;
    });

    // 点菜类别使用默认单位
    if (mpos.localStorage.enableUsedDefaultUnit) {
        usedDefaultUnit.prop("checked", true);
    }
    usedDefaultUnit.on("click", function () {
        var disabled = usedDefaultUnit.prop("checked");
        mpos.localStorage.enableUsedDefaultUnit = disabled;
    });

    //允许同时对同一桌台点单
    if (mpos.localStorage.enableMutilOrderDish) {
        mutilOrderDish.prop("checked", true);
    }
    mutilOrderDish.on("click", function () {
        var disabled = mutilOrderDish.prop("checked");
        mpos.localStorage.enableMutilOrderDish = disabled;
    });

    //点餐完停留在点餐页面
    if (mpos.localStorage.enableKeepOrderDish) {
        keepOrderDish.prop("checked", true);
    }
    keepOrderDish.on("click", function () {
        var disabled = keepOrderDish.prop("checked");
        mpos.localStorage.enableKeepOrderDish = disabled;
    });

    //显示餐台区域列表
    if (mpos.localStorage.enableFloorMenu) {
        floorMenu.prop("checked", true);
    }
    floorMenu.on("click", function () {
        var disabled = floorMenu.prop("checked");
        mpos.localStorage.enableFloorMenu = disabled;
    });

    //启用系统默认键盘
    if (mpos.localStorage.enableSystemKeyboard) {
        sysKeyboard.prop("checked", true);
    }
    sysKeyboard.on("click", function () {
        var disabled = sysKeyboard.prop("checked");
        mpos.localStorage.enableSystemKeyboard = disabled;
    });

    if (mpos.localStorage.PayToOrder) {
        payToOrder.prop("checked", true);
    }
    payToOrder.on("click", function () {
        var disabled = payToOrder.prop("checked");
        mpos.localStorage.PayToOrder = disabled;
    });

    $(page).find('li.logout').on("click",
        function () {
            mpos.logout();
        });

});

/*
 * 结账界面
 * */
mpos.controller(mpos.page.settle, function (page, obj) {
    var fmt = "yy-MM-dd HH:mm:ss",
        timeFmt = "HH:mm:ss";
    var settleData = obj.settle;
    var isSnackSettle = (settleData.SettleMode == SettleMode.SnackDining);
    var clearCheckPayTimeout = null;
    var fromPage = obj.from;
    var firstOrderStatus = settleData.EnterOrder.Order.OrderStatus;
    var refreshCount = 0;
    //预结或撤销预结的Dom
    var $pageDom = $(page);
    var $span = $("<span class='textEllipsis'></span>");
    var $tableName = $pageDom.find(".table-name").remove();
    var $billInfo = $pageDom.find(".bill-info").remove();
    var $tableInfo = $pageDom.find(".table-info").remove();
    var $dishItem = $pageDom.find(".dish-item").remove();
    var $dishList = $pageDom.find(".table-dish-list").remove();
    var $consumptionAmount = $pageDom.find(".consumption-amount").remove();
    var $paymentList = $pageDom.find('.payment-list').remove();
    var $paymentTypeList = $pageDom.find(".payment-type-list").remove();

    var $chkInvoice = $pageDom.find("input[name='chkInvoice']");
    var $invoiceAmount = $pageDom.find("div:has(>input[name='invoiceAmount'])");
    var isPaytoOrderModel = false;
    if (fromPage == "pay_to_order") {
        isPaytoOrderModel = true;
    }

    //发票金额处理
    if (settleData.Consumption.InvoiceMoney > 0) {
        $chkInvoice.prop("checked", true);
        $invoiceAmount.find("input").val(settleData.Consumption.InvoiceMoney);
        $invoiceAmount.show();
    } else {
        $chkInvoice.prop("checked", false);
        $invoiceAmount.hide();
    }

    /**
     * 金额focus事件
     */
    $invoiceAmount.find("input").on("focus", function () {
        this.select();
        var appContent = $pageDom.find(".app-content")[0];
        appContent.scrollTop = appContent.offsetHeight;
    });
    /**
     * 键盘弹出后，处理界面滚动到开发票，如果开发票金额活的了焦点
     */
    $pageDom.on("appLayout", function () {
        var input = $invoiceAmount.find("input")[0];
        if (input == document.activeElement) {
            setTimeout(function () {
                var appContent = $pageDom.find(".app-content")[0];
                appContent.scrollTop = 10000;
            }, 300);
        }
    });

    mpos.stopSearchMagCard();

    mpos.checkInputValue($invoiceAmount.find("input"), InputType.Amount);

    //发票金额选中事件
    $chkInvoice.on("click", function () {
        if ($chkInvoice.prop("checked")) {
            $invoiceAmount.show();
            $invoiceAmount.find("input")[0].focus()
        } else {
            $invoiceAmount.hide();
        }
    });

    //清理后台请求， 如消息循环获取
    $pageDom.on("appDestroy", function () {
        if (clearCheckPayTimeout)
            clearTimeout(clearCheckPayTimeout);

        mpos.stopSearchMagCard();
    });

    //返回事件
    function backToPrev() {
        if (clearCheckPayTimeout)
            clearTimeout(clearCheckPayTimeout);
        if (settleData.EnterOrder.Order.OrderStatus != DiningOrderStatus.Take) { //需要刷新
            if (firstOrderStatus != settleData.EnterOrder.Order.OrderStatus) {
                mpos.isNeedReloadTable = true;
            }
            mpos.back(mpos.page.home); //返回到首页
        } else {
            if (fromPage == "snack_order_dish") { //快餐返回
                if (refreshCount == 1) {
                    mpos.back();
                } else {
                    mpos.load(mpos.page.orderDishes, {
                        OrderIds: [settleData.EnterOrder.Order.OrderId],
                        IsSnack: true
                    });
                    mpos.removeFromStack();
                }
                return;
            }
            if (fromPage == "home") {
                if (firstOrderStatus != settleData.EnterOrder.Order.OrderStatus) {
                    mpos.isNeedReloadTable = true;
                }
                mpos.back(mpos.page.home); //返回到首页
            } else if (fromPage == "pay_to_order") {
                if (refreshCount == 1) {
                    mpos.back();
                } else {
                    mpos.load(mpos.page.orderDishes, {
                        OrderIds: [settleData.EnterOrder.Order.OrderId],
                        IsSnack: false
                    });
                }
            } else { //订单操作
                mpos.load(mpos.page.tableTaken, {
                    settle: settleData
                });
            }
        }
    }

    this.onBackKeyDown = backToPrev;
    $pageDom.find("#goBack").on("click", backToPrev);

    //结账
    $pageDom.find("#sub-settle").on("click", function (e) {
        var billId = mpos.localStorage.PreBilledOrderId;
        var printNum = mpos.preBilledOrderNumber();
        if (isPaytoOrderModel) { //酒吧模式确认收款
            //开始结账
            if (settleData.TotalObligationAmount > 0) {
                mpos.alert("未完成支付，不能确认收款");
                return;
            }
            mpos.post(mpos.api.saveConsumptionPaySettle, {
                OrderId: settleData.EnterOrder.Order.OrderId, //订单ID
                CashBillId: billId, //收银单ID
            }, function (result) {
                if (billId > 0) {
                    //打印
                    var consumptionBill = result.ConstumptionBills;
                    if (Array.isArray(consumptionBill) && consumptionBill.length > 0) {
                        for (var i = 0; i < printNum; i++) { //打印多份
                            var printData = mpos.addPrintEmptyLine(consumptionBill);
                            mpos.deviceFactory.printTicket(printData, null, function (err) {
                                mpos.alert(err);
                            });
                        }
                    } else {
                        mpos.alert("返回数据格式不对!");
                    }
                }
                //加载餐台页面
                if (result.msg.length > 0) {
                    mpos.alert(result.msg);
                }
                mpos.back(mpos.page.home);
                mpos.removeFromStack();
            });

            return;
        }

        //开始结账
        if (settleData.TotalObligationAmount > 0) {
            mpos.alert("消费未完成支付，不能结账");
            return;
        }

        var invoiceAmount;
        if ($chkInvoice.prop("checked")) {
            var canInvoiceAmount = settleData.CanInvoiceMoney;
            var maxInvoiceAmount = settleData.MaxMoney;
            invoiceAmount = $invoiceAmount.find("input").val();
            if (invoiceAmount == "") {
                mpos.alert("请输入发票金额");
                return;
            }
            invoiceAmount = parseFloat(invoiceAmount);
            if (invoiceAmount < 0) {
                mpos.alert("发票金额不能小于0");
                return;
            }
            if (invoiceAmount > 0) {
                if (invoiceAmount - canInvoiceAmount > maxInvoiceAmount) {
                    mpos.alert("“开发票金额”减“可开发票金额”不能大于 " + maxInvoiceAmount);
                    return;
                }
            }
        } else {
            invoiceAmount = 0;
        }
        billId = mpos.localStorage.CashOrderId;
        printNum = mpos.cashOrderNumber();
        mpos.post(mpos.api.submitSettle, {
            OrderId: settleData.EnterOrder.Order.OrderId, //订单ID
            CashBillId: billId, //收银单ID
            InvoiceAmount: invoiceAmount,
            SettleMode: settleData.SettleMode,
        }, function (r) {
            //打印
            if (billId > 0) {
                var consumptionBill = r.ConstumptionBills;
                if (Array.isArray(consumptionBill) && consumptionBill.length > 0) {
                    for (var i = 0; i < printNum; i++) { //打印多份
                        var printData = mpos.addPrintEmptyLine(consumptionBill);
                        mpos.deviceFactory.printTicket(printData, null, function (err) {
                            mpos.alert(err);
                        });
                    }
                } else {
                    mpos.alert("返回数据格式不对!");
                }
            }

            if (isSnackSettle) {
                var printSigleBill = mpos.printSigleBill();
                var printTotalBill = mpos.printTotalBill();
                if (printTotalBill == 1 && r.TotalBills) { //总单
                    if (r.TotalBills != null && Array.isArray(r.TotalBills) && r.TotalBills.length > 0) {
                        $.each(r.TotalBills, function (index, item) {
                            var printData = mpos.addPrintEmptyLine(item);
                            mpos.deviceFactory.printTicket(printData, null, function (err) {
                                //打印
                                mpos.alert(err);
                            });
                        })
                    }
                }

                if (printSigleBill == 1 && r.SigleBills) { //分单
                    if (r.SigleBills != null && Array.isArray(r.SigleBills) && r.SigleBills.length > 0) {
                        $.each(r.SigleBills, function (index, item) {
                            var printData = mpos.addPrintEmptyLine(item);
                            mpos.deviceFactory.printTicket(printData, null, function (err) {
                                //打印
                                mpos.alert(err);
                            });
                        })
                    }
                }
            }

            mpos.isNeedReloadTable = true;
            if (fromPage == "snack_order_dish") { //快餐返回
                mpos.load(mpos.page.orderDishes);
                mpos.removeFromStack();
            } else {
                //加载餐台页面
                mpos.back(mpos.page.home);
                mpos.removeFromStack();
            }
        }, {
            timeout: 60000
        });
    });

    //优惠，折扣减免
    $pageDom.find("#otherOperation").on("click", function () {
        if (settleData) {
            //预结不能操作
            if (settleData.EnterOrder.Order.OrderStatus == 2) {
                mpos.alert("已预结，不能操作");
                return;
            }
            mpos.pick(mpos.page.settleOperationMore, {
                settle: settleData
            }, function (data) {
                //返回刷新
                if (data && data.refresh) {
                    GetSettleData(refreshSettleData);
                }
            });
        }
    });

    if (isPaytoOrderModel) {
        $pageDom.find("div.invoice").hide();
        $pageDom.find("#otherOperation").hide();
        $pageDom.find("#sub-settle").css("float", "none");
        $pageDom.find("#sub-settle").text("确认收款");
    }

    //刷新UI
    function refresh() {
        refreshCount++;
        //增加整单ID
        $pageDom.data("whole_order_id", settleData.EnterOrder.Order.WholeBillId);
        var fragment = $(document.createDocumentFragment());
        var invoice = $pageDom.find(".app-content .invoice").remove();
        var expandDishDetail = $pageDom.find(".bill-info").hasClass("expand");
        var tableName = $tableName.clone();
        var billInfo = $billInfo.clone();
        var tableInfo = $tableInfo.clone();
        var dishList = $dishList.clone();

        //会员的显示
        $("<span class='app-button' id='member_input'/>").text(settleData.MemberCard != null ? ("会员：" + settleData.MemberCard.MemberName) : "会员")
            .appendTo(tableName).on("click", function () {
                if (!settleData)
                    return;

                //预结不能操作
                if (settleData.EnterOrder.Order.OrderStatus == 2) {
                    mpos.alert("已预结，不能操作");
                    return;
                }
                mpos.pick(mpos.page.memberInput, {
                    MemberCard: settleData.MemberCard,
                    Settle: settleData,
                    ConsumptionId: settleData.Consumption.ConsumptionId
                }, function (data) {
                    //监听磁卡
                    mpos.stopSearchMagCard();
                    //当会员卡有变动时刷新界面
                    if (data != undefined) {
                        if ((data.MemberCard == null && settleData.MemberCard != null) || (data.MemberCard != null && settleData.MemberCard == null) || (data.MemberCard != null && settleData.MemberCard != null && data.MemberCard.MemberCardId != settleData.MemberCard.MemberCardId)) {
                            GetSettleData(refreshSettleData);
                        }
                    }
                });
            });

        /*****显示菜品和其它餐台信息****/
        //输出开台信息
        if (!isSnackSettle) {
            //餐台名称
            //显示餐台名称
            tableName.find('.name').text(settleData.EnterOrder.Table.TableName + (settleData.EnterOrder.Order.IsMain == 1 ? "(主)" : ""))

            //二维码显示
            if (settleData.EnterOrder.Order.OrderStatus == 2) {
                $('<div class="prepay-bill-qr"></div>').on("click", function () {
                    mpos.showDialog(mpos.dialogPage.prepayBillQr, {
                        "settle": settleData
                    }, function () {

                    });
                }).appendTo(tableName);
            }

            //快餐时不输出餐台内容
            var openTableInfo = findOpenTableInfo(settleData.EnterOrder.Order.OrderId);
            tableInfo.find(".table-time").text("开台时间：" + (new Date(settleData.EnterOrder.Order.BeginTime)).formatDate(fmt));
            tableInfo.find(".table-people").text("人数：" + settleData.EnterOrder.Table.PeopleNum);
            tableInfo.find(".table-user").text("开台人：" + (openTableInfo == null ? "" : openTableInfo.OpenTableUser));
            tableInfo.find(".table-businesstimespan").text("市别：" + (openTableInfo == null ? "" : openTableInfo.BusinessTimeSpanName));
        } else { //快餐结账时处理
            tableName.find('.name').remove(); //移动餐台名称的显示
            $pageDom.addClass("snack-settle");
        }

        //输入当前餐台的菜品
        $.each(settleData.EnterOrder.Dishes, function (idx, item) {
            var dishItem = $dishItem.clone();
            dishItem.find('label.dish-selected').data("dishId", item.OrderDishId);
            dishItem.find(".dish-name").html(mpos.getDishTag(item) + item.DishName);
            dishItem.find(".dish-num").text("x" + item.DishNum);
            if (item.ReturnOrderDishId != 0) {
                dishItem.find(".dish-name").addClass('disabled');
            }
            if (item.DishProperty == OrderDishProperty.PackageDishChild) {
                // 套餐子菜
                dishItem.find(".dish-name").addClass('disabled');
                dishItem.find(".dish-amount").text("-");
            } else if (item.DishProperty == OrderDishProperty.MultiDishChild) {
                // 一品多吃子菜
                dishItem.find(".dish-name").addClass('disabled');
                dishItem.find(".dish-amount").text("-");
            } else {
                dishItem.find(".dish-amount").text(mpos.formatPrice(item.DishSaleAmount));
            }
            var cookies = "";
            var dishUnit = item.DishPortions || item.DishUnit;
            if (item.Discount < 100) {
                dishUnit += "/" + parseFloat((item.Discount / 10).toFixed(2)) + "折";
            }
            $.each(item.DishRequestList, function (idx, re) {
                cookies += re.RequestName + (Math.abs(re.RequestNum) == 1 ? "" : ("*" + re.RequestNum)) + "、"; //做法
            });

            if (cookies.length > 0) {
                dishItem.find(".dish-cookies").text(dishUnit + "/" + cookies.substr(0, cookies.length - 1));
            } else {
                dishItem.find(".dish-cookies").text(dishUnit);
            }
            dishItem.find(".order-date").text(item.OrderDate === '0001-01-01 00:00:00' ? '' : item.OrderDate);
            dishList.append(dishItem);
        });
        fragment.append(tableName);
        fragment.append(billInfo);
        fragment.append(tableInfo);
        fragment.append(dishList);

        if (isSnackSettle) { //快餐结账时
            fragment.find("#settlePrepayBill").remove();
            fragment.find("#printSettle").remove();
            //餐牌
            var brandName = settleData.EnterOrder.Order.TableCardNo;
            if (brandName == "") {
                brandName = "餐牌";
            }
            fragment.find("#snackTableName").text(brandName);
            if (settleData.EnterOrder.Order.SnackType == 2) { //外带时
                fragment.find("#snackIsTakeOut").removeClass("snack-takeout");
            }
            if (isPaytoOrderModel) {
                fragment.find("#snackTableName").remove();
                fragment.find("#snackIsTakeOut").remove();
            }
        } else {
            //移除快餐的按钮
            fragment.find("#snackTableName").remove();
            fragment.find("#snackIsTakeOut").remove();
            //预结的显示
            var settlePrepayBill = fragment.find("#settlePrepayBill");
            if (settleData.EnterOrder.Order.OrderStatus == 2) {
                settlePrepayBill.text("撤销预结");
            } else {
                settlePrepayBill.text("预结");
            }
        }

        //输出其它餐台及菜品
        //快餐没有以下的展示效果，可以不用判断
        $.each(settleData.Orders, function (idx, order) {
            if (order.Order.OrderId == settleData.EnterOrder.Order.OrderId)
                return;

            tableInfo = $tableInfo.clone();
            tableName = $tableName.clone();
            dishList = $dishList.clone();

            //餐台名称
            tableName.find(".name").text(order.Table.TableName + (order.Order.IsMain == 1 ? "(主)" : ""));

            //输出开台信息
            var openTableInfo = findOpenTableInfo(order.Order.OrderId);
            tableInfo.find(".table-time").text("开台时间：" + (new Date(order.Order.BeginTime)).formatDate(fmt));
            tableInfo.find(".table-people").text("人数：" + order.Table.PeopleNum);
            tableInfo.find(".table-user").text("开台人：" + (openTableInfo == null ? "" : openTableInfo.OpenTableUser));
            tableInfo.find(".table-businesstimespan").text("市别：" + (openTableInfo == null ? "" : openTableInfo.BusinessTimeSpanName));

            //输出菜品
            $.each(order.Dishes, function (index, item) {
                var dishItem = $dishItem.clone();
                dishItem.find('label.dish-selected').data("dishId", item.OrderDishId);
                dishItem.find(".dish-name").html(mpos.getDishTag(item) + item.DishName);
                dishItem.find(".dish-num").text("X" + item.DishNum);
                if (item.ReturnOrderDishId != 0) {
                    dishItem.find(".dish-name").addClass('disabled');
                }
                if (item.DishProperty == OrderDishProperty.PackageDishChild) {
                    // 套餐子菜
                    dishItem.find(".dish-name").addClass('disabled');
                    dishItem.find(".dish-amount").text("-");
                } else if (item.DishProperty == OrderDishProperty.MultiDishChild) {
                    // 一品多吃子菜
                    dishItem.find(".dish-name").addClass('disabled');
                    dishItem.find(".dish-amount").text("-");
                } else {
                    dishItem.find(".dish-amount").text(mpos.formatPrice(item.DishSaleAmount));
                }

                var cookies = "";
                var dishUnit = item.DishPortions || item.DishUnit;
                if (item.Discount < 100) {
                    dishUnit += "/" + parseFloat((item.Discount / 10).toFixed(2)) + "折";
                }
                $.each(item.DishRequestList, function (idx, re) {
                    cookies += re.RequestName + (Math.abs(re.RequestNum) == 1 ? "" : ("*" + re.RequestNum)) + "、"; //做法
                });
                if (cookies.length > 0) {
                    dishItem.find(".dish-cookies").text(dishUnit + "/" + cookies.substr(0, cookies.length - 1));
                } else {
                    dishItem.find(".dish-cookies").text(dishUnit);
                }
                dishItem.find('.order-date').text(item.OrderDate === '0001-01-01 00:00:00' ? '' : item.OrderDate);
                dishList.append(dishItem);

            });

            fragment.append(tableName);
            fragment.append(tableInfo);
            fragment.append(dishList);
        });

        //菜品点击事件
        fragment.find("label.dish-selected").on("click", function (e) {
            var listItem = $(this).parents('li');
            if (mpos.Components.OrderedDishOperation.has(listItem)) {
                mpos.Components.OrderedDishOperation.remove(listItem);
                listItem.removeClass('expand');
                return;
            }

            var orderDishId = $(this).data("dishId");
            var dish = findDishData(orderDishId);
            if (dish == null)
                return;
            //套餐子菜跳过
            if (dish.DishProperty == OrderDishProperty.PackageDishChild) {
                return;
            }
            // 一品多吃子菜
            if (dish.DishProperty == OrderDishProperty.MultiDishChild) {
                return;
            }

            //退完的菜不允许操作
            //if (dish.RealDishNum <= 0) {
            //    return;
            //}

            //只对非退的菜操作
            if (dish.ReturnOrderDishId != 0)
                return;

            //预结不能操作
            if (settleData.EnterOrder.Order.OrderStatus == 2) {
                mpos.alert("已预结，不能操作");
                return;
            }

            /**
             *
             * @type {DOOptions}
             */
            var options = {
                giveDish: -1,
                discountDish: false,
                returnDish: false,
                changeDishPrice: true,
                qicai: true
            };
            if (dish.IsFreeDish == IsFreeDishType.None) {
                if (dish.TeTeaType != OrderDishTeaType.Tea && dish.RealDishNum > 0) {
                    options.giveDish = 1;
                }
                if (dish.RealDishNum > 0) {
                    options.discountDish = true;
                }
            } else if (dish.IsFreeDish == IsFreeDishType.Present) {
                if (dish.TeTeaType != OrderDishTeaType.Tea) {
                    options.giveDish = 0;
                }
                //options.changeDishPrice = false; //赠送后不能改价
            }
            if (dish.IsFreeDish == IsFreeDishType.None && dish.ReturnOrderDishId == 0 && dish.RealDishNum > 0) {
                options.returnDish = true;
            }
            if (dish.RealDishNum <= 0) { //退完了的不显示
                options.giveDish = -1;
                options.qicai = false;
            }

            if (dish.IsFreeDish == IsFreeDishType.TicketExchange) { //兑换的不能改价
                options.changeDishPrice = false;
            }

            if (isSnackSettle) { //快餐不能操作的项
                options.changeDishPrice = false;
                options.returnDish = false;
                options.qicai = false;
            }

            options.parent = $(this).parents('li');
            options.callback = function (operation) {
                if (isPaytoOrderModel) {
                    if (operation.operationType == 1) {
                        // 酒楼模式启用先付款后下单时，可以赠送
                        // mpos.giveDish(dish, payToOrderRefreshSettleDishes, true);
                        mpos.giveDish(dish, function () {
                            //重新刷新
                            GetSettleData(refreshSettleData);
                        });

                    } else if (operation.operationType == 4) {
                        // // 酒楼模式启用先付款后下单时，取消赠送
                        // cancelPayToOrderRefreshSettleDishes(dish);
                        mpos.cancelGiveDish(dish, function () {
                            //重新刷新
                            GetSettleData(refreshSettleData);
                        });
                    } else {
                        mpos.alert("当前模式不支持此功能");
                    }
                    return;
                }
                switch (operation.operationType) {
                    case 1: //赠送
                        mpos.giveDish(dish, function () {
                            //重新刷新
                            GetSettleData(refreshSettleData);
                        });
                        break;
                    case 2: //退菜
                        mpos.returndish(dish, function () {
                            //重新刷新
                            GetSettleData(refreshSettleData);
                        });
                        break;
                    case 3: //折扣
                        mpos.discountDish(dish, function () {
                            //重新刷新
                            GetSettleData(refreshSettleData);
                        });
                        break;
                    case 4: //取消赠送
                        mpos.cancelGiveDish(dish, function () {
                            //重新刷新
                            GetSettleData(refreshSettleData);
                        });
                        break;
                    case 5: //修改单价
                        mpos.changeDishPrice(dish, function () {
                            //重新刷新
                            GetSettleData(refreshSettleData);
                        });
                        break;
                    case 6: //起菜
                        mpos.qicai(dish, settleData.EnterOrder.Order.OrderId);
                        break;
                    default:
                        break;
                }
            };

            new mpos.Components.OrderedDishOperation(options);
        });

        //显示金额信息
        var consumptionAmount = $consumptionAmount.clone();
        var amountDsc = "";
        $.each(settleData.AmountDesc, function (index, item) { //获取订单金额合集
            amountDsc += "<li>" + item.AmountName + "<span>" + mpos.shopConfig.AmountSymbol + item.Amount + "</span></li>";
        });
        var content = consumptionAmount.find(".content").empty();
        content.append(amountDsc);
        content.append("<li class='amount-total  sep-line'>应收金额<span>" + mpos.shopConfig.AmountSymbol + settleData.TotalPayableAmount + "</span></li>");
        content.append("<li class='amount-total'>已收金额<span>" + mpos.shopConfig.AmountSymbol + settleData.ReceivedAmount + "</span></li>");
        content.append("<li class='amount-total'>待收金额<span>" + mpos.shopConfig.AmountSymbol + settleData.TotalObligationAmount + "</span></li>");
        content.append("<li class='amount-total'>找零<span>" + mpos.shopConfig.AmountSymbol + settleData.ChangeAmount + "</span></li>");
        fragment.append(consumptionAmount);

        var paymentList = $paymentList.clone();
        var paymentTypeList = $paymentTypeList.clone();

        //处理并显示付款信息
        /*********付款信息***********/
        var _typeIndex = 0;   // 记录不显示全部付款方式的数量
        var hasAppendShowAll = false;  // 是否显示全部付款方式
        $.each(settleData.PaymentItems, function (index, item) {
            if (_typeIndex == 6 && !hasAppendShowAll) {
                paymentTypeList.append("<div class='show-all'></div>");
                hasAppendShowAll = true;
            }
            //酒吧模式不支持会员卡和票券，请到前台去支付
            if ((item.PaymentPattern.PaymentPatternType == PaymentPatternTypeEnum.MemberCardPayment ||
              item.PaymentPattern.PaymentPatternType == PaymentPatternTypeEnum.TicketPayment) && isPaytoOrderModel) {
                return;
            }

            var typeItem = $("<li class='textEllipsis' />").text(item.PaymentPattern.PaymentPatternName)
                .addClass("payment-type-" + item.PaymentPattern.PaymentPatternType);
            // 银行卡 4
            if (item.PaymentPattern.PaymentPatternType == PaymentPatternTypeEnum.BankCardPayment) {
                if (item.PaymentPattern.ThirdPaymentType != BankPaymentType.NormalPay) {
                    typeItem.data("pattern_id", item.PaymentPattern.PaymentPatternId);
                }
            } else {
                typeItem.data("pattern_id", item.PaymentPattern.PaymentPatternId);
            }
            //添加class, 银行卡支付和第三方支付的扩展
            if (item.PaymentPattern.PaymentPatternType ==  PaymentPatternTypeEnum.BankCardPayment ||
              item.PaymentPattern.PaymentPatternType ==  PaymentPatternTypeEnum.ThirdPayment) {
                typeItem.addClass("payment-type-" + item.PaymentPattern.PaymentPatternType +
                    "-" + item.PaymentPattern.ThirdPaymentType);
            }
            // 银行卡 4
            if (item.PaymentPattern.PaymentPatternType == PaymentPatternTypeEnum.BankCardPayment) {
                if (mpos.deviceFactory.deviceType == DeviceType.IboxPayDevice && item.PaymentPattern.ThirdPaymentType == BankPaymentType.IBoxPay) {
                    paymentTypeList.append(typeItem);
                    _typeIndex++;
                } else if (mpos.deviceFactory.deviceType == DeviceType.LklPayDevice && item.PaymentPattern.ThirdPaymentType == BankPaymentType.Lakala) {
                    paymentTypeList.append(typeItem);
                    _typeIndex++;
                }
            } else {
                paymentTypeList.append(typeItem);
                _typeIndex++;
            }

            /*付款明细*/
            $.each(item.Items, function (idx, pay) {
                var listPaymentItem = $("<li class='payment-detail flex-column'></li>");
                var deleteHtml = "<span class='app-button' data-return_amount_payment_id='" + pay.PaymentId + "'>";
                var deleteDesc = "删除";

                listPaymentItem.append($span.clone().addClass("flex-item-8").text(item.PaymentPattern.PaymentPatternName));

                if (item.PaymentPattern.PaymentPatternType == PaymentPatternTypeEnum.CashPayment) { //现金
                } else if (item.PaymentPattern.PaymentPatternType == PaymentPatternTypeEnum.MemberCardPayment) { //会员卡
                    listPaymentItem.append($span.clone().addClass("flex-item-8").text(pay.MemberName));
                    deleteDesc = "退款";
                } else if (item.PaymentPattern.PaymentPatternType == PaymentPatternTypeEnum.BankCardPayment) { //银行卡
                    if (item.PaymentPattern.ThirdPaymentType == BankPaymentType.Lakala) { //拉卡拉显示时间
                        listPaymentItem.append($span.clone().addClass("flex-item-8").text((new Date(pay.CreatedOn)).formatDate(timeFmt)));
                    } else {
                        listPaymentItem.append($span.clone().addClass("flex-item-8").text(pay.Remark));
                    }
                } else if (item.PaymentPattern.PaymentPatternType == PaymentPatternTypeEnum.CreditPayment) { //挂账
                    listPaymentItem.append($span.clone().addClass("flex-item-8").text(pay.CreditCustomerName + " - " + pay.CreditUserName));
                } else if (item.PaymentPattern.PaymentPatternType == PaymentPatternTypeEnum.FreePayment) { //免单
                } else if (item.PaymentPattern.PaymentPatternType == PaymentPatternTypeEnum.TicketPayment) { //票券
                    listPaymentItem.append($span.clone().addClass("flex-item-4").text(pay.TicketTypeName));
                    if (pay.TicketPattern == 1) {
                        listPaymentItem.append($span.clone().addClass("flex-item-4").text("实物券"));
                    } else if (pay.TicketPattern == 2) {
                        listPaymentItem.append($span.clone().addClass("flex-item-4").text("代金券"));
                    } else if (pay.TicketPattern == 3) {
                        listPaymentItem.append($span.clone().addClass("flex-item-4").text("抵扣券"));
                    } else if (pay.TicketPattern == 4) {
                        listPaymentItem.append($span.clone().addClass("flex-item-4").text("满减券"));
                    } else if (pay.TicketPattern == 5) {
                        listPaymentItem.append($span.clone().addClass("flex-item-4").text("次卡券"));
                    } else if (pay.TicketPattern == 6) {
                        listPaymentItem.append($span.clone().addClass("flex-item-4").text("折扣券"));
                    }
                } else if (item.PaymentPattern.PaymentPatternType == PaymentPatternTypeEnum.DownPayment) { //订金
                    deleteHtml = ""; //不能退
                } else if (item.PaymentPattern.PaymentPatternType == PaymentPatternTypeEnum.ThirdPayment) { //第三方支付
                    if (item.PaymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.Alipay) { //支付宝
                        listPaymentItem.append($span.clone().addClass("flex-item-8").text((new Date(pay.CreatedOn)).formatDate(timeFmt)));
                        if (pay.IsFromOnline == PaymentFromOnlineType.Offine) {
                            deleteDesc = "退款";
                        }
                    } else if (item.PaymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.Weixin) { //微信
                        deleteDesc = "退款";
                        listPaymentItem.append($span.clone().addClass("flex-item-8").text((new Date(pay.CreatedOn)).formatDate(timeFmt)));
                    } else if (item.PaymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.CloudFlashPay) { //云闪付
                        deleteDesc = "退款";
                        listPaymentItem.append($span.clone().addClass("flex-item-8").text((new Date(pay.CreatedOn)).formatDate(timeFmt)));
                    } else if (item.PaymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.Meituan) { //美团
                        if (pay.IsFromOnline == 1) {
                            deleteHtml = ""; //不能退
                        }
                        listPaymentItem.append($span.clone().addClass("flex-item-8").text(pay.Remark));
                    } else if (item.PaymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.Nuomi) { //糯米
                        if (pay.IsFromOnline == 1) {
                            deleteHtml = ""; //不能退
                        }
                        listPaymentItem.append($span.clone().addClass("flex-item-8").text(pay.Remark));
                    }  else if (item.PaymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.DouyinTicket) { //抖音券
                        if (pay.IsFromOnline == 1) {
                            deleteHtml = ""; //不能退
                        }
                        listPaymentItem.append($span.clone().addClass("flex-item-8").text(pay.Remark));
                    } else if (item.PaymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.DoublePeople) {

                    } else if (item.PaymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.MultiShopMember) {
                        mpos.alert("不支持此支付方式");
                    }
                }

                var amountSpan = $($.formatStr("<span class='flex-right amount flex-item-8 textEllipsis'>{0}</span>", mpos.formatPrice(pay.Amount, item.PaymentPattern.Symbol)));
                listPaymentItem.append(amountSpan);

                if (deleteHtml != "") {
                    deleteHtml += deleteDesc + "</span>";
                    listPaymentItem.append(deleteHtml);
                }

                paymentList.append(listPaymentItem);
            });
        });
        paymentTypeList.append("<div class='hide-all'></div>");

        fragment.append(paymentList);
        fragment.append(paymentTypeList);
        fragment.find("div.show-all").on("click", function () {
            $(this).remove();
        });
        fragment.find("div.hide-all").on("click", function () {
            $pageDom.find(".payment-type-list>li").eq(6).before($("<div class='show-all'></div>").on("click", function () {
                $(this).remove();
            }));
        });

        //退款或删除付款方式
        fragment.find("span[data-return_amount_payment_id]").on("click", function (e) {
            var $target = $(e.currentTarget);
            var targetText = $target.text();
            var paymentId = $target.data("return_amount_payment_id");
            var payItem = findPaymentInfo(paymentId);
            if (payItem != null) {
                var paymentPattern = payItem.PatternInfo;
                if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.CashPayment) { //现金
                    returnForCash(paymentId);
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.MemberCardPayment) { //会员卡
                    //退款，需要弹出界面
                    returnForMemberOrWx(paymentId, payItem.Amount, 1);
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.BankCardPayment) { //银行卡
                    if (paymentPattern.ThirdPaymentType != BankPaymentType.NormalPay) {
                        if (paymentPattern.ThirdPaymentType == BankPaymentType.IBoxPay && DeviceType[mpos.deviceFactory.deviceType] != "3.1") {
                            mpos.alert("不支持此付款方式退款");
                            return;
                        }
                        if (paymentPattern.ThirdPaymentType == BankPaymentType.Lakala && DeviceType[mpos.deviceFactory.deviceType] != "3.2") {
                            mpos.alert("不支持此付款方式退款");
                            return;
                        }
                        if (paymentPattern.ThirdPaymentType == BankPaymentType.WangPos && DeviceType[mpos.deviceFactory.deviceType] != "3.3") {
                            mpos.alert("不支持此付款方式退款");
                            return;
                        }

                        returnForIBoxPay(paymentId);

                    } else {
                        returnForBank(paymentId);
                    }
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.CreditPayment) { //挂账
                    returnForCredit(paymentId);
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.FreePayment) { //免单
                    returnForFree(paymentId);
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.TicketPayment) { //票券
                    returnForTicket(paymentId);
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.DownPayment) { //订金
                    //无退款
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.ThirdPayment) { //第三方支付
                    if (paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.Alipay) { //支付宝
                        if (payItem.IsFromOnline == PaymentFromOnlineType.Offine) {
                            returnForMemberOrWx(paymentId, payItem.Amount, 3);
                        } else {
                            returnForWxOrAliPay(paymentId);
                        }
                    } else if (paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.Weixin) { //微信
                        //退款，需要弹出界面
                        returnForMemberOrWx(paymentId, payItem.Amount, 2);
                    } else if (paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.CloudFlashPay) { //云闪付
                        //退款，需要弹出界面
                        returnForMemberOrWx(paymentId, payItem.Amount, 12);
                    } else if (paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.Meituan ||
                      paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.Nuomi ||
                      paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.DouyinTicket) {   // 美团、糯米、抖音
                        returnForGroup(paymentId);
                    } else if (paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.DoublePeople) {  // 优质双人餐
                        returnForThirdCustomPay(paymentId);
                    } else if (paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.MultiShopMember) {  // 跨店会员支付
                        mpos.alert("不支持此支付方式");
                    }
                }
            }
        });

        //付款方式点击事件
        fragment.find("li[data-pattern_id]").on("click", function (e) {
            var pid = $(e.currentTarget).data("pattern_id");
            var paymentPattern = findPaymentPatternInfo(pid);
            if (paymentPattern != null) {
                if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.CashPayment) { //现金
                    payForCash(paymentPattern);
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.MemberCardPayment) { //会员卡
                    payForMember(paymentPattern);
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.BankCardPayment) { //银行卡
                    if (paymentPattern.ThirdPaymentType != BankPaymentType.NormalPay) { //盒子支付
                        if (paymentPattern.ThirdPaymentType == BankPaymentType.IBoxPay && DeviceType[mpos.deviceFactory.deviceType] != "3.1") {
                            mpos.alert("此设备不支持此付款方式");
                            return;
                        }
                        if (paymentPattern.ThirdPaymentType == BankPaymentType.Lakala && DeviceType[mpos.deviceFactory.deviceType] != "3.2") {
                            mpos.alert("此设备不支持此付款方式");
                            return;
                        }
                        if (paymentPattern.ThirdPaymentType == BankPaymentType.WangPos && DeviceType[mpos.deviceFactory.deviceType] != "3.3") {
                            mpos.alert("此设备不支持此付款方式");
                            return;
                        }
                        payForIBoxPay(paymentPattern);
                    } else /* if (paymentPattern.ThirdPaymentType == BankPaymentType.NormalPay)*/ {
                        payForBank(paymentPattern);
                    }
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.CreditPayment) { //挂账
                    payForCredit(paymentPattern);
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.FreePayment) { //免单
                    payForFree(paymentPattern);
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.TicketPayment) { //票券
                    payForTicket(paymentPattern);
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.DownPayment) { //订金
                    mpos.alert("不能使用此付款方式");
                    return;
                } else if (paymentPattern.PaymentPatternType == PaymentPatternTypeEnum.ThirdPayment) { //第三方支付
                    if (paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.Alipay || paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.Weixin
                        || paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.CloudFlashPay) { //支付宝、微信、云闪付
                        payForWxOrAliPay(paymentPattern);
                    } else if (paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.Meituan || paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.Nuomi
                        || paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.DouyinTicket) {
                        //3=美团，4=糯米、15=抖音券
                        payForGrouponPay(paymentPattern);
                    } else if (paymentPattern.ThirdPaymentType == ThirdPaymentTypeEnum.DoublePeople) {
                        // 增加固定面额抵扣券
                        if (paymentPattern.FixedTicketType == 1) {
                            var usedFixedTickets = findUsedFixedTicketInfo(pid);
                            payForFixedTicket(paymentPattern, usedFixedTickets);
                        } else {
                            payForThirdCustomPay(paymentPattern);
                        }
                    }
                }
            }
        });

        //显示和隐藏操作列表项按钮
        fragment.find(".payment-detail").on("click", function () {
            $(this).toggleClass("operation");
        });

        fragment.append(invoice);
        $pageDom.find('.app-content').empty().append(fragment);
        $invoiceAmount.find("input").attr("placeholder", "可开发票金额:" + mpos.formatPrice(settleData.CanInvoiceMoney));

        /**************处理预打印和预结****************/
        if (!isSnackSettle) { //只有酒楼结账时才有预打印和预结功能
            //获取预打印数据
            $pageDom.find("#printSettle").on("click", function (e) { //预打印
                var billId = mpos.preBilledOrderId();
                if (billId <= 0) {
                    mpos.alert("未设置打印格式");
                    //mpos.load(mpos.page.printStyle);
                    return;
                }
                mpos.post(mpos.api.getPrintBill, {
                    ConsumptionId: settleData.Consumption.ConsumptionId,
                    BillId: billId, //打印单格式ID
                    BillType: 2,
                }, function (data, status, xhr) {
                    if (data != undefined && data.length > 0) {
                        $.each(data, function (idx, item) {
                            for (var i = 0; i < mpos.preBilledOrderNumber(); i++) { //打印多份
                                var printData = mpos.addPrintEmptyLine(item);
                                mpos.deviceFactory.printTicket(printData, null, function (err) {
                                    //打印
                                    mpos.alert(err);
                                });
                            }
                        });
                    }
                });
            });

            //预结按钮事件
            settlePrepayBill.on("click", function (e) {
                mpos.preBilledOrder(settleData.Consumption.ConsumptionId, 1, function () {
                    //重新刷新
                    mpos.getSettleInfo(settleData.EnterOrder.Order.OrderId, refreshSettleData);
                })
            });
        } else { //快餐处理餐牌和外带功能
            $pageDom.find("#snackTableName").tap(function (e) { //餐牌点击事件
                beginSelectTableBrandNo(function () {
                    //重新刷新
                    GetSettleData(refreshSettleData);
                });
            });
            $pageDom.find("#snackIsTakeOut").tap(function (e) { //外带点击事件
                mpos.post(mpos.api.setSnackOrderToTakeOut, {
                    DiningOrderId: settleData.EnterOrder.Order.OrderId,
                }, function () {
                    //重新刷新
                    GetSettleData(refreshSettleData);
                })
            });
        }

        //展开、收起订单详情
        $pageDom.find(".bill-info .bill-detail").on("click", function (e) {
            $(this).parent().toggleClass("expand");
        });

        //如果之前是展开的，刷新后继续展开
        if (expandDishDetail) {
            $pageDom.find(".bill-info").addClass("expand");
        }


    }

    refresh();

    /*
     获取一个菜品
     */
    function findDishData(orderDishId) {
        for (var j = 0; j < settleData.Orders.length; j++) {
            for (var i = 0; i < settleData.Orders[j].Dishes.length; i++) {
                if (settleData.Orders[j].Dishes[i].OrderDishId == orderDishId) {
                    return settleData.Orders[j].Dishes[i];
                }
            }
        }
        return null;
    }

    /*
     获取开台信息
     * */
    function findOpenTableInfo(orderId) {
        if (settleData.OpenTableInfos) {
            for (var i = 0; i < settleData.OpenTableInfos.length; i++) {
                if (settleData.OpenTableInfos[i].OrderId == orderId) {
                    return settleData.OpenTableInfos[i];
                }
            }
        }
        return null;
    }

    /**
     * 弹出餐牌选择(快餐专用)
     */
    function beginSelectTableBrandNo(callback) {
        var brandName = settleData.EnterOrder.Order.TableCardNo;
        var tableSerial = "";
        if (brandName != "") {
            tableSerial = settleData.EnterOrder.Table.TableSerial;
        }
        mpos.showDialog(mpos.dialogPage.selectSnackBrand, {
            TableSerial: tableSerial,
            PeopleNum: settleData.EnterOrder.Table.PeopleNum
        }, function (r) {
            if (r.Changed) {
                var peopleNum = r.PeopleNum;
                var tableSerial = r.TableSerial;
                mpos.post(mpos.api.updateSnackTableBrandNo, {
                    TableSerial: tableSerial,
                    OrderId: settleData.EnterOrder.Order.OrderId,
                    PeopleNum: peopleNum,
                }, function () {
                    if (callback) {
                        callback();
                    }
                });
            }
        });
    }

    /**
     * 获取付款方式信息
     * @param {Number} pid PaymentId
     */
    function findPaymentInfo(pid) {
        if (settleData.PaymentItems) {
            for (var i = 0; i < settleData.PaymentItems.length; i++) {
                for (var j = 0; j < settleData.PaymentItems[i].Items.length; j++) {
                    if (settleData.PaymentItems[i].Items[j].PaymentId == pid) {
                        var item = settleData.PaymentItems[i].Items[j];
                        item.PatternInfo = settleData.PaymentItems[i].PaymentPattern;
                        return item;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 获取付款信息
     * @param {Object} pid PaymentPatternId
     */
    function findPaymentPatternInfo(pid) {
        if (settleData.PaymentItems) {
            for (var i = 0; i < settleData.PaymentItems.length; i++) {
                if (settleData.PaymentItems[i].PaymentPattern.PaymentPatternId == pid) {
                    return settleData.PaymentItems[i].PaymentPattern;
                }
            }
        }
        return null;
    }

    /**
     * 获取固定面额票券已使用的票券信息
     * @param {Object} pid PaymentPatternId
     */
    function findUsedFixedTicketInfo(pid) {
        if (settleData.PaymentItems) {
            for (var i = 0; i < settleData.PaymentItems.length; i++) {
                if (settleData.PaymentItems[i].PaymentPattern.PaymentPatternId == pid) {
                    return settleData.PaymentItems[i].Items;
                }
            }
        }
        return [];
    }

    /*
     现金支付
     */
    function payForCash(paymentPattern) {
        mpos.showDialog(mpos.dialogPage.cashPay, {
            "paymentPattern": paymentPattern,
            "settle": settleData,
            IsPayToOrder: isPaytoOrderModel
        }, function (data) {
            refreshSettleData(data);
        });
    }

    /*
     现金退款
     */
    function returnForCash(paymentId) {
        confirmDelete(function () {
            mpos.clearSettlePaymentItem({
                OrderId: settleData.EnterOrder.Order.OrderId,
                PaymentId: paymentId,
                Amount: 0
            }, function (data) {
                refreshSettleData(data);
            })
        });
    }

    /*
    团购券退款
    */
    function returnForGroup(paymentId) {
        confirmDelete(function () {
            mpos.clearSettlePaymentItem({
                OrderId: settleData.EnterOrder.Order.OrderId,
                PaymentId: paymentId,
                Amount: 0
            }, function (data) {
                refreshSettleData(data);
            })
        });
    }

    /*
    自定义第三方退款
    */
    function returnForThirdCustomPay(paymentId) {
        confirmDelete(function () {
            mpos.clearSettlePaymentItem({
                OrderId: settleData.EnterOrder.Order.OrderId,
                PaymentId: paymentId,
                Amount: 0
            }, function (data) {
                refreshSettleData(data);
            })
        });
    }

    /*
     会员卡支付
     */
    function payForMember(paymentPattern) {
        mpos.showDialog(mpos.dialogPage.memberPay, {
            "paymentPattern": paymentPattern,
            "settle": settleData,
            IsPayToOrder: isPaytoOrderModel
        }, function (data) {
            if (data && data.redirectRecharge) {
                mpos.load(mpos.page.memberRecharge, data.memberCard);
            } else {
                refreshSettleData(data);
            }
        });
    }

    /*
     会员卡退款
     @paymentId:ID
     @amount：退款金额
     */
    function returnForMemberOrWx(paymentId, amount, payType) {
        mpos.showDialog(mpos.dialogPage.returnMemberPay, {
            "paymentId": paymentId,
            "amount": amount,
            "orderId": settleData.EnterOrder.Order.OrderId,
            "payType": payType
        }, function (data) {
            if (data && data.redirectRecharge) {
                mpos.load(mpos.page.memberRecharge, data.memberCard);
            } else {
                refreshSettleData(data);
            }
        });
    }

    /*
     免单支付
     */
    function payForFree(paymentPattern) {
        mpos.showDialog(mpos.dialogPage.freePay, {
            "paymentPattern": paymentPattern,
            "settle": settleData,
            IsPayToOrder: isPaytoOrderModel
        }, function (data) {
            refreshSettleData(data);
        });
    }

    /*
     免单退款
     */
    function returnForFree(paymentId) {
        confirmDelete(function () {
            mpos.clearSettlePaymentItem({
                OrderId: settleData.EnterOrder.Order.OrderId,
                PaymentId: paymentId,
                Amount: 0
            }, function (data) {
                refreshSettleData(data);
            })
        });
    }

    /*
     挂账支付
     */
    function payForCredit(paymentPattern) {
        mpos.showDialog(mpos.dialogPage.creditPay, {
            "paymentPattern": paymentPattern,
            "settle": settleData,
            IsPayToOrder: isPaytoOrderModel
        }, function (data) {
            refreshSettleData(data);
        });
    }

    /*
     挂账退款
     */
    function returnForCredit(paymentId) {
        confirmDelete(function () {
            mpos.clearSettlePaymentItem({
                OrderId: settleData.EnterOrder.Order.OrderId,
                PaymentId: paymentId,
                Amount: 0
            }, function (data) {
                refreshSettleData(data);
            })
        });
    }

    /*
     票券支付
     */
    function payForTicket(paymentPattern) {
        mpos.showDialog(mpos.dialogPage.ticketPay, {
            "paymentPattern": paymentPattern,
            "settle": settleData,
            IsPayToOrder: isPaytoOrderModel
        }, function (data) {
            refreshSettleData(data);
        });
    }

    /**
     * 固定面额抵扣票券支付
     * */
    function payForFixedTicket(paymentPattern, usedFixedTickets) {
        mpos.showDialog(mpos.dialogPage.fixedTicketPay, {
            "paymentPattern": paymentPattern,
            "usedFixedTickets": usedFixedTickets,
            "settle": settleData,
            IsPayToOrder: isPaytoOrderModel
        }, function (data) {
            refreshSettleData(data);
        });
    }


    /*
     票券退款
     */
    function returnForTicket(paymentId) {
        confirmDelete(function () {
            mpos.clearSettlePaymentItem({
                OrderId: settleData.EnterOrder.Order.OrderId,
                PaymentId: paymentId,
                Amount: 0
            }, function (data) {
                refreshSettleData(data);
            })
        });
    }

    /*
     第三方支付
     */
    function payForWxOrAliPay(paymentPattern) {
        //if (mpos.deviceFactory.deviceType == DeviceType.LklPayDevice) {
        //    if (mpos.shopConfig.EnabledLakalaScanPay) {
        //        mpos.alert("此设备不允许使用此付款方式");
        //        return;
        //    }
        //}
        mpos.showDialog(mpos.dialogPage.wxOrAliPay, {
            "paymentPattern": paymentPattern,
            "settle": settleData,
            "thirdPaymentType": paymentPattern.ThirdPaymentType,
            IsPayToOrder: isPaytoOrderModel
        }, function (data) {
            refreshSettleData(data);
        });
    }

    /*
     第三方退款
     */
    function returnForWxOrAliPay(paymentId) {
        confirmDelete(function () {
            mpos.clearSettlePaymentItem({
                OrderId: settleData.EnterOrder.Order.OrderId,
                PaymentId: paymentId,
                Amount: 0
            }, function (data) {
                refreshSettleData(data);
            }, {
                timeout: 30000
            })
        });
    }

    /*
     普通银行卡支付
     */
    function payForBank(paymentPattern) {
        mpos.showDialog(mpos.dialogPage.bankPay, {
            "paymentPattern": paymentPattern,
            "settle": settleData,
            IsPayToOrder: isPaytoOrderModel
        }, function (data) {
            refreshSettleData(data);
        });
    }

    /*
     普通银行卡支付退款
     */
    function returnForBank(paymentId) {
        confirmDelete(function () {
            mpos.clearSettlePaymentItem({
                OrderId: settleData.EnterOrder.Order.OrderId,
                PaymentId: paymentId,
                Amount: 0
            }, function (data) {
                refreshSettleData(data);
            })
        });
    }

    /*
    团购券付款
    */
    function payForGrouponPay(paymentPattern) {
        mpos.showDialog(mpos.dialogPage.grouponPay, {
            "paymentPattern": paymentPattern,
            "settle": settleData,
            IsPayToOrder: isPaytoOrderModel
        }, function (data) {
            refreshSettleData(data);
        });
    }

    /**
    优惠买单
    */
    function payForThirdPreferentialPay(paymentPattern) {
        mpos.showDialog(mpos.dialogPage.thirdPreferentialPay, {
            "paymentPattern": paymentPattern,
            "settle": settleData,
            IsPayToOrder: isPaytoOrderModel
        }, function (data) {
            refreshSettleData(data);
        });
    }

    /**
    自定义第三方支付
    */
    function payForThirdCustomPay(paymentPattern) {
        mpos.showDialog(mpos.dialogPage.thirdCustomPay, {
            "paymentPattern": paymentPattern,
            "settle": settleData,
            IsPayToOrder: isPaytoOrderModel
        }, function (data) {
            refreshSettleData(data);
        });
    }

    /*
     移动银行付款
     */
    function payForIBoxPay(paymentPattern) {
        mpos.showDialog(mpos.dialogPage.iBoxPayPay, {
            "paymentPattern": paymentPattern,
            "settle": settleData,
            IsPayToOrder: isPaytoOrderModel
        }, function (status) {
            if (status) {
                refreshSettleData(true);
            }
        });
    }

    /*
     移动银行付款退款
     */
    function returnForIBoxPay(paymentId) {
        mpos.dialog({
            title: "提醒",
            text: "确认要撤销支付吗？",
            okButton: "是",
            cancelButton: "否"
        }, function (status) {
            if (status) {
                mpos.post(mpos.api.cancelBoxPay, {
                    ConsumptionId: settleData.Consumption.ConsumptionId,
                    PaymentId: paymentId,
                }, function (config) {
                    if (typeof config == "object") {
                        if (config.OrderNo != "" && config.BoxConfig.ApiKey != "" && config.BoxConfig.AppCode != "" && config.BoxConfig.Md5Salt != "") {
                            mpos.showLoading();
                            mpos.isPaying = true;

                            var cfg = {
                                OrderNo: config.OrderNo,
                                PayAmount: config.PayAmount,
                                BoxConfig: config.BoxConfig,
                                PaymentType: config.PaymentType,
                            };
                            cfg.PayType = 3;
                            cfg.CbOrderNo = config.TradeNo;
                            mpos.deviceFactory.payOrder(cfg, function (result) {
                                mpos.hideLoading();
                                mpos.isPaying = false;
                                var outTradeNo = result.OutTradeNo;
                                mpos.post(mpos.api.updateCancelBoxPay, {
                                    PaymentId: paymentId,
                                    OutTradeNo: outTradeNo,
                                    ConsumptionId: settleData.Consumption.ConsumptionId,
                                }, function () {
                                    refreshSettleData(true);
                                });
                            }, function (err) {
                                mpos.hideLoading();
                                mpos.isPaying = false;
                                mpos.alert("撤销失败:" + err);
                            })
                        }
                    }
                });
            }
        });
    }

    /*
     删除确认
     */
    function confirmDelete(callback) {
        mpos.dialog({
            title: "提醒",
            text: "确认要删除吗？",
            okButton: "是",
            cancelButton: "否"
        }, function (status) {
            if (status) {
                callback();
            }
        });
    }

    /**
     获取最大点菜ID
    */
    function getMaxOrderDishId (dishes) {
        if (dishes.length == 0) {
            return 0;
        }
        var maxId = 0;
        dishes.forEach(function (item) {
            if (item.OrderDishId > maxId) {
                maxId = item.OrderDishId;
            }
        });

        return maxId;
    }

    /**
     * 酒楼模式下先付款后下单赠送功能刷新结账
     * @param{}  data  赠送的菜品信息
     */
    function payToOrderRefreshSettleDishes (giveData) {
        if (!settleData || !settleData.EnterOrder || settleData.EnterOrder.Dishes.length <= 0) {
            return ;
        }
        mpos.stopSearchMagCard();

        var OrderDishes = settleData.EnterOrder.Dishes;
        var OrderId = settleData.EnterOrder.Order.OrderId;
        var Waiter = settleData.EnterOrder.Order.Waiter;
        var orderDishId = giveData.OrderDishId;
        var dishNum = giveData.DishNum;  // 赠送的菜品数量
        var newDishes = [];
        // 查找出购物车中对应的菜品，进行数量的拆分
        var orderDishInfo = null;
        OrderDishes.forEach(function(item) {
            if (item.OrderDishId == orderDishId) {
                orderDishInfo = item;
            } else {
                newDishes.push(item);
            }
        });

        if (orderDishInfo.DishNum - dishNum > 0) {
            // 大于0，说明菜品拆分
            var giveDishInfo = JSON.parse(JSON.stringify(orderDishInfo));  // 赠送的菜品
            giveDishInfo.OrderDishId = getMaxOrderDishId(OrderDishes) + 1; //主键ID
            giveDishInfo.DishNum = dishNum;
            giveDishInfo.IsFreeDish = 1;

            orderDishInfo.DishNum = orderDishInfo.DishNum - dishNum;  // 修改赠送后的菜品数量

            newDishes.push(orderDishInfo);
            newDishes.push(giveDishInfo);
        } else {
            // 否则就是菜品全部赠送
            orderDishInfo.IsFreeDish = 1;
            newDishes.push(orderDishInfo);
        }
        // 重新请求数据
        mpos.post(mpos.api.getConsumptionPaySettle, {
            OrderId: OrderId,
            Dishes: JSON.stringify(newDishes),
            WaiterId: Waiter
        }, function (data) {
            settleData = mpos.fixSettleInfo(data);
            payToOrderRefreshSettleData(refresh);  //更新金额
        });
    }

    /**
     * 酒楼模式下先付款后下单取消赠送功能刷新结账
     * @param{}  data  赠送的菜品信息
     */
     function cancelPayToOrderRefreshSettleDishes (dishes) {
        if (!settleData || !settleData.EnterOrder || settleData.EnterOrder.Dishes.length <= 0) {
            return ;
        }
        mpos.stopSearchMagCard();

        var OrderDishes = settleData.EnterOrder.Dishes;
        var OrderId = settleData.EnterOrder.Order.OrderId;
        var Waiter = settleData.EnterOrder.Order.Waiter;
        for(var i=0;i<OrderDishes.length;i++) {
            if (OrderDishes[i].OrderDishId == dishes.OrderDishId) {
                OrderDishes[i].IsFreeDish = 0;
                break;
            }
        }
        mpos.post(mpos.api.getConsumptionPaySettle, {
            OrderId: OrderId,
            Dishes: JSON.stringify(OrderDishes),
            WaiterId: Waiter
        }, function (data) {
            settleData = mpos.fixSettleInfo(data);
            payToOrderRefreshSettleData(refresh);  //更新金额
        });
    }

    /**
     * 酒楼先付款后下单，刷新金额
     */
    function payToOrderRefreshSettleData (callback) {
        mpos.post(mpos.api.getConsumptionPaySettle, {
            OrderId: settleData.EnterOrder.Order.OrderId,
        }, function (settle) {
            if (callback) {
                settleData = mpos.fixSettleInfo(settle),
                callback();
            }
        });
    }

    /*
     刷新结账
     */
    function refreshSettleData(data) {
        mpos.stopSearchMagCard();
        //重新刷新
        if (data != undefined && typeof data == "object" && !isPaytoOrderModel) {
            settleData = data;
            refresh();
        } else {
            if (data != undefined) {
                if (data) {
                    GetSettleData(function (settle) {
                        settleData = settle;
                        refresh();
                    });
                }
            }
        }
    }

    /**
     * 获取结账数据
     * @param {*} callback
     */
    function GetSettleData(callback) {
        if (isPaytoOrderModel) {
            mpos.post(mpos.api.getConsumptionPaySettle, {
                OrderId: settleData.EnterOrder.Order.OrderId,
            }, function (settle) {
                if (callback) {
                    settle = mpos.fixSettleInfo(settle),
                        callback(settle);
                }
            });
        } else {
            mpos.getSettleInfo({
                OrderId: settleData.EnterOrder.Order.OrderId,
                IsSnackSettle: isSnackSettle
            }, function (settle) {
                if (callback) {
                    callback(settle);
                }
            });
        }
    }

    /*
     定时检测是否有来自其它的付款方式
     */
    function checkAutoInputOnlinePay() {
        if (!mpos.hasDialog()) {
            var paymentIds = "";
            for (var i = 0; i < settleData.PaymentItems.length; i++) {
                for (var j = 0; j < settleData.PaymentItems[i].Items.length; j++) {
                    paymentIds += "," + (settleData.PaymentItems[i].Items[j].PaymentId);
                }
            }
            mpos.post(mpos.api.checkAutoInputOnlinePay, {
                ConsumptionId: settleData.Consumption.ConsumptionId,
                HasPaymentIds: paymentIds
            }, function (r) {
                if (r) {
                    alert("提醒：检测到有新的付款，确定后此界面将自动刷新。");
                    refreshSettleData(true);
                }
            }, {
                hideLoading: true,
                error: function () { },
                blFailed: function () { }
            });
        }
        clearCheckPayTimeout = setTimeout(checkAutoInputOnlinePay, 5000);
    }

    if (!isSnackSettle) {
        clearCheckPayTimeout = setTimeout(checkAutoInputOnlinePay, 2000);
    }

    //启用了自动弹餐牌
    if (isSnackSettle && mpos.shopConfig.SnackPopTableNumber && !isPaytoOrderModel) {
        if (settleData.EnterOrder.Order.TableCardNo == "") {
            beginSelectTableBrandNo(function () {
                //重新刷新
                GetSettleData(refreshSettleData);
            });
        }
    }
});

/**
结账餐台更多操作
*/
mpos.controller(mpos.page.settleOperationMore, function (page, data) {
    var settleData = data.settle;
    var isSnackSettle = (settleData.SettleMode == SettleMode.SnackDining ? true : false);
    var hasChange = false;
    var freeServiceFee = $(page).find(".free-service-fee");
    var freeTea = $(page).find(".free-tea");
    var freeMincharge = $(page).find(".free-mincharge");
    var reductionAmount = $(page).find(".reduction-amount");
    var wholeDiscount = $(page).find(".whole-discount");
    var rateDiscount = $(page).find(".rate-discount");
    var discountScheme = $(page).find(".discount-scheme");
    var cancelMembercoupon = $(page).find(".cancel-membercoupon");
    var me = this;

    var $tableName = $(page).find(".table-name").remove();
    var $consumptionAmount = $(page).find(".consumption-amount").remove();

    freeServiceFeeFun();
    freeTeaFun();
    freeMinchargeFun();
    reductionAmountFun();
    wholeDiscountFun();
    rateDiscountFun();
    discountSchemeFun();
    cancelMembercouponFun();

    //加载结账数据
    loadSettleData();

    //返回事件
    function backToPrev() {
        if (hasChange) { //需要刷新
            me.reply({ refresh: true });
        } else { //直接返回
            me.reply({ refresh: false });
        }
    }
    this.onBackKeyDown = backToPrev;
    $(page).find("#goBack").on("click", backToPrev);

    /*
    重新加载结账信息
    */
    function reLoadSettleData() {
        mpos.getSettleInfo(
            {
                OrderId: settleData.EnterOrder.Order.OrderId,
                AllowGetDish: false,
                IsSnackSettle: isSnackSettle
            }
            , function (data) {
                settleData = data;
                loadSettleData();
            });
    }

    /*
    加载结账数据
    */
    function loadSettleData() {
        //增加整单ID
        $(page).data("whole_order_id", settleData.EnterOrder.Order.WholeBillId);
        freeServiceFee.show();
        freeMincharge.show();
        freeTea.show();
        var fragment = $(document.createDocumentFragment());
        var tableName = $tableName.clone();
        var consumptionAmount = $consumptionAmount.clone();
        var content = consumptionAmount.find(".content").empty();
        //显示餐台
        tableName.find(".name").text(settleData.EnterOrder.Table.TableName);

        //显示金额
        $.each(settleData.AmountDesc, function (index, item) { //获取订单金额合集
            content.append("<li>" + item.AmountName + "<span>" + mpos.shopConfig.AmountSymbol + item.Amount + "</span></li>");
        });

        if (!isSnackSettle) { //非快餐时显示餐台
            fragment.append(tableName)
        }
        fragment.append(consumptionAmount);

        $(page).find(".table-name, .consumption-amount").remove();
        $(page).find("#operationContainer").before(fragment);

        if (!isSnackSettle) { //非快餐时显示餐台
            //动态显示操作的内容
            if (settleData.Consumption.SourceFillMinimumCharge == 0) { //没有低消时，隐藏操作
                freeMincharge.hide();
            } else {
                if (settleData.Consumption.IsFreeMinCharge == 1) {
                    freeMincharge.addClass("cancel");
                } else {
                    freeMincharge.removeClass("cancel");
                }
            }
            if (settleData.Consumption.SourceServiceFee == 0) { //没有服务费时，隐藏操作
                freeServiceFee.hide();
            } else {
                if (settleData.Consumption.IsFreeServiceFee == 1) {
                    freeServiceFee.addClass("cancel");
                } else {
                    freeServiceFee.removeClass("cancel");
                }
            }
            if (!settleData.HasTea) {//没有茶，隐藏操作
                freeTea.hide();
            } else {
                if (settleData.IsFreeTea) {
                    freeTea.addClass("cancel");
                } else {
                    freeTea.removeClass("cancel");
                }
            }
            if (!settleData.MemberCard) {
                cancelMembercoupon.hide();
            }
        } else {
            freeMincharge.hide();
            freeServiceFee.hide();
            freeTea.hide();
            cancelMembercoupon.hide();
        }
    }

    /**
 * 取消会员优惠功能
 * */
    function cancelMembercouponFun() {
        cancelMembercoupon.on("click", function () {
            mpos.dialog({
                title: '取消会员优惠提醒',
                text: "确定要操作吗？",
                okButton: "是",
                cancelButton: "否"
            }, function (status) {
                if (status) {
                    hasChange = true;
                    mpos.post(mpos.api.cancelMemberCoupon, {
                        DiningOrderId: settleData.EnterOrder.Order.OrderId
                    }, function () {
                        mpos.alert("操作成功！");
                        reLoadSettleData();
                    });
                }
            });
        });
    }

    /*
    (取消)免最低消费
    */
    function freeMinchargeFun() {
        freeMincharge.on("click", function () {
            var title = $(this).text();
            if ($(this).hasClass("cancel")) {
                title = "取消" + title;
            }
            mpos.dialog({
                title: title,
                text: "确定要操作吗？",
                okButton: "是",
                cancelButton: "否"
            }, function (status) {
                if (status) {
                    hasChange = true;
                    mpos.post(mpos.api.setMinimumChargeFeeStatus, {
                        DiningOrderId: settleData.EnterOrder.Order.OrderId
                    }, function () {
                        reLoadSettleData();
                    });
                }
            });
        });
    }

    /*
    (取消)免茶位
    */
    function freeTeaFun() {
        freeTea.on("click", function () {
            var title = $(this).text();
            if ($(this).hasClass("cancel")) {
                title = "取消" + title;
            }
            mpos.dialog({
                title: title,
                text: "确定要操作吗？",
                okButton: "是",
                cancelButton: "否"
            }, function (status) {
                if (status) {
                    hasChange = true;
                    mpos.post(mpos.api.setTeaStatus, {
                        DiningOrderId: settleData.EnterOrder.Order.OrderId
                    }, function () {
                        reLoadSettleData();
                    });
                }
            });
        });
    }

    /*
    (取消)免服务费
    */
    function freeServiceFeeFun() {
        freeServiceFee.on("click", function () {
            var title = $(this).text();
            if ($(this).hasClass("cancel")) {
                title = "取消" + title;
            }
            mpos.dialog({
                title: title,
                text: "确定要操作吗？",
                okButton: "是",
                cancelButton: "否"
            }, function (status) {
                if (status) {
                    hasChange = true;
                    mpos.post(mpos.api.setServiceFeeStatus, {
                        DiningOrderId: settleData.EnterOrder.Order.OrderId
                    }, function () {
                        reLoadSettleData();
                    });
                }
            });
        });
    }

    /*
    减免
    */
    function reductionAmountFun() {
        reductionAmount.on("click", function () {
            mpos.showDialog(mpos.dialogPage.reductionAmount, {
                settle: settleData
            }, function (status) {
                if (status) {
                    hasChange = true;
                    reLoadSettleData();
                }
            });
        });
    }

    /*
    整单折扣 
    */
    function wholeDiscountFun() {
        wholeDiscount.on("click", function () {
            mpos.showDialog(mpos.dialogPage.wholeDiscount, {
                settle: settleData,
                isRate: false
            }, function (status) {
                if (status) {
                    hasChange = true;
                    reLoadSettleData();
                }
            });
        });
    }

    /*
    比例折扣 
    */
    function rateDiscountFun() {
        rateDiscount.on("click", function () {
            mpos.showDialog(mpos.dialogPage.wholeDiscount, {
                settle: settleData,
                isRate: true
            }, function (status) {
                if (status) {
                    hasChange = true;
                    reLoadSettleData();
                }
            });
        });
    }

    /*
    折扣方案
    */
    function discountSchemeFun() {
        discountScheme.on("click", function () {
            mpos.showDialog(mpos.dialogPage.discountScheme, {
                settle: settleData
            }, function (status) {
                if (status) {
                    hasChange = true;
                    reLoadSettleData();
                }
            });
        });
    }
});
/**
 * 侧边栏
 */
mpos.slidePage = (function () {
    var slidePage;

    $(function () {
        slidePage = $('body>.slide-page').remove();

        slidePage.find(".app-list>li[data-action]").on("click",
            /**
             * 点击事件， 判断跳转界面
             * @param {Event} e
             */
            function (e) {
                var target = e.currentTarget;
                var action = target.getAttribute("data-action");
                if (mpos.getCurrentPage() != action) {
                    //点击酒楼或者快餐时，需要判断当前的模式，如果不同，则处理掉整个界面
                    if (action == mpos.page.home || action == mpos.page.orderDishes) {
                        var type = mpos.localStorage.OrderPropertyType || OrderPropertyType.Normal;
                        if ((action == mpos.page.home && type == OrderPropertyType.Snack)
                            || (action == mpos.page.orderDishes && type == OrderPropertyType.Normal)) {

                            /**
                             * 切换酒楼/快餐模式
                             */
                            var switchOrderProperty = function () {
                                mpos.localStorage.OrderPropertyType = type == OrderPropertyType.Normal ? OrderPropertyType.Snack : OrderPropertyType.Normal;
                                setTimeout(function () {
                                    if (type == OrderPropertyType.Snack) {
                                        mpos.post(mpos.api.clearSnackOrder, function () {
                                            mpos.load(action);
                                            mpos.removeFromStack();
                                        });
                                    } else {
                                        mpos.load(action);
                                        mpos.removeFromStack();
                                    }

                                }, 310);
                                hide();
                            };

                            if (type == OrderPropertyType.Snack) {
                                mpos.dialog({
                                    text: "是否切换到酒楼模式，若有点单切换后将会丢失？",
                                    okButton: "是",
                                    cancelButton: "否"
                                }, function (status) {
                                    if (status) {
                                        switchOrderProperty();
                                    }
                                });
                            } else {
                                switchOrderProperty();
                            }


                            return;
                        }
                    }
                    setTimeout(function () {
                        if (mpos.getStackPages().indexOf(action) == -1) {
                            mpos.load(action);
                        } else {
                            mpos.back(action);
                        }
                    }, 310);
                }
                hide();
            }
        );
        //slidePage.find(".app-list>li.logout").on("click",
        /**
         * 退出登录
         */
        //function () {
        //   _.delay(mpos.logout, 310);
        //  hide();
        //});
    });

    return {
        /**
         * 显示边栏
         */
        show: show,
        /**
         * 隐藏边栏
         */
        hide: hide
    };

    /**
     * 显示边栏
     */
    function show() {
        setUserInfo();
        //noinspection JSUnresolvedFunction
        slidePage.appendTo('body').addClass("show");
        var curPage = $(mpos.getCurrentPageDom());
        curPage.addClass("slide-show");
        //noinspection JSUnresolvedFunction
        $("<div class='slide-mask'>").tap(function (e) {
            hide();
            e.stopPropagation();
        }).appendTo(curPage);
        //必须要settimeout
        setTimeout(function () {
            curPage.addClass("animation");
        }, 13);
    }

    /**
     * 隐藏边栏
     */
    function hide() {
        var curPage = $(mpos.getCurrentPageDom());
        curPage.removeClass("animation");
        setTimeout(function () {
            slidePage.removeClass("show").remove();
            curPage.removeClass("slide-show");
            curPage.find(".slide-mask").remove();
        }, 300);
    }

    /**
     * 设置用户信息
     */
    function setUserInfo() {
        slidePage.find(".username").text(mpos.currentUser.LoginName + "-" + mpos.currentUser.UserName);
        slidePage.find(".shopName").text(mpos.shopConfig.ShopName);
        var logo = mpos.shopConfig.MposLogo;
        if (logo == undefined || logo.length == 0) {
            logo = "img/cebianlan_touxiang.png";
        }
        slidePage.find(".shop-logo>img").attr("src", logo);
    }

})();

(function () {
    var tableOperationPage = null;
    var isOpen = false;  // 定义标记，记录餐台操作是否展开

    //初始化时拿到page
    $(function () {
        tableOperationPage = $("body>.table-operation-page").remove();
        tableOperationPage.find("li").each(function (index) {
            $(this).data("op", TableOperationType[index]);
        });
    });

    /**
     * 按给定原则显示餐台操作界面；点击后根据callback调用事件
     * @param {Object} options 每个餐台操作的可见及操作
     * @param {Function} callback callback for click
     */
    function show(options, callback) {
        if (tableOperationPage == null)
            return;
        if (typeof options != 'object') {
            throw TypeError("table operation options must be a object. got a " + options);
        }
        if (typeof callback != 'function') {
            throw TypeError("table operation options must be a function. got a " + callback);
        }

        var page = tableOperationPage.clone().on("click", function (e) {
            hide();
            e.stopPropagation();
        });
        page.find('section').on("click", function (e) {
            e.stopPropagation();
        });

        page.find(".operation-close").on("click", function (e) {
            hide();
            e.stopPropagation();
        });
        page.addClass("show");
        _.delay(function () {
            page.addClass("animation");
        }, 50);

        page.find("li").each(function (index) {
            var key = $(this).data("op");
            if (key == TableOperationType.PreBilledOrder) {
                $(this).text(options[key] ? "预结" : "撤销预结");
            } else if (key == TableOperationType.TakeAllDish) {
                $(this).text("整单" + mpos.shopConfig.TakeCalledDescption);
            } else if (key == TableOperationType.TakeTypeDish) {
                $(this).text("类别" + mpos.shopConfig.TakeCalledDescption);
            }
            if (options[key] || key == TableOperationType.PreBilledOrder) {
                page.find("li[data-op=" + key + "]").one("click", function (e) {
                    var target = $(e.target);
                    if (target.hasClass("disabled"))
                        return;
                    callback({
                        op: target.data("op")
                    });
                    hide();
                    e.stopPropagation();
                });
            } else {
                if (key == TableOperationType.PayToOrderData) {
                    $(this).hide()
                } else {
                    $(this).addClass("disabled");
                }
            }
        });

        setTimeout(function () {
            page.appendTo("body");
        },0);
    }

    /**
     * 隐藏餐台操作界面
     */
    function hide() {
        var page = $("body>.table-operation-page");
        if (page.length == 0)
            return;
        page.removeClass("animation");
        _.delay(function () {
            page.removeClass("show").remove();
        }, 200);
    }

    /**
     * 餐台操作
     * @type {{show: show, hide: hide, isShow: boolean}}
     */
    mpos.tableOperationPage = {
        /**
         * 按给定原则显示餐台操作界面；点击后根据callback调用事件
         */
        show: show,
        /**
         * 隐藏餐台操作界面
         */
        hide: hide,
        /**
         * 是否显示了餐台操作界面
         * @returns {boolean}
         */
        get isShow() {
            return $("body>.table-operation-page").length > 0;
        }
    };

})();
/*
 占用订单操作
 * */
mpos.controller(mpos.page.tableTaken, function (page, obj) {
    var fmt = "yy-MM-dd HH:mm:ss";
    var settleData = [];
    var $pageDom = $(page);
    var $tableName = $pageDom.find(".table-name").remove();
    var $tableInfo = $pageDom.find(".table-info").remove();
    var $dishItem = $pageDom.find(".dish-item").remove();
    var $dishList = $pageDom.find(".table-dish-list").remove();
    var $consumptionAmount = $pageDom.find(".consumption-amount").remove();
    var firstOrderStatus = 0;

    //返回事件
    function backToPrev() {
        mpos.back(mpos.page.home); //返回到首页
    }

    this.onBackKeyDown = backToPrev;
    $pageDom.find("#goBack").on("click", backToPrev);

    /**
     * 显示金额及菜品
     * @param {Object} data
     * @param {Number} [status]
     * @param {XMLHttpRequest} [xhr]
     */
    function loadSettleCallBak(data, status, xhr) {
        settleData = data;
        if (firstOrderStatus == 0) {
            firstOrderStatus = settleData.EnterOrder.Order.OrderStatus;
        }
        //增加整单ID
        $pageDom.data("whole_order_id", settleData.EnterOrder.Order.WholeBillId);
        var amountDsc = "";
        var dishesDsc = "";

        /*****循环输出餐台*****/
        // var dishAndOtherTable = "";

        $pageDom.find(".app-content").empty();
        var fragment = $(document.createDocumentFragment());

        var tableName = $tableName.clone();
        var tableInfo = $tableInfo.clone();
        var dishList = $dishList.clone();


        /****第一个餐台输入开始****/
        //餐台
        tableName.find(".name").text(settleData.EnterOrder.Table.TableName + (settleData.EnterOrder.Order.IsMain == 1 ? "(主)" : ""));
        //会员信息
        if (settleData.MemberCard != null) {
            $("<div class='member-name' />").text("会员：" + settleData.MemberCard.MemberName).appendTo(tableName);
        }

        //输出开台信息
        var openTableInfo = findOpenTableInfo(settleData.EnterOrder.Order.OrderId);
        var orderTimeStr = (new Date(settleData.EnterOrder.Order.BeginTime)).formatDate(fmt);
        // 总时长
        if (settleData.EnterOrder.Order.TotalTime) {
          orderTimeStr += "("+settleData.EnterOrder.Order.TotalTime+")";
        }

        tableInfo.find(".table-time").text("开台时间：" + orderTimeStr);
        tableName.find(".table-people").text("人数：" + settleData.EnterOrder.Table.PeopleNum); 
        tableInfo.find(".table-user").text("开台人：" + (openTableInfo == null ? "" : openTableInfo.OpenTableUser));
        tableInfo.find(".table-businesstimespan").text("市别：" + (openTableInfo == null ? "" : openTableInfo.BusinessTimeSpanName));

        //输入进入餐台的菜品
        $.each(settleData.EnterOrder.Dishes, function (idx, item) {
            var dishItem = $dishItem.clone();
            dishItem.find('label.dish-selected').data("dishId", item.OrderDishId);
            dishItem.find(".dish-name").html(mpos.getDishTag(item) + item.DishName);
            dishItem.find(".dish-num").text("x" + item.DishNum);
            if (item.ReturnOrderDishId != 0) {
                dishItem.find(".dish-name").addClass('disabled');
            }
            // 显示划菜
            if (item.IsCrossDish) {
              dishItem.find(".dish-name").addClass('cross-dish')
            }
            if (item.DishProperty == OrderDishProperty.PackageDishChild) {
                dishItem.find(".dish-name").addClass('disabled');
                dishItem.find(".dish-amount").text("-");
            } else if (item.DishProperty == OrderDishProperty.MultiDishChild) {
                // 一品多吃子菜
                dishItem.find(".dish-name").addClass('disabled');
                dishItem.find(".dish-amount").text("-");
            } else {
                dishItem.find(".dish-amount").text(mpos.formatPrice(item.DishSaleAmount));
            }

            var cookies = "";
            var dishUnit = item.DishPortions || item.DishUnit;
            if (item.Discount < 100) {
                dishUnit += "/" + parseFloat((item.Discount / 10).toFixed(2)) + "折";
            }
            $.each(item.DishRequestList, function (idx, re) {
                cookies += re.RequestName + (Math.abs(re.RequestNum) == 1 ? "" : ("*" + re.RequestNum)) + "、"; //做法
            });

            if (cookies.length > 0) {
                dishItem.find(".dish-cookies").text(dishUnit + "/" + cookies.substr(0, cookies.length - 1));
            } else {
                dishItem.find(".dish-cookies").text(dishUnit);
            }
            dishItem.find(".order-date").text(item.OrderDate);
            dishItem.find(".operate-name").text(item.OperateName || '');

            // 菜品状态
            if (item.KitchenRemarkDesc) {
                var statusBg = '';
                if ((item.KitchenRemark & KitchenRemarkEnum.TakeOut) == KitchenRemarkEnum.TakeOut) {
                  // 起菜
                } else if ((item.KitchenRemark & KitchenRemarkEnum.QuickDish) == KitchenRemarkEnum.QuickDish){
                  // 催菜
                  statusBg = 'dish-status-red-bg';
                } else if ((item.KitchenRemark & KitchenRemarkEnum.Called) == KitchenRemarkEnum.Called) {
                  // 等叫
                  statusBg = 'dish-status-orange-bg';
                }
                var statusList = dishItem.find(".dish-status-list");
                var $dishStatus = statusList.find(".dish-status").remove();
                var descList = item.KitchenRemarkDesc.split('、');

                for(var i=0;i<descList.length;i++) {
                  var statusNode = $dishStatus.clone();
                  statusNode.text(descList[i]);
                  statusNode.addClass('dish-status-show').addClass(statusBg);
                  statusList.append(statusNode);
                }
            }

            dishList.append(dishItem);
        });

        fragment.append(tableName);
        fragment.append(tableInfo);
        fragment.append(dishList);

        /****第一个餐台输入End****/

        //输出其它餐台及菜品
        $.each(settleData.Orders, function (idx, order) {
            if (order.Order.OrderId == settleData.EnterOrder.Order.OrderId)
                return;
            tableInfo = $tableInfo.clone();
            tableName = $tableName.clone();
            dishList = $dishList.clone();

            //餐台名称
            tableName.find(".name").text(order.Table.TableName + (order.Order.IsMain == 1 ? "(主)" : ""));

            //输出开台信息
            var openTableInfo = findOpenTableInfo(order.Order.OrderId);
            var orderTimeStr = (new Date(order.Order.BeginTime)).formatDate(fmt);
            // 总时长
            if (order.Order.TotalTime) {
              orderTimeStr += "("+order.Order.TotalTime+")";
            }
            tableInfo.find(".table-time").text("开台时间：" + orderTimeStr);
            tableInfo.find(".table-people").text("人数：" + order.Table.PeopleNum);
            tableInfo.find(".table-user").text("开台人：" + (openTableInfo == null ? "" : openTableInfo.OpenTableUser));
            tableInfo.find(".table-businesstimespan").text("市别：" + (openTableInfo == null ? "" : openTableInfo.BusinessTimeSpanName));

            //输出菜品
            $.each(order.Dishes, function (index, item) {
                var dishItem = $dishItem.clone();
                dishItem.find('label.dish-selected').data("dishId", item.OrderDishId);
                dishItem.find(".dish-name").html(mpos.getDishTag(item) + item.DishName);
                dishItem.find(".dish-num").text("x" + item.DishNum);
                if (item.ReturnOrderDishId != 0) {
                    dishItem.find(".dish-name").addClass('disabled');
                }
                // 显示划菜
                if (item.IsCrossDish) {
                  dishItem.find(".dish-name").addClass('cross-dish')
                }
                if (item.DishProperty == OrderDishProperty.PackageDishChild) {
                    dishItem.find(".dish-name").addClass('disabled');
                    dishItem.find(".dish-amount").text("-");
                } else if (item.DishProperty == OrderDishProperty.MultiDishChild) {
                    // 一品多吃子菜
                    dishItem.find(".dish-name").addClass('disabled');
                    dishItem.find(".dish-amount").text("-");
                } else {
                    dishItem.find(".dish-amount").text(mpos.formatPrice(item.DishSaleAmount));
                }

                var cookies = "";
                var dishUnit = item.DishPortions || item.DishUnit;
                if (item.Discount < 100) {
                    dishUnit += "/" + parseFloat((item.Discount / 10).toFixed(2)) + "折";
                }
                $.each(item.DishRequestList, function (idx, re) {
                    cookies += re.RequestName + (Math.abs(re.RequestNum) == 1 ? "" : ("*" + re.RequestNum)) + "、"; //做法
                });
                if (cookies.length > 0) {
                    dishItem.find(".dish-cookies").text(dishUnit + "/" + cookies.substr(0, cookies.length - 1));
                } else {
                    dishItem.find(".dish-cookies").text(dishUnit);
                }
                dishList.append(dishItem);

            });

            fragment.append(tableName);
            fragment.append(tableInfo);
            fragment.append(dishList);
        });


        /*****循环输出餐台结束*****/

        /*****事件处理******/
        //菜品点击事件
        fragment.find("label.dish-selected").on("click", function (e) {
            var listItem = $(this).parents('li');
            if (mpos.Components.OrderedDishOperation.has(listItem)) {
                mpos.Components.OrderedDishOperation.remove(listItem);
                return;
            }

            var orderDishId = $(this).data("dishId");
            var dish = findDishData(orderDishId);
            var isSub = false;
            if (dish == null)
                return;
            //套餐子菜跳过
            if (dish.DishProperty == OrderDishProperty.PackageDishChild) {
              isSub = true;
            }
            //一品多吃子菜跳过
            if (dish.DishProperty == OrderDishProperty.MultiDishChild) {
                return;
            }

            //退完的菜不允许操作
            //if (dish.RealDishNum <= 0) {
            //    return;
            //}

            //只对非退的菜操作
            if (dish.ReturnOrderDishId != 0)
                return;

            //预结不能操作
            if (settleData.EnterOrder.Order.OrderStatus == 2) {
                mpos.alert("已预结，不能操作");
                return;
            }

            /**
             * @type DOOptions
             */
            var options = {
                parent: $(this).parents('li'),
                callback: function (operation) {
                  // 操作菜品时，检测桌台是否被锁
                  fetchCheckTableLockedForOrderDish(function() {
                    // 执行菜品操作
                    dishOperationCallback(operation, dish);
                  });
                },
                giveDish: -1,
                discountDish: false,
                returnDish: false,
                changeDishPrice: true,
                qicai: true,
                cuicai: true,
                huacai: true,
            };
            if (dish.IsFreeDish == IsFreeDishType.None) {
                if (dish.TeTeaType != OrderDishTeaType.Tea && dish.RealDishNum > 0) {
                    options.giveDish = 1;
                }
                if (dish.RealDishNum > 0) {
                    options.discountDish = true;
                }
            } else if (dish.IsFreeDish == IsFreeDishType.Present) {
                if (dish.TeTeaType != OrderDishTeaType.Tea) {
                    options.giveDish = 0;
                }
                //options.changeDishPrice = false; //赠送后不能改价
            }
            if (dish.IsFreeDish == IsFreeDishType.None && dish.ReturnOrderDishId == 0 && dish.RealDishNum > 0) {
                options.returnDish = true;
            }
            if (dish.RealDishNum <= 0) { //退完了的不显示
                options.giveDish = -1;
                options.qicai = false;
                options.cuicai = false;
                options.huacai = false;
            }

            if (dish.IsFreeDish == IsFreeDishType.TicketExchange) { //兑换的不能改价
                options.changeDishPrice = false;
            }
            // 套餐子商品只能显示催菜
            if (isSub) {
              options.giveDish = -1;
              options.discountDish = false;
              options.returnDish = false;
              options.changeDishPrice = false;
              options.qicai = dish.RealDishNum <= 0 ? false : true;
              options.cuicai = dish.RealDishNum <= 0 ? false : true;
              options.huacai = dish.RealDishNum <= 0 ? false : true;
            }
            // 划菜不能进行起菜、催菜
            if (dish.IsCrossDish) {
              options.qicai = false;
              options.cuicai = false;
              options.huacai = false;
            }

            new mpos.Components.OrderedDishOperation(options);
        });

        //显示金额信息
        var consumptionAmount = $consumptionAmount.clone();

        //得到订单金额合集
        $.each(settleData.AmountDesc, function (index, item) { //获取订单金额合集
            amountDsc += "<li>" + item.AmountName + "<span>" + mpos.shopConfig.AmountSymbol + item.Amount + "</span></li>";
        });
        //显示到html中
        var content = consumptionAmount.find(".content").empty();
        content.append(dishesDsc);
        content.append(amountDsc);
        content.append("<li class='amount-total sep-line'>应收金额<span>" + mpos.formatPrice(data.TotalPayableAmount) + "</span></li>");
        content.append("<li class='amount-total'>已收金额<span>" + mpos.formatPrice(data.ReceivedAmount) + "</span></li>");
        content.append("<li class='amount-total'>待收金额<span>" + mpos.formatPrice(data.TotalObligationAmount) + "</span></li>");

        fragment.append(consumptionAmount);

        $pageDom.find(".app-content").append(fragment);
    }

    /**
     * 执行菜品按钮操作
     * */
    function dishOperationCallback (operation, dish) {
      switch (operation.operationType) {
        case 1: //赠送
          mpos.giveDish(dish, refreshSettleData);
          break;
        case 2: //退菜
          mpos.returndish(dish, refreshSettleData);
          break;
        case 3://折扣
          mpos.discountDish(dish, refreshSettleData);
          break;
        case 4://取消赠送
          mpos.cancelGiveDish(dish, refreshSettleData);
          break;
        case 5://修改单价
          mpos.changeDishPrice(dish, refreshSettleData);
          break;
        case 6://起菜
          mpos.qicai(dish, settleData.EnterOrder.Order.OrderId, refreshSettleData);
          break;
        case 7://催菜
          mpos.cuicai(dish, settleData.EnterOrder.Order.OrderId, refreshSettleData);
          break;
        case 8://划菜
          mpos.huacai(dish, settleData.EnterOrder.Order.OrderId, refreshSettleData);
          break;
        default:
          break;
      }
    }

    /**
     * 重新请求并刷新界面数据
     * */
    function refreshSettleData () {
      mpos.getSettleInfo({
        OrderId: settleData.EnterOrder.Order.OrderId,
      }, loadSettleCallBak);
    }

    /**
     * 检测订单是否被锁
     * */
    function fetchCheckTableLockedForOrderDish (callback) {
      var wholeBillId = settleData.EnterOrder.Order.WholeBillId;
      mpos.post(mpos.api.checkTableLockedForOrderDish, {
        WholeOrderId: wholeBillId
      }, function (err) {
        if (err.length > 0) {
          alert(err);
        } else {
          // 检测结账是否锁单
          fetchCheckTableLockedForSettle(callback);
        }
      }, {
        hideLoading: true,
        error: function () {
        },
        blFailed: function () {
        }
      });
    }

    /**
     * 检测订单结账界面是否被支付锁单
     * */
    function fetchCheckTableLockedForSettle (callback) {
      var wholeBillId = settleData.EnterOrder.Order.WholeBillId;
      mpos.post(mpos.api.checkTableLockedForSettle, {
        WholeOrderId: wholeBillId
      }, function (err) {
        if (err.length > 0) {
          alert(err);
        } else {
          callback && callback();
        }
      }, {
        hideLoading: true,
        error: function () {
        },
        blFailed: function () {
        }
      });
    }

    /*
     获取一个菜品
     */
    function findDishData(orderDishId) {
        for (var j = 0; j < settleData.Orders.length; j++) {
            for (var i = 0; i < settleData.Orders[j].Dishes.length; i++) {
                if (settleData.Orders[j].Dishes[i].OrderDishId == orderDishId) {
                    return settleData.Orders[j].Dishes[i];
                }
            }
        }
        return null;
    }

    /*
     获取开台信息
     * */
    function findOpenTableInfo(orderId) {
        if (settleData.OpenTableInfos) {
            for (var i = 0; i < settleData.OpenTableInfos.length; i++) {
                if (settleData.OpenTableInfos[i].OrderId == orderId) {
                    return settleData.OpenTableInfos[i];
                }
            }
        }
        return null;
    }


    if (obj.settle == undefined || obj.settle == null) {
        var orderId = obj.OrderId;
        mpos.getSettleInfo(orderId, loadSettleCallBak, {
            blFailed: function (data) {
                mpos.alert(data.data);
                mpos.back();
            }
        });
    } else {
        loadSettleCallBak(obj.settle);
    }

    /**
     * 加菜
     */
    $pageDom.find(".app-footer .add-btn").on("click", function (e) { 
      if (settleData && settleData.EnterOrder) {
        var orderIds = [settleData.EnterOrder.Order.OrderId];
        mpos.post(mpos.api.loadOrderDishDatas, {
            OrderIds: JSON.stringify(orderIds),
            BookOrderId: 0,
            NeedClearOrderDish: true,
            EnabledMutilOrderDish: mpos.localStorage.enableMutilOrderDish == true ? 1 : 2
        }, function (data) {
            mpos.load(mpos.page.orderDishes, {
                OrderIds: orderIds,
                DishData: data,
            });
            mpos.openedPayTable = true;
        });
      } else {
        mpos.alert('订单信息丢失，请返回重试')
      } 
    });

    /**
     * 付款
     */
    $pageDom.find(".app-footer .pay-btn").on("click", function (e) { 
      console.log(settleData, settleData.EnterOrder.Order)
      if (settleData && settleData.EnterOrder) {
        mpos.jumpToSettlePage(settleData.EnterOrder.Order.OrderId, "home");
      } else {
        mpos.alert('订单信息丢失，请返回重试')
      } 
    });

});

/**
 * 修改台头
 */
mpos.dialogController(mpos.dialogPage.takeTypeDish, function (page, data) {
    var orderId = data.OrderId;
    var checkedType = 0;
    var $tab = $(page).find(".tab");
    var $shopList = $(page).find(".shopList");
    var shopList = [];
    var DishTypeIds = new Array();
    var type = ['SmallType', 'BigType']
    init();
    $tab.find("span").on("click", function () {
        $tab.find("span").removeClass('active');
        $(this).addClass('active');
        $shopList.html(''); DishTypeIds = [];
        checkedType = $(this).index();
        shopType();
    });
    $(page).find(".app-submit").on("click", function (e) {
        var operationType = $(e.currentTarget).data("operation");
        if (operationType == 2) {
            mpos.dialog.close({
                Status: false
            });
        } else {
            var printSigleBill = mpos.printSigleBill();
            var printTotalBill = mpos.printTotalBill();
            mpos.post(mpos.api.takeOrderDishByDishType, {
                OrderId: orderId,
                DishTypeIds: JSON.stringify(DishTypeIds),
                PrintTotalBill: printTotalBill == 1,
                PrintSigleBill: printSigleBill == 1,
            }, function (r) {
                //本地打印总单
                if (r.TotalBillGrids != null && Array.isArray(r.TotalBillGrids)) {
                    $.each(r.TotalBillGrids, function (index, item) {
                        var printData = mpos.addPrintEmptyLine(item);
                        mpos.deviceFactory.printTicket(printData, null, function (err) {
                            //打印
                            mpos.alert(err);
                        });
                    })
                }
                //本地打印分单
                if (r.SigleBillGrids != null && Array.isArray(r.SigleBillGrids)) {
                    $.each(r.SigleBillGrids, function (index, item) {
                        var printData = mpos.addPrintEmptyLine(item);
                        mpos.deviceFactory.printTicket(printData, null, function (err) {
                            //打印
                            mpos.alert(err);
                        });
                    })
                }
                mpos.alert("类别" + mpos.shopConfig.TakeCalledDescption + " 操作成功");
                mpos.dialog.close({
                    Status: true,
                });
            });

        }
    })
    function init() {
        mpos.post(mpos.api.getDishTypeTakeUpData, {
            DiningOrderId: orderId,
        }, function (data) {
            shopList = data;
            console.log(shopList, data);
            shopType();
        });
    }
    function shopType() {
        //console.log(orderId, shopList, type[checkedType]);
        var list = shopList[type[checkedType]];
        //console.log(list);

        if (checkedType == 0) {
            for (var index = 0; index < list.length; index++) {
                $shopList.append('<div class="flex-between shop" id="' + list[index].TypeId + '"><span>' + list[index].Name + '</span><span>' + list[index].Num + '份商品</span></div>');
            }
        } else {
            for (var index = 0; index < list.length; index++) {
                $shopList.append('<div class="flex-between shop" id="' + list[index].TypeId + '"><span>' + list[index].Name + '</span><span>' + list[index].Num + '份商品</span></div>');
            }
        }
        $shopList.find(".shop").on("click", function () {
            $(this).addClass('active');
            var id = $(this).attr("id");
            if (DishTypeIds.indexOf(id) == -1) {
                DishTypeIds.push(id);
            } else {
                $(this).removeClass('active');
                DishTypeIds.splice(DishTypeIds.indexOf(id), 1)
            }

        });
    }
});

/*
菜品称重
*/
mpos.controller(mpos.page.weightdishes, function (page, data) {
    var me = this;
    var $page = $(page);

    var orderId = data.OrderId;
    var wholeBillId = data.wholeBillId;
    var dishes = data.Dishes;
    var $weightDishItem = $page.find(".weight-dish-item").remove();
    var $weightDishList = $page.find(".weight-dish-list");
    $page.data("whole_order_id", wholeBillId);

    //返回事件
    function backToPrev() {
        me.reply(false);
    }
    this.onBackKeyDown = backToPrev;
    $page.find("#goBack").on("click", backToPrev);

    //加载数据

    $weightDishList.empty();
    $.each(dishes, function (idx, item) {
        var weightDishItem = $weightDishItem.clone();
        weightDishItem.data("order_dish_id", item.Dish.OrderDishId);
        weightDishItem.find(".dish-name").text(item.Dish.DishName);
        weightDishItem.find(".table-name").text(item.TableName);
        weightDishItem.find("input[name='dishNum']").val(item.Dish.DishNum);
        weightDishItem.appendTo($weightDishList);
    });
    mpos.checkInputValue($page.find("input[name='dishNum']"), InputType.DishNum);
    $.selectOnFocus(page);

    /**
     * 称重确认
     */
    $page.find(".submit").on("click", function () {
        var dishData = [];
        var hasErrorDishNum = false;
        $.each($page.find(".weight-dish-item"), function (idx, item) {
            var orderDishId = $(item).data("order_dish_id");
            var dishNum = Number($(item).find("input[name='dishNum']").val());
            if (dishNum <= 0) {
                hasErrorDishNum = true;
            }
            dishData.push({
                OrderDishId: orderDishId,
                DishNum: dishNum
            });
        });
        if (dishData.length == 0) {
            mpos.alert("没有需要称重的菜品");
            return;
        }
        if (hasErrorDishNum) {
            mpos.alert("菜品数量不能为0");
            return;
        }

        //确认称重
        mpos.post(mpos.api.confirmWeightDishes, {
            ConfirmData: JSON.stringify(dishData)
        }, function (result) {
            me.reply(true);
        });
    });
});

(function(mpos) {
    var app = {
        // Application Constructor
        initialize: function() {
            this.bindEvents();
        },
        bindEvents: function() {
            document.addEventListener('deviceready', this.onDeviceReady, false);
        },
        onDeviceReady: function() {
            mpos.log("onDeviceReady.");

            if (mpos.localStorage.isDisableAnimation) {
                mpos.disablePageAnimation(true);
            }

            //判断是否为快餐模式
            if (mpos.localStorage.OrderPropertyType == OrderPropertyType.Snack)
                mpos.initialize(mpos.page.orderDishes);
            else
                mpos.initialize(mpos.page.home);
            
        }
    };

    app.initialize();
})(mpos);

