import {PanelBaseControl} from "../Control/PanelBaseControl";
import {GameStateControl} from "../Control/GameStateControl";
import { DispatcherManager } from "../utils/DispatcherManager";
import {GameState} from "../utils/GameState";
import {PropManager} from "../PrefabControl/PropManager";
import {AgencyUserMessage} from "../Agency/AgencyUserMessage";
import {RoleData} from "../Data/RoleData";
import {UserInfoEvent} from "../Data/UserInfoEvent";
import {AgencySkin} from "../Agency/AgencySkin";
import {AgencyInGame} from "../Agency/AgencyInGame";
import { GlobalTip } from "../utils/GlobalTip";
import { ViewManager } from "../View/ViewManager";
import {AgencyLottery} from "../Agency/AgencyLottery";
import ChoutiPanView from "../Push/ChoutiPanView";
import TuijianView from "../Push/TuijianView";
import { FYHD_Sdk } from "../WXSDK/FYHD_Sdk";
import { ttad } from "../WXSDK/ttad";
import { WxApi } from "../WXSDK/Sdk";
import { PlayerAccount } from "../WXSDK/PlayerAccount";
import { AssetPath } from "../Config/AssetPath";
import { LocalDataControl } from "../Control/LocalDataControl";
import { UserDataInfo } from "../Data/UserDataInfo";
import { SkinData } from "../Data/SkinData";
import { SceneControl } from "../Control/SceneControl";

export class MainPanel extends PanelBaseControl
{
    static key:string = "MainPanel";
    static instance:MainPanel;

    c_state:fairygui.Controller;
    load_clickpanel:fairygui.GLoader;
    load_start:fairygui.GLoader;
    txt_lv:fairygui.GTextField;
    pro_dis:fairygui.GProgressBar;
    txt_mingci:fairygui.GTextField;
    txt_gold:fairygui.GTextField;
    SkinBtn:fairygui.GButton;
    MoreGameBtn:fairygui.GButton;
    ExitBtn:fairygui.GButton;
    LotteryBtn:fairygui.GButton;
    SetBtn:fairygui.GButton;

    MoreFunBtnScale:fairygui.Transition;

    //更多好玩按钮
    MoreFunBtn:fairygui.GButton;

    //皮肤按钮动效
    SkinAni:fairygui.Transition;
    //更多好玩按钮动效
    MoreAni:fairygui.Transition;
    //抽奖按钮动效
    LotteryAni:fairygui.Transition;

    private agencyusermessage:AgencyUserMessage;

    constructor() 
    { 
        super("main","mainview"); 
        MainPanel.instance = this;
    }

    private updateUserDataHandler():void
    {
        this.txt_gold.text = this.agencyusermessage.RoleData.Money.toString();
    }

    private returnmainHandler():void
    {
        var RoleData:RoleData = this.agencyusermessage.RoleData;
        // if( RoleData.nowlevel <= 2 )
        // {
        //     this.c_state.selectedIndex = 0;
        // }
        // else
        // {
            this.c_state.selectedIndex = 1;
        // }
    }

    protected onInit():void
    {
        super.onInit();
    }

    /****************************************** */
     // 一只凤凰的分辨率是550 * 400
     private phoenixWidth: number = 550;
     private phoenixHeight: number = 400;

     private bgColorTweener:Laya.Tween = new Laya.Tween();
     private gradientInterval: number = 2000;
     private bgColorChannels: any = { r: 99, g: 0, b: 0xFF };
    private createPhoenixes(): void {
        var scaleFactor: number = Math.min(
            Laya.stage.width / (this.phoenixWidth * 2),
            Laya.stage.height / this.phoenixHeight);

        // 加了混合模式的凤凰
        var blendedPhoenix:Laya.Animation 
        blendedPhoenix.blendMode = "lighter";
        blendedPhoenix.scale(scaleFactor, scaleFactor);
        blendedPhoenix.y = (Laya.stage.height - this.phoenixHeight * scaleFactor) / 2;

        // 正常模式的凤凰
        var normalPhoenix:Laya.Animation;
        normalPhoenix.scale(scaleFactor, scaleFactor);
        normalPhoenix.x = this.phoenixWidth * scaleFactor;
        normalPhoenix.y = (Laya.stage.height - this.phoenixHeight * scaleFactor) / 2;
    }
/****************************************** */
    

