import { _decorator, Component, EventTouch, instantiate, Label, Node, Prefab, ProgressBar, resources, ScrollView, Size, Sprite, SpriteFrame, tween, Tween, UITransform, utils, Vec3 } from 'cc';
import { mei_nv_pos, node_and_index, server_mei_nv_zhao_xi_jie_data_item } from '../../data/server_play_list_data';
import { config } from '../../config';
import { gameManager } from '../../gameManager';
import { tools } from '../../tools';
import { component_item } from './component_item';
import { circle } from '../circle';
import { fail } from '../../dialog/fail';
import { Util } from '../../framework/util';
import { SdkUtil } from '../../framework/sdkUtil';
import { base_view } from '../base_view';
import { StatisticsManager } from '../../framework/statisticsManager';
const { ccclass, property } = _decorator;

@ccclass('view_game_play_mei_nv_zhao_xi_jie')
export class view_game_play_mei_nv_zhao_xi_jie extends base_view {
    @property(Node) img:Node;
    @property(Node) content:Node;
    @property(Prefab) component_item_prefab:Prefab;
    @property(Node) img_touch_err:Node;
    @property(ScrollView) scroll_view:ScrollView;
    private sfList:Map<number,SpriteFrame> = new Map;
    private answer:mei_nv_pos[];
    private img_sf:SpriteFrame;
    initUI() {
        this.img.on(Node.EventType.TOUCH_START,this.TOUCH_START_IMG_1.bind(this),this);
    }

