
import { props } from '../props';
import {getTextureByName, OptionState, GameState} from "./utils";
import { SvgaManager } from './SvgaManager';

export class AnswerArea extends engine.Container{
    private _area;//答题区域
    private _optionA;//选项A
    private _optionB;//选项A
    private _optionC;//选项A
    private _optionD;//选项A

    private _optionArray=[];//选项节点

    //懒得按选项节点查询处理 故在创建的时候 用对应的数组处理
    private _choiceWrong = [];//选错状态的节点数组
    private _choiceRight = [];//选对状态的节点数组
    private _choiceSelect = [];//选中状态的数组

    private _answerArray=['A','B','C','D'];
    private _answer = -1;//用户选择的选项

    private _gameState;
    private _people;//人物svga

    private _svgaArrayName = [];//答题后的动效
    private _randomSvga;//随机播放对应的svga动效
    private _right_mona;//回答正确的节点
    
    private _trueAnswer;//正确答案
    private _mona_confuse;//未选择答案 问号svga

    private _svgaPlayState;
    init(){
        let area = this._area = new engine.Container();
        area.x = 0;
        area.y = 0;
        this._gameState = GameState.STATE_END;

        this.addChild(area);
        this.initSvgaArray();
        this.initAnswerOption();
        this.initPeople();
        this.insideAddEventListener();
    }
    private initSvgaArray(){
        this.setSvgaName('rian_mona','rian_weather');
        this.setSvgaName('snow_mona','snow_weather');
        this.setSvgaName('thunder_mona','thunder_weather');
        this.setSvgaName('wind_mona','wind_weather');
    }

    private setSvgaName(peopleName,scene){
        let tmpSvgaName:any = {};
        tmpSvgaName.people = peopleName;
        tmpSvgaName.scene = scene;
        this._svgaArrayName.push(tmpSvgaName);
    }


    private insideAddEventListener(){
        //更新答案选项
        engine.globalEvent.addEventListener('updateOption',this.updateOption,this)
        //答题结果
        engine.globalEvent.addEventListener('handleAnswerOption',this.handleAnswerOption,this);
        //更新游戏状态
        engine.globalEvent.addEventListener('upDateGameState',this.upDateGameState,this);
        //开始答题 可选
        engine.globalEvent.addEventListener('start',this.start,this);
        //提交答案
        engine.globalEvent.addEventListener('sendAnswer',this.sendAnswer,this);
        engine.globalEvent.addEventListener('outRest',this.rest,this);
        //开始答题
        //engine.globalEvent.addEventListener('startAnswer',this.startAnswer,this)

    }
    
    private initPeople(){
        let people = this._people = SvgaManager.createSvga('mona_walk');
        people.x = props.people_X;
        people.y = props.people_Y;
        this._area.addChild(people);
        SvgaManager.play(people);

        let mona_confuse = this._mona_confuse = SvgaManager.createSvga('mona_confuse');
        mona_confuse.x = props.people_X;
        mona_confuse.y = props.people_Y;
        mona_confuse.visible = false;
        this._area.addChild(mona_confuse);

        //people.gotoAndStop(1);
    }
    public getArea(){
        return this._area;
    }

    //初始化选项
    private initAnswerOption(){
        let optionA = this._optionA = new engine.Image(getTextureByName('选区'))
        optionA.x = (750 - (optionA.width*2 + 30)) / 2;
        optionA.y = props.answerArea_Y;
        optionA.name = 'A';
        optionA.alpha = 0;
        this._area.addChild(optionA);
        this._optionArray.push(optionA);

        let optionB = this._optionB = new engine.Image(getTextureByName('选区'))
        optionB.x = optionA.x + optionA.width + 30;
        optionB.y = optionA.y;
        optionB.name = 'B';
        optionB.alpha = 0;
        this._area.addChild(optionB);
        this._optionArray.push(optionB);

        let optionC = this._optionC = new engine.Image(getTextureByName('选区'))
        optionC.x = optionA.x;
        optionC.y = optionA.y + optionA.height + props.option_spaceY;
        optionC.name = 'C';
        optionC.alpha = 0;
        this._area.addChild(optionC);
        this._optionArray.push(optionC);

        let optionD = this._optionD = new engine.Image(getTextureByName('选区'))
        optionD.x = optionB.x;
        optionD.y = optionC.y;
        optionD.name = 'D';
        optionD.alpha = 0;
        this._area.addChild(optionD);
        this._optionArray.push(optionD);
        

        this.initOptionState();
        this.initAddEventListener();
        this.initSvga(optionA);
        this.initSvga(optionB);
        this.initSvga(optionC);
        this.initSvga(optionD);

        // setTimeout(() => {
        //     this.handleWrong();
        // }, 1000);
    }
    //初始化svga节点
    private initSvga(tmpNode){
        this.initSvgaNode('right_mona',tmpNode);
        for (let index = 0; index < this._svgaArrayName.length; index++) {
            let element = this._svgaArrayName[index];
            this.initSvgaNode(element.people,tmpNode);
            this.initSvgaNode(element.scene,tmpNode);
        }
    }
    private initSvgaNode(svgaName,tmpNode){
        let tmpSvga = SvgaManager.createSvga(svgaName);
        tmpSvga.x = -30;
        tmpSvga.y = -105;
        tmpSvga.visible = false;
        tmpSvga.name = svgaName;
        tmpNode.addChild(tmpSvga);
    }

