import { _decorator, Animation, Canvas, Component, Director, director, instantiate, Label, Layout, Node, Prefab, ProgressBar, Size, Sprite, SpriteFrame, UIOpacity, UITransform, Vec3, view, Widget } from 'cc';
import { config } from '../../config';
import { font_grid_pos, server_han_zi_zhao_bu_tong_data_item } from '../../data/server_play_list_data';
import { gameManager } from '../../gameManager';
import { tools } from '../../tools';
import { font_grid_item } from './font_grid_item';
import { fail } from '../../dialog/fail';
import { Util } from '../../framework/util';
import { PoolManager } from '../../framework/poolManager';
import { SdkUtil } from '../../framework/sdkUtil';
import { base_view } from '../base_view';
import { lab_font } from '../../lab_font';
import { ClientEvent } from '../../framework/clientEvent';
import { StatisticsManager } from '../../framework/statisticsManager';
const { ccclass, property } = _decorator;

@ccclass('view_game_play_han_zi_zhao_bu_tong')
export class view_game_play_han_zi_zhao_bu_tong extends base_view {
    @property(Node) font_grid:Node;
    @property(Node) left_pos:Node;
    @property(Node) bottom_pos:Node;
    // @property(Prefab) item_prefab;
    @property(Prefab) lab_font:Prefab;
    @property(Animation) show_ani:Animation;

    private answer:font_grid_pos[];
    private default_img:SpriteFrame;
    private find_img:SpriteFrame;
    private d_img:SpriteFrame;
    initUI() {

    }

    public initView(data:server_han_zi_zhao_bu_tong_data_item,isUpdate=false){
        this.stop_time_count()
        this.categoryid = config.PLAY_TYPE.HAN_ZI_ZHAO_BU_TONG;
        this.m_data = data;
        let count = 0;
        if(!isUpdate){
            this.node.active = false;
        }
        let self = this;
        self.isShowWin = false;
        this.lab_time_count.active = false;
        gameManager.decRefSf(this.categoryid);
        let levels_item = gameManager.get_cur_level_by_categoryid(this.categoryid);
        let play_item = gameManager.get_play_list_item_by_categoryid(this.categoryid);
        if(levels_item.level>=play_item.barrier_number){
            this.btn_tip.active = false;
        }
        let call_back = ()=>{
            if(count>=3){
                gameManager.loadPlayMusicByCategoryId(this.categoryid,()=>{
                    self.node.active = true;
                    gameManager.hideLoading();
                    self.initGrid();
                    gameManager.playGamePlayMusicByCategoryId(this.categoryid,true);
                })
            }
        }
        tools.loadRemoteImgByCategoryid(this.categoryid,levels_item.level,this.m_data.default_img,(sf)=>{
            count++;
            self.default_img= sf;
            call_back();
        })
        tools.loadRemoteImgByCategoryid(this.categoryid,levels_item.level,this.m_data.find_img,(sf)=>{
            count++;
            self.find_img = sf;
            call_back();
        })
        tools.loadRemoteImgByCategoryid(this.categoryid,levels_item.level,this.m_data.d_img,(sf)=>{
            count++;
            self.d_img = sf;
            call_back();
        })
    }
    getTipItem():font_grid_item{
        let self  = this;
        for (let index = 0; index < self.font_grid.children.length; index++) {
            const element = self.font_grid.children[index];
            if(!element.getComponent(font_grid_item).isFinish()&&element.getComponent(font_grid_item).isRight()){
                return element.getComponent(font_grid_item);
            }
            
        }
        return null;
    }
    onTipBtnClick(){
 
        let tip_call = ()=>{
            let item = this.getTipItem();
            if(item){
                item.blinkShow()
            }
        }
        if(gameManager.isTestUser()){
            tip_call();
        }else{
            SdkUtil.showVideoAd(config.rewardVideoAdUnitId.Tip_AdUnitId,(res)=>{
                if(res.isEnded){
                    tip_call();
                }
                // 统计-激励视频广告
                let collect_data = StatisticsManager.get_collect_data(this.categoryid,this.m_data.id,0,res,config.STATISTICS_ACTION_TYPE.TI_SHI)
                StatisticsManager.request_collect_rewardVideoData(collect_data)
            })
        }
       
    }
    onGridItemClick(item:font_grid_item){
       if(item.isRight()&&!item.isFinish()){
            gameManager.playRightSoundByCategoryId(this.categoryid);
            item.Finish(this.d_img);
            this.hideGuid()
       }
       if(!item.isRight()){
            gameManager.playErrSoundByCategoryId(this.categoryid);;
            this.error_sub_time()
            item.showErrStatus()
            this.showErrLab(item.node)
       }
       if(this.checkAllAnswerFinish()&&!this.isShowWin){
            this.stop_time_count()
            if(gameManager.isFinishAllLevel(this.categoryid)){
                tools.showToast("当前已是最后一关，敬请期待最新版本");
            }else{
                let self = this;
                let tip_call = ()=>{
                    for (let index = 0; index < self.font_grid.children.length; index++) {
                        const element = self.font_grid.children[index];
                        if(element.getComponent(font_grid_item).isRight()){
                            element.getComponent(font_grid_item).rewardShow()
                        }
                    }
                }
                tip_call()
                self.scheduleOnce(()=>{
                    for (let index = 0; index < self.font_grid.children.length; index++) {
                        const element = self.font_grid.children[index];
                        if(element.getComponent(font_grid_item).isRight()){
                            element.getComponent(font_grid_item).hide()
                        }
                    }
                    this.showWin();
                },2)
            }
           
       }
    }