    TOUCH_START_IMG_1(event: EventTouch){
        if(this.err_node_1!=null){
            gameManager.playErrSoundByCategoryId(this.categoryid);
            this.error_sub_time()
            let v3 =  new Vec3(event.getUILocation().x,event.getUILocation().y,0);
            Tween.stopAllByTarget(this.err_node_1); 
            this.err_node_1.active = true;
            tween(this.err_node_1).delay(0.5).call(()=>{
                this.err_node_1.active = false;
            }).start();
            this.showErrLab(this.err_node_1)
            this.err_node_1.position =  this.img.getComponent(UITransform).convertToNodeSpaceAR(v3);
        }
    }
    getTipItem():circle
    {
        let self  = this;
        for (let index = 1; index < self.img.children.length; index++) {
            const element = self.img.children[index];
            if(!element.getComponent(circle).isFinish()){
                return element.getComponent(circle);
            }
            
        }
        return null;
    }
    onTipBtnClick(){
        let self  = this;
        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)
            })
        }
    }
    public initView(data:server_mei_nv_zhao_xi_jie_data_item,isUpdate=false){
        this.categoryid = config.PLAY_TYPE.MEI_NV_ZHAO_XI_JIE;
        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);
        self.sfList.clear()
        let call_back = ()=>{
            if(count>=this.m_data.component.length+1){
                gameManager.loadPlayMusicByCategoryId(this.categoryid,()=>{
                    self.node.active = true;
                    gameManager.hideLoading();
                    self.initComponent();
                    self.initAnswerView();
                    gameManager.playGamePlayMusicByCategoryId(this.categoryid,true);
                })
            }
        }
        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;
        }

        tools.loadRemoteImgByCategoryid(this.categoryid,levels_item.level,this.m_data.img,(sf)=>{
            count++;
            self.img_sf= sf;
            call_back();
        })

        for (let index = 0; index < this.m_data.component.length; index++) {
            const element = this.m_data.component[index];
            tools.loadRemoteImgByCategoryid(this.categoryid,levels_item.level,element.img,(sf,id)=>{
                count++;
                self.sfList.set(id ,sf);
                call_back();
            },element.id);
        }
    }
    initComponent(){
        this.content.removeAllChildren()
        if(this.m_data.content.length<=0){
            tools.showToast("关卡未配置数据！")
            return
        }
        this.answer = JSON.parse(this.m_data.content);
        for (let index = 0; index < this.answer.length; index++) {
            const element = this.answer[index];
            let item = instantiate(this.component_item_prefab);
            item.parent = this.content;
            item.getComponent(component_item).initView(element,this.sfList.get(element.id))
            
        }
        this.scroll_view.scrollToBottomLeft(0)
        this.img.getComponent(Sprite).spriteFrame = this.img_sf;
    }
    finishComponent(id:number):node_and_index{
        let node:Node = null;
        let n_i = null;
        let _index = 0;
        for (let index = 0; index < this.content.children.length; index++) {
            const element = this.content.children[index];
            if(element.getComponent(component_item).getData().id===id){
                element.getComponent(component_item).finish();
                node = element;
                _index = index;
                n_i = new node_and_index();
                break;
            }
            
        }
        n_i.node = node;
        n_i.index = _index;
        return n_i;
    }
    initAnswerView(){
        let self = this;
        self.old_coin_number = gameManager.get_user_coin();
        self.lab_coin.getComponent(Label).string = Util.coinNumberToK(self.old_coin_number);
        self.lab_title.getComponent(Label).string = this.m_data.name;
        self.img.removeAllChildren();

        let list = this.m_data.reward.split(",");
        let start = parseInt(list[0]);
        let end = parseInt(list[1]);
        this.reward =  Util.getRandomInt(start,end);

        resources.load(config.PREFAB_PATH.circle, Prefab, (err, prefab) => {
            if(err){
                return;
            }

            this.err_node_1  = null;
            this.err_node_1 = instantiate(this.img_touch_err);
            this.err_node_1.parent = self.img;
            this.err_node_1.active = false;
            let size:Size = new Size(80,80);
            for (let index = 0; index < this.answer.length; index++) {
                const v3 =new Vec3(this.answer[index].posx,this.answer[index].posy,0);
                let newNode:Node = instantiate(prefab);
                newNode.position = v3;
                newNode.parent = self.img;
                newNode.getComponent(circle).initMeiNvView(this.answer[index].id,size,this.onCircleClick.bind(this))
            }
        });
        this.start_time_count(this.m_data.s_time)

        if(this.checkShowGuid()){
            this.scheduleOnce(()=>{
                let item  = this.getTipItem();
                let v3 = item.node.position;
                let start_pos = new Vec3()
                this.img.getComponent(UITransform).convertToWorldSpaceAR(v3,start_pos)
                this.showGuid(start_pos,()=>{
                    // self.hideGuid()
                    // self.onCircleClick(item,item.get_relative_node())
                },item.getComponent(UITransform).contentSize)
            },0.5)
        }
    }
    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 = 1; index < self.img.children.length; index++) {
            const element = self.img.children[index];
            if(element.getComponent(circle).isFinish()){
                count++;
            }
            
        }
        return count;
    }

    onCircleClick(item:circle,id:number){
        if(!item.isFinish()){
            gameManager.playRightSoundByCategoryId(this.categoryid)
            item.Finish()
            item.show()
            let n_i = this.finishComponent(id);
            if(n_i.index<=3){
                this.scroll_view.scrollToBottomLeft(0)
            }
            if(n_i.index>=4){
                this.scroll_view.scrollToBottomRight(0)
            }

            if(n_i!=null){
                let new_node:Node = instantiate(n_i.node);
                let start_pos = new Vec3()
                this.img.getComponent(UITransform).convertToWorldSpaceAR(item.node.position,start_pos)
                let end_pos =  this.content.getComponent(UITransform).convertToWorldSpaceAR(n_i.node.position)
                new_node.parent = this.action_node;
                new_node.position = start_pos;
                new_node.getComponent(component_item).hideMask();
                tween(new_node).to(0.5, {position: end_pos}).removeSelf().start()
            }
            this.hideGuid();
        }

        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 = 1; index < self.img.children.length; index++) {
                        const element = self.img.children[index];
                        element.getComponent(circle).rewardShow();
                    }
                }
                tip_call()
                self.scheduleOnce(()=>{
                    self.img.removeAllChildren()
                    this.showWin();
                },2)
            }

        }
    }
  
    onFailReStartClick(fail_view:fail){
        gameManager.playBtnSound()
        if(this.m_data.ads_restart==1){
            SdkUtil.showVideoAd(config.rewardVideoAdUnitId.Resume_AdUnitId,(res)=>{
                if(res.isEnded){
                    this.initAnswerView();
                    this.initComponent();
                    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{
            fail_view.close()
            this.initAnswerView();
            this.initComponent();
        }


    }
}


