import { _decorator, Node, Label, Sprite, EventTouch, SpriteFrame, Tween, tween, Vec3} from 'cc';
import { BaseExp } from '../core/base/BaseExp';
import { autoBind } from '../extend/AutoBind';
import { userIns } from '../data/UserData';
import { Constants } from '../data/Constants';
import { stateMgr } from '../core/manager/StateManager';
import { uiMgr } from '../core/manager/UIManager';
import { ITEM_TYPE, ResUtil } from '../utils/ResUtil';
import i18n from '../core/i18n/runtime-scripts/LanguageData';
import { Utils } from '../utils/Utils';
import { Game } from '../game/Game';
import PlatformSystem from '../platform/PlatformSystem';
import { audioMgr } from '../core/manager/AudioManager';
const { ccclass, property } = _decorator;

@ccclass('SettleUI')
export class SettleUI extends BaseExp {
    @property({ type: SpriteFrame, tooltip: "成功的图片" })
    public success_sf: SpriteFrame;
    @property({ type: SpriteFrame, tooltip: "失败的图片" })
    public fail_sf: SpriteFrame;
    @property({ type: SpriteFrame, tooltip: "枪默认图片" })
    public gun_def_sf: SpriteFrame;
    @autoBind({ type: Sprite, tooltip: "成功状态的图片" })
    public success_status_icon: Sprite;
    @autoBind({ type: Label, tooltip: "关卡等级" })
    public task_num_lable: Label;
    @autoBind({ type: Sprite, tooltip: "解锁的枪的图片" })
    public gun_icon: Sprite;
    @autoBind({ type: Label, tooltip: "解锁进度" })
    public progress_num_lable: Label;
    @autoBind({ type: Sprite, tooltip: "未解锁的枪的图片" })
    public gun_not_unlock_icon: Sprite;
    @autoBind({ type: Sprite, tooltip: "未解锁的枪的图片" })
    public gun_unlock_icon: Sprite;
    @autoBind({ type: Node, tooltip: "旋转光节点" })
    public rotation_light: Node;

    @autoBind({ type: Node, tooltip: "任务奖励按钮" })
    public task_reward_btn: Node;
    @autoBind({ type: Node, tooltip: "爆头奖励按钮" })
    public headshot_reward_btn: Node;
    @autoBind({ type: Node, tooltip: "下一关按钮" })
    public next_level_btn: Node;
    @autoBind({ type: Node, tooltip: "返回首页" })
    public back_home_btn: Node;
    @autoBind({ type: Node, tooltip: "重新开始" })
    public restart_btn: Node;
    @autoBind({ type: Node, tooltip: "看视频双倍奖励" })
    public video_btn: Node;

    @autoBind({ type: Label, tooltip: "金币文本" })
    public gold_lable: Label;
    @autoBind({ type: Label, tooltip: "钻石文本" })
    public diamond_lable: Label;

    //关卡数据
    private levelData:any = null;
    //传递过后的参数
    private param:any = null;
    /*const param:any = {
        isWin: false,//是否胜利
        headShotNum: Game.I.player.headShotNum,//爆头数量
        cb: ()=>{//回调函数
            
        }
    }*/

    start() {
        this.closeOnBlank = false;
        //注册动态变化值
        stateMgr.registerUI(Constants.gold, this.gold_lable);
        stateMgr.registerUI(Constants.diamond, this.diamond_lable);
    }
    
    public show(...args: any[]){
        Tween.stopAllByTarget(this.rotation_light);
        this.rotation_light.active = false;
        this.hasAnim = true;
        this.param = args[0];
        //加载数据ui
        this.ui();
    }

