import { _decorator, Animation, Color, Component, instantiate, Label, log, Node, Prefab, ProgressBar, resources, Size, Sprite, SpriteFrame, tween, UITransform, Vec3, Widget } from 'cc';
import { gameManager } from '../gameManager';
import { ClientEvent } from '../framework/clientEvent';
import { config } from '../config';
import { SdkUtil } from '../framework/sdkUtil';
import { fail } from '../dialog/fail';
import { http } from '../http/http';
import { Util } from '../framework/util';
import { win } from '../dialog/win';
import { tools } from '../tools';
import { setting } from '../homepage/setting';
import { addCoinAni } from '../addCoinAni';
import { clock_angle } from '../clock_angle';
import { guid } from '../guid/guid';
import { PoolManager } from '../framework/poolManager';
import { StatisticsManager } from '../framework/statisticsManager';
const { ccclass, property } = _decorator;

@ccclass('base_view')
export class base_view extends Component {
    @property(Node) btn_back:Node = null;
    @property(Node) btn_pause:Node = null;
    @property(Node) btn_look_video:Node = null;
    @property(Node) btn_tip:Node = null;
    @property(Node) btn_coin:Node = null;
    @property(ProgressBar) progressbar:ProgressBar = null;
    @property(Node) lab_title:Node = null;
    @property(Node) lab_coin:Node = null;
    @property(Node) img_touch_err:Node = null;
    @property(Node) action_node:Node = null;
    @property(SpriteFrame) sf_btn_start:SpriteFrame = null;
    @property(SpriteFrame) sf_btn_pause:SpriteFrame = null;
    @property(Prefab) addCoinAni:Prefab = null;
    @property(Node) top_node:Node = null;
    @property(Node) lab_time_count:Node = null;
    @property(Node) clock_ani:Node = null;
    protected guid_view:Node = null;
    protected time_count:number = 0;
    protected time_all_count:number = 0;
    protected err_node_1:Node = null;
    protected isPause:boolean = false;
    protected reward:number = 0;
    protected isShowWin:boolean = false;
    protected categoryid:number = -1;
    protected old_coin_number:number = 0;
    protected m_data:any;
    protected coin_ani:Node;

    protected start(): void {
        let self = this;
        self.initUI()
        this.btn_back.on(Node.EventType.TOUCH_START,()=>{
            gameManager.playBtnSound()
            self.close();
        },this);
        this.btn_look_video.on(Node.EventType.TOUCH_START,()=>{     
            self.isPause  = true;
            SdkUtil.showVideoAd(config.rewardVideoAdUnitId.Earn_coins_AdUnitId,(res)=>{
                if(res.isEnded){
                    self.showLookVideoReward();
                }else{
                    self.isPause  = false;
                }

                // 统计-激励视频广告
                let collect_data = StatisticsManager.get_collect_data(this.categoryid, this.m_data.id, 0, res, config.STATISTICS_ACTION_TYPE.ZHUAN_JIN_BI)
                StatisticsManager.request_collect_rewardVideoData(collect_data)
            })
        })
        this.btn_tip.on(Node.EventType.TOUCH_START,()=>{
            gameManager.playBtnSound()
            this.onTipBtnClick();
        },this);
        if(this.btn_pause!=null){
            this.btn_pause.on(Node.EventType.TOUCH_START,()=>{
                self.isPause  = true;
                self.btn_pause.getComponent(Sprite).spriteFrame = self.sf_btn_start;
                gameManager.playBtnSound()
                gameManager.addTopView(config.PREFAB_PATH.setting,(node:Node)=>{
                    node.getComponent(setting).show(()=>{
                        self.btn_pause.getComponent(Sprite).spriteFrame = self.sf_btn_pause;
                        self.isPause = false;
                    })
                })
            },this);
        }
        ClientEvent.on(config.EVENT_MSG.ON_CHANGE_COIN_NUMBER,this.onChangeCoinNumber.bind(this),this);
    }
    protected onDestroy(): void {
        // if(this.categoryid===config.PLAY_TYPE.HAN_ZI_ZHAO_BU_TONG){
        //     PoolManager.instance.clearPool("font_item")
        // }
        ClientEvent.off(config.EVENT_MSG.ON_CHANGE_COIN_NUMBER,this.onChangeCoinNumber.bind(this),this);
    }
    close(){
        ClientEvent.dispatchEvent(config.EVENT_MSG.ON_BACK_HOME_VIEW);
        this.node.removeFromParent();
    }