    protected initView():void
    {
        this.ExitBtn.visible = false;
        this.MoreFunBtn.visible = false;
        this.MoreGameBtn.visible = false;
        ttad.Showbanner();
        // Laya.timer.once(500,this,()=>{
        //     console.log("main界面白名单----",FYHD_Sdk.iswhite);
        //     if(FYHD_Sdk.iswhite){
        //         this.ExitBtn.visible = true;
        //     }
        //     else{
        //         this.ExitBtn.visible = false;
        //     }
        // })
        this.MoreFunBtnScale = this.getTransitionByName("morefunbtnscale");
        
        Laya.timer.loop(1000,this,this.playanimator2);
        this.SkinAni = this.SkinBtn.getTransition("skinani");
        this.LotteryAni = this.LotteryBtn.getTransition("lotteryani");
        this.MoreAni = this.MoreGameBtn.getTransition("moreani");
        Laya.timer.loop(3000,this,this.playanimator);

        this.agencyusermessage = this.getProxy( AgencyUserMessage );
        PropManager.pro_jindu = this.pro_dis;
        PropManager.txt_mingci = this.txt_mingci;
        this.c_state = this.getControllerByBame( "c_state" );
        GameStateControl.Instance.setClickPanel( this.load_clickpanel );
        this.returnmainHandler();
        this.updateUserDataHandler();
        this.InitSignItem();
    }
    playanimator(){
        this.SkinAni.play(null,1);
        this.LotteryAni.play(null,1);
        this.MoreAni.play(null,1);
    }
    playanimator2(){
        this.MoreFunBtnScale.play(null,1);
    }

    private choujiangclick():void
    {
        if(SceneControl.IsShowSign)return
        ttad.Clear();
        ( this.getProxy( AgencyLottery ) as AgencyLottery ).openView();
    }

    private tuijianclick():void
    {
        if(SceneControl.IsShowSign)return
        ViewManager.Instance.add( TuijianView );
    }

    public skinclick():void
    {
        if(SceneControl.IsShowSign)return
        ttad.Clear();
        ( this.getProxy( AgencySkin ) as AgencySkin ).openview();
    }

    private moreclick():void
    {
        if(SceneControl.IsShowSign)return
        // ViewManager.Instance.add( ChoutiPanView );
        ttad.CreateMoreGameBtn();
    }

    private btnclick():void
    {
        if(SceneControl.IsShowSign)return
        GameState.GameNum++;
        ttad.Clear();
        this.c_state.selectedIndex = 2;
        this.txt_lv.text = this.agencyusermessage.RoleData.getNowServerLevel().toString();
        ( this.getProxy( AgencyInGame ) as AgencyInGame ).startGame();
    }

    private setclick():void{
        
    }

    /*************************************** */
    private tiledMap:Laya.TiledMap;
    private layer:Laya.MapLayer;
    private sprite:Laya.Sprite;
    private mapLoaded(): void {
        this.layer = this.tiledMap.getLayerByIndex(0);

        var radiusX: number = 32;
        var radiusY: number = Math.tan(180 / Math.PI * 30) * radiusX;
        var color: string = "#FF7F50";
        this.sprite = new Laya.Sprite();
        this.sprite.graphics.drawLine(0, 0, -radiusX, radiusY, color);
        this.sprite.graphics.drawLine(0, 0, radiusX, radiusY, color);
        this.sprite.graphics.drawLine(-radiusX, radiusY, 0, radiusY * 2, color);
        this.sprite.graphics.drawLine(radiusX, radiusY, 0, radiusY * 2, color);
        Laya.stage.addChild(this.sprite);
    }
    /*************************************** */

    protected initEvent():void
    {
        this.AddEventByType( this.load_start,Laya.Event.CLICK,this,this.btnclick );
        this.AddEventByType( this.SkinBtn,Laya.Event.CLICK,this,this.skinclick );
        // this.AddEventByType( this.MoreGameBtn,Laya.Event.CLICK,this,this.moreclick );
        // this.AddEventByType( this.MoreFunBtn,Laya.Event.CLICK,this,this.moreclick );
        // this.AddEventByType( this.ExitBtn,Laya.Event.CLICK,this,this.tuijianclick );
        this.addDataEvent( GameState.returnMainView,this,this.returnmainHandler );
        this.AddEventByType( this.LotteryBtn,Laya.Event.CLICK,this,this.choujiangclick );
        this.addDataEvent( UserInfoEvent.UserInfoEvent_updateUserData,this,this.updateUserDataHandler );
    }

