/**
 * @description 福袋界面类
 * @author kaka
 */

import JsbSystem from "../../../mk/system/JsbSystem";
import { AdFun } from "../../data/AdData";
import { cashProType } from "../../data/module/CashProData";


const { ccclass, property } = cc._decorator;

@ccclass
export default class BlessingBag extends cc.Component {

    @property(cc.Label)
    txtBigNum: cc.Label = null;

    @property(cc.Label)
    txtAddEft: cc.Label = null;

    @property(cc.RichText)
    txtTipAd: cc.RichText = null;

    @property(cc.RichText)
    txtBigDelta: cc.RichText = null;

    @property(cc.RichText)
    txtBigTask: cc.RichText = null;

    @property(cc.RichText)
    txtRemaindAdNum: cc.RichText = null;


    @property(cc.Prefab)
    blassingBagItem: cc.Prefab = null;

    @property(cc.Node)
    itemContent: cc.Node = null;

    @property(cc.Node)
    btnCash: cc.Node = null;

    @property(cc.Node)
    btnAd: cc.Node = null;

    @property(cc.Animation)
    aniBigAdBtn: cc.Animation = null;

    @property(cc.Node)
    adIcon: cc.Node = null;

    @property(cc.Animation)
    aniBtnAd: cc.Animation = null;

    @property(cc.Node)
    rbOpenBtn: cc.Node = null;

    @property(cc.Node)
    nodeRb: cc.Node = null;

    @property(cc.Label)
    txtRbNum: cc.Label = null;

    @property(cc.Node)
    testNode: cc.Node = null;

    @property(cc.EditBox)
    inputBox: cc.EditBox = null;

    /**红包页面类型 1 大额 2 任务*/
    private rbPanelType: number = 0;

    private adrbArray = [];

    private isPlayInitAni = true;

    onLoad() {
        this.testNode.active = gData.gameData.configs.ServerConfig.VideoRedBagEmpty == 1;
    }

    onEnable() {
        this.isPlayAni = false;
        this.isPlayInitAni = true;
        gData.blessingBag.isPlayAniUpdate = false;
        gData.blessingBag.init_videoRbData = true;
    }

    update(dt) {
        this.PlayMoneyAniUpdate(dt);
        if (gData.blessingBag.init_videoRbData) {
            this.UpdateInfo();
        }

        if (gData.blessingBag.init_openRb) {
            this.OpenRbPanel(gData.blessingBag.rbType, gData.blessingBag.rbNum);
        }
    }

    lateUpdate() {
        gData.blessingBag.init_videoRbData = false;
        gData.blessingBag.init_openRb = false;
    }

