import {
    _decorator,
    Node,
    Label,
    Button,
    tween,
    v3,
    easing
} from 'cc';
import Panel from '../../../Module/Panel';
import TaskCenter from '../../TaskCenter';
import { _asyncThrottle, strFormat } from '../../Utils/Utils';
import { sendWebNet, sendWebNetWithToken, WebNetName } from '../../Utils/WebNet/WebNet';
import { CircleItem } from './CircleItem';
import { HandItem } from './HandItem';
import { showToast } from 'db://assets/Module/UIFast';
import store from "../../../store/store";
import { toJS } from "mobx";

const {ccclass, property} = _decorator;


interface Loop {
    loopType: string;
    taskCode: string;
    title: string;
    completedSize: number;
    intervalLimitSize: number;
    isUsed: boolean;
    taskData: any
}

/** 财富圈加成 */
const BUFF = {
    1: 0,
    2: 10,
    3: 20,
    4: 40,
    5: 80
}

@ccclass("ChangeEquipPanel")
export class ChangeEquipPanel extends Panel {
    static bundle: string = "";
    static skin = "ChangeEquipPanel";
    static group = "ChangeEquipPanel";

    /** 当前手势 */
    handType: string = "1";

    /** 左2的套圈索引 */
    leftIndex2: number = 0;
    /** 左1的套圈索引 */
    leftIndex1: number = 0;
    /** 中间的套圈索引 */
    middleIndex: number = 0;
    /** 右1的套圈索引 */
    rightIndex1: number = 0;
    /** 右1的套圈索引 */
    rightIndex2: number = 0;
    /** 套圈数组长度 */
    len: number = 0;
    /** 套圈数据 */
    loopList: Loop[] = [];

    /** 中心套圈节点 */
    @property(Node)
    middleNode: Node = null;
    /** 左1节点 可见 */
    @property(Node)
    leftNode1: Node = null;
    /** 左2节点 不可见 */
    @property(Node)
    leftNode2: Node = null;
    /** 右1节点 可见 */
    @property(Node)
    rightNode1: Node = null;
    /** 右2节点 不可见 */
    @property(Node)
    rightNode2: Node = null;

    /** 套圈盒子 */
    @property(Node)
    CircleBox: Node = null;

    /** 左切换按钮 */
    @property(Node)
    leftIcon: Node = null;
    /** 右切换按钮 */
    @property(Node)
    rightIcon: Node = null;

    /** 置灰按钮 */
    @property(Node)
    mainBtnGrey: Node = null;
    /** 高亮按钮 */
    @property(Node)
    mainBtn: Node = null;
    /** 任务栏 */
    @property(Node)
    taskBox: Node = null;
    /** 加成气泡 */
    @property(Node)
    bubble: Node = null;

    /** 任务去完成 */
    @property(Node)
    taskBtn: Node = null;

    /** 猫猫爪 */
    @property(Node)
    cat: Node = null;
    /** 小龙爪 */
    @property(Node)
    dragon: Node = null;
    /** 幸运手 */
    @property(Node)
    hand: Node = null;

    /** 关闭按钮 */
    @property(Node)
    backBtn: Node = null;

    /** 装备手盒子 */
    @property(Node)
    handBox: Node = null;

    /** 防连点 */
    isClick: boolean = false;

    async start() {
        /** 绑定点击事件 */
        this.leftIcon.on(Button.EventType.CLICK, this.circleRender(1), this);
        this.rightIcon.on(Button.EventType.CLICK, this.circleRender(-1), this);
        this.taskBtn.on(Button.EventType.CLICK, this.doTask, this);
        this.mainBtn.on(Button.EventType.CLICK, this.changeLoop, this);
        this.backBtn.on(Button.EventType.CLICK, this.closePannel, this);

        await this.getEquipInfo();

        this.initCircle();
        this.circleRender()();
        this.taskRender();
        this.bubbleBreathe();

        this.getTaskInfo();
    }

    /** 气泡呼吸 */
    bubbleBreathe() {
        tween(this.bubble)
            .repeatForever(
                tween(this.mainBtn)
                    .to(0.5, {scale: v3(1.1, 1.1, 1.1)}, {easing: easing.smooth})
                    .to(0.5, {scale: v3(0.9, 0.9, 0.9)}, {easing: easing.smooth})
            )
            .start();
    }

