import {ResDataControl} from "../Control/ResDataControl";
import {ResourceControl} from "../Control/ResourceControl";
import { DispatcherManager } from "../utils/DispatcherManager";
import {PanelResDic} from "../PrefabControl/PanelResDic";
import {ViewAction} from "../utils/ViewAction";
import { ViewManager } from "../View/ViewManager";
import { Global } from "../Global";
import {ComponentEventData} from "../Data/ComponentEventData";
import {GamePool} from "../PrefabControl/GamePool";
import {GlobalWaiting} from "../GlobalWaiting";

/*
* name;
*/
export class PanelBaseControl extends fairygui.Window {
    static viewbgUrl:string = "";
    isguideing:boolean=false;
    private PackageName: string = "";
    private ResourcesName: string = "";
    private _isAddpackage: boolean;
    private _iscache: boolean = true;
    private _ActionType:string = ViewAction.ActionType_none;

    item_panel: fairygui.GComponent;
    item_bg: fairygui.GComponent;
    private _clickBg: fairygui.GLoader;

    private _clickBgIsColse: number = 0;

    public viewKey: any;
    public gameLayer:string;

    /**
     * 事件容器
     */
    private EventResDic:any = {};
    /**
     * 全局事件容器
     */
    private EventGlobal:any = {};

    /**
     * 界面初始化
     * @param pkgName 包名
     * @param resName 界面名
     * @param isAddpackage 是否添加包 
     * @param ActionType 界面打开动画类型
     * @param clickBgIsColse 黑色背景 0:无背景 1:背景无关闭事件 2:背景有关闭事件
     * @param iscache 是否添加到缓存池（如是为true,则加入进缓存池定时根据是否引用清理。 若是为false，则不清理当前缓存，如若清理，请手动清理 ）
     */
    constructor(pkgName: string = "", resName: string = "", isAddpackage: boolean = false, 
                ActionType:string=ViewAction.ActionType_none, clickBgIsColse:number=0, iscache: boolean = true) {
        super();
        this._iscache = iscache;
        this.PackageName = pkgName;
        this.ResourcesName = resName;
        this._isAddpackage = isAddpackage;
        this._ActionType = ActionType;
        this._clickBgIsColse = clickBgIsColse;
        this.showModalWait();
    }


    protected ResolveUI(pkgname: string, resname: string, isaddpackage: boolean,ActionType:string=ViewAction.ActionType_none, clickBgIsColse:number=0, iscache: boolean = true): void {
        this.PackageName = pkgname;
        this.ResourcesName = resname;
        this._ActionType = ActionType;
        this._clickBgIsColse = clickBgIsColse;
        ResDataControl.Instance.AddViewPackByName(pkgname, isaddpackage, iscache);
        this.contentPane = fairygui.UIPackage.createObject(pkgname, resname).asCom;
        for (var str in this.contentPane._children) {
            var item: fairygui.GObject = this.contentPane._children[str];
            if (item.name == "item_panel") {
                var itempanel: fairygui.GComponent = item as fairygui.GComponent;
                if (itempanel) {
                    for (var str1 in itempanel._children) {
                        var itempanelItem: fairygui.GObject = itempanel._children[str1];
                        this[itempanelItem.name] = itempanelItem;
                    }
                }
                // this[item.name] = item;
                this.item_panel = item as fairygui.GComponent;
            }
            else {
                this[item.name] = item;
            }
        }
        this.setSize(fairygui.GRoot.inst.width, fairygui.GRoot.inst.height);
        this.contentPane.setPivot(0.5,0.5);
        this.setPivot(0.5, 0.5);
        this.setclickBgIsColse();
        this.initView();
        this.initEvent();
        this.ShowViewACTION();
    }
    

    private _loadTarget:any;
    private _onLoadedHandler:Function;
    /**
     * 加载ui
     * @param groupName 组名
     * @param target    作用域
     * @param onLoadedHandler 加载完成回调函数
     */
    protected LoadViewUI(groupName: string, target: any, onLoadedHandler: Function): void {
        this._loadTarget = target;
        this._onLoadedHandler = onLoadedHandler;
        ResourceControl.Instance.loadGroup(groupName, this, this.LoadComplete);
    }


    /******************************************************************* */
    private createLabel(color: string, strokeColor: string):Laya.Label {
        const STROKE_WIDTH: number = 4;
        var label:Laya.Label = new Laya.Label();
        label.font = "Microsoft YaHei";
        label.text = "SAMPLE DEMO";
        label.fontSize = 30;
        label.color = color;
        if (strokeColor) {
            label.stroke = STROKE_WIDTH;
            label.strokeColor = strokeColor;
        }
        Laya.stage.addChild(label);
        return label;
    }
    /****************************************************************** */

