/*
 * 特别声明：本技术材料受《中华人民共和国著作权法》、《计算机软件保护条例》等法律、法规、行政
 * 规章以及有关国际条约的保护，赞同科技享有知识产权、保留一切权利并视其为技术秘密。未经本公司书
 * 面许可，任何人不得擅自（包括但不限于：以非法的方式复制、传播、展示、镜像、上载、下载）使用，
 * 不得向第三方泄露、透露、披露。否则，本公司将依法追究侵权者的法律责任。特此声明！
 *
 * 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 {EventHub} from "event/EventHub";
import {Event} from "event/Event";
import {MessageType} from "event/MessageType";
import {WidgetUtil} from "util/WidgetUtil";
import {Keys} from "hotkey/Keys";
/**
 * Created by huang.dy on 2016/5/29.
 */
export class MessageDialog extends Widget {

    private static Template: string = `
        <div class="modal modal-fixed-footer adore_dialog adore_dialog_size_level_1">
            <div class="adore_dialog_title">
                <h4 class="adore_dialog_title_content"></h4>
            </div>
            <div class="modal-content adore_dialog_message">
                <pre class="adore_dialog_message_content"></pre>
            </div>
            <div class="modal-footer"></div>
        </div>`;
    private static TemplateWrap = `
	    <div class="messageWrap">
	    <iframe class="myclass"></iframe><div class="messageWrap"></div>
    </div>`;
    private static TemplateButton = `<a href="#" class="waves-effect btn-flat modal-action modal-close adore_dialog_btn">Ok</a>`;

    private static TemplateOverlay = `<div class="adore_lean_overlay"></div>`;

    private static TemplateCloseButton: string = `
     <a href="#" class="waves-effect btn-flat modal-action modal-close adore_dialog_btn adore_dialog_cancel_icon large mdi-content-clear">
     </a>
    `;

    private $titleNode: JQuery;
    private $contentNode: JQuery;
    private $footerNode: JQuery;
    private $wrapMessage: JQuery;
    private currentFocusIndex: number;
    private modal: boolean = true;
    private type: number;
    private clickListener: any;
    private resizeListener: any;
    constructor(parentId: string, id: string, style: number) {
        super(parentId, id, style);
        this.$thisNode = $(MessageDialog.Template).attr("id", this.id);
        this.$wrapMessage = $(MessageDialog.TemplateWrap).attr("id", this.id + "_wrap");
        this.$titleNode = this.$thisNode.find("h4");
        this.$contentNode = this.$thisNode.find("pre").attr("id", this.id + "_p");
        this.$footerNode = this.$thisNode.find("div.modal-footer");
    }

    public setFocus() {

    }

    public setTitle(args: { title: string }) {
        this.$titleNode.text(args.title);
    }

    public setMessage(args: { message: string }) {
        this.$contentNode[0].innerHTML = args.message.replace(/</g, "&lt;").replace(/>/g, "&gt;");
    }


    private createBtnNode(btnLabel: string, code: number) {
        let $btnNode = $(MessageDialog.TemplateButton);
        $btnNode.text(btnLabel);
        $btnNode.appendTo(this.$footerNode);
        let own = this;
        $btnNode.on("click", (e: BaseJQueryEventObject) => {
            if (own.type === 2) {
                if (code === 0) {//text类型
                    let value = own.$thisNode.find("input").val();
                    EventHub.dispatchEvent(MessageType.WIDGET, { id: own.id, evtType: Event.CLICK, inputText: value });
                } else {
                    EventHub.dispatchEvent(MessageType.WIDGET, { id: own.id, evtType: Event.CLICK, inputText: "" });
                }

            } else if (own.type === 1) {//combo类型
                if (code === 0) {
                    let text = own.$thisNode.find("select").val();
                    EventHub.dispatchEvent(MessageType.WIDGET, { id: own.id, evtType: Event.CLICK, inputText: text });
                } else {
                    EventHub.dispatchEvent(MessageType.WIDGET, { id: own.id, evtType: Event.CLICK, inputText: "" });
                }
            } else {
                EventHub.dispatchEvent(MessageType.WIDGET, { id: this.id, evtType: Event.CLICK, returnCode: code });
                //own.dispose();
            }

        });
        $btnNode.on("focus", (e: BaseJQueryEventObject) => {
            this.setCurrentFocusIndex(code);
        });
    }


    private setCurrentFocusIndex(index: number) {
        this.currentFocusIndex = index;
    }