    taskInfo = null;

    async getTaskInfo() {
        if (!this.taskInfo) {
            const success = await store.updateTask();
            if (!success) return {};
            this.taskInfo = {};
            store.taskInfo.forEach((v) => {
                this.taskInfo[v.code] = v;
            });
        }

        console.log("taskInfo: ", this.taskInfo)
        return this.taskInfo;
    }

    /** 获取装备信息 */
    async getEquipInfo() {
        const [{success, data}, taskInfo] = await Promise.all([
            sendWebNetWithToken(WebNetName.equip),
            this.getTaskInfo(),
        ]);

        if (!success) return;

        // 从任务列表中匹配装备任务 拿到任务信息
        const equipTaskInfo = data?.taskInfo || [];
        if (equipTaskInfo?.length > 0) {
            equipTaskInfo.map(((item) => {
                if (!item.taskCode) return;
                const task = taskInfo[item.taskCode];
                if (!task) return;
                item.title = task.title
                item.intervalLimitSize = task.intervalLimitSize
                item.completedSize = task.completedSize
                item.taskData = task;
            }));
        }
        this.loopList = equipTaskInfo;
        this.handType = data?.handType || "1";
        this.len = data?.taskInfo?.length || 0;
        this.handInit();
    }

    /** 初始化套圈 */
    initCircle() {
        if (this.len == 0) return;
        const isUsedIndex = this.loopList.findIndex((item) => item?.isUsed == true);
        if (isUsedIndex !== -1) {
            this.middleIndex = isUsedIndex;
            this.leftIndex1 = this.judgeDataIndex(isUsedIndex - 1);
            this.leftIndex2 = this.judgeDataIndex(this.leftIndex1 - 1);
            this.rightIndex1 = this.judgeDataIndex(isUsedIndex + 1);
            this.rightIndex2 = this.judgeDataIndex(this.rightIndex1 + 1);
        } else {
            const middle = Math.floor(this.len / 2);
            this.middleIndex = middle;
            this.leftIndex1 = this.judgeDataIndex(middle - 1);
            this.leftIndex2 = this.judgeDataIndex(this.leftIndex1 - 1);
            this.rightIndex1 = this.judgeDataIndex(middle + 1);
            this.rightIndex2 = this.judgeDataIndex(this.rightIndex1 + 1);
        }
    }

    /** 边界移动判断 */
    judgeIndex(index: number) {
        if (index < 0) {
            return 4;
        }
        if (index >= 5) {
            return 0;
        }
        return index;
    }

    /** 数据判断 */
    judgeDataIndex(index: number) {
        if (index < 0) {
            return this.len - 1;
        }
        if (index >= this.len) {
            return 0;
        }
        return index;
    }

    /** 套圈列表更新 */
    circleRender(move: number = 0) {
        return () => {
            if (this.isClick) return;
            this.isClick = true;
            setTimeout(() => {
                this.isClick = false
            }, 700)
            // console.log("move: ", move, this);
            this.middleIndex = this.judgeDataIndex(this.middleIndex - move);
            if (!!!move) {
                this.middleNode.getComponent(CircleItem).init(2, this.loopList?.[this.middleIndex], this.middleIndex);
                this.leftNode1.getComponent(CircleItem).init(1, this.loopList?.[this.leftIndex1], this.leftIndex1);
                this.leftNode2.getComponent(CircleItem).init(0, this.loopList?.[this.leftIndex2], this.leftIndex2);
                this.rightNode1.getComponent(CircleItem).init(3, this.loopList?.[this.rightIndex1], this.rightIndex1);
                this.rightNode2.getComponent(CircleItem).init(4, this.loopList?.[this.rightIndex2], this.rightIndex2);
            } else {
                // console.log("开滑");
                const itemList = this.CircleBox.children;
                for (let node of itemList) {
                    let nodeIndex = node.getComponent(CircleItem).index;
                    if (nodeIndex === 0 && move === -1) {
                        nodeIndex = this.judgeIndex(nodeIndex + move);
                        let count = 2;
                        let finalIndex = this.middleIndex;
                        while (count > 0) {
                            finalIndex = this.judgeDataIndex(finalIndex + 1);
                            count--;
                        }
                        // console.log(`%c finalIndex: ${finalIndex}`, "color: pink", nodeIndex);
                        node.getComponent(CircleItem).updateItem(nodeIndex, this.loopList?.[finalIndex], finalIndex);
                    } else if (nodeIndex === 4 && move === 1) {
                        nodeIndex = this.judgeIndex(nodeIndex + move);
                        let count = 2;
                        let finalIndex = this.middleIndex;
                        while (count > 0) {
                            finalIndex = this.judgeDataIndex(finalIndex - 1);
                            count--;
                        }
                        node.getComponent(CircleItem).updateItem(nodeIndex, this.loopList?.[finalIndex], finalIndex);
                    } else {
                        nodeIndex = this.judgeIndex(nodeIndex + move);
                        let finalIndex = node.getComponent(CircleItem).dataIndex;
                        finalIndex = this.judgeDataIndex(finalIndex - move)
                        node.getComponent(CircleItem).updateItem(nodeIndex, null, finalIndex);
                    }
                }
            }
            this.taskRender();
        }
    }

