var test = true,
    orderState = "",
    webNotice = false,
    webNoticeId = "",
    oldOrderInfo = false,
    oldOrderInfo_malai = false;
window.onload = function (ev) {



    init(); 
    //日历控件
    laydate.render({
        elem: '#startTime', //指定元素
        type: 'datetime',
        // value: getFormatDate(false),
        max: getFormatDate(true),
        done: function (value, date, endDate) {
            $("#startTime").next().show();
        }
    });
    //日历控件
    laydate.render({
        elem: '#endTime', //指定元素
        type: 'datetime',
        // value: getFormatDate(true),
        max: getFormatDate(true),
        done: function (value, date, endDate) {
            $("#endTime").next().show();
        }
    });
}


init = function () {
    var today = getFormatDate(false),
        // var today = '2018-10-10 00:00:00',
        now = getFormatDate(true),
        val = "",
        state = orderState;
    $("#startTime").val(today);
    $("#endTime").val(now);
    $("#startTime").next().show();
    $("#endTime").next().show();
    getProductInfo(today, now, val, state, 1, 10, true);
	pagenotify();

}



pagenotify = function () {
    notifyMe();
    orderWheelSearch();
    orderWheelSearchMaLai();
}


notifyMe = function () {
    // 先检查浏览器是否支持
    if (!("Notification" in window)) {
       // alert("本浏览器不支持网页通知提示，如需要网页提示，请使用chrome浏览器打开此网站。");
    }
    else {
        Notification.requestPermission(function (permission) {
            if (permission === "granted") {
                webNotice = true;
            }
            else if (Notification.permission === "denied") {
               // alert("请打开网页通知权限，或者质询技术人员协助打开。");
            }
        });
    }
}

orderWheelSearch = function () {
    setInterval(function () {
        var parameter = urlEncode(["OrderWheelSearch"]);
        $.ajax({
            type: "post",
            url: "/new/php/index.php",
            data: {mode: parameter},
            dataType: "json",
            success: function (data) {
                if (oldOrderInfo == false) {
                    oldOrderInfo = data[0];
                }
                else {
                    if (oldOrderInfo.OrderId == data[0].OrderId) {

                    }
                    else {
                        oldOrderInfo = data[0];
                        orderNoticeBody(oldOrderInfo);
                        $("#audio")[0].play();
                    }
                }
                console.log(oldOrderInfo);
            }
        });
    }, 5000);
}


orderWheelSearchMaLai = function () {
    setInterval(function () {
        var parameter = urlEncode(["OrderWheelSearch"]);
        $.ajax({
            type: "post",
            url: "/malai/php/index.php",
            data: {mode: parameter},
            dataType: "json",
            success: function (data) {
                if (oldOrderInfo_malai == false) {
                    oldOrderInfo_malai = data[0];
                }
                else {
                    if (oldOrderInfo_malai.OrderId == data[0].OrderId) {

                    }
                    else {
                        oldOrderInfo_malai = data[0];
                        orderNoticeBodyMaLai(3, oldOrderInfo_malai);
                        $("#audio")[0].play();
                    }
                }
            }
        });
    }, 5000);
}












orderNoticeBody = function (type, data) {
    var title, obj;
    if (type == 1) {
        title = "泰国来订单啦";
    }
    else if (type == 2) {
        title = "台湾来订单啦";
    }
    else if (type == 3) {
        title = "马来西亚来订单啦";
    }
    webNoticeId = data.OrderId + '<>' + data.ProductId;
    obj = {
        dir: "auto",
        body: "订单号：" + data.OrderNum + "\n" +
        "产品编号：" + data.ProductRemarks,
        // tag: webNoticeId,
        icon: JSON.parse(data.ProductInfoClassId)[1].img,
        renotify: false
    }
    var notification = new Notification(title, obj);
    notification.onclick = function (event, data) {
        event.preventDefault(); // prevent the browser from focusing the Notification's tab
        var oid = webNoticeId.split("<>")[0],
            pid = webNoticeId.split("<>")[1];
        window.open('https://kjdspro.com/new/admin/orderinfo.html?oid=' + oid + '&pid=' + pid, '_blank');
    }
}




orderNoticeBodyMaLai  = function (type, data) {
    var title, obj;
    if (type == 1) {
        title = "泰国来订单啦";
    }
    else if (type == 2) {
        title = "台湾来订单啦";
    }
    else if (type == 3) {
        title = "马来西亚来订单啦";
    }
    webNoticeId = data.OrderId + '<>' + data.ProductId;
    obj = {
        dir: "auto",
        body: "订单号：" + data.OrderNum + "\n" +
        "产品编号：" + data.ProductRemarks,
        // tag: webNoticeId,
        icon: JSON.parse(data.ProductInfoClassId)[1].img,
        renotify: false
    }
    var notification = new Notification(title, obj);
    notification.onclick = function (event, data) {
        event.preventDefault(); // prevent the browser from focusing the Notification's tab
        var oid = webNoticeId.split("<>")[0],
            pid = webNoticeId.split("<>")[1];
        window.open('https://kjdspro.com/malai/admin/orderinfo.html?oid=' + oid + '&pid=' + pid, '_blank');
    }
}






