import { _decorator, Button, Color, Component, EventHandler, EventMouse, instantiate, isValid, JsonAsset, Label, math, Node, Prefab, ScrollView, sp, tween, UITransform, Vec3 } from 'cc';
import { getCsymbol, getHistory, getLanguage } from '../../../Loading/scripts/comm';
import { fixNum, getTimezoneOffsetString, getTranslate, hideAllChildren, hideToBottom, isBrahmic, showAllChildren, updateLang } from './Tools';
const { ccclass, property } = _decorator;

enum HISTORY_TYPE {
    TODAY,
    LAST7,
}

@ccclass('History')
export class History extends Component {

    @property(JsonAsset)
    langJson: JsonAsset | null = null;

    /**loading 动画节点*/
    @property(Node)
    loading: Node = null

    @property(Node)
    sel_pnl: Node = null;

    @property(Node)
    pnl_title: Node = null;

    @property(Node)
    item_list: Node = null;

    @property(ScrollView)
    scrollView: ScrollView = null;

    @property(Prefab)
    history_detail: Prefab = null;

    @property(Node)
    node_detail: Node = null;

    todayStart = null
    todayEnd = null
    last7Start = null
    last7End = null
    lastID = null

    holdOn = false
    finish = false

    sel_idx: HISTORY_TYPE = HISTORY_TYPE.TODAY

    DataArr:any[]

    dict = null
    scrollSpeed = 1;

    onLoad(): void {
        this.dict = this.langJson.json[getLanguage()] ?? this.langJson.json["en"];

        this.item_list.active = false
        this.sel_pnl.active = false
        this.loading.active = true
        this.holdOn = false
        this.finish = false

        this.showLoading()

        this.clickTodayList()

        this.node.on("hide_history_loading", this.hideLoading, this);
        this.scrollView.node.on('scrolling', this.onScrolling, this);
        this.scrollView.node.on(Node.EventType.MOUSE_WHEEL, this.onMouseWheel, this);
    }

    protected onDisable(): void {
        this.node.off("hide_history_loading", this.hideLoading, this)
        this.scrollView.node.off('scrolling', this.onScrolling, this);
        this.scrollView.node.off(Node.EventType.MOUSE_WHEEL, this.onMouseWheel, this);
    }


    start() {
        this.updateLang()
    }

    /*更新语言*/
    updateLang() {

        // let labelArr = []
        // getAllLabels(this.node, labelArr);

        // labelArr.forEach((label, i) => {
        //     console.log(`label.node.name: ${label.node.name}`)

        //     const staticTxt = label.node.getComponent(StaticTxt)

        //     let key = staticTxt?.key
        //     if (this.dict[key]) {
        //         label.string = this.dict[key]
        //         // label.updateRenderData()
        //     }
        // })

        updateLang(this.node, this.dict, getLanguage())

        const txt_time = this.pnl_title.getChildByName("txt_time").getComponent(Label)
        txt_time.string = `${this.dict["Time"]} \n ${getTimezoneOffsetString()}`

        const txt_bet = this.pnl_title.getChildByName("txt_bet").getComponent(Label)
        txt_bet.string = `${this.dict["Bet"]}(${getCsymbol()})`

        const txt_profit = this.pnl_title.getChildByName("txt_profit").getComponent(Label)
        txt_profit.string = `${this.dict["Profit"]}(${getCsymbol()})`

    }

    showLoading() {
        this.loading.active = true
        let sk = this.loading.getComponent(sp.Skeleton)
        sk.paused = false
        sk.loop = true
    }

    hideLoading() {
        let sk = this.loading.getComponent(sp.Skeleton)
        sk.paused = true
        sk.loop = false

        this.loading.active = false

    }

    clearContent() {
        this.scrollView.content.destroyAllChildren()
    }