     //#region 签到
     btn_Sign:fairygui.GButton;

     SignPanel:fairygui.GGroup;
     SignItem1:fairygui.GImage;
     SignItem2:fairygui.GImage;
     SignItem3:fairygui.GImage;
     SignItem4:fairygui.GImage;
     SignItem5:fairygui.GImage;
     SignItem6:fairygui.GImage;
     SignItem7:fairygui.GImage;
 
     SignAd:fairygui.GImage;
 
     SignItem:fairygui.GImage[];
     //#endregion

    
    //#region 初始化签到

    private isShowSign:boolean=false;

    /*勾选图*/
    private SignTickImage:fairygui.GImage;
    private signNoramButton:fairygui.GButton;
    private signAdButton:fairygui.GButton;

    private SignDanbeiBtn:fairygui.GButton;

    private InitSignItem()
    {
        this.LoadSignData();
        var _bo=true;
        if(this.getSystemTime()==this.SignInfo["time"])
        {
            _bo=false;
        }else
        {
            this.SignInfo["FisstLoad"]=0;
        }
        if(this.SignInfo["FisstLoad"]==1)
        {
            _bo=false;
        }
        // if(PlayerAccount.CurrentAccount.CurAccountData.SignDebug)
        // {
        //     _bo=true;
        // }
        SceneControl.IsShowSign=_bo;
        this.SignPanel.visible=_bo;
        if(!_bo)
        {
            return;
        }

        this.SignFun();
    }

    btn_SignFun()
    {
        if(this.getSystemTime()==this.SignInfo["time"])
        {
            this.isShowSign=true;
        }

        this.SignFun();

        if(this.isShowSign)
        {
            WxApi.ShowTxt("已签到");//y.WxApi.ShowTxt("已签到")
            this.SignSelectedMoney=0+"";
        }
    }

    SignFun()
    {
        this.SignItem=new Array();
        this.SignItem.push(this.SignItem1);
        this.SignItem.push(this.SignItem2);
        this.SignItem.push(this.SignItem3);
        this.SignItem.push(this.SignItem4);
        this.SignItem.push(this.SignItem5);
        this.SignItem.push(this.SignItem6);
        this.SignItem.push(this.SignItem7);

        this.SignTickImage=this.SignAd.asCom.getChildAt(2) as fairygui.GImage;
        var signTickButton=this.SignAd.asCom.getChildAt(1) as fairygui.GButton;
        this.signAdButton=this.SignAd.asCom.getChildAt(3) as fairygui.GButton;
        this.signNoramButton=this.SignAd.asCom.getChildAt(4) as fairygui.GButton;
        this.SignDanbeiBtn = this.SignAd.asCom.getChildAt(5) as fairygui.GButton;

        this.SignTickImage.visible=(PlayerAccount.CurrentAccount.CurAccountData.ShowSign);
        this.signNoramButton.visible = this.SignTickImage.visible;
        this.SignDanbeiBtn.visible = !this.signNoramButton.visible;

        this.AddEventByType( signTickButton,Laya.Event.CLICK,this,this.SignTickButtonFun );
        this.AddEventByType( this.signAdButton,Laya.Event.CLICK,this,this.SignAdButtonFun );
        this.AddEventByType( this.signNoramButton,Laya.Event.CLICK,this,this.SignAdButtonFun );
        this.AddEventByType(this.SignDanbeiBtn,Laya.Event.CLICK,this,this.SignNormalButtonFun);
        
        var num=this.SignInfo["day"];
        var numIndex=100;
        if(num<7)
        {
            numIndex=100;
        }else
        {
            numIndex=107;
            num=num%7;
        }
        
        this.SignPiFu=null;
        this.SignSelectedMoney=0+"";
        for (let index = 0; index < this.SignItem.length; index++) {

            var data= PlayerAccount.CurrentAccount.CurAccountData.GetRewardConfig((numIndex+1+index));

            var pifu=null;
            if(data["reward_item"]!=1000)
            {
                if(Number(data["reward_item"])>6000)
                {
                    var pifuIndedx=Number(data["reward_item"])%6000;
                    pifu=PlayerAccount.CurrentAccount.CurAccountData.GetSkinAttr(pifuIndedx);
                    console.log(pifu );
                }
            }
           
            var isOk=true;
            var isCnaSign=true;
            if(index<num)
            {
                isOk=true;
                isCnaSign=false;
            }else if(index==num)
            {
                isOk=false;
                isCnaSign=true;
       
            }else
            {
                isOk=false;
                isCnaSign=false;
            }
            var text;
            if(index<6){
                text="第 "+(index+1)+" 天";
            }
            else{
                text="豪华皮肤";
            }
            this.SetSignItemInfo(this.SignItem[index],text,data,isOk,isCnaSign,pifu);
        }

        ttad.Showbanner();//
        
    }