getProductInfo = function (today, now, val, state, pageindex, pagesize, flag) {
    var parameter = urlEncode(["SelectOrderInfo", today, now, val, state, pageindex, pagesize]);
    $.ajax({
        type: "post",
        url: "/new/php/index.php",
        data: {mode: parameter},
        dataType: "json",
        success: function (data) {

            if (data.length == 0 || data == -1) {
                $("#loading").css({"display": "none"});
                $("#warp").css({"display": "table-row-group"});
                var th = '<th colspan="11" scope="col" class="text-c f-20" style="padding: 50px 0;">暂无数据</th>';
                $("#warp").html(th);
                $("#Page").html("");
                // $("#warp").append(th);
                return;
            }

            printProductInfo(data);

            if (!flag) {
                test = true;
            }

            if (test) {
                test = false;
                var totalSize = data[0].allcount,
                    totalPage = Math.ceil(totalSize / pagesize);
                // $("#Page").whjPaging("setPage", {currPage: pageindex, totalPage: totalPage, totalSize: totalSize});
                $("#Page").html("");
                $("#Page").whjPaging({
                    currPage: pageindex,
                    totalSize: totalSize,//可选，总条数
                    totalPage: totalPage,//可选，总页数
                    isShowRefresh: false,//可选，是否展示刷新，默认true
                    isShowPageSizeOpt: false,//可选，是否展示每页条数下拉框，默认true，如果设置显示，总条数必须设置
                    // isResetPage:true,
                    callBack: function (currPage) {
                        $("#loading").css({display: "block"});
                        $("#warp").css({display: "none"});
                        getProductInfo(today, now, val, orderState, currPage, pagesize, true);
                        // console.log('currPage:' + currPage + '     pageSize:' + pageSize);
                    }
                });
            }

            console.log(data);
        }
    });
}


changeTab = function (state) {
    var starttime = $("#startTime").val(),
        endtime = $("#endTime").val(),
        val = $("#SearchPlaceBtn").val(),
        state = state;
    getProductInfo(starttime, endtime, val, state, 1, 10, false);

    // var li = $(el).parent().children();
    // li.removeClass("layui-this");
    // $(el).addClass("layui-this");
    // $("#loading").css({display: "table-row-group"});
    // $("#warp").css({display: "none"});
    // test = true;
    // getProductInfo(oid, pid, state, pageindex, pagesize);
    // $("#SearchPlaceBtn").val("");
}

