import { _decorator, Component, EventTouch, instantiate, Label, Node, Prefab, Rect, UITransform, Vec2, Vec3 } from 'cc';
import { base_view } from '../base_view';
import { config } from '../../config';
import { ddz_card } from './ddz_card';
import { tools } from '../../tools';
import { ddz_ai } from './ddz_ai';
import { fail } from '../../dialog/fail';
import { gameManager } from '../../gameManager';
import { SdkUtil } from '../../framework/sdkUtil';
import { Util } from '../../framework/util';
import { tip_layer } from './tip_layer';
import { out_ani } from './out_ani';
import { StatisticsManager } from '../../framework/statisticsManager';
const { ccclass, property } = _decorator;

@ccclass('game_play_dou_di_zhu')
export class game_play_dou_di_zhu extends base_view {
    private m_play_hand_cards:string[] =[];
    private m_computer_hand_cards:string[] =[];
    private m_answer_cards:string[] =[];
    private fullDoudizhuDeckIndex = {}
    private touch_status = false;
    private is_start_move = false;
    private touch_pos:Vec2 =Vec2.ZERO;
    private first_left_pos:Vec2 = Vec2.ZERO;
    private first_right_pos:Vec2 = Vec2.ZERO;
    private play_move:string[] = [];
    private ai_move:string[] = [];
    private legalActions:any[] = [];
    private is_look_answer = false;
    @property(Prefab) item_prefab:Prefab;
    @property(Node) play_hand_cards_layer:Node;
    @property(Node) play_out_cards_layer:Node;
    @property(Node) ai_hand_cards_layer:Node;
    @property(Node) ai_out_cards_layer:Node;
    @property(Node) btn_chu_pai:Node;
    @property(Node) btn_bu_chu:Node;
    @property(Node) btn_yao_bu_qi:Node;
    @property(Node) test_spr:Node;
    @property(Node) tip_layer:Node;
    @property(Node) play_out_ani:Node;
    @property(Node) ai_out_ani:Node;
    protected initUI(): void {
        this.btn_chu_pai.on(Node.EventType.TOUCH_END,()=>{
            gameManager.playBtnSound()
            if(this.checkCardCanOut()){
                this.hideBtns()
                if(this.outCards()){
                    this.scheduleOnce(()=>{
                        this.Aithink()
                    },0.3)
                }
            }else{
                this.backOut()
            }
        })
        this.btn_bu_chu.on(Node.EventType.TOUCH_END,()=>{
            gameManager.playBtnSound()
            this.play_move = []
            this.play_out_cards_layer.removeAllChildren()
            this.ai_out_cards_layer.removeAllChildren()
            this.play_out_ani.getComponent(out_ani).showPass()
            this.hideBtns()
            this.Aithink()
        })
        this.btn_yao_bu_qi.on(Node.EventType.TOUCH_END,()=>{
            gameManager.playBtnSound()
            this.play_move = []
            this.play_out_cards_layer.removeAllChildren()
            this.ai_out_cards_layer.removeAllChildren()
            this.hideBtns()
            this.Aithink()
            this.play_out_ani.getComponent(out_ani).showyaoBuQi()
            this.backOut()
        })
    }

