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

@ccclass('view_game_play_shuang_tu_zhao_xiang_tong')
export class view_game_play_shuang_tu_zhao_xiang_tong extends  base_view  {
    @property(Node) img_1:Node;
    @property(Node) img_2:Node;
    @property(Node) content_1:Node;
    @property(Node) content_2:Node;
    @property(Node) star_list:Node;
    @property(Node) effect:Node = null;
    private img_1_sf:SpriteFrame;
    private img_2_sf:SpriteFrame;
    private err_node_2:Node = null;
    protected initUI(): void {
        this.img_1.on(Node.EventType.TOUCH_END,this.TOUCH_START_IMG_1.bind(this),this);
        this.img_2.on(Node.EventType.TOUCH_END,this.TOUCH_START_IMG_2.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_1.getComponent(UITransform).convertToNodeSpaceAR(v3);
        }
    }

    TOUCH_START_IMG_2(event: EventTouch){
        if(this.err_node_2!=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_2); 
            this.err_node_2.active = true;
            tween(this.err_node_2).delay(0.5).call(()=>{
                this.err_node_2.active = false;
            }).start();
            this.showErrLab( this.err_node_2)
            this.err_node_2.position =  this.img_2.getComponent(UITransform).convertToNodeSpaceAR(v3);
        }
    }

    getTipItem():circle{
        let self = this;
        for (let index = 1; index < self.img_1.children.length; index++) {
            const element = self.img_1.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){
                return;
            }
            item.blinkShow();
            item.get_relative_node().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)
            })
        }
    
    }

    onImg1Scroll(){
        this.content_2.position = this.content_1.position;
    }

    onImg2Scroll(){
        this.content_1.position = this.content_2.position;
    }

    initAnswerView(){
        let self = this;
        self.img_1.removeAllChildren();
        self.img_2.removeAllChildren();
        this.err_node_1  = null;
        this.err_node_2  = null;
        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
        }
        self.star_list.getComponent(star_list).initView(this.m_data.answer_number);
        let top_list:xiang_tong_pos[] = JSON.parse(this.m_data.content)[0];
        let bottom_list:xiang_tong_pos[] = JSON.parse(this.m_data.content)[1];
        resources.load(config.PREFAB_PATH.circle, Prefab, (err, prefab) => {
            if(err){
                return;
            }
            this.err_node_1 = instantiate(this.img_touch_err);
            this.err_node_1.parent = self.img_1;
            this.err_node_1.active = false;

            this.err_node_2 = instantiate(this.img_touch_err);
            this.err_node_2.parent = self.img_2;
            this.err_node_2.active = false;
            let tmep_array = []
            let size_circle = new Size(60,60)
            for (let index = 0; index < top_list.length; index++) {
                const top_v3 =new Vec3( top_list[index].x, top_list[index].y,0);
                const bottom_v3 =new Vec3( bottom_list[index].x, bottom_list[index].y,0);
                let  top_id = top_list[index].id;
                let  bottom_id = bottom_list[index].id;
                // if(tmep_array[id]!=null&&tmep_array[id]!=undefined){

                // }

                let newNode:Node = instantiate(prefab);
                let newNode1:Node = instantiate(prefab);
                newNode.parent = self.img_1;
                newNode1.parent = self.img_2;
                newNode.position = top_v3;
                newNode1.position = bottom_v3;
                newNode.getComponent(circle).initXiangTongView(top_id,newNode1.getComponent(circle),size_circle,this.onCircleClick.bind(this))
                newNode1.getComponent(circle).initXiangTongView(bottom_id,newNode.getComponent(circle),size_circle,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_1.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_1.children.length; index++) {
            const element = self.img_1.children[index];
            if(element.getComponent(circle).isFinish()){
                count++;
            }
            
        }
        return count;
    }

    onCircleClick(item:circle,id,relative_node:circle){
        if(!item.isFinish()){
            item.Finish()
            item.show()
            relative_node.Finish()
            relative_node.show()
            let count = this.getFinishNumber();
            gameManager.playRightSoundByCategoryId(this.categoryid);
            let star = this.star_list.getComponent(star_list).showStartByNumber(count);
            //
            let parent = item.node.parent.name ==="img1"?this.img_1:this.img_2;
            let new_node:Node = instantiate(this.effect);
            new_node.active = true
            let start_pos = new Vec3()
            parent.getComponent(UITransform).convertToWorldSpaceAR(item.node.position,start_pos)

            let end_pos =  this.star_list.getComponent(UITransform).convertToWorldSpaceAR(star.position)
            new_node.parent = this.action_node;
            new_node.position = start_pos;
            new_node.angle =Util.lookAtObj(new Vec2(start_pos.x,start_pos.y),new Vec2(end_pos.x,end_pos.y)); 
            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_1.children.length; index++) {
                        self.img_1.children[index].getComponent(circle).rewardShow();
                        self.img_2.children[index].getComponent(circle).rewardShow();
                    }
                }
                tip_call()
                self.scheduleOnce(()=>{
                    self.img_1.removeAllChildren()
                    self.img_2.removeAllChildren()
                    this.showWin();
                },2)
            }

        }
    }

    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.initAnswerView()
                    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()
            self.initAnswerView()
        }
    }

    public initView(data:server_shuang_tu_zhao_bu_tong_data_item,isUpdate=false){
        this.categoryid = config.PLAY_TYPE.ZHAO_XIANG_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 call_back = ()=>{
            if(count>=2){
                gameManager.loadPlayMusicByCategoryId(this.categoryid,()=>{
                    self.node.active = true;
                    self.img_1.getComponent(Sprite).spriteFrame = self.img_1_sf;
                    self.img_2.getComponent(Sprite).spriteFrame = self.img_2_sf;
                    self.initAnswerView();
                    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 = self.m_data.name;
                    gameManager.hideLoading();
                    gameManager.playGamePlayMusicByCategoryId(this.categoryid,true);
                })
            }
        }
        let play_item = gameManager.get_play_list_item_by_categoryid(this.categoryid);
        let levels_item = gameManager.get_cur_level_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.img1,(sf)=>{
            count++;
            self.img_1_sf = sf;
            call_back();
        })
        tools.loadRemoteImgByCategoryid(this.categoryid,levels_item.level,this.m_data.img2,(sf)=>{
            count++;
            self.img_2_sf = sf;
            call_back();
        })
    }
 
}


