import { _decorator, Component, Director, director, Enum, Game, game, instantiate, Label, log, Node, Prefab, resources, SpriteFrame, sys, tween, UITransform, Vec2, Vec3, Animation, PageView, Layout } from 'cc';
import { config } from '../config';
import { gameManager } from '../gameManager';
import { server_play_list_data_item, statistics_collect_rewardVideo_data_item } from '../data/server_play_list_data';
import { tools } from '../tools';
import { ClientEvent } from '../framework/clientEvent';
import { http } from '../http/http';
import { view_game_play_shuang_tu_zhao_bu_tong } from '../play_list/zhaocha_up_down/view_game_play_shuang_tu_zhao_bu_tong';
import { view_game_play_han_zi_zhao_bu_tong } from '../play_list/zhaocha_font/view_game_play_han_zi_zhao_bu_tong';
import { view_game_play_mei_nv_zhao_xi_jie } from '../play_list/zhaocha_component/view_game_play_mei_nv_zhao_xi_jie';
import { AudioManager } from '../framework/audioManager';
import { SdkUtil } from '../framework/sdkUtil';
import { win } from '../dialog/win';
import { addCoinAni } from '../addCoinAni';
import { Util } from '../framework/util';
import { PoolManager } from '../framework/poolManager';
import { game_play_dou_di_zhu } from '../play_list/ddz/game_play_dou_di_zhu';
import { view_game_play_shuang_tu_zhao_xiang_tong } from '../play_list/zhaocha_xiang_tong/view_game_play_shuang_tu_zhao_xiang_tong';
import { view_game_play_ji_yi_li } from '../play_list/ji_yi_li/view_game_play_ji_yi_li';
import { view_game_play_zhao_bu_tong } from '../play_list/zhao_bu_tong/view_game_play_zhao_bu_tong';
import { StatisticsManager } from '../framework/statisticsManager';
import { reward_box_page } from './reward_box_page';
import { play_page_list_item } from './play_page_list_item';
const { ccclass, property } = _decorator;
export enum ETest {
    None = 0,
    ONe = 1,
    Two = 2
}
@ccclass('homepage')
export class homepage extends Component {
    @property(Node) content:Node = null;
    @property(SpriteFrame) sf_list:SpriteFrame[]=[];
    @property(Node) btn_setting:Node = null;
    @property(Node) btn_coin:Node = null;
    @property(Node) btn_look_video:Node = null;
    @property(Node) lab_coin:Node;
    @property(Prefab) addCoinAni:Prefab = null;
    @property(Node) top_node:Node = null;
    @property(Node) action_node:Node = null;
    @property(Node) pageView:Node = null;
    @property(Node) pageView_content_page1:Node = null;
    @property(Node) pageView_content_page2:Node = null;
    @property(Node) lab_page_count:Node = null;
    @property(Prefab) item_prefab = null;
    @property(Node) reward_box:Node = null;
    protected coin_ani:Node;
    protected old_coin_number:number = 0;
    private sp_map:Map<number,SpriteFrame> = new Map();
    private playItemList:Node[]=[];
     
    protected onLoad(): void {
        SdkUtil.ttRegisterSidebar()
    }