    /**
     * 加载数据ui
     */
    public ui(){
        //是否连续通关 动态增减游戏难度
        userIns.passNum = this.param.isWin ? (userIns.passNum += 1) : 0;
        //先填充默认图片
        this.gun_not_unlock_icon.spriteFrame = this.gun_def_sf;
        this.gun_unlock_icon.spriteFrame = this.gun_def_sf;
        //成功失败的图片
        this.success_status_icon.spriteFrame = this.param.isWin? this.success_sf : this.fail_sf;
        const data: any = userIns.getCurLevelData();
        this.levelData = data;
        if(data){
            //关卡数
            this.task_num_lable.string = i18n("main.关卡任务 %{value}",{value: data.id});
            //枪的图片 解锁进度
            const unlock:string = data.unlock;
            if(!Utils.isNull(unlock)){
                let [gun_id,progress_str] = unlock.split('|');
                let [cur,max] = progress_str.split('/');
                let gunData:any = userIns.playerGunsTable.find(e=>e.id == gun_id);
                ResUtil.setSpriteFrame(gunData.gun_unlock_icon,this.gun_unlock_icon);
                ResUtil.setSpriteFrame(gunData.gun_not_unlock_icon,this.gun_not_unlock_icon);
                //解锁该武器
                if(cur == max && !Utils.isNull(gun_id)){
                    this.rotation_light.active = true;
                    userIns.unlockGun(gun_id);
                    tween(this.rotation_light)
                        .by(2, { eulerAngles: new Vec3(0, 0, -360) })
                        .repeatForever()
                        .start();
                }
                //解锁进度
                this.progress_num_lable.string =`${cur}/${max}`;
                this.gun_not_unlock_icon.fillRange = 1 - Number(cur)/Number(max);
            }else{
                this.progress_num_lable.string = `looking forward to it`;
            }
        }
        //关卡的奖励
        const reward:string = this.param.isWin ? data.reward_1 : data.reward_2;
        let [g_id_1,num_1] = reward.split('_');
        //任务奖励
        let reward_icon_1: Node = this.task_reward_btn.getChildByName("reward_icon");
        const itemData:any = userIns.itemTable.find(e=>e.id == g_id_1);
        //任务奖励图片
        ResUtil.setSpriteFrame(itemData.icon,reward_icon_1);
        //任务奖励数量
        this.task_reward_btn.getChildByName("reward_num_lable").getComponent(Label).string = `x${num_1}`;
        //看视频双倍奖励
        this.video_btn.active = this.param.isWin;
        if(this.param.isWin){
           const doubleNum: number = Number(num_1) * 2;
           this.video_btn.getChildByName("reward_num_lable").getComponent(Label).string = `x${doubleNum}`;
        }
        //延迟0.5播放奖励动画
        this.scheduleOnce(() => {
            this.flyReward(itemData,Number(num_1),this.task_reward_btn);
        },0.5)
        //是否胜利 胜利的时候有爆头奖励
        const isShowHeadshot:boolean = this.param.isWin && this.param.headShotNum > 0;
        this.headshot_reward_btn.active = isShowHeadshot;
        if(isShowHeadshot){
            //爆头奖励
            let [g_id_2,num_2] = Game.I.player.pData.headshotReward.split('_');
            const t_num_2:number = Number(num_2) * Game.I.player.headShotNum;
            let reward_icon_2: Node = this.headshot_reward_btn.getChildByName("reward_icon");
            const hData:any = userIns.itemTable.find(e=>e.id == g_id_2);
            //爆头任务奖励图片
            ResUtil.setSpriteFrame(hData.icon,reward_icon_2);
            //爆头奖励数量
            this.headshot_reward_btn.getChildByName("reward_num_lable").getComponent(Label).string = `x${t_num_2}`;
            //延迟0.5播放奖励动画
            this.scheduleOnce(() => {
                this.flyReward(hData,Number(t_num_2),this.headshot_reward_btn);
            },0.5)
        }
        //下一关按钮
        this.next_level_btn.active = this.param.isWin;
        //重新开始按钮
        this.restart_btn.active = !this.param.isWin;
    }

    /**
     * 飞钻石和金币的奖励
     * @param data 奖励的数据
     * @param num 数量
     * @param clikTarget 飞动的节点
     */
    public flyReward(data:any,num:number,clikTarget: Node){
        if(num <= 0)return;
        audioMgr.playOneShot(Constants.audios.reward);
        if(data.type == 1){
            userIns.data.gold += num;
            ResUtil.flyAnim(ITEM_TYPE.Coin, clikTarget, this.gold_lable.node, 5, 50,(b) => {});
        }else if(data.type == 2){
            userIns.data.diamond += num;
            ResUtil.flyAnim(ITEM_TYPE.Diamond, clikTarget, this.diamond_lable.node, 5, 50,(b) => {});
        }
    }

    /**
     * 按钮点击事件
     * @param event 事件
     * @param param 参数
     */
    override onBtnClicked(event:EventTouch, param:any) {
        super.onBtnClicked(event, param);
        let btnName = event.target.name;
        if(btnName === 'restart_btn'){//重新开始
            uiMgr.hide(Constants.popUIs.settleUI,this.param.cb);
            Game.I.restart();
        }else if(btnName ==='back_home_btn'){//返回首页
            uiMgr.pop(Constants.mainUIs.main);
        }else if(btnName ==='next_level_btn'){//下一关
            const nLevel = ()=>{
                uiMgr.hide(Constants.popUIs.settleUI,this.param.cb);
                Game.I.nextLevel();
            }
            //下一关判断是否触发广告
            let odds:number = Game.I.player.pData.adforceShow2;
            if(Utils.getRandomFloat(0,1) <= odds){
                PlatformSystem.platform.showRewardVideo((f) => {
                    if(f) {//播放视频成功
                       nLevel();
                    }
                });
            }else{
                nLevel();
            }
        }else if(btnName ==='video_btn'){//看视频双倍奖励
            PlatformSystem.platform.showRewardVideo((f) => {
                if(f) {//播放视频成功
                    this.video_btn.active = false;
                    this.scheduleOnce(() => {
                        //视频再奖励一次
                        const reward:string = this.param.isWin ? this.levelData.reward_1 : this.levelData.reward_2;
                        let [g_id_1,num_1] = reward.split('_');
                        const doubleNum: number = Number(num_1) * 2;
                        const itemData:any = userIns.itemTable.find(e=>e.id == g_id_1);
                        this.flyReward(itemData,doubleNum,this.video_btn);
                    },0.3)
                }
            });
        }
    }
}