    checkAllAnswerFinish():boolean{
        let self = this;
        let answer_number = self.m_data.answer_number;
        let count = this.getFinishNumber();
        return count>=answer_number;
    }

    getFinishNumber():number{
        let self = this;
        let count = 0;
        for (let index = 0; index < self.font_grid.children.length; index++) {
            const element = self.font_grid.children[index];
            if(element.getComponent(font_grid_item).isFinish()){
                count++;
            }
            
        }
        return count;
    }

    isRight(r:number,c:number):boolean{
        for (let index = 0; index < this.answer.length; index++) {
            const element = this.answer[index];
            if(element.row==r&&element.col==c){
                return true;
            }
        }
        return false;
    }

    initFontList(){
        return new Promise((resolve, reject)=>{
            this.bottom_pos.removeAllChildren()
            this.left_pos.removeAllChildren()
            let k = this.font_grid.parent.getComponent(Widget).left +this.font_grid.getComponent(Widget).right;
            let width = view.getVisibleSize().width-k;
            let height = Math.floor((width-10)/11); 
            let cell_size = new Size(height,height);
            for (let index = this.m_data.row; index > 0; index--) {
                let item = instantiate(this.lab_font);
                item.parent = this.left_pos;
                item.getComponent(UITransform).contentSize  = cell_size
                item.getComponent(lab_font).initLab(index  + "")
            }
    
            for (let index = 0; index < this.m_data.col; index++) {
                let item = instantiate(this.lab_font);
                item.parent = this.bottom_pos;
                item.getComponent(UITransform).contentSize  = cell_size
                item.getComponent(lab_font).initLab(config.ABCD_LIST[index])
            }
        })
    }