    public setMessageType(args: { messageType: string }) {
        //先删除原来的Btn
        this.$footerNode.find("a").remove();
        /**
         * 根据Dialog类型添加按钮
         */
        let type = args.messageType;
        let 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);
        }
        //close Dialog 带有关闭按钮的message Dialog样式
        else if (type === "close") {
            // Ok Button and  Cancel Button
            this.createBtnNode("Cancel", 1);
            this.createBtnNode("Ok", 0);

            let closeIcon: JQuery = $(MessageDialog.TemplateCloseButton);
            let $titleBlock: JQuery = this.$thisNode.find(".adore_dialog_title");
            $titleBlock.append(closeIcon);
        }
    }

    public setButtonTexts(args: { buttonTexts: string }) {
        //先删除原来的Btn
        this.$footerNode.find("a").remove();
        let btnLabels = args.buttonTexts;
        let btnLabelArr = btnLabels.split("<!-- split -->");
        let len = btnLabelArr.length;
        for (let i = len - 1; i >= 0; i--) {
            this.createBtnNode(btnLabelArr[i], i);
        }
    }

    public setModal(args: { modal: boolean }) {
        this.modal = args.modal;
    }

    public show() {
        this.$thisNode.appendTo(this.$wrapMessage.find(".messageWrap"));
        this.$wrapMessage.appendTo(document.body);

        let own = this;
        let btns: any = ($("#" + this.id).find("div.modal-footer").find("a") as any).reverse();
        this.currentFocusIndex = 0;
        let index = this.currentFocusIndex;
        this.$thisNode.css({
            display: "block",
            opacity: 0,
            scaleX: "0.7"
        });
        this.$thisNode.velocity({ opacity: 1, scaleX: "1" }, {
            duration: 320,
            queue: false,
            ease: "easeOutCubic"
        });
        own.wrapBlockLocation();
        this.resizeListener = function () {
            own.wrapBlockLocation();
        };
        $(window).on("resize", this.resizeListener);
        //需要根据内容调整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");
            }
        }
        $(MessageDialog.TemplateOverlay).attr("id", this.id + "_overlay").appendTo(document.body);

        WidgetUtil.refreshDialogZIndex(this.$thisNode[0]);

        //把焦点设置到第一个按钮上
        if (btns.length !== 0) {
            $(btns[index]).focus();
        }
        this.clickListener = function (e: BaseJQueryEventObject) {
            own.handleClick(e);
        };
        $(document).on("click", this.clickListener);
    }


    private handleKeydown(e: KeyboardEvent) {
        let btns: any = (this.$thisNode.find("div.modal-footer").find("a") as any).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();
        }
    }

    private handleClick(e: BaseJQueryEventObject) {
        let btns: JQuery = this.$thisNode.find("div.modal-footer").find("a");
        if (!btns.is(this)) {
            this.currentFocusIndex = -1;
        }
    }

    public wrapBlockLocation() {
        this.$wrapMessage.find(".myclass").css({
            "width": this.$thisNode.width(),
            "height": this.$thisNode.height(),
            "left": this.$thisNode.offset().left,
            "top": this.$thisNode.offset().top
        });
    }

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

    public dispose() {
        $("#" + this.id + "_overlay").remove();
        if (this.clickListener) {
            $(document).off("click", this.clickListener);
        }
        if (this.resizeListener) {
            $(window).off("resize", this.resizeListener);
        }
        super.dispose();
        this.$wrapMessage.remove();
    }

    public handleKeyUpEvent(e: KeyboardEvent) {
    }

    public handleKeyDownEvent(e: KeyboardEvent, hasFilter: boolean) {
        this.handleKeydown(e);
    }

    public setInputType(args: { initialText: String }) {
        this.type = 2;
        let initialText = args.initialText;
        //找到Content.parent
        let $modalContent = this.$contentNode.parent();
        let $input = $("<input></input>");
        $input.val(initialText + "");
        $input.appendTo($modalContent);
    }
    /**
     * @attrs:{initialText:"",comboArr:["","",...]}
     */
    public setComboType(args: { combo: { initialText: String, comboArr: String[] } }) {
        this.type = 1;
        let data = args.combo;
        let initialText = data.initialText;
        let comboArr = data.comboArr;
        if (!comboArr || comboArr.length === 0) {
            return;
        }
        let $t = $("<select></select>");
        for (let i = 0; i < comboArr.length; i++) {
            let option = $("<option></option>").text(comboArr[i] + "");
            if (initialText === comboArr[i]) {
                option.prop("selected", true);
            }
            option.appendTo($t);
        }
        $t.appendTo(this.$contentNode.parent());

    }

}