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

    private static keyboardShowed: boolean;

    // 软键盘高度占整个屏幕高度的比例
    private static proportion: number;

    private static lastPanelID: string;
    private static lastOverflowYValue: string;
    private static lastDisplayValue: string;

    public static handleSoftwareKeyboardShow(args: { proportion: number }) {
        this.keyboardShowed = true;
        this.proportion = args.proportion;
        this.refresh();
    }

    public static refresh() {
        if (this.keyboardShowed === true) {
            let keyboardHeightProportion = this.proportion;
            let element = document.activeElement as HTMLElement;
            let widget = WidgetUtil.findWidgetByTarget(element);
            if (widget && widget.toString() === "Text") {//只有文本框才处理软键盘遮挡输入域
                //计算softKeyboard的高度
                let softKeyboardHeight = keyboardHeightProportion * window.innerHeight;
                let textWidget = widget as Text;
                this.scroll(textWidget.panelID, widget.$thisNode[0], softKeyboardHeight);
            }
        }
    }

    public static refreshKeyboardHide() {
        $("#softKeyboardDiv").remove();
        if (this.lastPanelID) {
            $("#" + this.lastPanelID).css({ "overflow-y": this.lastOverflowYValue, "display": this.lastDisplayValue });
            this.lastPanelID = null;
        }
    }

    public static handleSoftwareKeyboardHide() {
        this.keyboardShowed = false;
        this.refreshKeyboardHide();
    }

    /**
       * 控制滚动条往上滚，不让软键盘遮挡textNode
       * */
    private static scroll(panelID: string, textNode: HTMLElement, softKeyboardHeight: number) {
        if (this.lastPanelID !== panelID) {
            this.refreshKeyboardHide();
        }
        let top = this.getElementViewBottom(textNode);
        let i: number; //i用于for循环
        if (softKeyboardHeight - top >= 1) {//软键盘已经把输入域遮挡
            let containerNode = $("#" + panelID);
            this.lastPanelID = panelID;
            //小窗口交易只需滚小窗口的内容区即可
            if ($("div.adore_shell_content").length !== 0) {
                let adoreShells = $("div.adore_shell_content");
                for (i = 0; i < adoreShells.length; i++) {
                    if ($(adoreShells[i]).find("#" + panelID).length !== 0) {
                        containerNode = $(adoreShells[i]);
                        break;
                    }
                }
            }
            let container = containerNode[0];
            this.lastOverflowYValue = containerNode.css("overflow-y");
            this.lastDisplayValue = containerNode.css("display");
            // 添加样式让面板可滚动，软键盘隐藏后再重置回去
            containerNode.css({ "overflow-y": "auto", "display": "block" });
            //往上滚
            container.scrollTop = container.scrollTop + (softKeyboardHeight - top);
            let afterTop = this.getElementViewBottom(textNode);
            if (softKeyboardHeight - afterTop >= 1) {
                //滚了一次之后，软键盘还是遮挡textNode，往container容器添加一个高度为softKeyboardHeight的透明div
                let tempDivNode = $("<div></div>").css({
                    height: softKeyboardHeight + "px",
                    width: "1px"
                }).attr({ id: "softKeyboardDiv" });

                //滚动区是绝对布局的情况下，需要定位空div的top位置让他处于滚动区的最底部
                if (containerNode.css("position") === "absolute") {
                    let children = containerNode.children();
                    let totalHeight = 0;
                    for (i = 0; i < children.length; i++) {
                        totalHeight += children[i].offsetHeight;
                    }
                    let tempDivTop = container.offsetHeight >= totalHeight ? container.offsetHeight : totalHeight;
                    tempDivNode.css({
                        position: "absolute",
                        top: tempDivTop + "px"
                    });
                }
                tempDivNode.appendTo(container);
                //再往上滚
                container.scrollTop = container.scrollTop + (softKeyboardHeight - afterTop);
            }
        }
    }

    /**
     * 获取元素相对于屏幕下方的的距离
     * */
    private static getElementViewBottom(element: HTMLElement): number {
        let top = element.getBoundingClientRect().top;
        return window.innerHeight - top - element.offsetHeight;
    }

}