    async getHistoryList(startTime, endTime, lastID) {

        const res = await getHistory({
            GameId: "rp_11001",
            StartTime: startTime,
            EndTime: endTime,
            LastId: lastID
        })

        if (!isValid(this.node, true)) {
            return
        }

        this.unschedule(this.cancelHoldOn)
        this.holdOn = false

        console.log("拿到了历史记录, ", res)

        // 没有历史记录提示
        let isActive = res.length == 0 && this.scrollView.content.children.length == 0
        let Label_NoHistoryTip = this.node.getChildByName("Label_NoHistoryTip")
        Label_NoHistoryTip.active = isActive

        // 已全部加载提示,拿到的数据小于50条就证明那完了
        isActive = res.length < 50 && this.scrollView.content.children.length != 0
        let Label_AllRecordDisplayed = this.scrollView.content.parent.getChildByName("Label_AllRecordDisplayed")
        Label_AllRecordDisplayed.active = isActive

        // 加载更多提示,一次最多能拿50条
        isActive = res.length == 50
        let Label_LoadMore = this.scrollView.content.parent.getChildByName("Label_LoadMore")
        Label_LoadMore.active = isActive


        if (res.length == 0 && this.scrollView.content.children.length > 0) {
            this.finish = true
            Label_AllRecordDisplayed.active = true
            Label_LoadMore.active = false
        }

        this.hideLoading()

        if(res.length == 0){
            // do nothing
            return
        }

        this.loadListData(res)

        return res
    }

    clickTodayList() {
        this.sel_pnl.active = false

        this.finish = false
        this.scrollView.content.destroyAllChildren()

        this.sel_idx = HISTORY_TYPE.TODAY

        const txt_type = this.pnl_title.getChildByName("txt_type").getComponent(Label)
        txt_type.string = getTranslate(this.dict, "Today")

        const now = new Date();
        const zeroDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());

        const todayZeroTimestampSeconds = Math.floor(zeroDate.getTime() / 1000);
        const nowSeconds = Math.floor(now.getTime() / 1000);

        this.todayStart = todayZeroTimestampSeconds
        this.todayEnd = nowSeconds
        this.lastID = null