    onChangeCoinNumber(){
        let num:number = this.old_coin_number;
        let add_coin = gameManager.get_user_coin() - num;
        let obj = new Component
        gameManager.instance.addCoinNumber(obj,add_coin,this.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);
        })
    }
    reset_time_count(){
        if(this.lab_time_count!=null){
            this.lab_time_count.getComponent(Label).string = ""
        }
    }
    /**
        下一关 start
     */
    nextLevel(){
        this.reset_time_count()
        let is_have_next = gameManager.next_level(this.categoryid,(is_sync:boolean)=>{
            if(is_sync){
                let levels_item = gameManager.get_cur_level_by_categoryid(this.categoryid);
                if(this.categoryid!==config.PLAY_TYPE.JI_YI_LI&&this.categoryid!==config.PLAY_TYPE.DOU_DI_ZHU){
                    gameManager.add_coin(this.reward);
                }
                ClientEvent.dispatchEvent(config.EVENT_MSG.ON_CHANGE_COIN_NUMBER);
                http.get(config.static_url.levels_info(this.categoryid,levels_item.level),(err,data)=>{
                    if(!err){
                        let _data = JSON.parse(data)
                        if(_data.code===config.MSG_CODE.SUCCESS){
                            this.initView(_data.content,true);
                        }
                    }
                })
            }else{
                gameManager.hideLoading()
                tools.showDialogOne("请检查您的网络状态\n重新连接",()=>{
                    this.nextLevel()
                })
            }
        })

        if(!is_have_next){
            if(this.categoryid===config.PLAY_TYPE.JI_YI_LI){
                let categoryid = config.PLAY_TYPE.JI_YI_LI;
                let levels_item = gameManager.get_cur_level_by_categoryid(categoryid);
                levels_item.level = 0;
                gameManager.set_unlock_levels_data(levels_item)
                gameManager.sync_data(()=>{},config.sync_data_type.LEVELS)
                this.nextLevel()
            }else{
                tools.showToast("当前已是最后一关，敬请期待最新版本");
            }
          
        }
    }


    /**
        下一关 end
     */


    /**
        计时api start 
     */
    stop_time_count(){
        this.unscheduleAllCallbacks()
    }
    start_time_count(time:number){
        if(this.lab_time_count==null){
            return
        }
        this.time_all_count = time;
        this.lab_time_count.active = true;
       
        let self = this;
        this.time_count = 0;
        if(self.progressbar){
            self.progressbar.progress = 1;
        }
        
        if(self.clock_ani){
            self.clock_ani.getComponent(clock_angle).init();
        }
        this.schedule(()=>{
            if(self.isPause){
                return;
            }
            if(self.time_count<self.time_all_count){
                self.time_count+=1;
                if(this.categoryid===config.PLAY_TYPE.JI_YI_LI){
                    self.lab_time_count.getComponent(Label).string = `${this.time_all_count-this.time_count}s`
                }else{
                    self.progressbar.progress = (self.time_all_count-self.time_count)/self.time_all_count;
                    self.lab_time_count.getComponent(Label).string = `${this.time_all_count-this.time_count}s`
                    self.clock_ani.getComponent(clock_angle).addSecond();
                }
       
            }else{
                self.lab_time_count.getComponent(Label).string = "0s";
                if(this.categoryid===config.PLAY_TYPE.JI_YI_LI){
                    self.showQuestion()
                }else{
                    self.showFail()
                }
                self.stop_time_count();
            }
        },1)
    }
    error_sub_time(){
        let self = this;
        if( (self.time_count + self.m_data.wrong_time) >= self.time_all_count){
            self.time_all_count = 0;
            self.lab_time_count.getComponent(Label).string = "0s";
        }else{
            self.lab_time_count.getComponent(Label).string = `${this.time_all_count-this.time_count}s`
            self.time_count += self.m_data.wrong_time;
        }
        self.progressbar.progress = (self.time_all_count-self.time_count)/self.time_all_count;
    }
    /**
        计时api end 
     */
    showFail(){
        if(!this.isShowWin){
            gameManager.addUiView(config.PREFAB_PATH.fail,(node:Node)=>{
                gameManager.playFailSoundByCategoryId(this.categoryid)
                if(this.categoryid===config.PLAY_TYPE.JI_YI_LI||this.categoryid===config.PLAY_TYPE.DOU_DI_ZHU){
                    node.getComponent(fail).showJYLView(this.onFailReStartClick.bind(this),this.m_data.ads_restart,this.onFailQuitClick.bind(this),this.categoryid)
                }
                else{
                    node.getComponent(fail).showView(this.m_data.extend_time,this.onFailExtendTimeClick.bind(this),this.onFailReStartClick.bind(this),this.m_data.ads_restart)
                }
            })
        }
    }
    showWin(){
        gameManager.addTopView(config.PREFAB_PATH.win,(node:Node)=>{
            this.isShowWin = true;
            gameManager.playWinSoundByCategoryId(this.categoryid)
            if(config.PLAY_TYPE.JI_YI_LI===this.categoryid||config.PLAY_TYPE.DOU_DI_ZHU===this.categoryid){
                node.getComponent(win).showJYLView(this.onWinOrdinaryClick.bind(this),this.categoryid)
            }else{
                node.getComponent(win).showView(this.reward,this.m_data,this.onWinOrdinaryClick.bind(this),this.onWinDoubleClick.bind(this));
            }
            
        });
    }

    showLookVideoReward(){
        let self = this;
        gameManager.addTopView(config.PREFAB_PATH.win,(node:Node)=>{
            let reward = gameManager.get_reward_number();
            node.getComponent(win).showVideoAddCoinView(reward,this.m_data,(win_view:win)=>{
                gameManager.add_coin(reward)
                self.showCoinAni()
                tween(self.node).delay(0.5).call(()=>{
                    ClientEvent.dispatchEvent(config.EVENT_MSG.ON_CHANGE_COIN_NUMBER)
                }).start()
                win_view.close()
                self.isPause  = false;

            },(win_view:win)=>{
                SdkUtil.showVideoAd(config.rewardVideoAdUnitId.Earn_coins_AdUnitId,(res)=>{
                    if(res.isEnded){
                        reward = gameManager.get_deouble_reward_number();
                        tween(self.node).delay(0.5).call(()=>{
                            gameManager.add_coin(reward)
                            win_view.showDoubleCoin(reward,()=>{
                                self.showCoinAni()
                                win_view.close()
                                self.isPause  = false;
                                tween(self.node).delay(0.5).call(()=>{
                                    ClientEvent.dispatchEvent(config.EVENT_MSG.ON_CHANGE_COIN_NUMBER)
                                }).start()
                            })
                        }).start()
                    }

                    // 统计-激励视频广告
                    let coin_number = res.isEnded ? reward : 0
                    let collect_data = StatisticsManager.get_collect_data(this.categoryid, this.m_data.id, coin_number, res, config.STATISTICS_ACTION_TYPE.CHAO_JI_JIA_BEI)
                    StatisticsManager.request_collect_rewardVideoData(collect_data)
                   
                })
            });
        });
    }
    onWinOrdinaryClick(win_view:win){
        let self = this;
        gameManager.playBtnSound()
        tween(self.node).delay(0.5).call(()=>{
            self.nextLevel();
        }).start()
        win_view.close()
        win_view.hideAllBtn()
        if(this.categoryid!==config.PLAY_TYPE.JI_YI_LI&&this.categoryid!==config.PLAY_TYPE.DOU_DI_ZHU){
            this.showCoinAni()
        }
    }

    onWinDoubleClick(win_view:win){
        gameManager.playBtnSound()
        let self = this;
        let list = this.m_data.ads_fold.split(",");
        let start = parseInt(list[0]);
        let end = parseInt(list[1]);
        let reward = this.reward;
        reward*=  Util.getRandomInt(start,end);
        SdkUtil.showVideoAd(config.rewardVideoAdUnitId.Super_double_AdUnitId,(res)=>{
            if(res.isEnded){
                win_view.showDoubleCoin(reward,()=>{
                    self.showCoinAni()
                    self.reward = reward;
                    tween(self.node).delay(0.5).call(()=>{
                        self.nextLevel();
                    }).start()
                    win_view.close()
                })
            }

            // 统计-激励视频广告
            let coin_number = res.isEnded ? reward : 0
            let collect_data = StatisticsManager.get_collect_data(this.categoryid, this.m_data.id, coin_number, res, config.STATISTICS_ACTION_TYPE.CHAO_JI_JIA_BEI)
            StatisticsManager.request_collect_rewardVideoData(collect_data)
        })
    }

    onFailExtendTimeClick(fail_view:fail){
        gameManager.playBtnSound()
        let self = this;
        SdkUtil.showVideoAd(config.rewardVideoAdUnitId.Prolong_AdUnitId,(res)=>{
            if(res.isEnded){
                self.start_time_count(self.m_data.extend_time);
                fail_view.close()
            }

            // 统计-激励视频广告
            let collect_data = StatisticsManager.get_collect_data(this.categoryid, this.m_data.id, 0, res, config.STATISTICS_ACTION_TYPE.YAN_CHANG)
            StatisticsManager.request_collect_rewardVideoData(collect_data)
        })
       
    }
    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 start_pos = new Vec3()
                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()
            })
        }
    }

    showErrLab(parent:Node){
        let lab_err_number:Node = new Node();
        lab_err_number.addComponent(Label);
        lab_err_number.getComponent(Label).string = `-${this.m_data.wrong_time}`
        lab_err_number.parent = parent;
        lab_err_number.getComponent(Label).color = Color.RED;
        lab_err_number.getComponent(Label).fontSize = 25;
        lab_err_number.position = new Vec3(lab_err_number.position.x,30,lab_err_number.position.z)
        lab_err_number.getComponent(Label).isBold = true;
        this.clock_ani.getComponent(clock_angle).play()
        let end_pos = new Vec3(lab_err_number.position.x,lab_err_number.position.y+20,lab_err_number.position.z)
        tween(lab_err_number).to(0.5, {position: end_pos}).removeSelf().start()
    }

    checkShowGuid(){
        let levels_item = gameManager.get_cur_level_by_categoryid(this.categoryid);
        return levels_item.level === 1;
    }

    hideGuid(){
        if(this.guid_view!=null){
            this.guid_view.removeFromParent();
            this.guid_view = null;
        }

    }
    showGuid(v3:Vec3,call_back,size:Size){
        if(this.guid_view===null){
            size = new Size(50,50)
            resources.load(config.PREFAB_PATH.guid, Prefab, (err, prefab) => {
                if(err){
                    return;
                }
                this.guid_view = instantiate(prefab);
                this.guid_view.parent = this.action_node;
                this.guid_view.getComponent(guid).showGuid(v3,()=>{
                    call_back()
                },this.action_node,size)
            });
        }
  
    }
    protected onFailReStartClick(fail_view:fail): void{}
    protected onFailQuitClick(fail_view:fail): void{}
    protected initView(data,isUpdate=false): void{}
    protected initUI(): void{}
    protected onTipBtnClick(): void{}
    protected showQuestion(): void{}
    
}