    protected start(): void {
        this.sp_map.set(config.PLAY_TYPE.YI_QI_ZHAO_CHA,this.sf_list[0])
        this.sp_map.set(config.PLAY_TYPE.HAN_ZI_ZHAO_BU_TONG,this.sf_list[1])
        this.sp_map.set(config.PLAY_TYPE.MEI_NV_ZHAO_XI_JIE,this.sf_list[2])
        this.sp_map.set(config.PLAY_TYPE.ZHAO_XIANG_TONG,this.sf_list[3])
        this.sp_map.set(config.PLAY_TYPE.ZHAO_BU_TONG,this.sf_list[4])
        this.sp_map.set(config.PLAY_TYPE.DOU_DI_ZHU,this.sf_list[5])
        this.sp_map.set(config.PLAY_TYPE.JI_YI_LI,this.sf_list[6])

        this.btn_setting.on(Node.EventType.TOUCH_START,()=>{
            gameManager.playBtnSound()
            gameManager.addTopView(config.PREFAB_PATH.setting,()=>{});
        },this)
        this.btn_look_video.on(Node.EventType.TOUCH_START,()=>{      
            SdkUtil.showVideoAd(config.rewardVideoAdUnitId.Earn_coins_AdUnitId,(res)=>{
                if(res.isEnded){
                    this.showLookVideoReward();
                }
                // 统计-激励视频广告
                let collect_data = StatisticsManager.get_collect_data(0, 0, 0, res, config.STATISTICS_ACTION_TYPE.ZHUAN_JIN_BI)
                StatisticsManager.request_collect_rewardVideoData(collect_data)
            })
        })
        if(!PoolManager.instance.isHavePool(config.POOL_KEY)){
            PoolManager.instance.preloadPoolByName(config.POOL_KEY,11*15,this.item_prefab)
        }
        ClientEvent.on(config.EVENT_MSG.ON_CHANGE_COIN_NUMBER,this.onChangeCoinNumber.bind(this),this);
        ClientEvent.on(config.EVENT_MSG.ON_INIT_GAME_LIST,this.initPlayList.bind(this),this);
        ClientEvent.on(config.EVENT_MSG.ON_BACK_HOME_VIEW,this.onBackHomeView.bind(this),this);
        ClientEvent.on(config.EVENT_MSG.ON_UPDATE_HOME_VIEW,this.onUpdateHomeView.bind(this),this);
        ClientEvent.on(config.EVENT_MSG.ON_SHOW_REWARD_VIEW,this.onShowRewardView.bind(this),this);
        ClientEvent.on(config.EVENT_MSG.ON_USER_LOGIN_SUCCESS,this.onUserLoginSuccess.bind(this),this);
    }
    onUserLoginSuccess() {      
        if(SdkUtil.ttCheckSceneShowRewards()&&gameManager.get_user_is_sign()==false) {
            this.reward_box.active = true
            this.reward_box.getComponent(Animation).play()
            let self = this
            this.reward_box.on(Node.EventType.TOUCH_END, ()=> {
                gameManager.addTopView(config.PREFAB_PATH.reward_box_page, (node:Node)=> {
                    let coin_number = gameManager.get_sign_reward_number()
                    let sign_status = gameManager.userSignStatus.status
                    let is_toEnterFromSidebar = SdkUtil.ttCheckToEnterFromSidebar()
                    node.getComponent(reward_box_page).showView(coin_number, sign_status, is_toEnterFromSidebar, (coin_number:number, reward_box_page:reward_box_page)=> {
                        gameManager.add_coin(coin_number)
                        setTimeout(()=>{
                            ClientEvent.dispatchEvent(config.EVENT_MSG.ON_CHANGE_COIN_NUMBER)
                        },500)
                        self.showCoinAni()
                        reward_box_page.close()
                        this.reward_box.getComponent(Animation).stop()
                        this.reward_box.active = false
                    })
                })
            })
        }
    }
    onShowRewardView(){
        this.showLookVideoReward()
    }
    onUpdateHomeView(){
        this.playPageListItemUpdateView()

        this.old_coin_number = gameManager.get_user_coin();
        this.lab_coin.getComponent(Label).string = Util.coinNumberToK(this.old_coin_number);
        gameManager.playMainMusic(true);
    }   
    onBackHomeView(){
        this.playPageListItemUpdateView()

        this.old_coin_number = gameManager.get_user_coin();
        this.lab_coin.getComponent(Label).string = Util.coinNumberToK(this.old_coin_number);
        gameManager.playMainMusic(true);
    }
    onChangeCoinNumber(){
        let self = this;
        let num:number = this.old_coin_number;
        let obj = new Component
        gameManager.instance.addCoinNumber( obj,gameManager.get_user_coin() - num ,self.lab_coin.getComponent(Label),num,()=>{
            this.old_coin_number = gameManager.get_user_coin();
            this.lab_coin.getComponent(Label).string = Util.coinNumberToK(this.old_coin_number);
        })

        this.playPageListItemUpdateView()
    }

