/*
 * @Author: mojunshou 1637302775@qq.com
 * @Date: 2025-03-20 17:00:12
 * @LastEditors: mojunshou 1637302775@qq.com
 * @LastEditTime: 2025-04-29 16:48:54
 * @Description: 微信提现页面
 */
import { _decorator, ImageAsset, Label, Node, RichText, Size, Sprite, SpriteFrame, Texture2D, tween, UITransform, Vec3 } from "cc";
import { IRemoteOptions, resLoader } from "db://oops-framework/core/common/loader/ResLoader";
import { oops } from "db://oops-framework/core/Oops";
import { DeviceUtil } from "db://oops-framework/core/utils/DeviceUtil";
import { ecs } from "db://oops-framework/libs/ecs/ECS";
import { CCVMParentComp } from "db://oops-framework/module/common/CCVMParentComp";
import { GameEvent } from "../common/config/GameEvent";
import { UIID } from "../common/config/GameUIConfig";
import { ServerHandler } from "../common/manager/ServerHandler";
import { smc } from "../common/SingletonModuleComp";
import { Format } from "../utils/Format";
import { DCHandler } from "../common/manager/DCHandler";

const { ccclass, property } = _decorator;

/** 视图层对象 */
@ccclass('WechatWithdrawalViewComp')
@ecs.register('WechatWithdrawalView', false)
export class WechatWithdrawalViewComp extends CCVMParentComp {
    data: any = {
        nickName: "",
        money: 0,
        channel: "微信零钱",
        headUrl: "",
        cost: 0,
    }

    str_list: string[] = [
        `再收集<color =#C13935>$m块</color>金砖，<color =#C13935>现金</color>全部自动到账`,
        `微信大额提现需要<color =#C13935>$m元</color>手续费
已赚$y元，仅差<color =#C13935>$n元</color>`


    ]

    @property(RichText)
    private richText: RichText = null!;

    @property(Node)
    private node_notice: Node = null!;
    @property(Label)
    private lab_cost: Label = null!;  //手续费

    @property(RichText)
    private richText_tips: RichText = null!;  //提示



    /** 视图层逻辑代码分离演示 */
    start() {
        // const entity = this.ent as ecs.Entity;         // ecs.Entity 可转为当前模块的具体实体对象
        DCHandler.inst.reportData(3000800);
        this.setButton();
        this.updateNotice();
        this.setData();
        this.updateHead();
    }


    //设置数据
    setData() {
        // const curLevel = smc.account.AccountModel.curLevel;
        let name = smc.account.AccountModel.accountName
        this.data.nickName = Format.truncateCustom(name);
        this.data.headUrl = smc.account.AccountModel.headUrl;
        // this.richText_tips.string = this.str_list[curLevel > 12 ? 1 : 0];
        this.data.money = smc.game.GameModel.wechat_tx_info.money;
        const info = smc.game.GameModel.wechat_tx_info.handingChargeProgress;
        //判断替换
        if (info) {
            this.lab_cost.node.active = true;
            this.richText_tips.string = this.str_list[1];
            this.data.cost = smc.game.GameModel.wechat_tx_info.handingChargeProgress.handingCharge;
            this.richText_tips.string = this.richText_tips.string.replace(/\$m/g, `${info.handingCharge}`);
            this.richText_tips.string = this.richText_tips.string.replace(/\$y/g, `${info.hasNum}`);
            this.richText_tips.string = this.richText_tips.string.replace(/\$n/g, `${info.gapNum}`);
        } else {
            this.lab_cost.node.active = false;
            this.richText_tips.string = this.str_list[0];
            this.richText_tips.string = this.richText_tips.string.replace(/\$m/g, `${smc.game.GameModel.wechat_tx_info.gapGoldNum}`);
        }
    }


    /** 视图对象通过 ecs.Entity.remove(WechatWithdrawalViewComp) 删除组件是触发组件处理自定义释放逻辑 */
    reset() {
        this.node.destroy();
    }

    private btn_auto() {
        //判断能否提现
        const num = smc.game.GameModel.wechat_tx_info.gapGoldNum;
        const info = smc.game.GameModel.wechat_tx_info.handingChargeProgress
        if (num) {
            oops.gui.toast(`还需凑齐${num}金块即可微信打款`);
        } else if (info) {
            //弹出剩余多少手续费
            oops.gui.toast(`还差${info.gapNum}元手续费即可微信打款~`);
        }
    }

    private btn_back() {
        oops.gui.remove(UIID.WechatWithdraw);
        oops.message.dispatchEvent(GameEvent.updateGameState, "playing");
        DCHandler.inst.reportData(3000801);
    }

    private btn_record() {
        if (DeviceUtil.isNative && DeviceUtil.isAndroid) {
            ServerHandler.inst.getRecordList();
            DCHandler.inst.reportData(3000802);
        } else {
            oops.gui.open(UIID.WithdrawRecord);
        }

    }


    //更新滚动公告
    updateNotice() {
        this.node_notice.active = true;
        const num = oops.random.getRandomInt(1, 20)
        //随机1-500的数，有小数保留两位
        const randomNum = Math.random() * 500;
        const numStr = randomNum.toFixed(2);
        let name = this.getRandomChineseName();
        let str = "恭喜$y收集$n金砖，到账<color=#FFF07C>$m元</color>";
        //正则替换str里边的$y，$n，$m
        let str1 = str.replace(/\$y/g, name);
        str1 = str1.replace(/\$n/g, num + "块");
        str1 = str1.replace(/\$m/g, numStr);
        this.richText.string = str1;
        this.node_notice.setPosition(new Vec3(0, -40, 0));
        tween(this.node_notice)
            .to(4, { position: new Vec3(0, 40, 0) })
            .call(() => {
                this.updateNotice();
            })
            .start();
    }





    getRandomChineseName(): string {
        const surnames = ["王", "李", "张", "刘", "陈", "杨", "黄", "赵", "周", "吴", "徐", "孙", "胡", "朱", "高", "林", "何", "郭", "马", "罗"];
        const characters = "的一是了不在人有我他这中大来上国个到说们时用地为子就那和要出也得于里后自以会着对生能而多小学同见天去好她所然家前开";

        // 随机获取姓
        const surname = surnames[Math.floor(Math.random() * surnames.length)];

        // 生成 1 到 3 个字的名字
        const nameLength = Math.floor(Math.random() * 3) + 1;
        let givenName = "";
        for (let i = 0; i < nameLength; i++) {
            givenName += characters[Math.floor(Math.random() * characters.length)];
        }

        return surname + givenName;
    }


    private updateHead() {
        let url = smc.account.AccountModel.headUrl;
        let spriteNode = this.node.getChildByPath("Scene/Center/nameNode/Mask/sp_head");
        if (spriteNode) {
            const uiTransform = spriteNode.getComponent(UITransform);
            uiTransform?.setContentSize(new Size(34, 34))
            let sprite = spriteNode.getComponent(Sprite);
            if (sprite) {
                var opt: IRemoteOptions = { ext: ".png" };
                var onComplete = (err: Error | null, data: ImageAsset) => {
                    const texture = new Texture2D();
                    texture.image = data;
                    const spriteFrame = new SpriteFrame();
                    spriteFrame.texture = texture;
                    sprite.spriteFrame = spriteFrame;
                }
                resLoader.loadRemote<ImageAsset>(url, opt, onComplete);
            }
        }
    }


    formatNumber(num: number) {
        return Math.round(num * 100) / 100;
    }


}