import { _decorator, Node, tween, Vec3, Sprite, Asset, ImageAsset, SpriteFrame, Texture2D, Label, EventTouch, UITransform } from 'cc';
import BaseView from '../../../../../../extensions/app/assets/base/BaseView';
import { PageTips } from '../../tips/native/PageTips';
import { app } from 'db://assets/app/app';
import { PageRewardhistory } from '../../rewardhistory/native/PageRewardhistory';
import { Tools } from 'db://assets/res-native/tools/Tools';
import { USERDATA } from 'db://assets/res-native/data/UserData';
const { ccclass, property } = _decorator;
@ccclass('PageMain')
export class PageMain extends BaseView {
    /** 音乐按钮 */
    @property(Node)
    btn_music: Node = null!;
    /** 奖励文字 */
    @property(Label)
    lab_rw: Label = null!;
    /** 奖励 */
    @property(Node)
    reward_bg: Node = null!;
    /** 奖励 */
    @property(Node)
    noreward_bg: Node = null!;
    /** 宝箱item */
    @property(Node)
    box_item: Node = null!;
    /** 宝箱背景 */
    @property(Node)
    bg_box: Node = null!;
    /** 奖励icon */
    @property(Sprite)
    icon_rw: Sprite = null!;
    /** 剩余次数 */
    @property(Label)
    lab_remain: Label = null!;
    /** 奖励灯效 */
    @property(Node)
    rw_light: Node = null!;
    /** 奖励icon */
    @property(Sprite)
    game_logo: Sprite = null!;
    /** 奖励icon */
    @property(Sprite)
    game_logo_bg: Sprite = null!;

    /** 宝箱位置 */
    private _position: { [key: number]: Vec3 } = {
        0: new Vec3(-300, 200, 0),
        1: new Vec3(0, 200, 0),
        2: new Vec3(300, 200, 0),
        3: new Vec3(-300, -200, 0),
        4: new Vec3(0, -200, 0),
        5: new Vec3(300, -200, 0)
    };

    /** 宝箱初始位置 */
    private _startPos = new Vec3(0, 200, 0);

    /** 宝箱是否可以点击 */
    private _canClickBox = false;

    // 初始化的相关逻辑写在这
    onLoad() {}

    // 界面打开时的相关逻辑写在这(onShow可被多次调用-它与onHide不成对)
    onShow(params: any) {
        this.initBox();
        this.lab_remain.string = "" + USERDATA.point.toString()

        // 加载配置的logo
        if (USERDATA.logo && this.game_logo) {
            Tools.remoteLoadSprite(USERDATA.logo, this.game_logo)
        }

        if (USERDATA.logo_back && this.game_logo_bg) {
            Tools.remoteLoadSprite(USERDATA.logo_back, this.game_logo_bg)
        }

        tween(this.rw_light)
            .sequence(
                tween(this.rw_light).to(0.2,{scale:new Vec3(1.1, 1.1, 1)}),
                tween(this.rw_light).to(0.4,{scale:new Vec3(0.9, 0.9, 0)}),
                tween(this.rw_light).to(0.2,{scale:new Vec3(1, 1, 0)})
            )
            .repeatForever()
            .start();
    }

    // 界面关闭时的相关逻辑写在这(已经关闭的界面不会触发onHide)
    onHide(result: undefined) {
        // app.manager.ui.show<PageMain>({name: 'PageMain', onHide:(result) => { 接收到return的数据，并且有类型提示 }})
        return result;
    }


    /** 点击奖励确定 */
    onClickRewardSure(){
        this.reward_bg.active = false
        this.noreward_bg.active = false
        this.initBox()
    }

    /** 点击提示 */
    onClickTips(){
        app.manager.ui.show<PageTips>({name: 'PageTips'})
    }

    /** 点击音乐 */
    oncClickMusic(){
        let music = app.manager.sound.isMusicPlaying
        music ? app.manager.sound.stopMusic() : app.manager.sound.playDefaultMusic()
        this.loadSprite(music ? "main_btn_sounds_off" : "main_btn_sounds_on", this.btn_music)
    }

    /** 点击历史 */
    onClickRwHis(){
        app.manager.ui.show<PageRewardhistory>({name: 'PageRewardhistory'})
    }

    /** 初始化宝箱 */
    initBox(){
        this.bg_box.removeAllChildren();
        for(let i = 0; i < 6; i++){
            let item = Tools.AddChild(this.bg_box, this.box_item, 'item' + i);
            item.setPosition(this._startPos);
            item.active = true;

            tween(item)
            .to(0.5, {position: this._position[i]})
            .call(() => {
                this._canClickBox = true;
            })
            .start();
        }
    }

    /** 点击宝箱 */
    onClickBox(event: EventTouch, customEventData: string) { 
        if (!this._canClickBox) return;
        if (USERDATA.point <= 0) {
            app.manager.ui.showToast(Tools.GetLocalized("no chance"));
            return;
        }

        this._canClickBox = false;

        Tools.httpReq("lottery", {}, (res:any)=>{
            let n = null
            for (let i = 0; i < USERDATA.prize_list.length; i++) {
                const element = USERDATA.prize_list[i];
                if (res.prize_id == element.id){
                    n = i
                    break
                }
            }

            if (n == null){
                app.manager.ui.showToast(Tools.GetLocalized("fail"))
                return
            }

            USERDATA.point--
            this.lab_remain.string = "" + USERDATA.point.toString()
            this.lab_rw.string = Tools.StringLFormat(res.message)
            Tools.remoteLoadSprite(USERDATA.prize_list[n].pic, this.icon_rw)

            const target = event.target as Node;
            const uiTransform = target.getComponent(UITransform);

            // this.sp_flash.parent = target;
            // this.sp_flash.setPosition(new Vec3(0, 0, 0));
            // let comp = this.sp_flash.getComponent('sp.Skeleton') as sp.Skeleton;
            // comp.setAnimation(0, "finger_fx_lv1", false);
            
            if (uiTransform) {
                app.manager.sound.playEffect({name : "effect/open"});
                // 创建宝箱开启动画
                tween(target)
                    .by(0.1, { position: new Vec3(0, 10, 0) })  
                    .by(0.1, { position: new Vec3(0, -20, 0) })  
                    .by(0.1, { position: new Vec3(0, 20, 0) })  
                    .by(0.1, { position: new Vec3(0, -10, 0) })  
                    .to(0.2, { scale: new Vec3(0.8, 0.8, 0.8) })  // 缩小
                    .to(0.4, { scale: new Vec3(1.2, 1.2, 1.2) })  // 放大
                    .to(0.2, { scale: new Vec3(1, 1, 1) })  // 缩小
                    .call(() => {
                        // 动画结束后显示奖励
                        this.scheduleOnce(()=>{
                            Tools.ActChild(target, "box_1", false)
                            Tools.ActChild(target, "box_2", true)
                        }, 0.2)
                        
                        this.scheduleOnce(()=>{
                            this.reward_bg.active = res.prize_type != 3
                            this.noreward_bg.active = res.prize_type == 3
                            app.manager.sound.playEffect({name : "effect/win"});
                        }, 0.8)
                    })
                    .start();
            }
        })
    }

    loadSprite(pic: string, node: Node){
         this.loadRes(pic, Asset, (res: ImageAsset)=>{
            let sp = new SpriteFrame()
            let tex = new Texture2D();
            tex.image = res;
            sp.texture = tex
            node.getComponent(Sprite).spriteFrame = sp
        });
    }
}