/*
 * 特别声明：本技术材料受《中华人民共和国著作权法》、《计算机软件保护条例》等法律、法规、行政
 * 规章以及有关国际条约的保护，赞同科技享有知识产权、保留一切权利并视其为技术秘密。未经本公司书
 * 面许可，任何人不得擅自（包括但不限于：以非法的方式复制、传播、展示、镜像、上载、下载）使用，
 * 不得向第三方泄露、透露、披露。否则，本公司将依法追究侵权者的法律责任。特此声明！
 *
 * Special Declaration: These technical material reserved as the technical secrets by AGREE
 * TECHNOLOGY have been protected by the "Copyright Law" "ordinances on Protection of Computer
 * Software" and other relevant administrative regulations and international treaties. Without
 * the written permission of the Company, no person may use (including but not limited to the
 * illegal copy, distribute, display, image, upload, and download) and disclose the above
 * technical documents to any third party. Otherwise, any infringer shall afford the legal
 * liability to the company.
 */
import {Widget} from "widget/Widget";
import {Composite} from "widget/Composite";
import {WidgetManager} from "util/WidgetManager";
import {CheckButton}from "widget/CheckButton";
/**
 * Created by heweijun on 2016/10/25.
 */

export class FloatPanelComposite extends Composite {

    private static TemplateWrapper: string = `
           <div>
	            <iframe class="float_panel_iframe"></iframe>
	            <div class="content_wrap">
	            </div>
            </div>
            `;
    private static TemplateCotainer: string = `<div class="float_panel_content adore-hidden-scrollbar"></div>`;
    private static TemplateArrow: string = `<i class="float_panel_arrow mdi-navigation-arrow-drop-up"></i>`;

    private $wrapNode: JQuery;
    private $arrowNode: JQuery;
    private bindClickCount = 0;
    private resizeListener: any;

    constructor(parentId: string, id: string, style: number) {
        super(parentId, id, style);
        this.$wrapNode = $(FloatPanelComposite.TemplateWrapper).attr("id", this.id + "wrapper");
        this.$thisNode = $(FloatPanelComposite.TemplateCotainer).attr("id", this.id);
        this.$attachNode = this.$thisNode;
        this.$arrowNode = $(FloatPanelComposite.TemplateArrow).attr("id", "arrow" + this.id);
        let own = this;
        this.resizeListener = function () {
            if (own.$thisNode.css("display") === "block") {
                own.$thisNode.css("display", "none");
                own.$arrowNode.hide();
                $(".float_panel_iframe").hide();
                $(document).find(".personal_info_arrow").removeClass("mdi-navigation-arrow-drop-up").addClass("mdi-navigation-arrow-drop-down");
            }
        };
        $(window).on("resize", this.resizeListener);
    }

    private getPosition(obj: HTMLElement): number[] {
        let pos = [0, 0];
        if (obj && obj.offsetParent) {
            while (obj && obj.offsetParent) {
                pos[0] += obj.offsetTop;
                pos[1] += obj.offsetLeft;
                obj = obj.offsetParent as HTMLElement;
            }
        }
        return pos;
    }

    private addDocumentBind(wid: string) {
        let own = this;
        $(document).bind('click.' + wid + "_dropDown", function (e) {
            let $source = $(document).find("#" + wid);
            let isSource = false;
            let sourceParent = e.target;
            //判断点击事件源是否需要绑定的组件
            while (sourceParent) {
                if ($source.is(sourceParent)) {
                    isSource = true;
                    break;
                }
                sourceParent = sourceParent.parentElement;
            }
            if (!isSource) {
                let isHide = true;
                if (own.$thisNode.css("display") !== "none") {
                    var targetParent = e.target;
                    while (targetParent) {
                        if (own.$thisNode.is(targetParent)) {
                            isHide = false;
                            break;
                        }
                        targetParent = targetParent.parentElement;
                    }
                    if (isHide) {
                        own.$thisNode.css("display", "none");
                        own.$arrowNode.hide();
                        $(".float_panel_iframe").hide();
                        $source.find(".personal_info_arrow").removeClass("mdi-navigation-arrow-drop-up").addClass("mdi-navigation-arrow-drop-down");
                        $(document).unbind('click.' + wid + "_dropDown");
                    }
                }
                else {
                    $(document).unbind('click.' + wid + "_dropDown");
                }
            }
        });
    }