    /**
     * 加载资源数组
     * @param urls 资源数组
     * @param target 作用域
     * @param onLoadedHandler 加载完成回调函数
     */
    protected loadUibyArr(urls: Array<any>, target: any, onLoadedHandler: Function): void {
        // this.showModalWait();
        this._loadTarget = target;
        this._onLoadedHandler = onLoadedHandler;
        ResourceControl.Instance.Loaders(urls, this, this.LoadComplete);    
    }

    /********************************************************************* */
    private createRadioGroup(skin: string):Laya. RadioGroup {
        var rg:Laya. RadioGroup = new Laya.RadioGroup();
        rg.skin = skin;

        rg.space = 70;
        rg.direction = "v";

        rg.labels = "Item1, Item2, Item3";
        rg.labelColors = "#787878,#d3d3d3,#FFFFFF";
        rg.labelSize = 20;
        rg.labelBold = true;
        rg.labelPadding = "5,0,0,5";

        rg.selectHandler = new Laya.Handler(this, this.onSelectChange);
        Laya.stage.addChild(rg);

        return rg;
    }
    private onSelectChange(index: number): void {
        console.log("你选择了第 " + (index + 1) + " 项");
    }
    /********************************************************************* */


    private LoadComplete():void
    {
        if( this._loadTarget && this._onLoadedHandler )
        {
            this._onLoadedHandler.call( this._loadTarget );
        }
    }

    protected removeEffectPackage(packageName: string): void {
        ResDataControl.Instance.ClearPackByName(packageName, true);
    }

    protected getpanelController(name: string): fairygui.Controller {
        if (this.item_panel) {
            return this.item_panel.getController(name);
        }
        return null;
    }

    /************************************************************ */
    private setup(): void {
        this.createLabel("#FFFFFF", null).pos(30, 50);
        this.createLabel("#00FFFF", null).pos(290, 50);
        this.createLabel("#FFFF00", "#FFFFFF").pos(30, 100);
        this.createLabel("#000000", "#FFFFFF").pos(290, 100);
        this.createLabel("#FFFFFF", "#00FFFF").pos(30, 150);
        this.createLabel("#0080FF", "#00FFFF").pos(290, 150);
    }
   /************************************************************ */

   
    protected getpanelTransition(name: string): fairygui.Transition {
        if (this.item_panel) {
            return this.item_panel.getTransition(name);
        }
        return null;
    }

    protected getChildformContentPanel( name:string ):fairygui.GObject
    {
        if(this.contentPane){
            return this.contentPane.getChild(name);
        }
        return null;
    }

    /*界面初始化*/
    protected onInit(): void {
        super.onInit();
        if (this.PackageName != "" && this.ResourcesName != "") {
            this.ResolveUI(this.PackageName, this.ResourcesName, this._isAddpackage,this._ActionType,this._clickBgIsColse, this._iscache);
        }
    }

    //解析ui
    

    protected initView():void
    {

    }

    protected initEvent():void
    {

    }

    protected ShowViewACTION():void 
    {
        switch( this._ActionType )
        {
            case ViewAction.ActionType_none:
                this.windowanmoend();
            break;
            case ViewAction.ActionType_addmoveToMiddle:
                this.contentPane.x = fairygui.GRoot.inst.width;
                Laya.Tween.to(this.contentPane, { x:0 },300, laya.utils.Ease.quadInOut, Laya.Handler.create(this, this.windowanmoend));
            break;
            case ViewAction.ActionType_addmoveFromBottom:
                this.contentPane.y = fairygui.GRoot.inst.height;
                Laya.Tween.to(this.contentPane, { y:0 },300, laya.utils.Ease.quadInOut, Laya.Handler.create(this, this.windowanmoend));
            break;
            case ViewAction.ActionType_addscaleMinToMax:
                this.contentPane.scaleX = this.contentPane.scaleY = 0.01;
                Laya.Tween.to(this.contentPane, { scaleX:1,scaleY:1 },300, laya.utils.Ease.quadInOut, Laya.Handler.create(this, this.windowanmoend));
            break;
        }
    }