    public initView(data: any, isUpdate?: boolean): void {
        this.categoryid = config.PLAY_TYPE.DOU_DI_ZHU;
        this.m_data = data;
        this.btn_chu_pai.active = false;
        this.btn_bu_chu.active = false;
        this.btn_yao_bu_qi.active = false;
        this.is_look_answer = false;
        this.isShowWin = false;
        this.touch_status = false;
        this.is_start_move = false;
        this.touch_pos=Vec2.ZERO;
        this.first_left_pos = Vec2.ZERO;
        this.first_right_pos= Vec2.ZERO;
        this. play_move= [];
        this.ai_move = []
        this.legalActions= [];
        this.tip_layer.getComponent(tip_layer).initView(this.m_data.answer_content)
        this.tip_layer.active = false;
        this.old_coin_number = gameManager.get_user_coin();
        this.lab_coin.getComponent(Label).string = Util.coinNumberToK(this.old_coin_number);
        this.lab_title.getComponent(Label).string = this.m_data.name;

        this.m_play_hand_cards =tools.sortDoudizhuCards(this.m_data.player_content.split(','))
        this.m_computer_hand_cards = tools.sortDoudizhuCards(this.m_data.computer_content.split(',')) 
        this.m_answer_cards = tools.sortDoudizhuCards(this.m_data.answer_content.split(','))
        this.fullDoudizhuDeckIndex = {}
        for (const key in config.fullDoudizhuDeckIndex) {
            if (Object.prototype.hasOwnProperty.call(config.fullDoudizhuDeckIndex, key)) {
                const element = config.fullDoudizhuDeckIndex[key];
                this.fullDoudizhuDeckIndex[key] = element;
            }
        }
        this.play_hand_cards_layer.removeAllChildren();
        this.play_out_cards_layer.removeAllChildren();
        this.ai_hand_cards_layer.removeAllChildren();
        this.ai_out_cards_layer.removeAllChildren();
        for (let index = this.m_play_hand_cards.length-1; index >=  0; index--) {
            const card =  this.m_play_hand_cards[index];
            let item:Node = instantiate(this.item_prefab)
            item.parent = this.play_hand_cards_layer;
            item.active = false;
            item.getComponent(ddz_card).initView(card,this.getCardType(card),index)
        }
        this.start_play_hand_card_action()
        this.play_hand_cards_layer.off(Node.EventType.TOUCH_START)
        this.play_hand_cards_layer.on(Node.EventType.TOUCH_START,(event:EventTouch)=>{
            this.touch_pos = event.getUILocation()
            this.touch_status = true;
        })
        this.play_hand_cards_layer.off(Node.EventType.TOUCH_MOVE)
        this.play_hand_cards_layer.off(Node.EventType.TOUCH_END)
        this.play_hand_cards_layer.off(Node.EventType.TOUCH_CANCEL)
        this.play_hand_cards_layer.on(Node.EventType.TOUCH_MOVE,this.handCardTouchBegin.bind(this),this)
        this.play_hand_cards_layer.on(Node.EventType.TOUCH_END,this.handCardTouchEnd.bind(this),this)
        this.play_hand_cards_layer.on(Node.EventType.TOUCH_CANCEL,this.handCardTouchEnd.bind(this),this)
        for (let index = this.m_computer_hand_cards.length-1; index >=0; index--) {
            const card =  this.m_computer_hand_cards[index];
            let item:Node = instantiate(this.item_prefab)
            item.parent = this.ai_hand_cards_layer;
            item.active = false;
            item.getComponent(ddz_card).initView(card,this.getCardType(card),index)
        }
        this.start_ai_hand_card_action()
        this.showChuPaiStatus()
        this.predict();
        gameManager.loadPlayMusicByCategoryId(this.categoryid,()=>{
            gameManager.playGamePlayMusicByCategoryId(this.categoryid,true);
        })
    }
    start_play_hand_card_action(){
        this.scheduleOnce(()=>{
            for (let index = 0; index < this.play_hand_cards_layer.children.length; index++) {
                const item = this.play_hand_cards_layer.children[index];
                let time = index*50
                setTimeout(() => {
                    item.active = true;
                }, time);
            }
        },0.2)
    }
    start_ai_hand_card_action(){
        this.scheduleOnce(()=>{
            for (let index = 0; index < this.ai_hand_cards_layer.children.length; index++) {
                const item = this.ai_hand_cards_layer.children[index];
                let time = index*50
                setTimeout(() => {
                    item.active = true;
                }, time);
            }
        },0.2)

    }
    predict(call_back=null){
        this.legalActions = []
        this.legalActions = ddz_ai.instance._get_legal_card_play_actions(this.m_play_hand_cards,this.ai_move);
        // console.log("this.legalActions",this.legalActions)
        if(call_back!=null){
            call_back()
        }
    }

    checkCardCanOut():boolean{
        this.getAllMoveCards();
        let isCanOut = false;
        console.log("玩家当前想出的牌",this.play_move)
        console.log("判定玩家可以出的牌",this.legalActions)
        // let play_move_str = JSON.stringify(this.play_move).toString()
        for (let index = 0; index < this.legalActions.length; index++) {
            const actions = this.legalActions[index];
            if(actions.length>0){
                if(tools.isEqualArray(this.play_move,actions)){
                    return true;
                }
                if(!Array.isArray(actions[0])){
                    if(tools.isEqualArray(this.play_move,actions)){
                        isCanOut = true;
                        return true;
                    }
                }else{
                    for (let i = 0; i < actions.length; i++) {
                        let cards:any = actions[i];
                        if(!Array.isArray(cards)){
                            cards = [cards]
                        }
                        if(tools.isEqualArray(this.play_move,cards)){
                            isCanOut = true;
                            return true;
                        }
                     
                    }
                }
          
            }
        }
        return isCanOut;
    }