printProductInfo = function (data) {
    // data = data[0];
    var warp = $("#warp"),
        tr,
        state = {1: "已付款,<p style='color:red'>等待发货</p>", 2: "已发货<p style='color:red'>等待收货</p>", 3: "已收货"},
        title = "'订单详情'";
    var ordernum,
        product_remarks,
        product_name,
        order_class, order_class_img, order_class_color, order_class_size, order_class_div,
        product_price,
        order_number,
        order_price,
        order_time,
        order_state,
        order_operation, order_operation_delivergoods, order_operation_buygood, order_operation_href, odrer_address;

    warp.html("");
    for (var i = 0; i < data.length; i++) {
        order_class = "";
        order_class_div = "";
        ordernum = '<td>' + data[i].OrderNum + '</td>';
        product_remarks = '<td>' + data[i].ProductRemarks + '</td>';
        product_name = '<td>' + data[i].ProductName + '</td>';
        product_price = '<td>' + Math.ceil(data[i].ProductPrice) + '</td>';
        if (data[i].ProductInfoClassId == "") {
            order_class_img = '<img src="' + data[i].ProductAttributeId.split(",")[0] + '" style="width: 80px;"/>';
            order_class_color = data[i].ProductAttributeId.split(",")[1];
            order_class_size = (data[i].ProductAttributeId.split(",")[2] && data[i].ProductAttributeId.split(",")[2] != "" && data[i].ProductAttributeId.split(",")[2] != "undefined") ? data[i].ProductAttributeId.split(",")[2] : "无";
            order_class = '<td style="text-align: initial;"><div>' +
                '<p>颜色：' + order_class_color + '</p>' +
                '<p>图片：' + order_class_img + '</p>' +
                '<p>尺寸：' + order_class_size + '</p></div></td>';
            order_number = '<td>' + data[i].ProductNumber + '</td>';
            order_price = '</td>' + '<td>' + data[i].Payment + '</td>';
        }
        else {
            data[i].ProductInfoClassId = JSON.parse(unescape(data[i].ProductInfoClassId));
            for (var j in data[i].ProductInfoClassId) {
                if (j == 0) {
                    order_number = '<td>' + data[i].ProductInfoClassId[0].Number + '</td>';
                    order_price = '<td>' + parseInt(data[i].ProductInfoClassId[0].Money) * parseInt(data[i].ProductInfoClassId[0].Number) + '</td>';
                }
                else {
                    order_class_img = '<img src="' + data[i].ProductInfoClassId[j].img + '" style="width: 80px;"/>';
                    order_class_color = data[i].ProductInfoClassId[j].color;
                    order_class_size = data[i].ProductInfoClassId[j].size ? data[i].ProductInfoClassId[j].size : "无";
                    order_class_div += '<div style="margin-bottom: 10px;border-bottom: 1px solid #cecece;">' +
                        '<p>颜色：' + order_class_color + '</p>' +
                        '<p>图片：' + order_class_img + '</p>' +
                        '<p>尺寸：' + order_class_size + '</p>' +
                        '</div>';
                    order_class = '<td style="text-align: initial;">' + order_class_div + '</td>';
                }
            }
        }
        order_time = '<td><p>' + data[i].OrderAddtime.split(" ")[0] + '</p><p>' + data[i].OrderAddtime.split(" ")[1] + '</p></td>';
        order_state = '<td class="state">' + state[data[i].OrderState] + '</td>';
        if (data[i].OrderState == 1) {
            order_operation_delivergoods = '<a class="btn btn-primary radius td-button" onclick="deliverGoods(\'' + data[i].OrderId + '\',this)">发货</a>';
        }
        else if (data[i].OrderState == 2) {
            order_operation_delivergoods = '<a class="btn btn-primary radius td-button" onclick="collectGoods(\'' + data[i].OrderId + '\',this)">确认买家已收货</a>';
        }
        else if (data[i].OrderState == 3) {
            order_operation_delivergoods = "";
        }

        if (data[i].BuyGoods == 0 || !data[i].BuyGoods) {
            order_operation_buygood = '<a class="btn btn-primary radius td-button" onclick="buygood(\'' + data[i].OrderId + '\',this)">采购</a>';
        }
        else {
            order_operation_buygood = '<a class="btn btn-primary radius td-button">已采购</a>';
        }
        order_operation_href = "'orderinfo.html?oid=" + data[i].OrderId + "&pid=" + data[i].ProductId + "'";
        order_operation = '<td>' + order_operation_delivergoods + order_operation_buygood +
            '<a class="btn btn-primary radius td-button" onclick="product_add(' + title + ',' + order_operation_href + ')">查看订单信息</a>' +
            '<a class="btn btn-primary radius td-button" onclick="deleteProduct(\'' + data[i].OrderId + '\',this)">删除</a>' +
            '</td>';
//        odrer_address = '<td>' + data[i].ProductIntroduce + '</td>';
odrer_address = '<td><a href="' + data[i].ProductIntroduce + '">' + data[i].ProductIntroduce + '</a></td>';
        tr = $('<tr class="text-c">' + ordernum + product_remarks + product_name + order_class + product_price + order_number + order_price + order_time + order_state + odrer_address + order_operation + '</tr>');
        warp.append(tr);
    }
    $("#loading").css({"display": "none"});
    $("#warp").css({"display": "table-row-group"});
}


//搜索
searchProductInfo = function () {

    var starttime = $("#startTime").val(),
        endtime = $("#endTime").val(),
        val = $("#SearchPlaceBtn").val(),
        state = orderState;
    getProductInfo(starttime, endtime, val, state, 1, 10, false);


    // var _val = $("#SearchPlaceBtn").val().trim();
    // if (_val == "") {
    //     layer.msg('请输入订单号、人名、地址、手机号其中一个', {icon: 1});
    // }
    // else {
    //     $("#loading").css({display: "table-row-group"});
    //     $("#warp").css({display: "none"});
    //     test = true;
    //     var parameter = urlEncode(["OrderInfoSearch", _val, 1, 10]);
    //     $.ajax({
    //         type: "post",
    //         url: "/new/php/index.php",
    //         data: {mode: parameter},
    //         dataType: "json",
    //         success: function (data) {
    //             $("#Page").html("");
    //             if (data.length == 0 || data == -1) {
    //                 $("#loading").css({"display": "none"});
    //                 $("#warp").css({"display": "table-row-group"});
    //                 var th = '<th colspan="10" scope="col" class="text-c f-20" style="padding: 50px 0;">暂无数据</th>';
    //                 $("#warp").html(th);
    //                 // $("#warp").append(th);
    //                 return;
    //             }
    //             printProductInfo(data);
    //             console.log(data);
    //         }
    //     });
    // }
}


