/**
 * YourTeam Tooltips(Popover) 小視窗
 * 
 * 使用方式:
 * <button type="button" id="testBtn">出現視窗</button>
 * 
 * <script>
 *    $("#testBtn").YTTooltip({ option... });
 * </script>
 * */

/**
 * option :
 *    html -> 出現內容 (ex: <div><p>你好</p></div>)
 *    toggle -> 觸發條件 (click/hover)
 *    direction -> 顯示位置 (top/bottom/left/right)
 *    onShow -> callback 顯示後
 */
$.fn.YTTooltip = function (option) {
    let eleArr = [];

    this.each(function (index, value) {

        let obj = {
            ele: value,
            isShowArr: [],
            html: $(option.html) || '',
            tooltipDiv: null,
            direction: option.direction || 'bottom',
            toggle: option.toggle || "click",
            hideTooltipEvent: hideTooltipEvent,
            onShow: option.onShow || null,
            group: option.group || null,
        };

        if (obj.toggle == "hover") {
            obj.toggle == "mouseenter"
        }

        $(obj.ele).on(obj.toggle, function () {
            let tooId = $(this).data("yttooltipid");
            let display = "flex";
            //顯示 tooltip 程序 及 存入已顯示紀錄arr
            if (!tooId || obj.isShowArr.indexOf(tooId) == -1) {
                let ranId = Math.floor((Math.random() * (9999999 - 1000000)) + 1000000);
                let clone = $(obj.html);
                //body 元素 高寬
                let bodyWidth = $("body")[0].offsetWidth;
                let bodyHeight = $("body")[0].offsetHeight;
                //計算引用元素 offset
                let offset = $(this).offset();
                //引用元素 高寬
                let width = $(this)[0].offsetWidth;
                let height = $(this)[0].offsetHeight;

                $(this).data("yttooltipid", ranId);
                $(clone).attr("id", "yt_tooltip_" + ranId);
                if (obj.group) {
                    $(clone).data("group", obj.group).attr("data-group", obj.group);
                }
                //同一 group tooltip 先隱藏 (只顯示一個)
                if (obj.group) {
                    $(`body [id^=yt_tooltip_][data-group=${obj.group}]`).each((index, groTooEle) => {
                        let eleId = $(groTooEle).prop("id").split("yt_tooltip_")[1];
                        obj.hideTooltipEvent(eleId);
                    })
                }
                $("body").append(clone);
                //push 已顯示紀錄
                obj.isShowArr.push(ranId);
                obj.tooltipDiv = clone;
                //顯示 tooltip
                $(clone).css({ "display": display, "position": "absolute" });
                
                //tooltip 高寬
                let toolWidth = $(clone)[0].offsetWidth;
                let toolHeight = $(clone)[0].offsetHeight;
                //超出視窗計算
                let left = offset.left + width + toolWidth > bodyWidth ? offset.left - toolWidth : offset.left + width;
                let top = offset.top + height + toolHeight > bodyHeight ? offset.top - toolHeight : offset.top + height;

                //計算 位置
                if (obj.direction == "left") {
                    left = offset.left < toolWidth ? offset.left + width + 5 : offset.left - toolWidth - 10;
                } else if (obj.direction == "right") {
                    left = offset.left + toolWidth + width > bodyWidth ? offset.left - toolWidth - 10 : offset.left + width + 10;
                } else if (obj.direction == "bottom") {
                    top = offset.top + toolHeight + height > bodyHeight ? offset.top - toolHeight - 10 : offset.top + height + 10;
                } else if (obj.direction == "top") {
                    top = offset.top < toolHeight ? offset.top + height + 5 : offset.top - toolHeight - 10;
                }

                if (obj.direction == "left" || obj.direction == "right") {
                    $(clone).css({ left: left, top: offset.top });
                } else if (obj.direction == "top" || obj.direction == "bottom"){
                    $(clone).css({ left: offset.left, top: top});
                }
                setTimeout(function () { 
                    obj.onShow ? obj.onShow(clone, obj.ele, obj) : "";
                }, 10)
                event();
            } else {
                obj.hideTooltipEvent(tooId);
            }

            if (obj.toggle == "hover") {
                $(obj.tooltipDiv).off("mouseover").on("mouseover", function () {
                    $(this).css("display", "flex");
                })
                $(obj.tooltipDiv).off("mouseleave").on("mouseleave", function () {
                    let tooId = $(this).attr("id").split("yt_tooltip_")[1];
                    obj.hideTooltipEvent(tooId);
                })
            }

            
        })

        if (obj.toggle == "hover") {
            $(obj.ele).on("mouseleave", function (e) {
                let tooId = $(this).data("yttooltipid");
                hideTooltipEvent(tooId);
                e.stopPropagation();
            })
        }


        function hideTooltipEvent(tooId) {
            $("#yt_tooltip_" + tooId).remove();
            obj.isShowArr.splice($.inArray(tooId, obj.isShowArr), 1);
            //setTimeout(function () {
            //    if ($("#yt_tooltip_" + tooId).css("display") == "none") {
            //        obj.isShowArr.splice($.inArray(tooId, obj.isShowArr), 1);
            //        $("#yt_tooltip_" + tooId).remove();
            //    }
            //}, 100)
        }

        function event() {
            let tooId = $(obj.ele).data("yttooltipid");
            $("#yt_tooltip_" + tooId).off("click", "[data-close='yttooltip']");
            $("#yt_tooltip_" + tooId).on("click", "[data-close='yttooltip']", function () {
                hideTooltipEvent(tooId);
            })
        }

        
        eleArr.push(obj);
    })

    let result = eleArr.filter(x => this.toArray().findIndex(y => y == x.ele) != -1)[0];

    return result;
}



function resetYTTooltip() {
    $("[id^=yt_tooltip_]").remove();
}