/*
 * @Author: mojunshou 1637302775@qq.com
 * @Date: 2025-03-21 11:57:43
 * @LastEditors: mojunshou 1637302775@qq.com
 * @LastEditTime: 2025-04-30 12:06:15
 * @Description: 惊喜翻倍弹窗
 */
import { _decorator, instantiate, Label, Node, Prefab, UITransform } from 'cc';
import { oops } from 'db://oops-framework/core/Oops';
import VMParent from 'db://oops-framework/libs/model-view/VMParent';
import { AD_TYPE } from '../common/config/GameDefine';
import { UIID } from '../common/config/GameUIConfig';
import { ADHandler } from '../common/manager/ADHandler';
import { smc } from '../common/SingletonModuleComp';
import { BricsItem } from './BricsItem';
import { DCHandler } from '../common/manager/DCHandler';
import { ServerHandler } from '../common/manager/ServerHandler';
import { GameEvent } from '../common/config/GameEvent';

const { ccclass, property } = _decorator;


interface LevelInfo {
    level: number;
    eventType: string;
    withdraw: boolean;
    position?: number; //位置
    isFirstNotWithdraw?: boolean; //是否第一个没提现
    isAllWithdrawBeforeSecondLast?: boolean; //是否所有提现点都提现
}

/** 显示对象控制 */
@ccclass('DoubleRewardsView')
export class DoubleRewardsView extends VMParent {
    @property([Label])
    lab_list: Label[] = [];
    @property(Node)
    private redBagNode: Node = null!; //红包Node
    @property(Node)
    private iconNode: Node = null!;  //角标Node
    //进度条Node
    @property(Node)
    private progressNode: Node = null!; //进度条Node
    //提示文字Node
    @property(Node)
    private tipsLabelNode: Node = null!; //提示文字Node

    @property(Node)
    private levelListNode: Node = null!; //等级Node

    @property(Prefab)
    private levelItemPrefab: Prefab = null!; //等级Item预制体

    data: any = {
        cd: 0,
        cdMax: 0,
        //总金额
        totalGoldNum: 0,
        //手续费
        handlingCharge: 0,
        //已经有的金额
        curGoldNum: 0,
        //差多少
        gapGoldNum: 0,
        //自动领取时间
        time: 0,
        goldNum: 0, //金砖数量
    }

    private callback: Function = null!;
    private isAuto: boolean = true;


    protected start() {
        DCHandler.inst.reportData(2000400);
        this.setButton();
        this.setData();
        this.setAutoReceive();
        oops.message.dispatchEvent(GameEvent.updateGameState, "paused");
    }


    btn_alittle() {
        oops.gui.remove(UIID.DoubleRewards);
        ServerHandler.inst.getLittleRewards();
        ADHandler.inst.showAd(AD_TYPE.Double_Close);
        DCHandler.inst.reportData(2000401);
        DCHandler.inst.reportData(2000403);
        oops.message.dispatchEvent(GameEvent.updateGameState, "playing");
        smc.game.GameModel.smallAdCount++;
    }


    btn_all() {
        this.isAuto = false;
        smc.game.GameModel.viewType = "double_reward";
        ADHandler.inst.showAd(AD_TYPE.Double_Receive);
        oops.gui.remove(UIID.DoubleRewards);
        oops.message.dispatchEvent(GameEvent.updateGameState, "playing");
        smc.game.GameModel.allAdCount++;
    }


    //设置3秒自动领取
    private setAutoReceive() {
        this.callback = () => {
            this.data.time--;
            if (this.data.time <= 0) {
                //
                if (this.isAuto) {
                    this.isAuto = false;
                    oops.gui.remove(UIID.DoubleRewards);
                    ServerHandler.inst.getLittleRewards();
                    ADHandler.inst.showAd(AD_TYPE.Double_Close);
                    DCHandler.inst.reportData(2000402);
                    DCHandler.inst.reportData(2000403);
                    oops.message.dispatchEvent(GameEvent.updateGameState, "playing");
                    smc.game.GameModel.smallAdCount++;
                }
                if (this.callback) {
                    this.unschedule(this.callback);
                }
            }
        }
        this.schedule(this.callback, 1, this.data.time - 1);
    }


    //算出底部进度条位置