    /** 任务栏渲染 */
    taskRender() {
        const data = this.loopList?.[this.middleIndex];
        const {taskData, taskCode, isUsed, title: T = "", completedSize, intervalLimitSize, loopType} = data || {};

        const [title] = T.split("@");

        /** 气泡渲染 */
        if (loopType == "1") {
            this.bubble.active = false;
        } else {
            this.bubble.active = true;
            this.bubble.getChildByName("Content").getComponent(Label).string = `分数提升 ${BUFF?.[loopType] || ""}%`
        }

        console.log(data);
        if (!!isUsed) {
            /** 已装备 */
            this.mainBtnGrey.active = true;
            this.mainBtn.active = false;
            this.taskBox.active = false;
        } else if (!!!isUsed) {
            // loopType 1 青铜没有taskCode 没有这俩字段 直接展示「更换装备」
            if (loopType == '1' || completedSize >= intervalLimitSize) {
                /** 已解锁未装备 */
                this.mainBtnGrey.active = false;
                this.mainBtn.active = true;
                this.taskBox.active = false;
            } else {
                /** 未解锁 */
                this.mainBtnGrey.active = false;
                this.mainBtn.active = false;
                this.taskBox.active = true;
                this.taskBox.getChildByName("Title").getComponent(Label).string = strFormat(title, 22);

                if (taskCode == "bank_2201") {
                    const descObj = taskData.desc ? JSON.parse(taskData.desc) : {};
                    const t = descObj?.progressAmount || 0;
                    this.taskBox.getChildByName("Progress").getComponent(Label).string = `累计已提升金额：${t}元`;
                } else {
                    this.taskBox.getChildByName("Progress").getComponent(Label).string = `完成 ${completedSize}/${intervalLimitSize}`;
                }
            }
        }
    }

    /** 去完成任务 */
    doTask() {
        const data = this.loopList?.[this.middleIndex];
        const {taskCode, loopType} = data || {};
        // 原本的3个任务 不做交互
        if (taskCode.indexOf("login_") >= 0 || taskCode.indexOf("join_") >= 0 || taskCode.indexOf("score_") >= 0) {
            showToast("暂未达标哦，继续努力吧～")
            return
        }
        this.btnEnable(this.taskBtn, false);
        TaskCenter.handleClickTask(data.taskData);
        this.btnEnable(this.taskBtn, true);
    }

    /** 初始化套圈手 */
    async handInit() {
        this.cat.getComponent(HandItem).updateInfo(this.handType == "1", "1", this.node);
        this.dragon.getComponent(HandItem).updateInfo(this.handType == "2", "2", this.node);
        this.hand.getComponent(HandItem).updateInfo(this.handType == "3", "3", this.node);
    }

    /** 更换套圈 */
    changeLoop = _asyncThrottle(async () => {
        const data = this.loopList?.[this.middleIndex];
        const {loopType} = data || {};
        this.btnEnable(this.mainBtn, false);
        const res = await sendWebNetWithToken(WebNetName.changeLoop, {id: loopType});
        if (res?.success) {
            await this.getEquipInfo();
        }
        this.taskRender();
        this.btnEnable(this.mainBtn, true);
    })

    /** 关闭弹窗 */
    closePannel() {
        this.hidePanel();
    }

    update(deltaTime: number) {
    }
}