    getAllMoveCards(){
        this.play_move = []
        for (let index = 0; index < this.play_hand_cards_layer.children.length; index++) {
            const element = this.play_hand_cards_layer.children[index];
            if(element.getComponent(ddz_card).IsOutCard()){
                let card = element.getComponent(ddz_card).getCard()
                this.play_move.push(card);
            }
        }
        return this.play_move
    }

    backOut(){
        for (let index = 0; index < this.play_hand_cards_layer.children.length; index++) {
            const element = this.play_hand_cards_layer.children[index];
            if(element.getComponent(ddz_card).IsOutCard()){
                element.getComponent(ddz_card).moveUp()
            }
        }
    }
    
    outCards(){
        let list = [];
        let ai_continue = true;
        for (let index = 0; index < this.play_hand_cards_layer.children.length; index++) {
            const element = this.play_hand_cards_layer.children[index];
            if(element.getComponent(ddz_card).IsOutCard()){
                list.push(element)
            }
        }
        if(list.length>0){
            this.ai_out_cards_layer.removeAllChildren()
            this.play_out_cards_layer.removeAllChildren()
            for (let index = 0; index < list.length; index++) {
                const element:Node = list[index];
                let card = element.getComponent(ddz_card).getCard()
                let type = element.getComponent(ddz_card).getType()
                let item:Node = instantiate(this.item_prefab)
                item.parent = this.play_out_cards_layer;
                item.getComponent(ddz_card).initView(card,type,index)
                element.removeFromParent()
            }
            this.updatePlayHandCards()
            list=[]
        }

        if(this.play_hand_cards_layer.children.length<=0){
            console.log("胜利！")
            this.hideBtns()
            this.showWin();
            ai_continue = false;
        }
        return ai_continue

    }
    updateAiHandCards(){
        this.m_computer_hand_cards = []
        let temp = []
        for (let index = 0; index < this.ai_hand_cards_layer.children.length; index++) {
            const element = this.ai_hand_cards_layer.children[index];
            temp.push(element.getComponent(ddz_card).getCard())
        }
        temp.sort((a,b)=>{return parseInt(a)-parseInt(b)})
        this.m_computer_hand_cards = temp;
    }
    updatePlayHandCards(){
        this.m_play_hand_cards = []
        let temp = []
        for (let index = 0; index < this.play_hand_cards_layer.children.length; index++) {
            const element = this.play_hand_cards_layer.children[index];
            temp.push(element.getComponent(ddz_card).getCard())
        }
        temp.sort((a,b)=>{return parseInt(a)-parseInt(b)})
        this.m_play_hand_cards = temp;
    }

    onEventTouch(event:EventTouch){
        let isLeft = false;
        let offsetY = this.touch_pos.y-event.getUILocation().y
        if(offsetY>=1){
            console.log("左边")
            isLeft = true;
            this.first_right_pos = Vec2.ZERO;
        }else if(offsetY<=-1){
            isLeft = false;
            console.log("右边")
            this.first_left_pos = Vec2.ZERO;
        }else{
            return;
        }
        this.is_start_move = true;
        if(isLeft){
            if(this.first_left_pos===Vec2.ZERO){
                this.first_left_pos = this.touch_pos;
            }
        }else{
            if(this.first_right_pos===Vec2.ZERO){
                this.first_right_pos = this.touch_pos;
            }
        }
        this.touch_pos = event.getUILocation()
        for (let index = 0; index < this.play_hand_cards_layer.children.length; index++) {
            const element:Node = this.play_hand_cards_layer.children[index];
            let v3 = element.position;
            let start_pos = new Vec3()
            this.play_hand_cards_layer.getComponent(UITransform).convertToWorldSpaceAR(v3,start_pos)
            let width =  element.getComponent(UITransform).contentSize.width
            if(isLeft){
                let offset =  this.touch_pos.y - this.first_left_pos.y;
                if((this.first_left_pos.y+offset-width/2)<=start_pos.y&&start_pos.y<=this.first_left_pos.y){
                    element.getComponent(ddz_card).onSelect()
                }else{
                    element.getComponent(ddz_card).unSelect()
                }
            }else{
                let offset =  this.touch_pos.y - this.first_right_pos.y;
                if((this.first_right_pos.y+offset+width/2)>=start_pos.y&&start_pos.y+width>=this.first_right_pos.y){
                    element.getComponent(ddz_card).onSelect()
                }else{
                    element.getComponent(ddz_card).unSelect()
                }
            }
        }
    }
    handCardTouchBegin(event:EventTouch){
        if(this.touch_status){
           this.onEventTouch(event)
        }
    }