    UpdateInfo() {
        let data = gData.blessingBag.videoRbData;
        if (!data) {
            return
        }

        this.targetProgress = data.cumulativeAmount;

        this.txtBigDelta.node.active = data.showTask != 1;
        this.txtBigTask.node.active = data.showTask == 1;
        this.txtTipAd.string = data.showTask == 1 ? "提现中..." : "<b>满<color=#FFE00C>" + data.requestAmount + "元</color>可提现</b>";
        this.txtBigDelta.string = "<outline color=#8C1010 width=4><b>每次视频额外奖励<color=#FFE00C>" + data.videoAmountPerTime + "元</color></b></outline>";
        this.txtBigTask.string = "<outline color=#8C1010 width=4>金额已达标，完成<color=#4EB7FF>观看视频</color>任务可到账"
            + "\n观看视频次数：<color=#FFE00C>" + data.taskVideoWatchTime + "/" + data.taskVideoTime + "</color>，连续观看天数：<color=#FFE00C>" + data.taskVideoWatchDay + "/" + data.taskVideoDay + "</color></outline>"

        this.txtRemaindAdNum.string = "<b>今日剩余次数：<color=#B02D29>" + data.videoTime + "</color></b>";
        this.adIcon.active = data.needToWatchTheVideo == 1;

        if (gData.blessingBag.isPlayAniUpdate) {
            if (this.lastNum < data.cumulativeAmount) {
                let world_pos = this.btnCash.parent.convertToWorldSpaceAR(this.btnCash.getPosition());
                mk.fly.PlayCoinAnim(1, 10, this.btnAd.getPosition(), world_pos, () => {
                    this.aniBigAdBtn.setCurrentTime(0);
                    this.aniBigAdBtn.play();
                });
                this.txtAddEft.node.setPosition(cc.v2(0, 380));
                this.txtAddEft.string = "+" + data.videoAmountPerTime + "元";
                this.txtAddEft.node.stopAllActions();
                this.txtAddEft.node.scale = 0;
                this.txtAddEft.node.opacity = 255;
                this.txtAddEft.node.active = true;

                let a0 = cc.delayTime(0.8);
                let a1t = cc.sequence(cc.scaleTo(0.15, 1.2), cc.scaleTo(0.15, 1));
                let a1a = cc.spawn(cc.moveBy(0.3, cc.v2(0, 30)), a1t);
                let a2 = cc.delayTime(0.5);
                let a3 = cc.fadeOut(0.15);
                let a4 = cc.callFunc(() => {
                    //this.txtBigNum.string = data.cumulativeAmount + "元";
                    this.PlayMoneyAni(0.2);
                    this.txtAddEft.node.active = false;
                });
                this.txtAddEft.node.runAction(cc.sequence(a0, a1a, a2, a3, a4));

            } else {
                this.txtBigNum.string = data.cumulativeAmount.toFixed(2) + "元";
                this.lastNum = data.cumulativeAmount;
            }
        } else {
            this.txtBigNum.string = data.cumulativeAmount.toFixed(2) + "元";
            this.lastNum = data.cumulativeAmount;
        }


        if (this.adrbArray.length < 4) {
            this.adrbArray = [];

            for (let i = 0; i < data.redMonies.length; i++) {
                let obj = {
                    data: data.redMonies[i],
                    isPlayAniUpdate: gData.blessingBag.isPlayAniUpdate,
                    isPlayInitAni: this.isPlayInitAni
                }
                this.adrbArray.push(obj);
            }
            this.itemContent.emit('srollview-init', this.adrbArray);
        } else {
            this.adrbArray = [];

            for (let i = 0; i < data.redMonies.length; i++) {
                let obj = {
                    data: data.redMonies[i],
                    isPlayAniUpdate: gData.blessingBag.isPlayAniUpdate,
                    isPlayInitAni: this.isPlayInitAni
                }
                this.adrbArray.push(obj);
            }
            //刷新
            this.itemContent.emit('srollview-update', this.adrbArray);
        }

        this.isPlayInitAni = false;
        gData.blessingBag.isPlayAniUpdate = false;
    }

    private isPlayAni = false;

    targetProgress: number = 0;

    delta: number = 0;
    curValue: number = 0;
    curTime: number = 0;
    totalTime: number = 0;
    lastNum: number = 0;

    PlayMoneyAni(time) {
        this.totalTime = time;
        this.delta = (this.targetProgress - this.lastNum) / time;
        this.curValue = this.lastNum;
        this.curTime = 0;
        console.log("--->Update Time: " + time + " delta: " + this.delta + " curValue: " + this.curValue + " lastNum: " + this.lastNum);
        this.isPlayAni = true;
    }

    PlayMoneyAniUpdate(dt) {
        if (this.isPlayAni) {
            if (this.curTime < this.totalTime) {
                this.curTime += dt;
                this.curValue += this.delta * dt;
                if (this.curValue >= this.targetProgress) {
                    this.isPlayAni = false;
                    this.curValue = this.targetProgress;
                    this.lastNum = this.targetProgress;
                }
                console.log("-->CurValue:" + this.curValue);
            } else {
                this.isPlayAni = false;
                this.curTime = this.totalTime;
                this.curValue = this.targetProgress;
                this.lastNum = this.targetProgress;
            }
            this.txtBigNum.string = this.curValue.toFixed(2) + "元";
        }
    }