        this.getHistoryList(todayZeroTimestampSeconds, nowSeconds, this.lastID)
    }

    clickLast7() {

        this.sel_pnl.active = false

        this.finish = false
        this.scrollView.content.destroyAllChildren()

        this.sel_idx = HISTORY_TYPE.LAST7
        const txt_type = this.pnl_title.getChildByName("txt_type").getComponent(Label)
        txt_type.string = this.dict["Last 7 days"]

        const now = new Date();
        // 当前时间减去 6 天（6 * 24 * 60 * 60 * 1000 毫秒）
        const sevenDaysAgo = new Date(now.getTime() - 6 * 24 * 60 * 60 * 1000);
        // 设置时间为 0 点
        // sevenDaysAgo.setHours(0, 0, 0, 0);

        const last7ZeroTimestampSeconds = Math.floor(sevenDaysAgo.getTime() / 1000);

        const nowSeconds = Math.floor(now.getTime() / 1000);

        this.last7Start = last7ZeroTimestampSeconds
        this.last7End = nowSeconds

        this.lastID = null
        this.getHistoryList(last7ZeroTimestampSeconds, nowSeconds, this.lastID)



    }

    loadListData(res) {

        if (this.lastID == null) {
            this.scrollView.content.destroyAllChildren()
            this.DataArr = []
        }

        // 记录一次本次请求中最后一次spin的 roundId
        if (res.length > 0) {
            this.lastID = res[res.length - 1].roundId
        }

        this.scrollView.content.active = true

        res.forEach((data, idx) => {
            const item = instantiate(this.item_list)
            item.active = true

            /*
            balance: 100000001580500
            bet: 10000
            currency: "THB"
            currencySymbol: "฿"
            endTime: 1759040624
            isBuy: false
            mode: 0
            panDetails: [{…}]
            roundId: "68d8d470908480f75bcc34a8"
            startTime: 1759040624
            win: 0
            */

            this.DataArr[data.roundId] = data;


            // name 当标签用
            item.name = data.roundId


            // time
            let time = new Date(data.startTime * 1000)
            const pad = (n: number) => (n < 10 ? '0' + n : String(n));
            let str = `${pad(time.getHours())}:${pad(time.getMinutes())}:${pad(time.getSeconds())} ` + "\n"
                + `${pad(time.getMonth() + 1)}/${pad(time.getDate())}`;
            item.getChildByName("txt_time").getComponent(Label).string = str

            // "transaction"
            item.getChildByName("layout_transaction").getChildByName("txt_transaction").getComponent(Label).string = data.roundId
            item.getChildByName("layout_transaction").getChildByName("sp_icon").active = data.mode == 1

            // Bet
            item.getChildByName("txt_bet").getComponent(Label).string = fixNum(data.bet)

            // profit : 1267000
            item.getChildByName("txt_profit").getComponent(Label).string = fixNum(data.win - data.bet)
            // profit 大于0 高亮白
            if (data.win - data.bet > 0) {
                item.getChildByName("txt_profit").getComponent(Label).color = new Color(0xFF, 0xFF, 0xFF, 255);
            } else {
            }

            let btn = item.getChildByName("btn")
            btn.active = true

            // btn.getComponent(Button).normalColor = "#343440"
            // btn.getComponent(Button).normalColor = "#30303D"


            if (idx % 2 == 0) {
                btn.getComponent(Button).normalColor = new Color(0x34, 0x34, 0x40, 255);
            } else {
                btn.getComponent(Button).normalColor = new Color(0x30, 0x30, 0x3D, 255);
            }



            // // 添加点击事件
            const clickEventHandler = new EventHandler();
            clickEventHandler.target = this.node;
            clickEventHandler.component = 'History';
            clickEventHandler.handler = 'clickItem';
            clickEventHandler.customEventData = data.roundId
            const button = btn.getComponent(Button);
            button.clickEvents.push(clickEventHandler);

            this.scrollView.content.addChild(item)
        });

        this.refreshVisibleZone(this.scrollView.getScrollOffset())
    }

    cancelHoldOn() {
        this.holdOn = false
    }

    onScrolling(scrollView: ScrollView) {

        const offset = this.scrollView.getScrollOffset();
        const maxOffset = this.scrollView.getMaxScrollOffset();

        this.refreshVisibleZone(scrollView.getScrollOffset())

        if (this.finish) {
            return
        }

        if (this.holdOn) {
            // console.log("请求过于频繁")
            return
        }



        if (offset.y >= maxOffset.y - 5) {
            this.holdOn = true
            this.scheduleOnce(this.cancelHoldOn, 5)

            if (this.sel_idx == HISTORY_TYPE.TODAY) {
                this.getHistoryList(this.todayStart, this.todayEnd, this.lastID)
            } else {
                this.getHistoryList(this.last7Start, this.last7End, this.lastID)
            }
        }

    }

    hideSelPnl() {
        this.sel_pnl.active = false
    }

    showSelPnl() {

        const Label_Today = this.sel_pnl.getChildByName("btn_today").getChildByName("Label_Today").getComponent(Label)
        const Label_last7 = this.sel_pnl.getChildByName("btn_last7").getChildByName("Label_last7").getComponent(Label)

        const yellowColor = new Color(0xFF, 0xAE, 0x00)
        const grayColor = new Color(0xAC, 0xAC, 0xB1)

        Label_Today.color = this.sel_idx == HISTORY_TYPE.TODAY ? yellowColor : Color.WHITE
        Label_last7.color = this.sel_idx == HISTORY_TYPE.LAST7 ? yellowColor : Color.WHITE

        this.sel_pnl.active = true
    }

    clickCloseHistory() {
        const destroyFunc = () => { this.node.destroy() }
        hideToBottom(this.node,destroyFunc)
    }



    clickItem(event: Event, roundId: string) {

        console.log("clickItem, roundId = ", roundId)

        const history_detail = instantiate(this.history_detail)
        this.node_detail.addChild(history_detail)

        const comp = history_detail.getComponent("HistoryDetail") as any
        comp.setDetailData(this.DataArr[roundId], getLanguage())

        const self = this
        history_detail.position = new Vec3(1080, 0)
        tween(history_detail).to(0.2, { position: new Vec3(0, 0) })
            .call(() => {
                self.scheduleOnce(() => { comp.entryFinish() })
            })
            .start()

    }


    // 只显示上下相邻的区域，远离view 窗口的content内容都隐藏掉
    refreshVisibleZone(offset: math.Vec2) {

        let height = this.scrollView.node.getChildByName("view").getComponent(UITransform).height

        this.scrollView.content.children.forEach((child,idx) => {
            let pos = child.position

            let res = Math.abs(-offset.y - pos.y)

            if (Math.abs(-offset.y - pos.y) < (height+200)) {
                // child.active = true
                showAllChildren(child)

            } else {
                // child.active = false
                hideAllChildren(child)
            }
        })
    }

    onMouseWheel(event: EventMouse) {

        // console.log("鼠标滚动")

        // deltaY > 0：向下滚；deltaY < 0：向上滚
        const delta = event.getScrollY() * this.scrollSpeed;

        // 获取当前滚动位置
        const offset = this.scrollView.getScrollOffset();

        let vec2 = offset.add2f(0, -delta)
        this.refreshVisibleZone(vec2)
        // 更新纵向滚动
        this.scrollView.scrollToOffset(vec2, 0.1, true);
    }

}

