import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import { callNetworkApiGet } from "../script/util";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    addPreloadImage() {
    }

    addPreloadAudio() {
    }

    addPreloadAnima() {

    }

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

    middleLayer = null;
    async onLoadEnd() {
        const middleLayer = cc.find('middleLayer');
        if (middleLayer) {
            this.middleLayer = middleLayer.getComponent('middleLayer');
        }
        await this.initView();
        this.initListener();

        
    }

    treeNode = null;
    treeList = null;
    pid = null;
    nodePath = [];
    async loadData() {
        let res;
        const queryObj = {engine_code: this.middleLayer?this.middleLayer.engineCode:'debug-xxxxxx-xxxxxx'};
        if (this.pid) {
            queryObj['pid'] = this.pid;
        }
        if (this.middleLayer) {
            res = await this.middleLayer.callNetworkApiGet("/v1/preference/list", queryObj);
        } else {
            res = await callNetworkApiGet("/v1/preference/list", queryObj);
        }
        if (res.code !== 200) {
            this.showTips(res.msg);
            return;
        }
        this.treeList = res.rows;
    }

    async initView() {
        await this.loadData();
        this.drawPage();
    }

    initListener() {
    }

    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 key_words = rows.map(item => {
            return {id: item.id};
        });
        cc.sys.localStorage.setItem("wordIds", JSON.stringify(key_words));

        if (this.middleLayer) {
            const res = await this.middleLayer.callNetworkApiPost("/v1/preference/word/save", {user_code: this.middleLayer.engineCode, key_words});
            if (res.code !== 200) {
                this.showTips(res.msg);
                return;
            }
            this.middleLayer.loadOnlineBundle("wordgame_learning");
        } else {
            console.log('jump to bundle: wordgame_learning');
            this.canTouch = true;
        }
    }
}