    initGrid(){
        this.initFontList()
        return new Promise((resolve, reject)=>{
            this.font_grid.getComponent(Layout).constraintNum = this.m_data.col;
            this.old_coin_number = gameManager.get_user_coin();
            this.lab_coin.getComponent(Label).string = Util.coinNumberToK(this.old_coin_number);
            // this.font_grid.removeAllChildren()
            this.lab_title.getComponent(Label).string = this.m_data.name;
            let list = this.m_data.reward.split(",");
            let start = parseInt(list[0]);
            let end = parseInt(list[1]);
            this.reward =  Util.getRandomInt(start,end);
            if(this.m_data.content.length<=0){
                tools.showToast("关卡未配置数据！")
                return
            }
    
            this.answer = JSON.parse(this.m_data.content);
            let k = this.font_grid.parent.getComponent(Widget).left +this.font_grid.getComponent(Widget).right;
            let width = view.getVisibleSize().width-k;
            let height = Math.floor((width-10)/11); 
            let cell_size = new Size(height,height);
            this.font_grid.getComponent(Layout).cellSize = cell_size
            this.font_grid.parent.getComponent(UITransform).contentSize = new Size(this.font_grid.parent.getComponent(UITransform).contentSize.width,height*15+10)
            if(this.font_grid.children.length>0){
                for (let index = 0; index <this.m_data.col*this.m_data.row; index++) {
                    let col = index%this.m_data.col;
                    let row = Math.floor(index/this.m_data.col);
                    let item = this.font_grid.children[index];
                    item.getComponent(font_grid_item).initView(this.default_img,this.find_img,row,col,this.onGridItemClick.bind(this),this.isRight(row,col));
                }
            }else{
                for (let index = 0; index <this.m_data.col*this.m_data.row; index++) {
                    let col = index%this.m_data.col;
                    let row = Math.floor(index/this.m_data.col);
                   
                    // let item =  instantiate(this.item_prefab)
                    let item = PoolManager.instance.getNodeByPoolName(config.POOL_KEY)
                    item.parent = this.font_grid;
                    // item.getComponent(UITransform).contentSize = new Size(height,height)
                    // item.position = new Vec3(-col*height-(height*0.5)-spacX,row*height+(height*0.5),item.position.z)
                    item.getComponent(font_grid_item).initView(this.default_img,this.find_img,row,col,this.onGridItemClick.bind(this),this.isRight(row,col));
                }
            }
            this.start_time_count(this.m_data.s_time)
            gameManager.hideLoading();
            if(this.checkShowGuid()){
                this.show_ani.node.getComponent(UIOpacity).opacity = 0;
                // this.show_ani.node.position = new Vec3(600,this.show_ani.node.position.y,this.show_ani.node.position.z)
                this.show_ani.play()
                this.scheduleOnce(()=>{
                    let item  = this.getTipItem();
                    let v3 = item.node.position;
                    let start_pos = new Vec3()
                    this.font_grid.getComponent(UITransform).convertToWorldSpaceAR(v3,start_pos)
                    this.showGuid(start_pos,()=>{
                        // this.hideGuid()
                        // this.onGridItemClick(this.font_grid.children[0].getComponent(font_grid_item))
                    },item.getComponent(UITransform).contentSize)
                },1)
            }else{
                this.show_ani.node.getComponent(UIOpacity).opacity = 0;
                // this.show_ani.node.position = new Vec3(600,this.show_ani.node.position.y,this.show_ani.node.position.z)
                this.show_ani.play()
            }
            resolve && resolve(true);
        })

    }
    onFailReStartClick(fail_view:fail){
        gameManager.playBtnSound()
        let self = this;
        if(this.m_data.ads_restart==1){
            SdkUtil.showVideoAd(config.rewardVideoAdUnitId.Resume_AdUnitId,(res)=>{
                if(res.isEnded){
                    self.initGrid().then()
                    fail_view.close()
                }
                // 统计-激励视频广告
                let collect_data = StatisticsManager.get_collect_data(this.categoryid, this.m_data.id, 0, res, config.STATISTICS_ACTION_TYPE.CHONG_XIN_KAI_SHI)
                StatisticsManager.request_collect_rewardVideoData(collect_data)
            })
        }else{
            self.initGrid().then()
            fail_view.close()
        }
    }

    close(): void {
        this.stop_time_count()
        this.lab_time_count.getComponent(Label).string = ""
        this.lab_time_count.active = false;
        this.node.active = false;
        ClientEvent.dispatchEvent(config.EVENT_MSG.ON_BACK_HOME_VIEW)
    }
}