    showCoinAni(){
        if( this.coin_ani!=null){
            this.coin_ani.removeFromParent()
            this.coin_ani = null;
        }
        if(this.addCoinAni!=null){
            this.coin_ani = instantiate(this.addCoinAni)
            this.coin_ani.parent = this.action_node;
            this.coin_ani.position = new Vec3(200,400,0)
            this.coin_ani.getComponent(addCoinAni).play(()=>{
                let end_pos =  this.top_node.getComponent(UITransform).convertToWorldSpaceAR(this.btn_coin.position)
                tween(this.coin_ani).to(0.2, {position: end_pos}).hide().start()
            })
        }
    }
    showLookVideoReward(){
        let self = this;
        gameManager.addTopView(config.PREFAB_PATH.win,(node:Node)=>{
            let reward = gameManager.get_reward_number();
            node.getComponent(win).showVideoAddCoinView(reward,null,(win_view:win)=>{
                gameManager.add_coin(reward)
                setTimeout(()=>{
                    ClientEvent.dispatchEvent(config.EVENT_MSG.ON_CHANGE_COIN_NUMBER)
                },500)
                self.showCoinAni()
                win_view.close()

            },(win_view:win)=>{
                SdkUtil.showVideoAd(config.rewardVideoAdUnitId.Earn_coins_AdUnitId,(res)=>{
                    if(res.isEnded){
                        reward = gameManager.get_deouble_reward_number();
                        tween(self.btn_setting).delay(0.5).call(()=>{
                            gameManager.add_coin(reward)
                            win_view.showDoubleCoin(reward,()=>{
                                self.showCoinAni()
                                win_view.close()
                                ClientEvent.dispatchEvent(config.EVENT_MSG.ON_CHANGE_COIN_NUMBER)
                            })
                        }).start()
                
                    }
                    // 统计-激励视频广告
                    let collect_data = StatisticsManager.get_collect_data(0, 0, 0, res, config.STATISTICS_ACTION_TYPE.CHAO_JI_JIA_BEI)
                    StatisticsManager.request_collect_rewardVideoData(collect_data)
                })
            });
        });
    }
    protected onDestroy(): void {
        ClientEvent.off(config.EVENT_MSG.ON_CHANGE_COIN_NUMBER,this.onChangeCoinNumber.bind(this),this);
        ClientEvent.off(config.EVENT_MSG.ON_INIT_GAME_LIST,this.initPlayList.bind(this),this);
        ClientEvent.off(config.EVENT_MSG.ON_BACK_HOME_VIEW,this.onBackHomeView.bind(this),this);
    }

    initPlayList(){
        this.pageView_content_page1.removeAllChildren()
        this.pageView_content_page2.removeAllChildren()

        let list = gameManager.g_server_play_list_data.list;
        let every_page_count: number = 6
        let pageView_total_page_count:number = Math.ceil(list.length / every_page_count)
        let number_string = '1' + ' / ' + pageView_total_page_count + ''
        this.lab_page_count.getComponent(Label).string = number_string

        let self = this;
        this.pageView.on('page-turning', (event: PageView) => {
            let currentPageIndex = event.getCurrentPageIndex()
            let number_string = currentPageIndex+1 + ' / ' + pageView_total_page_count + ''
            self.lab_page_count.getComponent(Label).string = number_string
        })

        let call_back = (prefab)=>{
            let prefabInstance = instantiate(prefab)
            // 设置横向(左、中、右)间隙
            let col_num = this.pageView_content_page1.getComponent(Layout).constraintNum
            let paddingTop = 40
            let spacingY = 30
            let padding_x = (this.pageView_content_page1.getComponent(UITransform).width - col_num * prefabInstance.getComponent(UITransform).width) / (col_num+1)
            // console.log(padding_x)
            let content_page1_layout = this.pageView_content_page1.getComponent(Layout)
            content_page1_layout.paddingLeft = padding_x
            content_page1_layout.spacingX = padding_x
            content_page1_layout.paddingTop = paddingTop
            content_page1_layout.spacingY = spacingY

            let content_page2_layout = this.pageView_content_page2.getComponent(Layout)
            content_page2_layout.paddingLeft = padding_x
            content_page2_layout.spacingX = padding_x
            content_page2_layout.paddingTop = paddingTop
            content_page2_layout.spacingY = spacingY

            for (var index = 0; index < list.length; index++) {
                let newNode: Node = instantiate(prefab)
                if (index < every_page_count) {
                    newNode.parent = self.pageView_content_page1
                } else {
                    newNode.parent = self.pageView_content_page2
                }
                self.playItemList.push(newNode)
                newNode.getComponent(play_page_list_item).initView(list[index],this.sp_map.get(list[index].id),this.onItemClick.bind(this));
            }

        }
        resources.load(config.PREFAB_PATH.play_page_list_item, Prefab, (err, prefab) => {
            if(err){
                console.log("err::",err);
                return;
            }
            call_back(prefab);
        });
    }

