$(function () {
    let shippingStatus = getQueryString("shippingStatus");
    let payStatus = getQueryString("payStatus");
    let orderStatus = getQueryString("orderStatus");
    let merchOrderSn = getQueryString("merchOrderSn");
    let startTime = getQueryString("startTime");
    let endTime = getQueryString("endTime");
    let storeId = getQueryString("storeId");
    let orderBizType = getQueryString("orderBizType");
    let url = '../order/list?1';
    if (shippingStatus) {
        url += '&shippingStatus=' + shippingStatus;
    }
    if (payStatus) {
        url += '&payStatus=' + payStatus;
    }
    if (orderStatus) {
        url += '&orderStatus=' + orderStatus;
    }
    if (merchOrderSn) {
        url += '&merchOrderSn=' + merchOrderSn;
    }
    if (startTime) {
        url += '&startTime=' + startTime;
    }
    if (endTime) {
        url += '&endTime=' + endTime;
    }
    if (storeId) {
        url += '&storeId=' + storeId;
    }
    if (orderBizType) {
        url += '&orderBizType=' + orderBizType;
    }
    $("#jqGrid").jqGrid({
        url: url,
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
            {label: '所属门店', name: 'storeName', index: 'storeName', width: 80},
            {label: '订单号', name: 'orderSn', index: 'order_sn', width: 100},
            {label: '会员', name: 'userName', index: 'user_name', width: 80},
            {label: '支付类型', name: 'isMergePay', index: 'is_merge_pay', width: 60,
                formatter: function (value) {
                    if (value == '2') {
                        return '合并支付';
                    }else if (value == '1') {
                        return '合并支付';
                    } else if (value == '0') {
                        return '单笔支付';
                    }
                    return '-';
                }
            },
            {label: '商户订单号', name: 'merchOrderSn', index: 'merchOrderSn', width: 140},
            {
                label: '订单业务类型', name: 'orderBizType', index: 'order_biz_type', width: 80,
                formatter: function (value) {
                    if (value == '00') {
                        return '保税备货';
                    } else if (value == '02') {
                        return '保税展示补货';
                    } else if (value == '10') {
                        return '保税展示跨境';
                    } else if (value == '11') {
                        return '普通货物';
                    }
                    return '-';
                }
            },
            {
                label: '订单状态', name: 'orderStatus', index: 'order_status', width: 80,
                formatter: function (value) {
                    if (value == '0') {
                        return '订单创建成功等待付款';
                    } else if (value == '100') {
                        return '订单付款中';
                    } else if (value == '101') {
                        return '订单已取消';
                    } else if (value == '102') {
                        return '订单已删除';
                    } else if (value == '201') {
                        return '订单已付款，等待发货';
                    } else if (value == '300') {
                        return '订单已发货';
                    } else if (value == '301') {
                        return '用户确认收货';
                    } else if (value == '401') {
                        return '没有发货，退款';
                    } else if (value == '402') {
                        return '已收货，退款退货';
                    }
                    return value;
                }
            },
            {
                label: '订付人核验', name: 'buyerPayCheck', index: 'buyer_pay_check', width: 80,
                formatter: function (value) {//订购人支付人校验，0:未知，1:一致，2:不一致,3:校验异常
                    if (value == '0') {
                        return '未知';
                    } else if (value == '1') {
                        return '一致';
                    } else if (value == '2') {
                        return '不一致';
                    }
                    return "-";
                }
            },
            {
                label: '付款状态', name: 'payStatus', index: 'pay_status', width: 80,
                formatter: function (value) {
                    if (value == '0') {
                        return '未付款';
                    } else if (value == '1') {
                        return '付款中';
                    } else if (value == '2') {
                        return '已付款';
                    } else if (value == '3') {
                        return '退款中';
                    } else if (value == '4') {
                        return '退款';
                    }
                    return value;
                }
            },
            // {label: '收货人', name: 'consignee', index: 'consignee', width: 80},
            // {label: '收货地址', name: 'address', index: 'address', width: 80},
            // {label: '联系电话', name: 'mobile', index: 'mobile', width: 80},
            {label: '实际支付', name: 'actualPrice', index: 'actual_price', width: 60},
            {label: '订单总价', name: 'orderPrice', index: 'order_price', width: 60},
            {
                label: '下单时间', name: 'addTime', index: 'add_time', width: 120,
                formatter: function (value) {
                    console.log(value);
                    return transDate(value, 'yyyy-MM-dd hh:mm:ss');
                }
            },
            {label: '快递公司', name: 'shippingName', index: 'shipping_name', width: 80},
            {label: '配送单号', name: 'shippingNo', index: 'shipping_No', width: 80},
            {label: '快递费用', name: 'shippingFee', index: 'shipping_fee', width: 80},
            {
                label: '发货状态', name: 'shippingStatus', index: 'shipping_status', width: 60,
                formatter: function (value) {
                    if (value == '0') {
                        return '未发货';
                    } else if (value == '1') {
                        return '已发货';
                    } else if (value == '2') {
                        return '已收货';
                    } else if (value == '4') {
                        return '退货';
                    }
                    return value;
                }
            },
            {label: '修改人', name: 'moderSn', index: 'moderSn', width: 80},
            {
                label: '操作', width: 180, sortable: false,
                formatter: function (value, col, row) {
                    let htmlStr = '<button class="btn btn-outline btn-info" onclick="vm.lookDetail(' + row.id + ')"><i class="fa fa-info-circle"></i>详情</button>&nbsp;';
                    //订单状态： 0订单创建成功等待付款，　101订单已取消，　102订单已删除，201订单已付款，等待发货，300订单已发货， 301用户确认收货，401 没有发货，退款　402 已收货，退款退货
                    if(hasPermission('order:printMsg')){
                        if (row.orderStatus == 300 && (row.orderBizType == '10' || row.orderBizType == '02')) {
                            htmlStr += '<button class="btn btn-outline btn-primary" onclick="vm.printDetail(' + row.id + ')"><i class="fa fa-print"></i>打印</button>&nbsp;';
                        }
                    }
                    if (hasPermission('order:refund')) {
                        if (row.orderStatus == 0) {
                            htmlStr += '<button class="btn btn-outline btn-danger" onclick="vm.cancelUpdate(' + row.id + ')"><i class="fa fa-times-circle-o"></i>&nbsp;取消</button>&nbsp;';
                        }
                        if (row.orderStatus == 201) {
                            if (row.isPaymentSend == 0 || row.isEleOrderSend == 0 || row.isCustomsSend == 0) {
                                htmlStr += '<button class="btn btn-outline btn-danger" onclick="vm.refundUpdate(' + row.id + ')"><i class="fa fa-times-circle-o"></i>&nbsp;退款</button>&nbsp;';
                            }
                        }
                    }
                    return htmlStr;
                }
            }
        ],
        viewrecords: true,
        height: 550,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
});

let vm = new Vue({
    el: '#rrapp',
    data: {
        showDiv: 1, // 1查询 2编辑 3发货 4选择骑手 5退款
        title: null,
        order: {},
        shippings: [],
        q: {
            orderSn: '',
            orderStatus: '',
            merchOrderSn: '',
            startTime: '',
            endTime: '',
            storeId: '',
            payStatus:'',
            orderBizType:''
        },
        refundMoney: 0,
        shipping: {},
        logisticsInfo: {
            tracesList: [],
            logisticCode: '',
            shipperCode: ''
        },
        macros: [],
        orderProcessRecordEntity: {},
        orderGoodsList: [],
        stores: [],
        orderStatusList:[],
        payStatusList:[],
        ruleValidate: {
            /*name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]*/
        },
        orderBizTypeList:[]
    },
    methods: {
        query: function () {
            vm.reload(1);
        },
        getMacro: function () {
            $.get("../sys/macro/queryMacrosByValue?value=goodsBizType", function (r) {
                vm.macros = r.list;
            });
        },
        getLogistics: function (event) {
            let id = getSelectedRow();
            if (id == null) {
                return;
            }
            $.get("../order/getLogistics/" + id, function (r) {
                if (r.code != 0) {
                    alert(r.msg);
                    return;
                }
                vm.logisticsInfo = r.result;
                vm.showDiv = 3;
                vm.title = "快递信息";
            });
        },
        getExpressInfo: function (event) {
            let id = getSelectedRow();
            if (id == null) {
                return;
            }
            $.get("../order/infos/" + id, function (r) {
                vm.order = r.order;
                vm.showDiv = 8;
                vm.title = "修改快递信息";
            });
        },
        updateExpressInfo: function (event) {
            $.ajax({
                type: "POST",
                url: '../order/updateExpressInfo',
                contentType: "application/json",
                data: JSON.stringify(vm.order),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        handleSubmit: function (name) {
            // handleSubmitValidate(this, name, function () {
            vm.updateExpressInfo()
            // });
        },
        getProcess: function (event) {
            let orderSn = getSelectedRowData().orderSn;
            if (orderSn == null) {
                return;
            }
            $.get("../order/getProcess/" + orderSn, function (r) {
                if (r.code != 0) {
                    alert(r.msg);
                    return;
                }
                if (r.orderProcessRecordEntity != null) {
                    vm.orderProcessRecordEntity = r.orderProcessRecordEntity;
                    vm.showDiv = 7;
                } else {
                    alert(orderSn + "暂无清关信息");
                }
            });
        },
        confirm: function (event) {
            let id = getSelectedRow();
            if (id == null) {
                return;
            }
            confirm('确定收货？', function () {
                $.ajax({
                    type: "POST",
                    url: "../order/confirm",
                    contentType: "application/json",
                    data: JSON.stringify(id),
                    dataType: "json",
                    success: function (r) {

                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        openComment: function (event) {
            let id = getSelectedRow();
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '评价',
                content: '../shop/comment.html?orderId=' + id
            });
        },
        shippingChange: function (opt) {
            vm.order.shippingName = opt.label;
            vm.order.shippingCode = opt.value;
        },
        saveOrUpdate: function (event) {
            $.ajax({
                type: "POST",
                url: '../order/sendGoods',
                contentType: "application/json",
                data: JSON.stringify(vm.order),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        reload: function (event) {
            vm.showDiv = 1;
            let page = event;
            if (event != 1) {
                page = $("#jqGrid").jqGrid('getGridParam', 'page');
            }
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'orderSn': vm.q.orderSn,
                    'orderStatus': vm.q.orderStatus,
                    'merchOrderSn': vm.q.merchOrderSn,
                    'startTime': vm.q.startTime,
                    'endTime': vm.q.endTime,
                    'storeId': vm.q.storeId,
                    'payStatus': vm.q.payStatus,
                    'orderBizType': vm.q.orderBizType
                },
                page: page
            }).trigger("reloadGrid");
        },
        reloadSearch: function () {
            vm.q = {
                orderSn: '',
                orderStatus: '',
                merchOrderSn: '',
                startTime: '',
                endTime: '',
                storeId: '',
                payStatus: '',
                orderBizType: ''
            };
        },
        lookDetail: function (rowId) { //第三步：定义编辑操作
            vm.showDiv = 2;
            vm.title = "订单详情";
            $.get("../order/infos/" + rowId, function (r) {
                vm.order = r.order;
                vm.orderGoodsList = r.order.orderGoodsEntityList;
            });
            vm.getMacro();
        },
        printDetail: function (rowId) {
            confirm('确定连接打票机打印出票？', function () {
                $.ajax({
                    type: "POST",
                    url: "../order/printMsg",
                    contentType: "application/json",
                    data: JSON.stringify(rowId),
                    success: function (r) {
                        if (r.ticket != null) {
                            // printArea(r.ticket);
                            var content = getPrintContent(r.ticket);
                            printArea(content);
                            alert('打印小票完成');
                        }else{
                            alert("打印小票失败");
                        }
                    }
                });
            })
        },
        shippingBind: function (event) {
            let orderId = vm.order.id;
            $.ajax({
                type: "POST",
                url: '../order/shippingBind',
                data: {orderId: orderId, shippingCode: vm.shipping},
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        refund: function (rowId) {
            vm.showDiv = 5;
            vm.refundMoney = 0;
            Ajax.request({
                url: "../order/info/" + rowId,
                async: true,
                successCallback: function (r) {
                    vm.order = r.order;
                    vm.refundMoney = r.order.actualPrice;
                }
            });
        },
        cancelUpdate: function (rowId) {
            let params = {};
            params.orderId = rowId;

            $.ajax({
                type: "POST",
                url: '../order/cancel',
                data: params,
                success: function (r) {
                    if (r.code === 0) {
                        alert('取消成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        refundUpdate: function (rowId) {
            let params = {};
            params.orderId = rowId;

            $.ajax({
                type: "POST",
                url: '../order/refund',
                data: params,
                success: function (r) {
                    if (r.code === 0) {
                        alert('退款成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        exportOrder: function() {
            var params = {};
            params.orderSn = vm.q.orderSn, params.orderStatus = vm.q.orderStatus, params.merchOrderSn = vm.q.merchOrderSn
                , params.startTime = vm.q.startTime, params.endTime = vm.q.endTime, params.storeId = vm.q.storeId,params.payStatus = vm.q.payStatus,
                params.orderBizType = vm.q.orderBizType;

            exportFile('#rrapp', '../order/export', params);
            /*$.ajax({
                type: "get",
                url: '../order/export',
                data: params,
                success: function (r) {
                    if (r.code === 0) {
                        alert('导出成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });*/
        }
    },
    created: function () {
        $.get("../shipping/queryAll", function (r) {
            vm.shippings = r.list;
        });
    },
    mounted() {
        $.get("../store/queryAll", function (r) {
            vm.stores = r.list;
        });
        $.get("../sys/macro/queryMacrosByValue?value=orderStatus", function (r) {
            vm.orderStatusList = r.list;
        });
        $.get("../sys/macro/queryMacrosByValue?value=payStatus", function (r) {
            vm.payStatusList = r.list;
        });
        $.get("../sys/macro/queryMacrosByValue?value=goodsBizType", function (r) {
            vm.orderBizTypeList = r.list;
        });
    }
});



    // var printAreaCount = 0;
    // function printArea(ticket) {
    //     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;
    //     $(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();
    // }
    // var removePrintArea = function (id) {
    //     $("iframe#" + id).remove();
    // };

    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.ticketHead.title;
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "会员:" + ticket.ticketHead.memberId;
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "订单号:" + ticket.ticketHead.orderId;
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "交易时间:" + ticket.ticketHead.tradeTime;
        content += "</div>";
        content += "<div style=\"width: 100%;overflow:hidden;white-space: nowrap;\">--------------------------------------------------</div>";
        //商品信息
        content += "<table style=\"width: 100%;\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
        content += "<tr>";
        content += "<td style=\"width: 50%;text-align: left;font-size: 10px;font-weight: bold;\">商品名称</td>";
        content += "<td style=\"width: 17%;text-align: right;font-size: 10px;font-weight: bold;\">单价</td>";
        content += "<td style=\"width: 15%;text-align: right;font-size: 10px;font-weight: bold;\">数量</td>";
        content += "<td style=\"width: 18%;text-align: right;font-size: 10px;font-weight: bold;\">小计</td>";
        content += "</tr>";
        content += "</table>";
        content += "<div style=\"width: 100%;overflow:hidden;white-space: nowrap;\">--------------------------------------------------</div>";
        content += "<table style=\"width: 100%;\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
        for (var i=0;i< ticket.goods.length;i++){
            content += "<tr>";
            content += "<td style=\"width: 50%;text-align: left;font-size: 8px;padding-top: 8px;\">";
            content += "<table style=\"width: 100%;\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
            content += "<tr>";
            content += "<td style=\"text-align: left;font-size: 8px;vertical-align:top;\">#</td>";
            content += "<td style=\"text-align: left;font-size: 8px;\">" + ticket.goods[i].gname + "</td>";
            content += "</tr>";
            content += "</table>";
            content += "</td>";
            content += "<td style=\"width: 17%;text-align: right;font-size: 8px;vertical-align:bottom;padding-top: 8px;\">" + ticket.goods[i].uprice + "</td>";
            content += "<td style=\"width: 15%;text-align: right;font-size: 8px;vertical-align:bottom;padding-top: 8px;\">" + ticket.goods[i].num + "</td>";
            content += "<td style=\"width: 18%;text-align: right;font-size: 8px;vertical-align:bottom;padding-top: 8px;\">" + ticket.goods[i].subtotal + "元</td>";
            content += "</tr>";

        }
        content += "</table>";
        content += "<div style=\"width: 100%;overflow:hidden;white-space: nowrap;\">--------------------------------------------------</div>";
        //收银信息
        content += "<div style=\"width: 100%;\">";
        content += "<span style=\"float: left;width: 50%;text-align: left;\">商品合计:</span>";
        content += "<span style=\"float: left;width: 17%;text-align: left;\">" + ticket.cashInfo.goodsTotal + "件</span>";
        content += "<span style=\"float: right;width: 33%;text-align: right;\">" + ticket.cashInfo.total + "元</span>";
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "<span style=\"float: left;width: 50%;text-align: left;\">实收:</span>";
        content += "<span style=\"float: right;width: 50%;text-align: right;\">" + ticket.cashInfo.receipts + "元</span>";
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "<span style=\"float: left;width: 50%;text-align: left;\">找零:</span>";
        content += "<span style=\"float: right;width: 50%;text-align: right;\">" + ticket.cashInfo.oddChange + "元</span>";
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "<span style=\"float: left;width: 50%;text-align: left;\">优惠券:</span>";
        content += "<span style=\"float: right;width: 50%;text-align: right;\">" + ticket.cashInfo.coupon + "元</span>";
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "<span style=\"float: left;width: 50%;text-align: left;\">运费:</span>";
        content += "<span style=\"float: right;width: 50%;text-align: right;\">" + ticket.cashInfo.freight + "元</span>";
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "<span style=\"float: left;width: 50%;text-align: left;\">支付渠道:</span>";
        content += "<span style=\"float: right;width: 50%;text-align: right;\">" + ticket.cashInfo.paymentMode + "</span>";
        content += "</div>";
        content += "<div style=\"width: 100%;overflow:hidden;white-space: nowrap;\">--------------------------------------------------</div>";
        //海关清单信息
        content += "<div style=\"width: 100%;\">";
        content += "订单号:" + ticket.cusListing.orderId;
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "运单编号:" + ticket.cusListing.waybillId;
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "海关清单号:" + ticket.cusListing.invtNo;
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "收货人:" + ticket.cusListing.consignee;
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "收货人电话:" + ticket.cusListing.consigneeTel;
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "始发地:" + ticket.cusListing.originAddress;
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "交货地:" + ticket.cusListing.deliveryAddress;
        content += "</div>";
        content += "<div style=\"width: 100%;overflow:hidden;white-space: nowrap;\">--------------------------------------------------</div>";
        content += "<div style=\"width: 100%;\">";
        content += ticket.ticketFoot.summary;
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "客服电话:" + ticket.ticketFoot.serviceTel;
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += "网址:" + ticket.ticketFoot.url1;
        content += "</div>";
        content += "<div style=\"width: 100%;\">";
        content += ticket.ticketFoot.welcome;
        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();
    }
    var removePrintArea = function (id) {
        $("iframe#" + id).remove();
    };