/*
 * 特别声明：本技术材料受《中华人民共和国著作权法》、《计算机软件保护条例》等法律、法规、行政
 * 规章以及有关国际条约的保护，赞同科技享有知识产权、保留一切权利并视其为技术秘密。未经本公司书
 * 面许可，任何人不得擅自（包括但不限于：以非法的方式复制、传播、展示、镜像、上载、下载）使用，
 * 不得向第三方泄露、透露、披露。否则，本公司将依法追究侵权者的法律责任。特此声明！
 *
 * 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.
 */
/**
 * Created by huangdeyun on 2015/3/13.
 */
define(["adoreapp/widget/BaseWidget", "adoreapp/widget/EventHub",
    "adoreapp/util/WidgetUtil","adoreapp/hotkey/Keys"], function (BaseWidget, EventHub, WidgetUtil, Keys) {
    return BaseWidget.extend(function (base) {
        return {
            _initWidget: function (attrs) {
                var template = attrs.template;
                this.templates = template.split("<!-- split -->");
                if (window.innerWidth <= 600) {
                    //小屏
                    this.jqueryNode = $(this.templates[1]).attr("id", this.id);
                } else {
                    //大、中屏
                    this.jqueryNode = $(this.templates[0]).attr("id", this.id);
                }
                this.attachNode = this.jqueryNode;
                this.titleNode = this.jqueryNode.find("h4");
                this.contentNode = this.jqueryNode.find("pre").attr("id", this.id + "_p");
                this.footerNode = this.jqueryNode.find("div.modal-footer");
            },
            _setTitle: function (attrs) {
                this.titleNode.text(attrs.title);
            },
            _setMessage: function (attrs) {
                this.contentNode[0].innerHTML = attrs.message.
                    replace(/</g, "&lt;").
                    replace(/>/g, "&gt;");
            },
            _createBtnNode: function (btnLabel, code) {
                var btnNode = $(this.templates[2]);
                var tmpId = this.id;
                btnNode.text(btnLabel);
                btnNode.appendTo(this.footerNode);
                btnNode.on("click", function (e) {
                    EventHub.dispatchEvent(EventHub.MSG_TYPE.WIDGET, {id: tmpId, evtType: EventHub.CLICK, returnCode: code });
                });
                var own = this;
                btnNode.on("focus", function (e) {
                    own.setCurrentFocusIndex(code);
                });
            },

            setCurrentFocusIndex: function (index) {
                this.currentFocusIndex = index;
            },

            _setMessageType: function (attrs) {
                //先删除原来的Btn
                this.footerNode.find("a").remove();
                /**
                 * 根据Dialog类型添加按钮
                 */
                var type = attrs.messageType;
                var tmpId = this.id;
                // confirm Dialog
                if (type === "confirm") {
                    // Ok Button and  Cancel Button
                    this._createBtnNode("Cancel", 1);
                    this._createBtnNode("Ok", 0);
                }
                // question Dialog
                else if (type === "question") {
                    // Yes Button and No Button
                    this._createBtnNode("No", 1);
                    this._createBtnNode("Yes", 0);
                }
                // information Dialog
                else if (type === "information") {
                    //Ok Button
                    this._createBtnNode("Ok", 0);
                }
            },
            _setButtonLables: function (attrs) {
                //先删除原来的Btn
                this.footerNode.find("a").remove();
                var btnLabels = attrs.buttonTexts;
                var btnLabelArr = btnLabels.split("<!-- split -->");
                var len = btnLabelArr.length;
                for (var i = len - 1; i >= 0; i--) {
                    this._createBtnNode(btnLabelArr[i], i);
                }
            },
            _layout: function () {
                this.append();
            },
            _setModal: function (attrs) {
                this.modal = attrs.modal + "";
            },
            _show: function () {
                var dismiss = this.modal === "false";
                var tmpId = this.id;
                var own = this;
                var btns = $("#" + tmpId).find("div.modal-footer").find("a").reverse();
                this.currentFocusIndex = 0;
                var index = this.currentFocusIndex;
                $("#" + this.id).openModal({
                    dismissible: dismiss, // Modal can be dismissed by clicking outside of the modal
                    opacity: .5, // Opacity of modal background
                    in_duration: 300, // Transition in duration
                    out_duration: 200, // Transition out duration
                    ready: function () {
                        // Callback for Modal open
                        if (btns.length !== 0) {
                            $(btns[index]).focus();
                        }
                        $(document).bind("keydown." + tmpId, function (e) {
                            own.handleKeydown(e);
                        });
                        $(document).bind("click." + tmpId, function (e) {
                            own.handleClick(e);
                        });
                    },
                    complete: function () {
                        $(document).unbind("keydown." + tmpId);
                        $(document).unbind("click." + tmpId);
                        EventHub.dispatchEvent(EventHub.MSG_TYPE.WIDGET, {id: tmpId, evtType: EventHub.CLICK, returnCode: -1 });
                    }
                });

                //需要根据内容调整dialog大小
                if (window.innerWidth <= 600) {
                    if (this.resetDialogSize("adore_dialog_mobile_size_level_1", "adore_dialog_mobile_size_level_2")) {
                        this.resetDialogSize("adore_dialog_mobile_size_level_2", "adore_dialog_mobile_size_level_3");
                    }
                } else {
                    if (this.resetDialogSize("adore_dialog_size_level_1", "adore_dialog_size_level_2")) {
                        this.resetDialogSize("adore_dialog_size_level_2", "adore_dialog_size_level_3");
                    }
                }
                $("#lean-overlay").remove();
                $(this.templates[3]).attr("id", this.id + "_lean_overlay").appendTo(document.body);

                WidgetUtil.refreshDialogZIndex(this.jqueryNode[1]);
            },

            handleClick: function (e) {
                var btns = this.jqueryNode.find("div.modal-footer").find("a");
                if (!btns.is(e.target)) {
                    this.currentFocusIndex = -1;
                }
            },

            handleKeydown: function (e) {
                var btns = this.jqueryNode.find("div.modal-footer").find("a").reverse();
                //tab 9 //arrow_down 40 //arrow_right 39
                if (e.keyCode === Keys.TAB || e.keyCode === Keys.DOWN_ARROW || e.keyCode === Keys.RIGHT_ARROW) {
                    this.currentFocusIndex++;
                    if (this.currentFocusIndex >= btns.length) {
                        this.currentFocusIndex = 0;
                    }
                    $(btns[this.currentFocusIndex]).focus();
                    e.preventDefault();
                }
                //arrow_left 37 //arrow_up 38
                else if (e.keyCode === Keys.LEFT_ARROW || e.keyCode === Keys.UP_ARROW) {
                    this.currentFocusIndex--;
                    if (this.currentFocusIndex < 0) {
                        this.currentFocusIndex = btns.length - 1;
                    }
                    $(btns[this.currentFocusIndex]).focus();
                    e.preventDefault();
                }
                //enter 13
                else if (e.keyCode === Keys.ENTER) {
                    if (this.currentFocusIndex >= 0 && this.currentFocusIndex < btns.length) {
                        $(btns[this.currentFocusIndex]).click();
                    }
                    e.preventDefault();
                }
            },

            resetDialogSize: function (removeClass, addClass) {
                var titleH = this.jqueryNode.find("div.adore_dialog_title").height();
                var footerH = this.footerNode.height();
                var contentH = this.contentNode.height();
                var totalH = $("#" + this.id).height();
                //内容区可用的高度
                var contentCanUseH = totalH - titleH - footerH;
                if (contentH >= contentCanUseH) {
                    this.jqueryNode.removeClass(removeClass).addClass(addClass);
                    return true;
                }
                return false;
            },

            _handleKeyUpEvent: function (e) {
            },

            _handleKeyDownEvent: function (e, hasFilter) {
            },

            _dispose: function () {
                $(".lean-overlay").remove();
                $("#" + this.id + "_lean_overlay").remove();
                $(document).unbind("keydown." + this.id);
                $(document).unbind("click." + this.id);
                base._dispose.call(this);
            }
        }
    })
})