    private initAddEventListener(){
        for (let index = 0; index < this._optionArray.length; index++) {
            const element = this._optionArray[index];
            element.addEventListener(engine.MouseEvent.CLICK,this.selectOption,this);
        }
    }
    //初始化 答案字体
    private optionLabel(parent){
        let answerText = new engine.Label();
        //answerText.font = 'OPPOSans_J';
        answerText.fillColor = 0x164b81;
        answerText.bold = true;
        //answerText.strokeColor = '#164b81';
        //answerText.stroke = 4;
		answerText.size = 30;
		answerText.width = parent.width;
		answerText.height = parent.height;
		answerText.textAlign = engine.TEXT_ALIGN.CENTER;
		answerText.x = 0;
        answerText.y = 0.75*answerText.height;
        answerText.text = '';
        answerText.name = 'answerText';
        
        return answerText;
    }


    //初始化选项 选中-选错-选对 状态
    private initOptionState(){
        for(let i=0; i<this._optionArray.length;i++){
            let tmpNode = this._optionArray[i];
            tmpNode.addChild(this.getChoiceStateImg('选中',OptionState.CHOICE_SELECT,tmpNode.name));
            tmpNode.addChild(this.getChoiceStateImg('选错',OptionState.CHOICE_WRONG,tmpNode.name));
            tmpNode.addChild(this.getChoiceStateImg('选对',OptionState.CHOICE_RIGHT,tmpNode.name));
            tmpNode.addChild(this.optionLabel(tmpNode))
            
        }
    }
    //获取图片资源
    private getChoiceStateImg(imgName,imgType,imgAnswer){
        let choiceImage = new engine.Image(getTextureByName(imgName));
        choiceImage.x = 0;
        choiceImage.y = 0;
        choiceImage['type'] = imgType;
        choiceImage['imgAnswer'] = imgAnswer;
        choiceImage.visible = false;
        switch (imgType) {
            case OptionState.CHOICE_WRONG:
                this._choiceWrong.push(choiceImage);
                break;
            case OptionState.CHOICE_RIGHT:
                this._choiceRight.push(choiceImage);
                break;
            case OptionState.CHOICE_SELECT:
                this._choiceSelect.push(choiceImage);
                break;                            
            default:
                break;
        }
        return choiceImage;
    }
    //选中答案
    private selectOption(event: engine.Event){
        if(this._gameState != GameState.STATE_START || this._svgaPlayState == GameState.STATE_START){
            console.log('暂时不能答题');
            return;
        }
        this._gameState = GameState.STATE_END;
        this.handleSelect(event.target.name);
        this.peopleMove(event.target.x-30,event.target.y-110,false);

        this._answer = this._answerArray.indexOf(event.target.name);
        console.log('点击选择选项',event.target.name,this._answer);
    }
    //人物移动
    peopleMove(moveX,moveY,isPlaySVGA){
        let tmpX = moveX;
        let tmpY = moveY;
        engine.Tween.get(this._people,{loop:false})
        .to({x:tmpX,y:tmpY},500,engine.Ease.cubicInOut)
        .call(()=>{
            this._gameState = GameState.STATE_START;
            if(isPlaySVGA){
                SvgaManager.play(this._people);
                engine.globalEvent.dispatchEvent('updateSubject');
            }
        })
    }

    //重置人物位置
    rest(){
        this._answer = -1;
        if(this._right_mona){
            SvgaManager.stop(this._right_mona);
            this._right_mona.visible = false;
        }
        this._people.visible = true;
        this._mona_confuse.visible = false;
   
        this.peopleMove(props.people_X,props.people_Y,true);

        this.handleRight();
        this.handleWrong();
        this.handleSelect();
        this.optionsShow(false);
        engine.globalEvent.dispatchEvent('resetTitle');

    }