    /**签到*/
    private SetSignItemInfo(_signItem:fairygui.GImage,text:string,data:any,_isOk:boolean,_isCanSign:boolean,pifu:any)
    {
        console.log(data);
        if(pifu==null)
        {
            console.log(111111111111);
            var mytext=_signItem.asCom.getChildAt(2) as fairygui.GTextField;
            mytext.text=text;
            var mymoney=_signItem.asCom.getChildAt(3) as fairygui.GTextField;
            mymoney.text=data["reward_num"];
    
            _signItem.asCom.getChildAt(5).visible=false;
            
            if(_isOk)
            {
                _signItem.asCom.getChildAt(1).visible=false;
                _signItem.asCom.getChildAt(6).visible=true;
                _signItem.asCom.getChildAt(7).visible=true;
            }else if(_isCanSign)
            {
                _signItem.asCom.getChildAt(1).visible=true;
                _signItem.asCom.getChildAt(7).visible=false;
                _signItem.asCom.getChildAt(6).visible=false;
                this.SignSelectedItem=_signItem;
                this.SignSelectedText=text;
                this.SignSelectedMoney=data["reward_num"];
                // var child1=_signItem.asCom.getChildAt(7) as fairygui.GButton;
                // child1.visible=true;
                // this.addListener(child1,Laya.Event.CLICK,this.SignButtonFun,null);
                // this.addListener( child1,Laya.Event.CLICK,this,this.SignButtonFun );
            }else
            {
                _signItem.asCom.getChildAt(1).visible=false;
                _signItem.asCom.getChildAt(6).visible=false;
                _signItem.asCom.getChildAt(7).visible=false;
            }
        }
        else
        {
            console.log(2222222222);
            var mytext=_signItem.asCom.getChildAt(2) as fairygui.GTextField;
            var mymoney=_signItem.asCom.getChildAt(3) as fairygui.GTextField;
            mymoney.visible=false;
            var myimage=_signItem.asCom.getChildAt(4) as fairygui.GTextField;
            myimage.visible=false;
    
            var GLoader=_signItem.asCom.getChildAt(5) as fairygui.GLoader;
            
            if(_isOk)
            {
                GLoader.icon = AssetPath.getroleicon( pifu.icon );
                _signItem.asCom.getChildAt(1).visible=false;
                _signItem.asCom.getChildAt(6).visible=true;
                _signItem.asCom.getChildAt(7).visible=true;
               
            }else if(_isCanSign)
            {
                _signItem.asCom.getChildAt(1).visible=true;
                _signItem.asCom.getChildAt(7).visible=false;
                _signItem.asCom.getChildAt(6).visible=false;
                this.SignSelectedItem=_signItem;
                this.SignSelectedText=text;
                this.SignSelectedMoney=0+"";
                this.SignPiFu=pifu;
                GLoader.visible=true;
                GLoader.icon = AssetPath.getroleicon( this.SignPiFu.icon );
                // this.addListener(child1,Laya.Event.CLICK,this.SignButtonFun,null);
                // this.addListener( child1,Laya.Event.CLICK,this,this.SignButtonFun );
            }else
            {
                GLoader.icon = AssetPath.getroleicon( pifu.icon );
                _signItem.asCom.getChildAt(1).visible=false;
                _signItem.asCom.getChildAt(6).visible=false;
                _signItem.asCom.getChildAt(7).visible=false;
            }
        }

    }

    private SignSelectedItem:fairygui.GImage;
    private SignSelectedText:string;
    private SignSelectedMoney:string;

    private SignPiFu:any;

