$(function () {

    openWebSocket();
});



let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        goodsDetail:false,
        title: null,
        goods:{},
        sysNotice: {},
        goodsList:[],
        orderInfo:[],
        userInfo:{},
        prodBarcode:null,
        sessionId:null,
        pickUpCodeList:[],
        goodsDetailList:[],
        orderEntity:{},
        orderProcessRecord:{},
        currentOrderNo:null,
        index:0,
        max:0,
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]
        },
        q: {
            name: ''
        }
    },
    methods: {
        query: function () {

            var thisGoods = {};
            $.get("../goods/details/"+vm.prodBarcode, function (r) {
                if (r.code == 0) {

                    vm.goodsDetail = true;
                    thisGoods.name = r.goodsDetails.name;
                    thisGoods.primaryPicUrl = r.goodsDetails.primaryPicUrl;
                    thisGoods.retailPrice = r.goodsDetails.retailPrice;
                    thisGoods.specification = r.goodsDetails.specification;
                    thisGoods.prodBarcode = r.goodsDetails.prodBarcode;
                    thisGoods.goodsDesc = r.goodsDetails.goodsDesc;
                    thisGoods.sellVolume = 1;

                    if(!vm.goodsList[vm.index]){
                        vm.index = vm.max;
                    }

                    thisGoods.id = vm.index++;
                    vm.max++;

                    var data = Object.assign({}, JSON.parse(JSON.stringify(thisGoods)));
                    vm.goodsList.push(data);
                    vm.goods = thisGoods;

                } else {
                    alert(r.msg);
                }
            });

        },
        add:function(value){
            // 增加数量
            var goods = this.goodsList[value];
            goods.sellVolume = goods.sellVolume + 1;
        },
        minus:function(value){
            // 减少数量
            var goods = this.goodsList[value];
            if(goods.sellVolume === 1){
                alert("数量至少为1个");
                return ;
            }
            goods.sellVolume = goods.sellVolume - 1;
        },
        deleteItem:function(value){
            // 删除这条记录
            this.goodsList.splice(value,1,"");
            this.index = value;

        },
        clearGoodsList:function(){
            this.goodsList = [];
        },
        submitOrder:function(){
            $('#payCode').unbind('keydown').keydown(function(event){});
            $(".form-group input[type=text]").each(function(){
                this.value = '';
            })
            var saler = "张三";
            var saleNo = "001";

            var param = {'userInfo':vm.userInfo,'payCode':this.$refs.payCode.currentValue,'goodsList':vm.goodsList,'sessionId':vm.sessionId};
            this.$refs.payCode.currentValue = '';
            $.ajax({
                type: "POST",
                url: "../order/orderConfirm",
                contentType: "application/json",
                data: JSON.stringify(param),
                success: function (r) {
                    if (r.code == 0) {
                        if (r.resultObj != null) {

                            // 打印取货码小票
                            var content = getPrintContent(r.resultObj);
                            printArea(content);
                            vm.goodsList = [];
                            // alert('打印小票完成');
                        }else{
                            // alert("打印小票失败");
                        }
                    } else {
                        alert(r.msg);
                    }
                }
            });

        },
        submitCustomInfo:function(){
            this.userInfo.customName = this.$refs.customName.value;
            this.userInfo.customIDCard = this.$refs.customIDCard.value;
            this.userInfo.customPhone = this.$refs.customPhone.value;




            $("#Send").attr("data-dismiss","modal");
            $('#payModal').modal('show');
            $("#payCode").keydown(function(e){
                if(e.keyCode==13){
                    $("#submitOrder").click();
                    event.preventDefault();
                }
            });


            $('body').on('hidden.bs.modal', '.modal', function () {
                $(this).removeData();
            });



        },
        queryOrderDetail:function(orderSn){
            $.get("../order/orderDetail/"+orderSn, function (r) {
                if (r.code == 0) {
                    vm.orderProcessRecord = r.resultObj.orderProcessRecordEntity;
                    vm.orderEntity = r.resultObj.orderEntity;
                    vm.goodsDetailList = r.resultObj.goodsList;
                    vm.currentOrderNo = r.resultObj.orderEntity.id;
                }
            });
        },
        verification:function(){

            confirm('确认核销吗？', function () {
                $.ajax({
                    type: "POST",
                    url: "../order/printMsg",
                    contentType: "application/json",
                    data: JSON.stringify(vm.currentOrderNo),
                    success: function (r) {
                        if (r.ticket != null) {
                            // printArea(r.ticket);
                            var content = getPrintContent(r.ticket);
                            printArea(content);
                            alert('打印小票完成');
                        }else{
                            alert("打印小票失败");
                        }
                    }
                });
            })
        },
        refundOrder:function(){
            console.log("退款的订单号："+vm.currentOrderNo);
        },
        retrySendOrder:function(){
            console.log("重推的订单号："+vm.currentOrderNo);
        },
        getInfo: function (id) {
            $.get("../sys/notice/info/" + id, function (r) {
                vm.sysNotice = r.sysNotice;
            });
        },
        reload: function (event) {
            vm.showList = false;
            vm.showViewList = true;
            vm.showSaveSupplierGoods = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    storeId: vm.q.storeId,
                    goodsName: vm.q.goodsName,
                    goodsSn: vm.q.goodsSn,
                    productSn: vm.q.productSn, category: vm.q.category, categoryTwo: vm.q.categoryTwo, goodsBizType:vm.q.goodsBizType,
                    thirdPartyMerchCode: vm.q.thirdPartyMerchCode
                },
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        logout: function () {
            confirm('注：您确定要安全退出本次登录吗？', function () {
                dialogLoading(true);
                setTimeout(function () {
                    toUrl('../logout?_' + $.now());
                }, 500);
            });
        }
    }
});

