

/*
 * @Author: dgflash
 * @Date: 2022-06-02 09:38:48
 * @LastEditors: dgflash
 * @LastEditTime: 2022-09-20 17:18:29
 */
import { EventTouch, Node, Widget, _decorator, sys, view } from "cc";
import { oops } from "../../../../../extensions/oops-plugin-framework/assets/core/Oops";
import { ecs } from "../../../../../extensions/oops-plugin-framework/assets/libs/ecs/ECS";
import { CCComp } from "../../../../../extensions/oops-plugin-framework/assets/module/common/CCComp";
import { UIID } from "../../common/config/GameUIConfig";
import { SingletonModuleComp } from "../../common/SingletonModuleComp";
import { CheckpointLevelItemViewComp } from "./CheckpointLevelItem";
import { AdManager } from "../../../platform/ad/AdManager";
import { ClearCellOperationComp } from "../bll/ClearCellOperation";
import { AddCellOperationComp } from "../bll/AddCellOperation";
import { FullVehicleOperationComp } from "../bll/FullVehicleOperation";


const { ccclass, property } = _decorator;

/** 主界面 */
@ccclass('CheckpointMainViewComp')
@ecs.register('CheckpointMainView', false)
export class CheckpointMainViewComp extends CCComp {

    @property({ type: [CheckpointLevelItemViewComp], visible: true, tooltip: '关卡item' })
    itemArr: Array<CheckpointLevelItemViewComp> = []

    onAdded(args: any) {
        console.log(args);
    }


    onLoad() {
        const btnSkin = this.node.getChildByName("btn_skin")
        const btnAddCell = this.node.getChildByPath("bottom/btn_add_cell")
        const btnClear = this.node.getChildByPath("bottom/btn_clear")
        const btnLeave = this.node.getChildByPath("bottom/btn_leave")
        const btnReward = this.node.getChildByPath("btn_reward")
        const btnSetting = this.node.getChildByPath("btn_setting")
        const levelGroup = this.node.getChildByPath("level")
        // console.log('当前平台',sys.os)
        // if (sys.os === sys.OS.IOS || sys.os === sys.OS.ANDROID) {

           
        // }
        const safeArea = sys.getSafeAreaRect();
        const winSize = view.getVisibleSize();

        // 调整其 Widget 组件来适配刘海
        const widget = levelGroup.getComponent(Widget);
        if (widget) {
            widget.top = winSize.height - safeArea.height - safeArea.y;
            // console.log('偏移高度',widget.top)
            widget.updateAlignment(); // 立即更新 widget 对齐
        }
        btnSkin.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        btnAddCell.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        btnClear.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        btnLeave.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        btnSetting.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        btnReward.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.initLevel()
        if (sys.platform === sys.Platform.BYTEDANCE_MINI_GAME) {
            //判断用户是否支持侧边栏进入功能，有些旧版的抖音没有侧边栏，这种情况就把入口有礼那个按钮给隐藏掉
            tt.checkScene({
                scene: "sidebar",
                success: (res) => {
                    btnReward.active = true
                },
                fail: (res) => {
                    btnReward.active = false
                }
            });

        } else {
            btnReward.active = false
        }
    }

    initLevel() {
        const lv = ecs.getSingleton(SingletonModuleComp).account.AccountModel.lv
        const arr = this.generateRange(lv)
        for (let index = 0; index < arr.length; index++) {
            const element = arr[index];
            this.itemArr[index].lv = element
        }

    }

    generateRange(n: number) {
        // // 计算起始数字
        // let start = n - ((n - 1) % 5);
        // // 创建一个数组，包含从起始数字开始的5个连续数字
        // let range = Array.from({ length: 5 }, (v, i) => start + i);
        // return range;

        // 直接处理1-5的特殊情况
        if (n >= 1 && n <= 5) {
            return [1, 2, 3, 4, 5];
        } else {
            // 计算中间值的位置，确保n位于中间
            let start = n - 2; // 使n成为中间值
            // 确保开始值不小于1
            start = Math.max(start, 1);
            let range = Array.from({ length: 5 }, (v, i) => start + i);
            // 调整以确保数组不超过n的下一个完整5的倍数段
            if (range[4] - range[0] !== 4) { // 如果计算的范围超出了预期（比如遇到边界情况）
                range = range.map((_, i) => n - 2 + i); // 重新计算以保持n在中间
            }
            return range;
        }
    }

    private onTouchEnd(event: EventTouch) {
        // console.log('点到我了',event.target.name)
        const checkpoint = ecs.getSingleton(SingletonModuleComp).account.checkpoint
        switch (event.target.name) {
            case "btn_setting":
                oops.gui.open(UIID.Setting);
                break;
            case "btn_skin":
                oops.gui.open(UIID.Skin);
                break;
            case "btn_clear":
                if (checkpoint.CheckpointModelBase.vm.clearCount >= 3) {
                    oops.gui.toast('该关卡使用次数已满')
                    return
                }
                if (sys.platform === sys.Platform.WECHAT_GAME) {
                    oops.gui.open(UIID.ClearCell);
                } else {
                    AdManager.getInstance().showRewardVideoAd(() => {
                        console.log('成功看完广告')
                        ecs.getSingleton(SingletonModuleComp).account.checkpoint.add(ClearCellOperationComp)
                        ecs.getSingleton(SingletonModuleComp).account.checkpoint.CheckpointModelBase.vm.clearCount += 1
                    })
                }

                break;
            case "btn_add_cell":
                if (checkpoint.CheckpointModelBase.vm.addCellCount >= 3) {
                    oops.gui.toast('该关卡使用次数已满')
                    return
                }
                if (sys.platform === sys.Platform.WECHAT_GAME) {
                    oops.gui.open(UIID.AddCell);
                } else {
                    AdManager.getInstance().showRewardVideoAd(() => {
                        console.log('成功看完广告')
                        ecs.getSingleton(SingletonModuleComp).account.checkpoint.add(AddCellOperationComp)
                        ecs.getSingleton(SingletonModuleComp).account.checkpoint.CheckpointModelBase.vm.addCellCount += 1
                    })
                }

                break;
            case "btn_leave":
                if (checkpoint.CheckpointModelBase.vm.leaveCount >= 3) {
                    oops.gui.toast('该关卡使用次数已满')
                    return
                }
                if (sys.platform === sys.Platform.WECHAT_GAME) {
                    oops.gui.open(UIID.VehicleLeave);
                } else {
                    AdManager.getInstance().showRewardVideoAd(() => {
                        console.log('成功看完广告')
                        ecs.getSingleton(SingletonModuleComp).account.checkpoint.add(FullVehicleOperationComp)
                        ecs.getSingleton(SingletonModuleComp).account.checkpoint.CheckpointModelBase.vm.leaveCount += 1
                    })
                }
                break;
            case "btn_reward":
                oops.gui.open(UIID.SideReward);
                break;
        }

        event.propagationStopped = true;
    }

    reset() {
        this.node.destroy();
    }
}