    public SignButtonFun()
    {

        console.log("收取了");
        if(this.getSystemTime==this.SignInfo["time"])
        {
            return;
        }
        this.SignAd.visible=true;
        Laya.timer.once(3000,this,()=>{this.signNoramButton.visible=true});

        this.SetSignItemInfo(this.SignSelectedItem,this.SignSelectedText,this.SignSelectedMoney,true,false,this.SignPiFu);
        this.SaveSignData();
    }


    /*勾选方法*/
    private SignTickButtonFun()
    {
        this.SignTickImage.visible=!this.SignTickImage.visible;
        this.SignDanbeiBtn.visible = !this.SignTickImage.visible;
        this.signNoramButton.visible = this.SignTickImage.visible;
    }

    /*点击视频双倍领取*/
    private SignAdButtonFun()
    {
        this.WinAdButtonFun();
    }

    /*普通领取*/
    private SignNormalButtonFun()
    {
        this.SaveSignData();
        if(this.SignTickImage.visible==true)
        {
            this.WinAdButtonFun();
        }else
        {
            (this.getProxy( AgencyUserMessage ) as AgencyUserMessage ).GoldUp( Number(this.SignSelectedMoney) * 1 );
            if(this.SignPiFu!=null)
            {
                this.SignAddPifu();
            }
      
            this.updateUserDataHandler();
        }

        SceneControl.IsShowSign=false;
        this.SignPanel.visible = false;
        ttad.Clear();//;y.WxApi.ShowTxt("签到成功")
    }

            /**胜利界面广告按钮*/
        private WinAdButtonFun()
        {
            WxApi.recordAldEvent("签到...");
            if(!Laya.Browser.onMobile)
            {
                return;
            }
            ttad.ShowVideo((flag)=>
                {
                    console.log("播放视频返回成功"+flag);
                    if(flag)
                    {
                        console.log("播放视频返回");
                        ( this.getProxy( AgencyUserMessage ) as AgencyUserMessage ).GoldUp( Number(this.SignSelectedMoney) * 2 );
                        if(this.SignPiFu!=null)
                        {
                            this.SignAddPifu();
                        }
                        this.SaveSignData();//this.SaveSignData()
                        this.SignPanel.visible = false;
                        SceneControl.IsShowSign=false;
                        this.updateUserDataHandler();
                    }
                })
        }


        private PaoKuSign:string="PaoKuSignInfo";
        SignInfo:any=null;
        private LoadSignData()
        {
            // this.SignInfo={"day":0,"time":0,"FisstLoad":0};
            //     Laya.LocalStorage.setJSON("PaoKuSign",this.SignInfo);
            this.SignInfo=Laya.LocalStorage.getJSON(this.PaoKuSign);
            if(this.SignInfo==0||this.SignInfo==null)
            {
                var time=this.getSystemTime();
                this.SignInfo={"day":0,"time":0,"FisstLoad":0};
                Laya.LocalStorage.setJSON(this.PaoKuSign,this.SignInfo);
            }
            console.log("asdasd");
        }

        private SaveSignData()
        {
            this.SignInfo["FisstLoad"]=1;
            this.SignInfo["day"]++;

            this.SignInfo["time"]=this.getSystemTime();
            
            Laya.LocalStorage.setJSON(this.PaoKuSign,this.SignInfo);
        }

        private getSystemTime(): number {
            var curDate: Date = new Date();
            var month: number = curDate.getMonth() + 1;
            console.log("月:" + month.toString());
    
            var date: number = curDate.getDate();
            console.log("日:" + date.toString());
    
            return Number( (month + "" + date));
        }



        private SignAddPifu()
        {
            var cachedata = LocalDataControl.Instance.GetLocalCaCheData( UserDataInfo.skin );
            // var cachedata = CacheManager.getInstance().getCacheObj( UserCacheType.skin );
            var id=this.SignPiFu["id"];
            var _skinProxy:AgencySkin = this.getProxy( AgencySkin );

            var piFuVO:SkinData=null
            for (let index = 0; index < _skinProxy.pifuArr.length; index++) {
                
                piFuVO=_skinProxy.pifuArr[index];
                if(piFuVO.roleCFG.id==id)
                {
                    break;
                }
            }
            piFuVO.state = 1;
            AgencySkin.instance.AddLocalSkinData(piFuVO.roleCFG.id,piFuVO.state,piFuVO.hasnum);
            DispatcherManager.dispatchEvent( GameState.updateSKinView);
            console.log("获取皮肤");
            console.log(cachedata);
        }


    //#endregion

    

}