function getPrintContent(ticket) {
    var content = "<div style=\"width: 250px;font-family: 微软雅黑;font-size: 8px;\">";
    //小票头
    content += "<div style=\"text-align: center;width: 100%;font-weight:bold;font-size: 13px;\">";
    content += ticket.shopName
    content += "</div>";
    content += "<div style=\"width: 100%;overflow:hidden;white-space: nowrap;\">--------------------------------------------------</div>";
    content += "<div style=\"width: 100%;\">";
    content += "收银机号:" + ticket.salesNo;
    content += "</div>";
    content += "<div style=\"width: 100%;\">";
    content += "收银员:" + ticket.userName;
    content += "</div>";
    content += "<div style=\"width: 100%;\">";
    content += "取货码:" + ticket.code;
    content += "</div>";

    content += "<div style=\"width: 100%;\">";
    content += "该取货单号只有当天有效"
    content += "</div>";
    content += "<div style=\"width: 100%;\">";
    content += "订单编号:" + ticket.orderNo;
    content += "</div>";
    content += "<div style=\"width: 100%;\">";
    content += "打印日期:" + ticket.time;
    content += "</div>";

    return content;
}


var printAreaCount = 0;
function printArea(content) {
    var idPrefix = "printArea_";
    removePrintArea(idPrefix + printAreaCount);
    printAreaCount++;
    var iframeId = idPrefix + printAreaCount;
    var iframeStyle = 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;';
    iframe = document.createElement('IFRAME');
    $(iframe).attr({
        style: iframeStyle,
        id: iframeId
    });
    document.body.appendChild(iframe);
    var doc = iframe.contentWindow.document;
    doc.open();
    //$(document).find("link").filter(function () {
    //return $(this).attr("rel").toLowerCase() == "stylesheet";
    //}).each(
    //function () {
    //doc.write('<link type="text/css" rel="stylesheet" href="'
    //+ $(this).attr("href") + '" >');
    //});
    doc.write('<div class="">' + content
        + '</div>');
    doc.close();
    var frameWindow = iframe.contentWindow;
    frameWindow.close();
    frameWindow.focus();
    frameWindow.print();
    frameWindow.print();
}
var removePrintArea = function (id) {
    $("iframe#" + id).remove();
};


var webSocket;

function openWebSocket() {
    if ("WebSocket" in window) {
        console.log("当前浏览器支持WebSocket");

        //实现化WebSocket对象
        //指定要连接的服务器地址与端口建立连接
        //注意ws、wss使用不同的端口。我使用自签名的证书测试，
        //无法使用wss，浏览器打开WebSocket时报错
        //ws对应http、wss对应https。
        webSocket = new WebSocket("ws://localhost:8080/ws/server/{10}");
        if (webSocket.readyState === webSocket.CONNECTING) {
            console.log('1.连接正在打开......');
        }

        // ---------- WebSocket 对象注册事件 ----------

        //连接打开事件
        webSocket.onopen = function () {
            if (webSocket.readyState === webSocket.OPEN) {
                console.log('2.连接已打开');
            }
            console.log('2.向服务端发送测试消息......');
            // webSocket.send("2.client发测试消息:Client sent test msg。");
        };
        //收到消息事件
        webSocket.onmessage = function (msg) {

            var data = Object.assign({}, JSON.parse(msg.data));
            vm.sessionId = data.sessionId;
            vm.pickUpCodeList = [];
            vm.pickUpCodeList = vm.pickUpCodeList.concat(data.pickUpCodeList);
            // webSocket.send("2.client发测试消息:Client sent test msg。");
        };
        //连接关闭事件
        webSocket.onclose = function () {
            if (!webSocket) {
                console.log('4.Socket连接已关闭');
            }
        };
        //发生了错误事件
        webSocket.onerror = function () {
            console.log("5.Socket发生了错误");
        }
    } else {
        console.log("当前浏览器不支持WebSocket");
        return false;
    }
}

function sendMessage() {
    if(webSocket && webSocket.readyState === webSocket.OPEN) {
        webSocket.send("client manual send message.")
    } else {
        console.log('6.未创建WebSocket连接');
    }
}

function closeWebSocket() {
    if (webSocket != null) {
        webSocket.close();
        webSocket = null;
    }
    console.log("关闭WebSocket");
}

//窗口关闭时，关闭连接
window.unload = function () {
    webSocket.close();
};
