import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import { getRoomId, asyncCallNetworkApiGet } from "../../douyin_xiaoxiaole/script/supportToolsDy";
import { asyncDelay } from "../../douyin_xiaoxiaole/script/hw_elimination_letter_util";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    @property(cc.Node)
    rankContent: cc.Node = null;

    @property(cc.Node)
    rankTemplate: cc.Node = null;

    @property(cc.Node)
    rankpage: cc.Node = null;

    addPreloadImage() {
    }

    addPreloadAudio() {
    }

    addPreloadAnima() {

    }

    showTips(tips) {
        console.log(tips);
    }

    roomId = null;
    async onLoadEnd() {
        this.roomId = await getRoomId();
        await this.initView();
    }

    async initView() {

        // 直接显示排行榜
        this.runRankList();
        await this.loadData();
        this.drawPage();
    }

    async runRankList() {
        const startFlag = await this.isGameStart();
        if (startFlag) { 
            this.rankpage.active = true;
            let rows = await asyncCallNetworkApiGet('/api/douyin/v1/rank', {roomid: this.roomId});
            // let rows = await asyncCallNetworkApiGet('/api/douyin/v1/rank', {roomid: "7248252618835790603"});
            rows = JSON.parse(rows);
            this.rankContent.removeAllChildren();
            for (let i = 0; i < rows.length; i++) {
                const row = rows[i];
                const itemClone = cc.instantiate(this.rankTemplate);
                itemClone.parent = this.rankContent;
                itemClone.active = true;
                itemClone.attr({user_id: row.user_id});
                cc.find(`ready`,itemClone).active = false;
                cc.find(`score`,itemClone).active = true;
                cc.find(`score`,itemClone).getComponent(cc.Label).string = row.score;
                const nickObj = JSON.parse(row.nick_name);
                await this.drawNickName(itemClone, nickObj);
            }
        } else {
            this.rankpage.active = false;
        }


        this.scheduleOnce( async () => {
            await this.runRankList();
        }, 1);
    }

    drawNickName(node, nickObj) {
        return new Promise((resolve) => {
            const image = new Image();
            image.onload = () => {
                const texture = new cc.Texture2D();
                texture.initWithElement(image);
                texture.handleLoadedTexture();
                const spriteFrame = new cc.SpriteFrame(texture);
                const coverNode = cc.find(`nickname`, node);
                coverNode.getComponent(cc.Sprite).spriteFrame = spriteFrame;
                const sx = nickObj.width / coverNode.width;
                const sy = nickObj.height / coverNode.height;
                coverNode.scale = Math.max(sx, sy);
                resolve();
            }
            image.src = nickObj.data;
            // image.src = `data:image/png;base64, `;
        });
    }

    async isGameStart() {
        const flag = await asyncCallNetworkApiGet('/api/douyin/v1/isstart', {roomid: this.roomId});
        return flag==='true';
    }

    treeNode = null;
    treeList = null;
    pid = null;
    nodePath = [];
    async loadData() {
        const queryObj = {};
        if (this.pid) {
            queryObj['pid'] = this.pid;
        }
        let res = await asyncCallNetworkApiGet("/api/douyin/v1/list", queryObj);
        res = JSON.parse(res);
        if (res["code"] !== 200) {
            this.showTips(res["msg"]);
            return;
        }
        this.treeList = res["rows"];
    }

    drawPage() {
        if (!this.treeList) {
            return;
        }
        let rows = this.treeList;
        if (!rows || rows.length==0) {
            return;
        }
        const scroolView = cc.find(`Canvas/mainpage`).getComponent(cc.ScrollView);
        const itemsContent = cc.find(`Canvas/mainpage/view/content`);
        itemsContent.active = true;
        const templateItem = cc.find(`item`, itemsContent);
        cc.find(`syllabus_item/sure`, templateItem).active = false;

        templateItem.parent = this.node;
        itemsContent.removeAllChildren();
        templateItem.active = true;

        for (let i = 0; i < rows.length; i++) {
            const row = rows[i];
            const itemClone = cc.instantiate(templateItem);
            itemsContent.addChild(itemClone);

            cc.find(`syllabus_item/label`, itemClone).active = true;
            cc.find(`syllabus_item/label_disable`, itemClone).active = false;
            cc.find(`syllabus_item/label`, itemClone).getComponent(cc.Label).string = row.text_en;
            cc.find(`syllabus_item/label_disable`, itemClone).getComponent(cc.Label).string = row.text_en;
            if (row.has_child) {
                cc.find(`Canvas/check_all`).active = false;
            } else {
                cc.find(`Canvas/check_all`).active = true;
            }
            itemClone.attr({treeNodeId: row.id, treeNodePid: row.pid, hasChild: row.has_child});
        }

        templateItem.active = false; 

        setTimeout(() => {
            scroolView.scrollToTop();
        }, 100);

    }

    checkAll() {
        // 全选按钮
        const node = cc.find(`Canvas/mainpage/view/content`);
        for (let i = 0; i < node.children.length; i++) {
            const nd = node.children[i];
            const sure = cc.find(`syllabus_item/sure`, nd);
            nd.attr({itemChecked: true});
            sure.active = true;
            cc.find(`syllabus_item/label_disable`, nd).active = true;
        }
    }

    canTouch = true;
    async loadTreeNode(evt: cc.Event) {
        const node = evt.currentTarget;
		if (!node.hasChild) {
            // 单个单词
            const sure = cc.find(`syllabus_item/sure`, node);
            sure.active = !sure.active;
            cc.find(`syllabus_item/label_disable`, node).active = sure.active;
            node.attr({itemChecked: sure.active});
			return;
        }
        if (!this.canTouch) {
            return;
        }
        this.canTouch = false;
        this.pid = node.treeNodeId;
        this.nodePath.push(node);
        await this.loadData();
        this.drawPage();

        this.canTouch = true;
    }

    async backTreeNode(evt: cc.Event) {
        if (!this.canTouch) {
            return;
        }
        this.canTouch = false;

        const node = this.nodePath.pop();
        if (node && node.treeNodePid) {
            this.pid = node.treeNodePid;
        } else {
            this.pid = null;
        }
        await this.loadData();
        this.drawPage();

        this.canTouch = true;
    }

    async backTreeRoot(evt: cc.Event) {
        if (!this.canTouch) {
            return;
        }
        this.canTouch = false;

        this.pid = null;
        this.nodePath = [];
        await this.loadData();
        this.drawPage();

        this.canTouch = true;
    }

    async chose() {
        if (!this.canTouch) {
            return;
        }
        this.canTouch = false;

        const rows = cc.find(`Canvas/mainpage/view/content`).children
        .filter(item => item["treeNodePid"] == this.pid && item["itemChecked"] == true)
        .map(item => {
            return {id: item["treeNodeId"], pid: item["treeNodePid"], has_child: item["hasChild"]}
        });
        if(rows.length==0 || rows.some(item => item.has_child)) {
            this.showTips("请选择到单词级别！");
            this.canTouch = true;
            return;
        }
        const keys = rows.map(item => item.id);
        if (keys.length == 0) {
            this.showTips("请选择单词或点击全选！");
            this.canTouch = true;
            return;
        }
        await asyncCallNetworkApiGet("/api/douyin/v1/startgame", {
            roomid: this.roomId,
            data: keys.join(","),
        });
        this.rankpage.active = true;
        this.canTouch = true;
    }

    async restart() {
        if (!this.canTouch) {
            return;
        }
        this.canTouch = false;
        cc.find(`Canvas/loading`).active = true;
        await asyncCallNetworkApiGet("/api/douyin/v1/stopgame", {
            roomid: this.roomId
        });
        await asyncDelay(5);
        await asyncCallNetworkApiGet("/api/douyin/v1/startgame", {
            roomid: this.roomId
        });
        cc.find(`Canvas/loading`).active = false;
        this.canTouch = true;
    }
    async reset() {
        if (!this.canTouch) {
            return;
        }
        this.canTouch = false;
        await asyncCallNetworkApiGet("/api/douyin/v1/stopgame", {
            roomid: this.roomId
        });
        this.rankpage.active = false;

        this.canTouch = true;
    }
}