    //设置数据
    private setData() {
        this.data.time = 3;
        this.isAuto = true;
        const info = smc.game.GameModel.doubleRewardInfo;
        if (info) {
            if (info.handingChargeProgress) {
                this.data.totalGoldNum = info.handingChargeProgress.totalMoney;
                this.data.handlingCharge = info.handingChargeProgress.handingCharge;
                this.data.curGoldNum = info.handingChargeProgress.hasNum;
                this.data.gapGoldNum = info.handingChargeProgress.gapNum;
                const showNode = this.node.getChildByPath("bottonNode/tips_node1");
                if (showNode) {
                    showNode.active = true;
                }
                //计算红包的位置，计算角标位置
                //获取进度条长度
                const transform = this.progressNode.getComponent(UITransform);
                if (transform) {
                    const progressWidth = transform.width;
                    //通过长度，然后加上原始位置加长度*进度，就等于红包和icon需要放置的X轴位置
                    const progressX = this.progressNode.position.x;
                    //计算红包的位置
                    const redBagX = progressX + (this.data.curGoldNum / this.data.handlingCharge) * progressWidth;
                    this.redBagNode.setPosition(redBagX, this.redBagNode.position.y);
                    //计算角标的位置
                    this.iconNode.setPosition(redBagX, this.iconNode.position.y);
                    //可以通过除，如果大于0.5就右边一点小于就左边一点，中间就在中间
                    //x轴位置，-60， 0,60；
                    if (this.data.curGoldNum / this.data.handlingCharge > 0.5) {
                        this.tipsLabelNode.setPosition(50, this.tipsLabelNode.position.y);
                    } else if (this.data.curGoldNum / this.data.handlingCharge < 0.5) {
                        this.tipsLabelNode.setPosition(-80, this.tipsLabelNode.position.y);
                    } else {
                        this.tipsLabelNode.setPosition(0, this.tipsLabelNode.position.y);
                    }
                }
            } else {
                //隐藏节点
                const showNode = this.node.getChildByPath("bottonNode/tips_node1");
                if (showNode) {
                    showNode.active = false;
                }
            }
            if (info.levelProgress) {
                //设置进度条
                //克隆，然后添加
                const showNode = this.node.getChildByPath("bottonNode/tips_node2");
                if (showNode) {
                    showNode.active = true;
                }
                this.data.goldNum = info.levelProgress.nextProgress;
                const levelInfoList = this.processLevelInfo(info.levelProgress.levelInfoList);
                this.levelListNode.destroyAllChildren();
                levelInfoList.forEach((item, index) => {
                    const levelItem = instantiate(this.levelItemPrefab);
                    this.levelListNode.addChild(levelItem);
                    if (item.position) {
                        levelItem.setPosition(item.position, 0);
                        //设置数据
                        const script = levelItem.getComponent(BricsItem);
                        if (script) {
                            script.updateData(item);
                        }
                    }
                });

                //计算进度//如果当前关提现了
                //const 最大关
                const maxLevel = levelInfoList[levelInfoList.length - 1].level;
                //const 当前关
                const currentLevel = smc.account.AccountModel.curLevel;
                this.data.curGoldNum = currentLevel;
                this.data.handlingCharge = maxLevel;



            } else {
                //隐藏节点
                const showNode = this.node.getChildByPath("bottonNode/tips_node2");
                if (showNode) {
                    showNode.active = false;
                }

            }
            if (info.showReward) {
                info.showReward.forEach((item, index) => {
                    if (this.lab_list[index]) {
                        this.lab_list[index].string = item.propNum + "";
                    }
                })
            }
        }
    }


    //计算位置
    calculatePositions(levelInfoList: LevelInfo[], totalLength: number = 516): LevelInfo[] {
        if (levelInfoList.length === 0) return [];

        const firstLevel = levelInfoList[0].level;
        const lastLevel = levelInfoList[levelInfoList.length - 1].level;
        const levelRange = lastLevel - firstLevel || 1; // 避免除0

        return levelInfoList.map((item, index) => {
            if (index === 0) {
                item.position = this.progressNode.position.x;
            } else if (index === levelInfoList.length - 1) {
                item.position = this.progressNode.position.x + totalLength;
            } else {
                //这里还有是进度条的初始位置+进度条的长度*当前的进度
                item.position = this.progressNode.position.x + ((item.level - firstLevel) / levelRange) * totalLength;
            }
            return item;
        });
    }



    processLevelInfo(levelInfoList: LevelInfo[], totalLength: number = 516): LevelInfo[] {
        if (levelInfoList.length === 0) return [];

        const firstLevel = levelInfoList[0].level;
        const lastLevel = levelInfoList[levelInfoList.length - 1].level;
        const levelRange = lastLevel - firstLevel || 1;
        let foundFirstNotWithdraw = false;
        //现在要算平均长度，总长度除数组长度
        let singleLength = totalLength / (levelInfoList.length - 1);
        const secondLastIndex = levelInfoList.length - 2;
        const allBeforeSecondLastWithdrawed = levelInfoList
            .slice(0, secondLastIndex)
            .every(item => item.withdraw);

        return levelInfoList.map((item, index) => {
            // 设置 position
            if (index === 0) {
                item.position = this.progressNode.position.x;
            } else if (index === levelInfoList.length - 1) {
                item.position = this.progressNode.position.x + totalLength;
            } else {
                //因为产品和UI说只要算平均长度就好
                // item.position = this.progressNode.position.x + (((item.level - firstLevel) / levelRange) * totalLength);
                item.position = this.progressNode.position.x + index * singleLength;
            }

            // 标记第一个未提现
            if (!foundFirstNotWithdraw && !item.withdraw) {
                item.isFirstNotWithdraw = true;
                foundFirstNotWithdraw = true;
            } else {
                item.isFirstNotWithdraw = false;
            }

            // 标记是否倒数第二个之前的都提现
            item.isAllWithdrawBeforeSecondLast = allBeforeSecondLastWithdrawed;

            return item;
        });
    }
}