    getTouchBeginCard(event:EventTouch):ddz_card{
        let pos = event.getUILocation();
        let tempArray:ddz_card[] = []
        for (let index = 0; index < this.play_hand_cards_layer.children.length; index++) {
            const element:Node = this.play_hand_cards_layer.children[index];
            let v3 = element.position;
            let start_pos = new Vec3()
            this.play_hand_cards_layer.getComponent(UITransform).convertToWorldSpaceAR(v3,start_pos)
            let width =  element.getComponent(UITransform).contentSize.width
            if(pos.y>=start_pos.y-width&&pos.y<start_pos.y+width){
                tempArray.push(element.getComponent(ddz_card))
            }
        }
        tempArray  = tempArray.sort((a, b) => {
            return  a.getIndex()-b.getIndex();
        });
        return tempArray.length<=0?null:tempArray[0];
    }
    handCardTouchEnd(event:EventTouch){
        if(this.is_start_move){
            for (let index = 0; index < this.play_hand_cards_layer.children.length; index++) {
                const element:Node = this.play_hand_cards_layer.children[index];
                if(element.getComponent(ddz_card).IsSelectStatus()){
                    element.getComponent(ddz_card).moveUp()
                }else{
                    element.getComponent(ddz_card).unSelect()
                }
            }
        }else{
            let card:ddz_card = this.getTouchBeginCard(event);
            if(card!=null){
                card.onSelect()
                card.moveUp()
            }
        }
        this.is_start_move = false;
        this.touch_status = false;
        this.first_right_pos = Vec2.ZERO;
        this.first_left_pos = Vec2.ZERO;

    }
    getCardType(card:string):string{
        let types =['S','C','H','D']
        let c = config.EnvCard2RealCard[card].toLocaleUpperCase()
        for (let index = 0; index < types.length; index++) {
            let key = types[index]+c
            const element = this.fullDoudizhuDeckIndex[key];
            if(element!=null){
                this.fullDoudizhuDeckIndex[key] = null;
                return types[index]
            }
        }
        console.log("error ,key",card)
        return "";
    }

    Aithink(){
        // # RLCard state
        let  state = {}
        let self = this;
        // state['actions'] = ddz_ai.instance._get_legal_card_play_actions(this.m_computer_hand_cards,this.rival_move)
        state['actions'] = ddz_ai.instance.ai_think(this.m_play_hand_cards,this.m_computer_hand_cards,this.play_move,(data)=>{
            console.log("Aithink",data)
            self.scheduleOnce(()=>{
                self.AiOutCard(data)
            },0.25)
            
        })
        // state['actions'] = state['actions'].map(a => a.map(c => config.EnvCard2RealCard[c]).join(''));
        // for (let i = 0; i < state['actions'].length; i++) {
        //     if (state['actions'][i] === '') {
        //         state['actions'][i] = 'pass';
        //     }
        // }


        // console.log("Aithink",state)
        if(state['actions'].length<=0){
            this.AiOutCard([])
        }
    }