    /******************************************************** */
    private createCheckBox(skin: string):Laya.CheckBox {
        var cb:Laya. CheckBox = new Laya.CheckBox(skin);
        Laya.stage.addChild(cb);

        cb.labelColors = "white";
        cb.labelSize = 20;
        cb.labelFont = "Microsoft YaHei";
        cb.labelPadding = "3,0,0,5";

        return cb;
    }
    private updateLabel(checkBox:Laya.CheckBox): void {
        checkBox.label = checkBox.selected ? "已选中" : "未选中";
    }
   /******************************************************** */


    private windowanmoend():void
    {
        Laya.timer.callLater( this,this.onShowView );
    }

    protected onShowView():void
    {
        this.closeModalWait();
        this.showClickBg();
    }

    private showClickBg():void
    {
        if( this._clickBg )
        {
            this._clickBg.alpha = 0.55;
            if( this._clickBgIsColse==2 && !this.hasClickListener() )
            {
                this._clickBg.onClick(this, this.ClickExitView);
            }
        }
    }

    /**点击关闭页面按钮 */
    public ClickExitView():void
    {
        ViewManager.Instance.close( this.viewKey,true );
    }


    /*获取管理数据模块*/
    public getProxy(d: any): any {
        return PanelResDic.Instance.getSingleTon(d);
    }

    /**
     * 界面关闭事件
     */
    public ExitView( ActionType:string = "" ):void
    {
        if( this._clickBg )
        {
            this._clickBg.visible = false;
        }
        if( ActionType == "" )
        {
            switch( this._ActionType )
            {
                case ViewAction.ActionType_none:
                this.destory();
            break;
            case ViewAction.ActionType_addmoveToMiddle:
                Laya.Tween.to(this, { x:fairygui.GRoot.inst.width },300, laya.utils.Ease.quadInOut, Laya.Handler.create(this, this.destory));
            break;
            case ViewAction.ActionType_addmoveFromBottom:
                Laya.Tween.to(this, { y:fairygui.GRoot.inst.height },300, laya.utils.Ease.quadInOut, Laya.Handler.create(this, this.destory));
            break;
            case ViewAction.ActionType_addscaleMinToMax:
                Laya.Tween.to(this, { scaleX:0.01,scaleY:0.01 },300, laya.utils.Ease.quadInOut, Laya.Handler.create(this, this.destory));
            break;
            }
        }
        else
        {
            switch( ActionType )
            {
                case ViewAction.ActionType_none:
                    this.destory();
                break;
                case ViewAction.ActionType_removescaleMaxToMin:
                    Laya.Tween.to(this, { scaleX:0.01,scaleY:0.01 },300, laya.utils.Ease.quadInOut, Laya.Handler.create(this, this.destory));
                break;
                case ViewAction.ActionType_removemoveToRight:
                Laya.Tween.to(this, { x:fairygui.GRoot.inst.width },300, laya.utils.Ease.quadInOut, Laya.Handler.create(this, this.destory));
                break;
            }
        }
    }

  

    public getTransitionByName(id: string): fairygui.Transition {
        return this.contentPane.getTransition(id);
    }

    

    /**注册事件 */
    public dispacheDatatrigger(type: string, data: any = null): void {
        DispatcherManager.dispatchEvent(type, data);
    }

    /**
     * 注册全局事件
     * @param type 
     * @param thisObject 
     * @param listener 
     */
    protected addDataEvent(type: string, thisObject: any, listener: Function): void {
        if( !this.EventGlobal.hasOwnProperty( type ) )
            {
                var vo:ComponentEventData = GamePool.GetItem( ComponentEventData.ResDicValue );
                this.EventGlobal[type] = vo;
                vo.type = type;
                vo.thisObject = thisObject;
                vo.listener = listener;
                DispatcherManager.addEventListener(type, thisObject,listener);
            }
    }

    /**
     * 移除全局事件
     * @param type 
     * @param thisObject 
     * @param listener 
     */
    protected ClearEventData(type: string, thisObject: any, listener: Function): void {
        if( this.EventGlobal[type] )
        {
            var vo:ComponentEventData = this.EventGlobal[type];
            DispatcherManager.removeEventListener(type, thisObject, listener);
            vo.clear();
            delete this.EventGlobal[type];
        }
    }

    /**
     * 移除组件事件
     * @param type 时间类型
     * @param callbackobj 作用域
     * @param callbackHandler 事件回调 
     */
    protected ClearEventByType( target:any, type: string, thisObject: any, listener: Function ):void
    {
        if( target && this.EventResDic[target.name] )
        {
            var arr:Array<ComponentEventData> = this.EventResDic[target.name];
            var i:number=0;
            var nums:number = arr.length;
            var vo:ComponentEventData;
            for(i;i<nums;i++)
            {
                vo = arr[i];
                if( vo && vo.type==type && vo.thisObject == thisObject && vo.listener == listener )
                {
                    target.off( type,thisObject,listener );
                    vo.clear();
                    arr.splice( i,1 );
                    break;
                }
            }
        }
    }

