﻿var pb_dbload = true; //判斷資料是否載入(true=有資料時載入, false=,無資料時不載入)
var pb_page = 1; //初始化頁碼
var pb_loading = false;  //判斷ajax是否執行(true=執行,不執行false)
var po_addControl;
$(function () {
    $(document).ready(function () {
        if ($('#categoryId').val() != undefined) {
            of_loadContent()//進入頁面時 自動載入第一次資料
            $(window).scrollTop(0);
            //自動載入判斷 
            $(window).scroll(function () {
                var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height();
                var scrolltrigger = 0.75;
                if ((pb_dbload == true) && (pb_loading == false)) { //必須是有資料且ajax目前不執行中
                    if ((wintop / (docheight - winheight)) > scrolltrigger && pb_page < 100) {
                       // $(".loading").show(); //載入load畫面
                        pb_loading = true;  //判斷ajax是否執行(true=執行,不執行false)
                        pb_page++;
                        of_loadContent();

                    }
                }
            });
        }
        // Handle sortby selection for product-listing pages
        let sortby_selections = document.querySelectorAll('[data-sortby]');
        let handleOnSortbySelectionChange = function (event) {
            var ls_url = $('#ownerSystem').val() + "/Product/List?id=" + $('#categoryId').val() + "&sort=" + $("#sortby").val() + "&order=" + $(".orderby-btn").attr('aria-checked');
            window.location.replace(ls_url);
            /** window.location.replace(ls_url); **/
        };
        for (select of sortby_selections) {
            select.addEventListener('change', handleOnSortbySelectionChange);
        }
        // Handle orderby icon switch functionality
        // sort - desc 高到低 aria - checked=false
        // sort - asc  低到高 aria - checked=true
        let orderby_icons = document.querySelectorAll('[data-orderby]');
        let handleOnOrderByIconToggle = function (event) {
            event.preventDefault();
            let self = event.target;
            if (self.ariaChecked == "true") {
                //當點擊前為true狀態
                $(".orderby-btn").removeClass('sort-asc');
                $(".orderby-btn").addClass('sort-desc');
                self.ariaChecked = "false";
                self.querySelector('#orderby-label').innerText = '高到低';
            } else {
                //當點擊前為false狀態
                $(".orderby-btn").removeClass('sort-desc');
                $(".orderby-btn").addClass('sort-asc');
                self.ariaChecked = "true";
                self.querySelector('#orderby-label').innerText = '低到高';
            }
            var ls_url = $('#ownerSystem').val() + "/Product/List?id=" + $('#categoryId').val() + "&sort=" + $("#sortby").val() + "&order=" + $(".orderby-btn").attr('aria-checked');
            window.location.replace(ls_url);
        };
        for (icon of orderby_icons) {
            icon.addEventListener('click', handleOnOrderByIconToggle);
        }
    });
});