    AiOutCard(actions:[]){
        if(actions.length<=0){
            // tools.showToast("要不起！")
            this.ai_out_ani.getComponent(out_ani).showyaoBuQi()
            this.play_out_cards_layer.removeAllChildren()
            this.ai_out_cards_layer.removeAllChildren()
            this.ai_move = []
            this.predict(()=>{
                this.showChuPaiStatus()
            });
        }else{
            let str_act:any = actions
            this.play_out_cards_layer.removeAllChildren()
            console.log("str_act==",str_act)
            if(!Array.isArray(str_act)){
                str_act = [str_act]
            }
            if(str_act==='pass'||str_act.length<=0){
                // tools.showToast("要不起！")
                // this.ai_move = []
                // this.predict(()=>{
                //     this.showChuPaiStatus()
                // });
            }else{
                let temp_list = []
                this.ai_move = []
                this.ai_out_cards_layer.removeAllChildren()
                for (let index = 0; index < str_act.length; index++) {
                    const card = str_act[index];
                    for (let i = 0; i <  this.ai_hand_cards_layer.children.length; i++) {
                        let item:Node = this.ai_hand_cards_layer.children[i]
                        if(card === item.getComponent(ddz_card).getCard()&&!item.getComponent(ddz_card).isWaitDelete()){
                            item.getComponent(ddz_card).setDeleteStatus()
                            this.ai_move.push(card)
                            temp_list.push(item)
                            break;
                        }
                    } 
                }
                // if(str_act[0].length<1){
                //     const card = tools.getCardMin(actions[actions.length-1]);
                //     console.log("出单牌==",card)
                //     for (let i = 0; i <  this.ai_hand_cards_layer.children.length; i++) {
                //         let item:Node = this.ai_hand_cards_layer.children[i]
                //         if(card === item.getComponent(ddz_card).getCard()&&!item.getComponent(ddz_card).isWaitDelete()){
                //             item.getComponent(ddz_card).setDeleteStatus()
                //             this.ai_move.push(card)
                //             temp_list.push(item)
                //             break;
                //         }
                //     }  
                // }else{
                //     console.log("出多牌==",str_act)
                //     for (let index = 0; index < str_act[0].length; index++) {
                //         const card = str_act[0][index];
                //         for (let i = 0; i <  this.ai_hand_cards_layer.children.length; i++) {
                //             let item:Node = this.ai_hand_cards_layer.children[i]
                //             if(card === item.getComponent(ddz_card).getCard()&&!item.getComponent(ddz_card).isWaitDelete()){
                //                 item.getComponent(ddz_card).setDeleteStatus()
                //                 this.ai_move.push(card)
                //                 temp_list.push(item)
                //                 break;
                //             }
                //         }  
                //     }
                // }
  
                for (let index = 0; index < temp_list.length; index++) {
                    const element = temp_list[index];
                    const card = element.getComponent(ddz_card).getCard();
                    let type = element.getComponent(ddz_card).getType();
                    let item:Node = instantiate(this.item_prefab)
                    item.parent = this.ai_out_cards_layer;
                    item.getComponent(ddz_card).initView(card,type,index)
                    element.removeFromParent()
                }
                this.updateAiHandCards()
                if(this.ai_hand_cards_layer.children.length<=0){
                    console.log("失败！")
                    this.hideBtns()
                    this.showFail()
                }else{
                    this.predict(()=>{
                        this.checkShowBtsStatus()
                    });
                }
            }
        }

    }

    checkShowBtsStatus(){
        console.log("this.legalActions and checkShowBtsStatus",this.legalActions)
        this.showNormalBtnsStatus()
        if(this.legalActions.length<=0){
            this.showYaoBuQiStatus()
        }else if(this.legalActions.length===1&&this.legalActions[0].length===0){
            this.showYaoBuQiStatus()
        }
    }

    showNormalBtnsStatus(){
        let isCan = false;
        for (let index = 0; index < this.legalActions.length; index++) {
            const element = this.legalActions[index];
            if(element.length!=0){
                isCan = true;
                break;
            }
            
        }
        if(isCan){
            this.btn_bu_chu.active  = true;
            this.btn_yao_bu_qi.active = false;
            this.btn_chu_pai.active = true;
        }else{
            this.showYaoBuQiStatus()
        }
        console.log("showNormalBtnsStatus")
    }

    showChuPaiStatus(){
        this.btn_bu_chu.active  = false;
        this.btn_yao_bu_qi.active = false;
        this.btn_chu_pai.active = true;
    }

    showYaoBuQiStatus(){
        this.btn_bu_chu.active  = false;
        this.btn_yao_bu_qi.active = true;
        this.btn_chu_pai.active = false;
    }

    hideBtns(){
        this.btn_bu_chu.active  = false;
        this.btn_yao_bu_qi.active = false;
        this.btn_chu_pai.active = false;
    }
    protected onFailReStartClick(fail_view: fail): void {
        gameManager.playBtnSound()
        if(this.m_data.ads_restart==1){
            SdkUtil.showVideoAd(config.rewardVideoAdUnitId.Resume_AdUnitId,(res)=>{
                if(res.isEnded){
                    this.initView(this.m_data,false);
                    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{
            this.initView(this.m_data,false);
            fail_view.close()
        }
    }

    protected onTipBtnClick(): void {
        if(gameManager.isTestUser()){
            this.tip_layer.active = true;
        }else{
            if(!this.is_look_answer){
                SdkUtil.showVideoAd(config.rewardVideoAdUnitId.Resume_AdUnitId,(res)=>{
                    if(res.isEnded){
                        this.is_look_answer = true;
                        this.tip_layer.active = true;
                    }
                    // 统计-激励视频广告
                    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)
                })
            }else{
                this.tip_layer.active = true;
            }
        }

    }

    protected onFailQuitClick(fail_view: fail): void {
        fail_view.close()
        this.close()
    }
}


