import {Widget} from "widget/Widget";
import {EventHub} from "event/EventHub";
import {MessageType} from "event/MessageType";
import {Event} from "event/Event";
import {Keys} from "hotkey/Keys";
import {ADORE} from "ADORE";
import {Composite} from "widget/Composite";
import {TreeItem} from "widget/tree/TreeItem";
import {WidgetManager} from "util/WidgetManager";

export class Tree extends Composite {

    private static TemplateNormal = `
        <div style="overflow:auto;">
            <ul tabindex="-1" class="side-nav adore_tree adore_root_tree" style="left:0px;width:100%; position: inherit;webkit-box-shadow:none;box-shadow:none;transform:none;">
            </ul>
        </div>`;
    $thisNode: JQuery;
    children = new Array();
    treeId: string;
    $attachNode: JQuery;
    $delectNode: JQuery;
    candragAndDrop: boolean = false;
    indrag: boolean = false;


    constructor(parentId: string, id: string, style: number) {
        super(parentId, id, style);
        this.children = new Array();
        this.$thisNode = $(Tree.TemplateNormal).attr("id", this.id);
        this.$attachNode = this.$thisNode.find("ul");
        this.treeId = this.id;
        let own = this;
        this.$thisNode.find("ul").on("focus", function (e) {
            console.log("tree focus in");
            own.sendFocusGain();
        }).on("blur", function (e) {
        });
    }

    public addChild(child: Widget) {
        this.children.push(child);
    }

    public removeItem(args: { itemId: string }) {
        let itemId = args.itemId;
        if (itemId != null) {
            this.$delectNode = this.$thisNode.find("#" + itemId);
            this.$delectNode.remove();
        }
    }

    public dragAndDrop(args: { candragAndDrop: boolean }) {
        this.candragAndDrop = args.candragAndDrop;
        if (this.candragAndDrop === true) {
            this.initTree(this.treeId);
        }
    }

    private initTree(id: string) {
        let root = document.getElementById(id);
        if (root === null) {
            return false;
        }
        this.initEv();
    }

    private initEv() {
        let own = this;
        // document.onmousedown = function DragStart(e) {
        //     e = (window.event || e) as MouseEvent;
        //     this.DragObj = e.target || e.srcElement;
        //     if (this.DragObj.className !== `waves-effect`) return;
        //     this.tmpNode = document.getElementById(own.treeId);
        //     this.tmpNode.innerHTML = this.DragObj.lastChild.nodeValue;
        //     this.DragObj = this.DragObj.parentNode;
        //     this.indrag = true;
        //     this.x = e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
        //     this.y = e.pageY || (e.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
        //     this.left = parseInt(this.tmpNode.offsetLeft);
        //     this.top = parseInt(this.tmpNode.offsetTop);
        //     return false;
        // };
        // document.onmouseup = function DragStop(e) {
        //     if (!this.indrag) return;
        //     this.indrag = false;
        //     this.tmpNode.style.display = `none`;
        //     e = (e || window.event) as MouseEvent;
        //     this.target = e.target || e.srcElement;
        //     try {
        //         // let $node = $(own.treeParent).find("li.bold adore_tree");
        //         // if ($node.length <= 0) {
        //         //     $(own.treeParent).removeClass("adore_tree_node_selected active");
        //         //     $(own.treeParent).find("div.adore_tree_node_circle").remove();
        //         // }
        //         // let $nodeStop = $(this.target).parent().find(".collapsible-body");
        //         // if ($nodeStop.length > 0) {
        //         //     $nodeStop.append(this.DragObj);
        //         // } else {
        //         //     $(this.target).parent().append(this.DragObj);
        //         // }
        //         $(this.target).parent().find(".collapsible-body").first().append(this.DragObj);
        //     }
        //     catch (e) {
        //         alert("error");
        //     }
        //     return true;
        // };
        // document.onmousemove = function Draging(e) {
        //     if (!this.indrag) return;
        //     e = (e || window.event) as MouseEvent;
        //     let step = 10;
        //     let wh = window.innerHeight || document.body.clientHeight;

        //     if (e.clientY < 20) {
        //         window.scrollBy(0, -step);
        //     }
        //     else if (e.clientY > wh - 20) {
        //         window.scrollBy(0, step);
        //     }
        //     let x = e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
        //     let y = e.pageY || (e.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
        //     this.tmpNode.style.left = x + 2 + `px`;
        //     this.tmpNode.style.top = y + 2 + `px`;
        //     this.tmpNode.style.display = `block`;
        //     return false;
        // };
    }

    public layout() {
        // for(let i = 0 ; i < this.children.length ; i++){
        //     (<TreeItem>this.children[i]).append();
        // }
        // for(let i = 0 ; i < this.children.length ; i++){
        //     (<TreeItem>this.children[i]).layout();
        // }
    }

    public viewCheckbox(args: { viewCheckbox: boolean }) {
        var viewCheckbox = args.viewCheckbox;
        var $checkboxNodes = this.$attachNode.find("div input:checkbox").parent();
        if (viewCheckbox) {
            $checkboxNodes.css("display", "block");
        } else {
            $checkboxNodes.css("display", "none");
        }
    }

    public setCheckBoxState(args: { checkBoxState: string }) {
        //入参stateData是一个map，得出第几个input的状态要set成checked;
        let stateData = JSON.parse(args.checkBoxState);
        let z = this.$attachNode.find("label").length;
        for (let key in stateData) {
            let treeItem: TreeItem = WidgetManager.byId(key);
            if (treeItem) {
                let checked = treeItem.$checkboxNode.find("input:checkbox").eq(0).prop("checked");
                // 两者不相等的时候才需要重新设置值
                if (checked !== stateData[key]) {
                    treeItem.setCheckboxState(stateData[key]);
                    treeItem.refreshCheckState();
                }
            }
        }
    }

    public changeLeafLocation(args: { treeItemId: string, index: number }) {
        // 找到对应的TreeItem
        var treeItem: TreeItem = WidgetManager.byId(args.treeItemId);
        // 想要放的位置的索引
        let index = args.index;
        // 父亲孩子节点的数量
        let size = treeItem.parent.children.length;
        if(index < 0 || index >= size){
            index = size -1;
        }
        var treeItemIndex = treeItem.parent.children.indexOf(treeItem);
        if(treeItemIndex === index){
            // 索引一致，就不需要做任何动作了
            return;
        }
        let afterTreeItem = treeItem.$attachNode.siblings().eq(args.index);
        // 千万不要使用remove，这样子会把所有的事件都干掉；使用detach还会保留事件
        treeItem.$attachNode.detach();
        treeItem.$attachNode.insertBefore(afterTreeItem);
    }

    public moveNode(args: { currentNodeId: string, targetNodeId: string }) {
        // 找到当前的TreeItem
        let currentItem: TreeItem = WidgetManager.byId(args.currentNodeId);
        currentItem.$attachNode.detach();
        if (currentItem.parent) {
            let index = currentItem.parent.children.indexOf(currentItem);
            currentItem.parent.children.splice(index, 1);
        }
        let targetItem: TreeItem = WidgetManager.byId(args.targetNodeId);
        currentItem.parent = targetItem;
        targetItem.children.push(currentItem);
        currentItem.append();
        if (currentItem.parent) {
            var treeNode = currentItem.parent.$attachNode.find(".collapsible");
            if (treeNode) {
                treeNode.collapsible();
            }
        }
    }

    public sendFocusGain() {
        super.sendFocusGain();
    }

    public setFocus() {
        this.sendFocusGain();
    }


}