    private setLocation(target: JQuery, isUp: boolean) {
        //取得需要绑定的组件的位置
        let pos = this.getPosition(target[0]);
        let height = target.height();
        let tmpHeight: number;
        let iframeTop: any;
        if (isUp) {
            tmpHeight = pos[0] - this.$thisNode.height() - 5;
            this.$arrowNode.css("top", pos[0] - 21);
            this.$arrowNode.removeClass("mdi-navigation-arrow-drop-up").addClass("mdi-navigation-arrow-drop-down");
            iframeTop = tmpHeight;
        } else {
            tmpHeight = height + pos[0] + 5;
            this.$arrowNode.css("top", tmpHeight - 19);
            iframeTop = this.$arrowNode.css("top");
        }
        //设置DropDownPanel位置
        this.$thisNode.css("top", tmpHeight);
        this.$thisNode.css("left", pos[1]);
        let width = this.$thisNode.width();
        let limitWidth = document.body.clientWidth - pos[1];
        if (width > limitWidth) {
            this.$thisNode.css("left", document.body.clientWidth - width - 2);
        }

        //定位箭头的位置
        this.$arrowNode.css("left", pos[1] + this.$thisNode.width() / 3 * 2);

        //设置iframe的样式
        $(".float_panel_content > div").css({
            "position": "static"
        });
        $(".float_panel_iframe").css({
            "width": this.$thisNode.width(),
            "height": this.$thisNode.height() + 20,
            "top": iframeTop,
            "left": this.$thisNode.css("left"),
            "display": "block"
        });
    }


    public bindClick(args: { item: { wid: string, isUp: boolean } }) {
        let wid = args.item.wid;
        let bindWidget: Widget = WidgetManager.byId(wid);
        let own = this;
        if (bindWidget) {
            let $bindNode = bindWidget.$thisNode;
            if (bindWidget instanceof CheckButton) {
                $bindNode = $bindNode.find("input");
            }
            $bindNode.on("click", function (e) {
                if (own.$thisNode.css("display") === "none") {
                    own.$thisNode.css("display", "block");
                    own.$arrowNode.show();
                    //定位
                    own.setLocation(bindWidget.$thisNode, args.item.isUp);
                    //添加全局click监听
                    own.addDocumentBind(wid);
                    //改变targetWidget的箭头指向
                    $(this).find(".personal_info_arrow").removeClass("mdi-navigation-arrow-drop-down").addClass("mdi-navigation-arrow-drop-up");
                }
                else {
                    own.$thisNode.css("display", "none");
                    own.$arrowNode.hide();
                    $(".float_panel_iframe").hide();
                    //改变targetWidget的箭头指向
                    $(this).find(".personal_info_arrow").removeClass("mdi-navigation-arrow-drop-up").addClass("mdi-navigation-arrow-drop-down");
                }
            });
        } else {
            this.bindClickCount++;
            if (this.bindClickCount > 5) {
                return;
            }
            setTimeout(function () {
                own.bindClick(args);
            }, 300);
        }
    }

    public dispose() {
        $(window).off("resize", this.resizeListener);
        super.dispose();
        this.$wrapNode.remove();
    }

    public setEnabled(args: { enabled: boolean }) {
        let enabled = args.enabled;
        if (!enabled) {
            //不可用并且在可见状态下，才设置不可见
            if (this.$thisNode.css("display") !== "none") {
                this.$wrapNode.css("display", "none");
                this.$thisNode.css("display", "none");
            }
        }
    }

    public setVisible(args: { visible: boolean }) {
        let visible = args.visible;
        if (visible) {
            this.$wrapNode.css("display", "block");
            this.$thisNode.css("display", "block");
        } else {
            this.$wrapNode.css("display", "none");
            this.$thisNode.css("display", "none");
        }
    }

    public append() {
        this.$thisNode.appendTo(this.$wrapNode.find(".content_wrap"));
        this.$arrowNode.appendTo(this.$wrapNode.find(".content_wrap"));
        this.$wrapNode.appendTo(document.body);
    }


}