keySearchProductInfo = function () {
    if (event.keyCode == 13) {
        searchProductInfo();
    }
}

//发货
deliverGoods = function (oid, e) {
    var el = e;
    layer.confirm('是否确定发货？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        $("#loading").css({"display": "block"});
        var parameter = urlEncode(["UpdateOrderState", oid, 2]);
        $.ajax({
            type: "post",
            url: "/new/php/index.php",
            data: {mode: parameter},
            dataType: "json",
            success: function (data) {
                if (data === 1) {
                    layer.msg('发货成功', {icon: 1});
                    // $(el).parents().children(".state").html("已发货");
                    $("#loading").css({"display": "none"});
                    $(el).remove();
                }
            }
        });
    })
}

//收货
collectGoods = function (oid, e) {
    var el = e;
    layer.confirm('是否确定买家已经收货了？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        $("#loading").css({"display": "block"});
        var parameter = urlEncode(["UpdateOrderState", oid, 3]);
        $.ajax({
            type: "post",
            url: "/new/php/index.php",
            data: {mode: parameter},
            dataType: "json",
            success: function (data) {
                if (data === 1) {
                    layer.msg('确认成功', {icon: 1});
                    // $("#asd").parents().children(".state")[0].html("已完成");
                    // $("#loading").css({"display": "none"});
                    $(el).parent().parent('tr')[0].remove();
                    $("#loading").css({"display": "none"});
                }
            }
        });
    })
}

//删除
deleteProduct = function (oid, e) {
    var el = e;
    layer.confirm('是否删除订单？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        $("#loading").css({"display": "block"});
        var parameter = urlEncode(["DeleteOrderRecycleBin", oid, 1]);
        $.ajax({
            type: "post",
            url: "/new/php/index.php",
            data: {mode: parameter},
            dataType: "json",
            success: function (data) {
                if (data === 1) {
                    layer.msg('删除成功', {icon: 1});
                    $(el).parent().parent('tr')[0].remove();
                    $("#loading").css({"display": "none"});
                }
            }
        });
    })
}

//是否采购
buygood = function (oid, e) {
    var el = e;
    if ($(el).html() == "采购") {
        layer.confirm('是否确认采购？', {
            btn: ['确定', '取消'] //按钮
        }, function () {
            var parameter = urlEncode(["OrderBuyGoods", oid]);
            $.ajax({
                type: "post",
                url: "/new/php/index.php",
                data: {mode: parameter},
                dataType: "json",
                success: function (data) {
                    if (data === 1) {
                        $(el).html("已采购");
                    }
                    layer.msg('采购成功', {icon: 1});
                }
            });
        });
    }
}


orderWheelSearch = function () {
    setInterval(function () {
        var parameter = urlEncode(["OrderWheelSearch"]);
        $.ajax({
            type: "post",
            url: "/new/php/index.php",
            data: {mode: parameter},
            dataType: "json",
            success: function (data) {
                if (oldOrderInfo == false) {
                    oldOrderInfo = data[0];
                }
                else {
                    if (oldOrderInfo.OrderId == data[0].OrderId) {

                    }
                    else {
                        oldOrderInfo = data[0];
                        orderNoticeBody(1,oldOrderInfo);
                        $("#audio")[0].play();
                    }
                }
                console.log(oldOrderInfo);
            }
        });
    }, 5000);
}

getJsonObjLength = function (jsonObj) {
    var Length = 0;
    for (var item in jsonObj) {
        Length++;
    }
    return Length;
}


function product_add(title, url) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}


urlEncode = function (arr) {
    var i; //循环初始化
    for (i = 0; i < arr.length; i++) {
        arr[i] = encodeURIComponent(encodeURIComponent(arr[i]));
    }
    return arr.join();
}


getFormatDate = function (flag) {
    var nowDate = new Date();
    var year = nowDate.getFullYear();
    var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
    var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
    var hour = nowDate.getHours() < 10 ? "0" + nowDate.getHours() : nowDate.getHours();
    var minute = nowDate.getMinutes() < 10 ? "0" + nowDate.getMinutes() : nowDate.getMinutes();
    var second = nowDate.getSeconds() < 10 ? "0" + nowDate.getSeconds() : nowDate.getSeconds();
    var val;
    if (flag == true) {
        val = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    }
    else if (flag == false) {
        val = year + "-" + month + "-" + date + " 00:00:00";
    }
    else if (flag == -1) {
        val = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    }
    return val;
}


hideSelectClose = function (el) {
    $(el).hide();
    $("#" + $(el).prev().attr("id")).val("");
}


toogle = function (cs) {
    var child = $(cs);
    for (var i = 0; i < child.length; i++) {
        if (child[i].style.display == "none") {
            child[i].style.display = "block";
        } else {
            child[i].style.display = "none";
        }
    }
}
