import { _decorator, assetManager, Component, EventTouch, ImageAsset, instantiate, Label, math, Node, Prefab, ProgressBar, Quat, resources, Size, Sprite, SpriteFrame, Texture2D, tween, Tween, UITransform, utils, Vec2, Vec3 } from 'cc';
import { gameManager } from '../../gameManager';
import { config } from '../../config';
import { server_shuang_tu_zhao_bu_tong_data_item, unlock_levels_item } from '../../data/server_play_list_data';
import { tools } from '../../tools';
import { circle } from '../circle';
import { star_list } from '../star_list';
import { fail } from '../../dialog/fail';
import { ClientEvent } from '../../framework/clientEvent';
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_shuang_tu_zhao_bu_tong')
export class view_game_play_shuang_tu_zhao_bu_tong extends base_view {
    @property(Node) btn_amplify:Node;
    @property(Node) img_1:Node;
    @property(Node) img_2:Node;
    @property(Node) content_1:Node;
    @property(Node) content_2:Node;
    @property(SpriteFrame) sf_amplify_magnify_status:SpriteFrame;
    @property(SpriteFrame) sf_amplify_shrink_status:SpriteFrame;
    @property(Node) star_list:Node;
    @property(Node) effect:Node = null;
    private img_1_sf:SpriteFrame;
    private img_2_sf:SpriteFrame;
    private cur_amplify_status:number = 0;
    private err_node_2:Node = null;
    private scale_multiple:number = 2;
    initUI() {
        let self = this;
        this.btn_amplify.on(Node.EventType.TOUCH_START,()=>{
            gameManager.playBtnSound()
            if(self.cur_amplify_status==0){
                self.cur_amplify_status = 1;
            }else{
                self.cur_amplify_status = 0;
            }
            self.updateAmplifyStatus();
        },this);

        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);
        }
    }


    updateAmplifyStatus(){
        let self = this;
        if(self.cur_amplify_status==0){
            let newSize = new Size(375,240);
            let newScale = new Vec3(1,1,self.img_1.scale.z);
            self.content_1.getComponent(UITransform).contentSize = newSize;
            self.content_2.getComponent(UITransform).contentSize = newSize;
            self.btn_amplify.getComponent(Sprite).spriteFrame = self.sf_amplify_magnify_status;
            self.img_1.scale = newScale;
            self.img_2.scale = newScale;
        }else{
            let newSize = new Size(375*this.scale_multiple,240*this.scale_multiple);
            let newScale = new Vec3(this.scale_multiple,this.scale_multiple,self.img_1.scale.z);
            self.content_1.getComponent(UITransform).contentSize = newSize;
            self.content_2.getComponent(UITransform).contentSize = newSize;
            self.btn_amplify.getComponent(Sprite).spriteFrame = self.sf_amplify_shrink_status;
            self.img_1.scale = newScale;
            self.img_2.scale = newScale;
        }
    }
    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 = ()=>{
            if(self.cur_amplify_status==1){
                self.cur_amplify_status = 0;
                self.updateAmplifyStatus();
            }
            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;
        this.cur_amplify_status = 0;
        this.updateAmplifyStatus()
        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 list:Vec2[] = JSON.parse(this.m_data.content);
        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;

            for (let index = 0; index < list.length; index++) {
                const v3 =new Vec3( list[index].x, list[index].y,0);
                let newNode:Node = instantiate(prefab);
                let newNode1:Node = instantiate(prefab);
                newNode.parent = self.img_1;
                newNode1.parent = self.img_2;
                newNode.position = v3;
                newNode1.position = v3;
                newNode.getComponent(circle).initView(newNode1.getComponent(circle),this.onCircleClick.bind(this))
                newNode1.getComponent(circle).initView(newNode.getComponent(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,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 = ()=>{
                    if(self.cur_amplify_status==1){
                        self.cur_amplify_status = 0;
                        self.updateAmplifyStatus();
                    }
                    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.YI_QI_ZHAO_CHA;
        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();
        })
    }
 

}