    Click_AdProgressBtn() {
        mk.audio.playEffect("button");
        if (!gData.loginData.isAuth) {
            JsbSystem.WxAuth();
            return;
        }
        if (gData.blessingBag.videoRbData.needToWatchTheVideo != 1) {
            //免费加进度
            gData.blessingBag.HttpNoAdProgress();
        } else {
            if (gData.blessingBag.videoRbData.videoTime > 0) {
                mk.ad.watchAd((success: boolean) => {
                    mk.console.log("watchAD:" + success);
                    if (success) {
                        gData.adData.watchVideo(AdFun.bigCash)
                    }
                });
            } else {
                mk.tip.pop('今日观看次数已用完');
            }
        }
        mk.audio.playEffect('button');

        console.log("--->You Click AdProgressBtn  ", gData.blessingBag.videoRbData);
    }

    /**
     * 打开红包页面
     * @param type 打开红包类型 1 大额红包 2 任务红包
     * @param num  红包金额
    */
    OpenRbPanel(type: number, num: number) {
        this.rbPanelType = type;
        this.txtRbNum.string = num + "元";
        this.nodeRb.active = true;
        this.rbOpenBtn.active = true;
    }

    CheckCashRedCode() {
        let data = gData.blessingBag.videoRbData;
        if (data.redMoneyCode.length > 0) {
            for (let i = 0; i < data.redMoneyCode.length; i++) {
                if (data.preLargeAmountCashId == data.redMoneyCode[i].RedMoneyId) {
                    if (data.redMoneyCode[i].RedMoneyCode != "") {
                        gData.redCodeData.openRedCode(data.redMoneyCode[i].VideoCashBig, data.redMoneyCode[i].RedMoneyCode);
                    } else {
                        mk.tip.pop('提现成功');
                    }
                    return;
                }
            }
        }
        mk.tip.pop('请先完成提现任务');
    }

    async Click_CashBtn() {
        console.log("--->You Click CashBtn");
        mk.audio.playEffect("button");

        if (gData.blessingBag.videoRbData.cumulativeAmount >= gData.blessingBag.videoRbData.requestAmount) {
            let response = await gData.blessingBag.HttpCashBig();
            if (response && response.data.code == 1) {
                //弹红包码界面
                this.CheckCashRedCode();
            } else {
                mk.tip.pop('请先完成提现任务');
            }
        } else {
            mk.tip.pop("累计到" + gData.blessingBag.videoRbData.requestAmount + "元才可提现");
        }
    }

    canOpen: boolean = true;
    /**红包界面开按钮*/
    async Click_CashOpenBtn() {
        mk.audio.playEffect("button");
        if (!this.canOpen) return;
        this.canOpen = false;
        if (this.rbPanelType == 1) {
            gData.cashPro.openCashPro(cashProType.blessing_bigCash, gData.blessingBag.bigRbNum)
        } else {
            //弹确认提现界面
            this.rbOpenBtn.active = false;
            this.aniBtnAd.node.active = true;
            this.aniBtnAd.setCurrentTime(0);
            this.aniBtnAd.play();
            setTimeout(() => {
                this.aniBtnAd.stop();
                this.aniBtnAd.node.active = false;
                this.rbOpenBtn.active = true;
                this.nodeRb.active = false;

                gData.cashPro.openCashPro(cashProType.blessing_taskCash, gData.blessingBag.taskRbNum)
                this.canOpen = true;
            }, 1000);
        }
    }


    /** 点击帮助回调 */
    clickHelpCallBack() {
        let des = "1、观看大量视频可以快速增加提现进度。\n\n2、提现进度到100%，可以提现对应档位的红包。\n\n3、余额累计满一定金额，可以申请大额提现。";
        gData.help.des = des;
    }

    Click_InitData() {
        mk.audio.playEffect("button");
        gData.blessingBag.HttpInitAdRbData();
    }

    EditBox_End() {
        console.log("-->Input：", this.inputBox.string);
        gData.blessingBag.adsource_id_value = this.inputBox.string;
    }


    /** 点击关闭 */
    onClickClose() {
        mk.ad.checkShowInterByChance();
    }
}