//載入商品清單
function of_loadContent() {
    if ($("#item").Length != 0) {
        //var P_id = window.location.search.substr(4, 4);//取得頁面上的商品ID值
        //判斷頁面是否為第一次執行     
        var pb_nunber = "?";
        if (window.location.href.indexOf("?") > 0) {
            pb_nunber = "&";
        }
        var ls_url = "";
        if ($('#ownerSystem').val() == "") {
            ls_url = "../Product/of_ajaxListResult";
        }
        else {
            ls_url = $('#ownerSystem').val() + "/Product/of_ajaxListResult";
        }
        $(".loading").show();//載入load畫面
        //blockUI();
        // $('#modal_msg_loading').modal('show');
        $.ajax({
            type: 'POST',
            url: ls_url,
            datatype: "json",
            contentType: "application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true // 这里设置了withCredentials(ajax回傳)
            },
            data: JSON.stringify({
                categoryId: $('#categoryId').val(),
                sortId: $('#sortId').val(),
                page: pb_page
            }),
            success: function (data) {
                var datams = $.parseJSON(data); //解析回傳資料json格式
                if (datams.return == true) {
                    $("#item").append(datams.message);//把回傳的資料 加入網頁                   
                    pb_dbload = datams.reLoad; //判斷是否有資料(true=有資料時載入, false=,無資料時不載入)
                }
                else {
                    // alert(data.message);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // alert(XMLHttpRequest.status);
                //  alert(XMLHttpRequest.readyState);
                // alert(textStatus);
            },
            //執行完成之後要做什麼動作
            complete: function (XMLHttpRequest, textStatus) {
                pb_loading = false;  //判斷ajax是否執行(true=執行,不執行false)
                $(".loading").hide(); //關閉load畫面
                // unblockUI();
                // $('#modal_msg_loading').modal('hide');
            }
        });
    }
}
function isAlertConfirmCancelHide(e) {
    $('#modal_add_check').modal('hide');
}
function isConfirmAdd(e) {
    of_addShoppingBag_run(detail_e, false, detail_msg1, detail_msg2, detail_msg3, detail_msg4);
    po_addControl.attr('data-salesIsGiftStock', 'N');
    $('#modal_add_check').modal('hide');
}
var detail_e;
var detail_msg1;
var detail_msg2;
var detail_msg3;
var detail_msg4;
//加入購物車
function of_addShoppingBag(e, msg1, msg2, msg3, msg4, depTime) {

    // 2024-04-23 未達14天內不得預購
    if (Date.now() + (14 * 24 * 60 * 60 * 1000) < Date.parse(depTime) ) {
        $('#modal_unvailable_time').modal('show');
        return;
    }

    if (parseInt($('.num').html()) == 0) {
        alertMsg(msg1);
    }
    else {      
        if ($($(e).parent().parent().find(".btn-plus")[0]).attr('data-salesIsGiftStock') == "Y")
        {
            var li_qty = 0;
            if ($($(e).parent().parent().find(".btn-plus")[0]).attr('data-shoppingbagqty') != "")
            {
                li_qty = parseInt($($(e).parent().parent().find(".btn-plus")[0]).attr('data-shoppingbagqty'));
            }
            li_qty = li_qty + parseInt($('.num').html());
            if (li_qty > parseInt($($(e).parent().parent().find(".btn-plus")[0]).attr('data-salesgiftstockqty'))) {
                detail_e = e;
                detail_msg1 = msg1;
                detail_msg2 = msg2;
                detail_msg3 = msg3;
                detail_msg4 = msg4;
                $('#modal_add_check').modal('show');
                po_addControl = $($(e).parent().parent().find(".btn-plus")[0]);
                //$($(e).parent().parent().find(".btn-plus")[0]).attr('data-salesIsGiftStock','N');
               
            }
            else {
                of_addShoppingBag_run(e, false, msg1, msg2, msg3, msg4);
            }
        }
        else {
            of_addShoppingBag_run(e,false, msg1, msg2, msg3, msg4);
        }
    }

}
function of_addShoppingBag_run(e,ab_msg, msg1, msg2, msg3, msg4) {
  
    if (parseInt($('.num').html()) == 0)
    {
        alertMsg(msg1);
    }
    else if (($('#orderToken').val()) != "") {
        $('#modal_orderCheck').modal('show');
    }
    else {
        var ls_url = "";
        var ls_productId = $(e).attr('data-productId');
        var ls_isCelebrus = $(e).attr("data-isCelebrus");
        if ($('#ownerSystem').val() == "") {
            ls_url = "../ShoppingBag/of_ajaxAddShoppingBag";
        }
        else {
            ls_url = $('#ownerSystem').val() + "/ShoppingBag/of_ajaxAddShoppingBag";
        }
        $('#modal_msg_loading').modal('show');
        $.ajax({
            type: 'POST',
            url: ls_url,
            datatype: "json",
            contentType: "application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true // 这里设置了withCredentials(ajax回傳)
            },
            data: JSON.stringify({
                categoryId: $('#categoryId').val(),
                productId: $(e).attr('data-productId'),
                num: $('.num').html(),
                msg:ab_msg,
                shoppingHistory: $.cookie("_shoppingHistory")
            }),
            success: function (data) {
                //  var datams = $.parseJSON(data); //解析回傳資料json格式
                if (data.return == true) {
                    $('.num').html("1");
                    if ((data.sumQty != "") && (data.sumQty != "0")) {
                        $('.badge-info').html(data.sumQty); //顯示購物車數量    
                    }
                    else {
                        $('.badge-info').html(""); //顯示購物車數量    
                    }
                    $($(e).parent().parent().find(".btn-plus")[0]).attr('data-shoppingbagqty', data.qty);
                    if (parseInt(data.qty) >= parseInt($($(e).parent().parent().find(".btn-plus")[0]).attr('data-salesmaxqty'))) {
                        $('.btn-minus').addClass('disabled');
                        $('.btn-plus').addClass('disabled');
                        //'已逹銷售上限'
                        $('.text-danger').html(msg2);
                        $('.btn-primary').addClass('disabled');
                        $('.num').html("0");
                    }
                    
                    if (data.qtyStockMsg != "")
                    {
                        if (data.qtyStockMsg == "0")
                        {
                            $('.text-danger').html(msg4);
                            $('.btn-minus').addClass('disabled');
                            $('.btn-plus').addClass('disabled');
                            $('.num').html("0");
                        }
                        else
                        {
                            if (parseInt(data.qty) >= parseInt(data.qtyStockMsg)) {
                                $('.btn-minus').addClass('disabled');
                                $('.btn-plus').addClass('disabled');
                                $('.btn-primary').addClass('disabled');
                                $('.num').html("0");
                                //'已逹銷售上限'
                                $('.text-danger').html(msg2);
                            }
                            else {
                                //'僅剩 X 件!
                                $('.text-danger').html(msg3.replace("{0:s}", data.qtyStockMsg));
                            }
                        }
                        
                    }
                    if (data.shoppingHistory != "") {
                        var ls_domain = data.domain;
                        var ls_path = "";
                        // if (ls_domain != "")
                        // {
                        ls_path = '/';
                        // }
                        $.cookie("_shoppingHistory", data.shoppingHistory, {
                            expires: 10,           // Expires in 10 days

                            path: ls_path,          // The value of the path attribute of the cookie
                            // (Default: path of page that created the cookie).

                            domain: ls_domain, // The value of the domain attribute of the cookie
                            // (Default: domain of page that created the cookie).

                            secure: true          // If set to true the secure attribute of the cookie
                            // will be set and the cookie transmission will
                            // require a secure protocol (defaults to false).
                        });
                        $('#shoppingHistory').val(data.shoppingHistory);
                    }
                    if (ls_isCelebrus == "T") {
                        var lo_targetObj = new Object();
                        lo_targetObj.name = ls_productId;
                        lo_targetObj.id = 'beProdAddCart';
                        lo_targetObj.alt = '';
                        lo_targetObj.tagName = '';
                        if (window.jxcsaclick) {
                            window.jxcsaclick(lo_targetObj);
                        }
                        //if (window.jxcsatextchange) {
                        //    window.jxcsatextchange(lo_targetObj);
                       // }
                        console.log("celebrus(product):targetName=" + ls_productId + ',targetId=' + 'beProdAddCart')
                    }
                    $('#modal_msg_add_cart').modal('show');

                    setTimeout(function () {
                        $('#modal_msg_add_cart').modal('hide');
                    }, 2000)
                }
                else {
                    alertMsg(data.message);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // alert(XMLHttpRequest.status);
                //  alert(XMLHttpRequest.readyState);
                // alert(textStatus);
            },
            //執行完成之後要做什麼動作
            complete: function (XMLHttpRequest, textStatus) {
                pb_loading = false;  //判斷ajax是否執行(true=執行,不執行false)
                // $(".loading").hide(); //關閉load畫面
                // unblockUI();
                $('#modal_msg_loading').modal('hide');
            }
        });
    }

}
//開放瀏覽專案
function of_redirectToLoginPage(e) {
    var ls_url = $('#ownerSystem').val() + "/Login/Index/";
    window.location.replace(ls_url);
}

// 2024-04-23 未達14天不得預購
function unAvailableTime_Logout() {
    if ($('#ownerSystem').val() == "") {
        redirect("../Logout/Index");
    }
    else {
        var ls_url = of_clientDomXss($('#ownerSystem').val()) + "/Logout/Index";
        redirect(ls_url);
    }
    return false;
}