    /**
     * 注册组件事件，调用此方法，界面关闭会自动移除
     * @param type 时间类型
     * @param callbackobj 作用域
     * @param callbackHandler 事件回调
     */
    public AddEventByType( target:any, type: string, thisObject: any, listener: Function,args:any=null):void
    {
        if( target )
        {
            if( target.name == null || target.name == "" )
            {
                throw "baseview addListener target.name is null";
            }
            var vo:ComponentEventData = GamePool.GetItem( ComponentEventData.ResDicValue );
            vo.target = target;
            vo.type = type;
            vo.thisObject = thisObject;
            vo.listener = listener;
            if( !this.EventResDic.hasOwnProperty( target.name ) )
            {
                this.EventResDic[target.name] = [];
            }
            var bo:boolean = this.JudgeIsHaveEvent( target,type );
            if( !bo )
            {
                target.on( type,thisObject,listener,args );
                this.EventResDic[target.name].push( vo );
            }
        }
    }

    /**判断是否含有事件 */
    public JudgeIsHaveEvent( target:any,type: string ):boolean
    {
        var eventArr:Array<ComponentEventData>;
        eventArr = this.EventResDic[target.name];
        var childvo:ComponentEventData;
        for( var s in eventArr )
        {
            childvo = eventArr[s];
            if( childvo && childvo.type == type )
            {
                return true;
            }
        }
        return false;
    }

    
    public getComById(id: string): fairygui.GComponent {
        return this.contentPane.getChild(id).asCom;
    }

    public getControllerByBame(id: string): fairygui.Controller {
        return this.contentPane.getController(id);
    }
    

    /**
     * 移除所有组件事件
     */
    public ClearEvent():void
    {
        if(this.EventResDic)
        {
            var s;
            var dict:any = this.EventResDic;
            var arr:Array<ComponentEventData>;
            var i:number;
            var nums:number = 0;
            var vo:ComponentEventData;
            for( s in dict )
            {
                arr = dict[s];
                if( arr && arr.length > 0 )
                {
                    i=0;
                    nums = arr.length;
                    for( i=nums-1;i>=0;i-- )
                    {
                        vo = arr[i];
                        if( vo )
                        {
                            if( vo.target )
                            {
                                vo.target.off( vo.type,vo.thisObject,vo.listener );
                            }
                            vo.clear();
                        }
                        arr.splice( i,1 );
                    }
                }
                delete this.EventResDic[s];
            }
        }
        this.EventResDic = {};
    }

    public clearEvent():void
    {

    }

    /* 销毁*/
    public destory(): void {
        this.clearEvent();
        this.closeModalWait();
        this.ClearGlobalEvent();
        this.ClearEvent();
        this._loadTarget = null;
        this._onLoadedHandler = null;
        Laya.Tween.clearTween( this );
        ResDataControl.Instance.ClearPackByName(this.PackageName, false);
        this.PackageName = null;
        this.ResourcesName = null;
        if (this._clickBg) {
            this._clickBg.offClick(this, this.ClickExitView);
            this._clickBg.dispose();
            this._clickBg = null;
        }
        this.viewKey = null;
        this.dispose();
    }


    public setclickBgIsColse() {
        if (this.isShowing && this._clickBgIsColse > 0 && this.contentPane) {
            if (!this._clickBg && PanelBaseControl.viewbgUrl != "" ) {
                this._clickBg = new fairygui.GLoader();
                this._clickBg.touchable = true;
                this._clickBg.setSize(fairygui.GRoot.inst.width, fairygui.GRoot.inst.height);
                this._clickBg.url = PanelBaseControl.viewbgUrl;
                this._clickBg.fill = fairygui.LoaderFillType.ScaleFree;
                this._clickBg.alpha = 0;
                this.contentPane.addChildAt(this._clickBg, 0);
            }
        }
    }


    /**
     * 移除所有全局事件
     */
    public ClearGlobalEvent():void
    {
        if( this.EventGlobal )
        {
            var s;
            var dict:any = this.EventGlobal;
            for( s in dict )
            {
                var vo:ComponentEventData = dict[s];
                if( vo )
                {
                    this.ClearEventData( vo.type,vo.thisObject,vo.listener );
                }
            }
        }
        this.EventGlobal={};
    }
}