    private optionsShow(isShow){
        for (let index = 0; index < this._optionArray.length; index++) {
            const element = this._optionArray[index];
            let tmpAlpha = isShow?1:0;
            this.optionIsShowTween(element,tmpAlpha);
        }
    }
    //选项渐入渐出效果
    private optionIsShowTween(tweenNode,tmpAlpha){
        engine.Tween.get(tweenNode,{loop:false})
        .to({alpha:tmpAlpha},500)
    }
    //处理选中状态
    private handleSelect(select?){
        for (let index = 0; index < this._choiceSelect.length; index++) {
            let element = this._choiceSelect[index];
            if(!select){
                element.visible = false;
                continue;
            }
            if(element['imgAnswer'] === select){
                element.visible = true;
                continue;
            }
            element.visible = false;
        }
    }
    //正确答案展示
    private handleRight(select = ''){
        for (let index = 0; index < this._choiceRight.length; index++) {
            let element = this._choiceRight[index];
            if(select == ''){
                element.visible = false;
                continue;
            }
            if(element['imgAnswer'] === select){
                element.visible = true;
                continue;
            }
            element.visible = false;
            
        }
    }
    //错误答案展示
    private handleWrong(select?){
        let count = 0;
        for (let index = 0; index < this._choiceWrong.length; index++) {
            let element = this._choiceWrong[index];
            if(!select){
                element.visible = false;
                this.hideSvga(element);
                continue;
            }
            if(element['imgAnswer'] == select){
                element.visible = false;
                continue;
            }
            count++;
            element.visible = true;
            this.playWrongTween(element,(count == this._choiceWrong.length-1));
        }
    }
    private hideSvga(svgaNode){
        svgaNode.parent.children.forEach(element => {
            if(element._instanceType == 'MovieClip')
            {
                element.visible = false;
            }
        });
    }
    playWrongTween(tweenNode,isLast){
        engine.Tween.get(tweenNode,{loop:false})
        .wait(460)
        .to({alpha:0.3},160,engine.Ease.circInOut)
        .to({alpha:1},160,engine.Ease.circInOut)
        .to({alpha:0.3},160,engine.Ease.circInOut)
        .to({alpha:1},160,engine.Ease.circInOut)
        .call(()=>{
            engine.Tween.removeTweens(tweenNode);
            if(isLast){
                if(this._answer >= 0){
                    this._people.visible = false;
                    this.handleSeceltRight();
                    this.handleSeceltError();
                }else{
                    this._people.visible = false;
                    this._mona_confuse.visible = true;
                    SvgaManager.play(this._mona_confuse,()=>{
                        this.rest();
                    });
                }

            }
        })
    }

    //播放对应的人物动效
    playResultSvga(svgaNode,isLast,isShowPeople){
        let svgaData =this._svgaArrayName[this._randomSvga-1]; 
        if(isShowPeople){
            let peopleNode = this.getSvgaNode(svgaNode,svgaData.people);
            this.playSvga(peopleNode);
        }
        let sceneNode = this.getSvgaNode(svgaNode,svgaData.scene);
        this.playSvga(sceneNode,()=>{
            if(isLast)this.rest();
        });
    }
    private getSvgaNode(svgaNode,svgaName){
        let tmp = svgaNode.getChildByName(svgaName);
        if(!tmp){console.log('svga节点未找到');return}
        return tmp
    }
    //播放svga
    playSvga(svgaNode,callBack?){
        svgaNode.visible = true;
        SvgaManager.play(svgaNode,()=>{
            svgaNode.visible = false;
            if(callBack)callBack();
        });
    }

    //更新选项
    private updateOption(optionData){
        this._randomSvga = Math.floor(Math.random()*(this._svgaArrayName.length)+1);

        let tmpOptionData = optionData.data.options;
        for (let index = 0; index < tmpOptionData.length; index++) {
            let element = tmpOptionData[index];
            this._optionArray[index].getChildByName('answerText').text = element;
        }
    }
    //答案
    private handleAnswerOption(result){
        //SvgaManager.stop(this._people);
        this._people.gotoAndStop(1)

       let trueAnswer = this._trueAnswer = result.data.state;

        this.handleRight(this._answerArray[trueAnswer]);
        this.handleWrong(this._answerArray[trueAnswer]);
        this.handleSelect();
        this._svgaPlayState = GameState.STATE_START;
        //处理动效
    }

    private handleSeceltRight(){
        //if(this._gameState == GameState.STATE_START)return;

        for (let index = 0; index < this._optionArray.length; index++) {
            let element = this._optionArray[index];
            if(element.name == this._answerArray[this._answer] && this._trueAnswer == this._answer){
                this._right_mona = this.getSvgaNode(element,'right_mona')
                if(this._right_mona){
                    this._right_mona.visible = true;
                    SvgaManager.play(this._right_mona);
                }
            }
        }
    }
    private handleSeceltError(){
        //if(this._gameState == GameState.STATE_START)return;
        
        let tmpNum = 0;
        for (let index = 0; index < this._optionArray.length; index++) {
            let element = this._optionArray[index];
            if(element.name != this._answerArray[this._trueAnswer]){
                tmpNum++;
                let isShowPeople = false;
                if(element.name == this._answerArray[this._answer]){
                    isShowPeople = true;
                }
                this.playResultSvga(element,(tmpNum==3),isShowPeople);
            }
        }
    }

    //更新答题状态
    private upDateGameState(gameState){
        this._gameState = gameState.data.gameState;
    }

    private start(){
        this.optionsShow(true);
        this._gameState = GameState.STATE_START;
        this._svgaPlayState = GameState.STATE_END;
    }

    sendAnswer(){
        engine.globalEvent.dispatchEvent('sendAnswerResult',{answer:this._answer});
    }
}