    playPageListItemUpdateView() {
        let self = this
        for (let index = 0; index < self.playItemList.length; index++) {
            let item = self.playItemList[index]
            item.getComponent(play_page_list_item).updateView()
        }
    }
    
    onItemClick(data:server_play_list_data_item){
        gameManager.playBtnSound()
        switch(data.id){
            case config.PLAY_TYPE.YI_QI_ZHAO_CHA:
            {
                let categoryid = config.PLAY_TYPE.YI_QI_ZHAO_CHA;
                let levels_item = gameManager.get_cur_level_by_categoryid(categoryid);
                // gameManager.showLoading();
                http.get(config.static_url.levels_info(categoryid,levels_item.level),(err,data)=>{

                    if(!err){
                        let _data = JSON.parse(data)
                        if(_data.code===config.MSG_CODE.SUCCESS){
                            gameManager.addUiView(config.PREFAB_PATH.game_play_shuang_tu_zhao_bu_tong,(node:Node)=>{
                                node.getComponent(view_game_play_shuang_tu_zhao_bu_tong).initView(_data.content);
                            })
                        }
                    }
        
                })
            
                break;
            }
            case config.PLAY_TYPE.HAN_ZI_ZHAO_BU_TONG:
            {
                let categoryid = config.PLAY_TYPE.HAN_ZI_ZHAO_BU_TONG;
                let levels_item = gameManager.get_cur_level_by_categoryid(categoryid);
                // gameManager.showLoading();
                http.get(config.static_url.levels_info(categoryid,levels_item.level),(err,data)=>{
                    if(!err){
                        let _data = JSON.parse(data)
                        if(_data.code===config.MSG_CODE.SUCCESS){
                            if(gameManager.uiViewList.get(config.PREFAB_PATH.game_play_han_zi_zhao_bu_tong)){
                                gameManager.uiViewList.get(config.PREFAB_PATH.game_play_han_zi_zhao_bu_tong).getComponent(view_game_play_han_zi_zhao_bu_tong).initView(_data.content);
                            }else{
                                gameManager.addUiView(config.PREFAB_PATH.game_play_han_zi_zhao_bu_tong,(node)=>{
                                    node.getComponent(view_game_play_han_zi_zhao_bu_tong).initView(_data.content);
                                })
                            }
                           
                        }
                    }
        
                })

          
                break;
            }
            case config.PLAY_TYPE.MEI_NV_ZHAO_XI_JIE:
            {

                let categoryid = config.PLAY_TYPE.MEI_NV_ZHAO_XI_JIE;
                let levels_item = gameManager.get_cur_level_by_categoryid(categoryid);
                // gameManager.showLoading();
                http.get(config.static_url.levels_info(categoryid,levels_item.level),(err,data)=>{
                    if(!err){
                        let _data = JSON.parse(data)
                        if(_data.code===config.MSG_CODE.SUCCESS){
                            gameManager.addUiView(config.PREFAB_PATH.game_play_mei_nv_zhao_xi_jie,(node)=>{
                                node.getComponent(view_game_play_mei_nv_zhao_xi_jie).initView(_data.content);
                            })
                        }
                    }
        
                })
                break;
            }
            case config.PLAY_TYPE.ZHAO_XIANG_TONG:
                {
                    let categoryid = config.PLAY_TYPE.ZHAO_XIANG_TONG;
                    let levels_item = gameManager.get_cur_level_by_categoryid(categoryid);
                    // gameManager.showLoading();
                    http.get(config.static_url.levels_info(categoryid,levels_item.level),(err,data)=>{
                        if(!err){
                            let _data = JSON.parse(data)
                            if(_data.code===config.MSG_CODE.SUCCESS){
                                gameManager.addUiView(config.PREFAB_PATH.game_play_shuang_tu_zhao_xiang_tong,(node:Node)=>{
                                    node.getComponent(view_game_play_shuang_tu_zhao_xiang_tong).initView(_data.content);
                                })
                            }
                        }
            
                    })
                    break;
                }
            case config.PLAY_TYPE.ZHAO_BU_TONG:
                {
                    let categoryid = config.PLAY_TYPE.ZHAO_BU_TONG;
                    let levels_item = gameManager.get_cur_level_by_categoryid(categoryid);
                    // gameManager.showLoading();
                    http.get(config.static_url.levels_info(categoryid,levels_item.level),(err,data)=>{
                        if(!err){
                            let _data = JSON.parse(data)
                            if(_data.code===config.MSG_CODE.SUCCESS){
                                gameManager.addUiView(config.PREFAB_PATH.game_play_zhao_bu_tong,(node:Node)=>{
                                    node.getComponent(view_game_play_zhao_bu_tong).initView(_data.content);
                                })
                            }
                        }
            
                    })
                    break;
                }

            case config.PLAY_TYPE.DOU_DI_ZHU:
                {
    
                    let categoryid = config.PLAY_TYPE.DOU_DI_ZHU;
                    let levels_item = gameManager.get_cur_level_by_categoryid(categoryid);
                    // gameManager.showLoading();
                    console.log("斗地主")
                    http.get(config.static_url.levels_info(categoryid,levels_item.level),(err,data)=>{
                        if(!err){
                            let _data = JSON.parse(data)
                            if(_data.code===config.MSG_CODE.SUCCESS){
                                gameManager.addUiView(config.PREFAB_PATH.game_play_dou_di_zhu,(node:Node)=>{
                                    node.getComponent(game_play_dou_di_zhu).initView(_data.content);
                                })
                            }
                        }
            
                    })
                    break;
                }
            case config.PLAY_TYPE.JI_YI_LI:
                {
                    let categoryid = config.PLAY_TYPE.JI_YI_LI;
                    let levels_item = gameManager.get_cur_level_by_categoryid(categoryid);
                    const element = gameManager.get_play_list_item_by_categoryid(config.PLAY_TYPE.JI_YI_LI);
                    if(element.barrier_number<levels_item.level){
                        levels_item.level = 1;
                        gameManager.set_unlock_levels_data(levels_item)
                        gameManager.sync_data(()=>{},config.sync_data_type.LEVELS)
                    }
                    if(levels_item.level<=0){
                        levels_item.level = 1;
                        gameManager.set_unlock_levels_data(levels_item)
                    }
                    http.get(config.static_url.levels_info(categoryid,levels_item.level),(err,data)=>{
                        if(!err){
                            let _data = JSON.parse(data)
                            if(_data.code===config.MSG_CODE.SUCCESS){
                                gameManager.addUiView(config.PREFAB_PATH.game_play_ji_yi_li,(node:Node)=>{
                                    node.getComponent(view_game_play_ji_yi_li).initView(_data.content);
                                })
                            }
                        }
            
                    })
                    break;
                }
        }
    }
}


