import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import Attributes from "../script/Attributes";
import { callNetworkApiGet, callNetworkApiPost, jumpToCourseWare, buttonOnClick, jumpToBundle, delayCall, exchangeNodePos } from "../script/util";
// @ts-ignore 
import { assign, createMachine, interpret, actions, forwardTo, matchesState } from "../script/xstate";
const { pure, send, raise, sendParent } = actions;


const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

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

    @property(cc.Node)
    UnitView: cc.Node = null;
    @property(cc.PageView)
    UnitViewPager: cc.PageView = null;
    @property(cc.AudioClip)
    bgMusic1: cc.AudioClip = null;
    @property(cc.AudioClip)
    bgMusic2: cc.AudioClip = null;
    @property(cc.AudioClip)
    bgMusic3: cc.AudioClip = null;
    @property(cc.AudioClip)
    bgMusic4: cc.AudioClip = null;

    tws: any[] = [];
    gameMachineService: any = null;
    LoadingCount: number = 1;
    _mapScaleMin: number = 1;
    _mapScaleMax: number = 1;
    _cocosScale: number = 1;
    ROOT_PID: number = null;
    MACHINE_INITED: boolean = false;
    mute: boolean = true;
    UnitsListNode: cc.Node = null;
    UnitPageViewBgNode: cc.Node = null;
    rootAttrTree: Attributes = null;

    kidInfo: any;


    async onLoadEnd() {
        this.tws = [];
        this.LoadingCount = 0;
        this.initSize();
        cc.debug.setDisplayStats(false);

        const middleLayer = cc.find('middleLayer');
        if (middleLayer) {
            this.kidInfo = await middleLayer.getComponent('middleLayer').getUserInfo();
        }

        this.rootAttrTree = this.getComponent('Attributes');
        this.initBg();
        this.initUnitViewPager();
        await this.createFiniteStateMachines();
        const BackViewButtons = this.rootAttrTree.querySelectorAll('.back-view');
        BackViewButtons.forEach(b => {
            buttonOnClick(b, ()=> {
                jumpToBundle("NJ_MoTianLun");
            });
        });

        this.initialized();
    }
    initialized() {
        if (this.gameMachineService) {
            this.gameMachineService.start();
        }
    }
    initSize() {
        // 注意cc.winSize只有在适配后(修改fitHeight/fitWidth后)才能获取到正确的值,因此使用cc.getFrameSize()来获取初始的屏幕大小
        let screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height
        let design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height
        let f = screen_size >= design_size
        cc.Canvas.instance.fitHeight = f
        cc.Canvas.instance.fitWidth = !f

        const frameSize = cc.view.getFrameSize();
        this._frameSize = frameSize;

        this._designSize = cc.view.getDesignResolutionSize();

        let sx = cc.winSize.width / frameSize.width;
        let sy = cc.winSize.height / frameSize.height;
        this._cocosScale = Math.min(sx, sy);

        sx = frameSize.width / this._designSize.width;
        sy = frameSize.height / this._designSize.height;
        this._mapScaleMin = Math.min(sx, sy) * this._cocosScale;
        this._mapScaleMax = Math.max(sx, sy) * this._cocosScale;
    }
    initUnitViewPager() {
        const pages = this.UnitViewPager.getPages();
        let pIndex = pages.length - 1;
        this.UnitViewPager.scrollToPage(pIndex, 0.001);
        this.UnitViewPager.node.on('scrolling', this.moveUnitViewBackground, this);
        this.UnitView.active = false;
        const attr: Attributes = this.UnitViewPager.getComponent('Attributes');
        this.UnitPageViewBgNode = attr.querySelector('#UnitPageViewBg');
        this.UnitsListNode = attr.querySelector('#UnitsList');
        const lessonButtons = attr.querySelectorAll('.lesson-button');
        lessonButtons.forEach((n) => {
            n.off(cc.Node.EventType.TOUCH_END);
            n.on(cc.Node.EventType.TOUCH_END, function (e) {
                const b = e.currentTarget;
                const lock = cc.find('icon_key', b);
                const syllabusId = b.data_id;
                const folderId = b.data_pid;

                if (!syllabusId) {
                    this.showTips("未解锁 [101]");
                    return;
                }
                if (lock.active) {
                    this.showTips("未解锁");
                    return;
                }

                const middleLayer = cc.find('middleLayer');
                if (middleLayer) {
                    middleLayer.getComponent('middleLayer').setData('NJ_MonkyTree_Son', {
                        folderId,
                        syllabusId,
                    });
                }
                jumpToCourseWare(syllabusId);
            }, this, true)
        });
    }


    drawTextBorder(pname, bg) {
        const colorObj = {
            "level 1": {
                bg_1: "#80bb07",
                bg_2: "#d053dd",
                bg_3: "#e79a00",
                bg_4: "#f64159",
                bg_5: "#3192e3",
                bg_6: "#97c321",
                bg_7: "#d5a103",
                bg_8: "#e44f96",
            },
            "level 2": {
                bg_1: "#00a9b8",
                bg_2: "#d63f8d",
                bg_3: "#228dcb",
                bg_4: "#91c100",
                bg_5: "#f34662",
                bg_6: "#9765c7",
                bg_7: "#00b780",
                bg_8: "#e1ba06",
            },
            "level 3": {
                bg_1: "#f34662",
                bg_2: "#e1ba06",
                bg_3: "#9765c7",
                bg_4: "#fa7b0b",
                bg_5: "#d63f8d",
                bg_6: "#228dcb",
                bg_7: "#00a9b8",
                bg_8: "#91c100",
            }
        };
        return colorObj[pname]?colorObj[pname][bg]:"#80bb07";
    }

    drawLevelItemPic(pname) {

        const _pname = pname.replace(/\s+/g, "");
        const left = cc.find(`Canvas/MainScene/UnitView/UnitPageView/view/units_list/line_left`);
        const right = cc.find(`Canvas/MainScene/UnitView/UnitPageView/view/units_list/line_right`);
        for(let i=1; i<=8; i++) {
            if (i % 2 == 1) {
                const group = cc.find(`unit_group${i}`, left);
                group.children.forEach(item => {
                    if (item.name == `bg_unit${i}` || item.name == `bg_${i}`) {
                        const sf = cc.find(`Canvas/res/${_pname}/${item.name}`).getComponent(cc.Sprite).spriteFrame;
                        item.getComponent(cc.Sprite).spriteFrame = sf;
                    }
                });
            } else {
                const group = cc.find(`unit_group${i}`, right);
                group.children.forEach(item => {
                    if (item.name == `bg_unit${i}` || item.name == `bg_${i}`) {
                        const sf = cc.find(`Canvas/res/${_pname}/${item.name}`).getComponent(cc.Sprite).spriteFrame;
                        item.getComponent(cc.Sprite).spriteFrame = sf;
                    }
                });
            }
        }

    }

    moveUnitViewBackground() {
        //获取滚动视图相对于左上角原点的当前滚动偏移
        let scrollOffset: cc.Vec2 = this.UnitViewPager.getScrollOffset();
        this.UnitsListNode.y = (scrollOffset.y * 8 / 9) + 600 * this._mapScaleMax;
        this.UnitPageViewBgNode.y = (scrollOffset.y * .81) + 600 * this._mapScaleMax;
    }
    initBg() {
        this.rootAttrTree.querySelectorAll('.page-holder').forEach(p => {
            p.opacity = 0;
        })
        const fullPageNode = this.rootAttrTree.querySelectorAll('.full-bg');
        fullPageNode.forEach(n => {
            n.scale = this._mapScaleMax;
        });
    }

    showTips(tips) {
        const middleLayer = cc.find('middleLayer');
        if (!middleLayer) {
            console.log(tips);
            return;
        }
        middleLayer.getComponent('middleLayer').showTips(tips);
    }

    playBgMusic(audio) {
        cc.audioEngine.stopMusic();
        cc.audioEngine.playMusic(audio, true);
    }
    createFiniteStateMachines() {
        return new Promise((resolve) => {
            let pid = 21228; // 本地测试用
            let pname = 'level 1'; // 本地测试用
            const middleLayer = cc.find('middleLayer');
            if(middleLayer) {
                pid = middleLayer.getComponent('middleLayer').getData('NJ_MonkyTree');
                pname = middleLayer.getComponent('middleLayer').getData('NJ_MonkyTree_name');
                if (pname) {
                    pname = pname.toLowerCase().trim();
                }
            }
            // 根据不同级别渲染图片
            this.drawLevelItemPic(pname);

            const operationState = {
                id: 'operation',
                initial: 'UnitView',
                context: {
                    UnitViewData: null,
                    currentDataset: null,
                },
                states: {
                    UnitView: {
                        entry: (ctx, event) => {
                            console.log('entry UnitView stage');
                            this.UnitView.active = true;

                            if (pname == 'level 1') {
                                this.playBgMusic(this.bgMusic2);
                            } else if (pname == 'level 2') {
                                this.playBgMusic(this.bgMusic3);
                            } else if (pname == 'level 3') {
                                this.playBgMusic(this.bgMusic4);
                            }


                            const lessonsBtn = this.rootAttrTree.querySelectorAll('.lesson-button');
                            lessonsBtn.forEach((b, idx) => {
                                const attr: Attributes = b.getComponent('Attributes');
                                const lock = cc.find('icon_key', b);
                                lock.active = true;
                                const titleNode = attr.querySelector('.title');

                                const outline = '#000';
                                const name = "";
                                const richText = titleNode.getComponent(cc.RichText);
                                if ( !richText.fontSizeBase ) {
                                    richText.fontSizeBase = richText.fontSize;
                                }
                                richText.fontSize = richText.fontSizeBase;
                                if (name.length > 14) {
                                    richText.fontSize = richText.fontSizeBase * 0.7;
                                }
                                richText.font = cc.find("Canvas/res/font/BRLNSDB").getComponent(cc.Label).font;
                                
                                titleNode.getComponent(cc.RichText).string = `<outline align=top color=${outline}
                                width=4>${name}</outline>`


                                // const pos = exchangeNodePos(b, titleNode);
                                // titleNode.x = pos.x;
                                // titleNode.y = pos.y;
                                // titleNode.parent = b;


                                // const textPng = this.getSprNode("Game");
                                // titleNode.addChild(textPng);
                                // textPng.y = -titleNode.height;
                                // textPng.active = false;
                                // titleNode.textPng = textPng;
                            });


                            callNetworkApiGet('/api/syllabus/v2/tree', { pid, deep: 1 }, (resp: any) => {
                                resp = JSON.parse(resp);
                                if (resp.msg == 'success') {
                                    let { rows } = resp;
                                    const list = rows.reduce((result, next) => {
                                        const { children } = next;
                                        // has_courseware true  是文件夹
                                        let childrenList = children.filter(r => r.has_courseware)
                                        if (childrenList.length > 3) {
                                            childrenList.length = 3
                                        }
                                        result = [...result, ...childrenList]
                                        return result
                                    }, []);
                                    // rows = rows.filter(r => !r.has_courseware)

                                    lessonsBtn.forEach((b, idx) => {
                                        const attr: Attributes = b.getComponent('Attributes');
                                        const index = attr.attrMap['index'];

                                        const lesson = list[index];
                                        const lock = cc.find('icon_key', b);
                                        // console.log("===liu2===", index);
                                        // if (index == 0) {
                                        //     lock.active = false;
                                        // } else {
                                            lock.active = true;
                                        // }
                                        const titleNode = attr.querySelector('.title');
                                        if (!lesson) {
                                            return;
                                        }
                                        b.attr({ 'data_id': lesson.id });
                                        b.attr({ 'data_pid': lesson.pid });


                                        if (index == 0 || ( this.kidInfo && this.kidInfo.unlock_syllabuses?.includes(lesson.id+"") && (index-0) % 3 === 0)) {
                                            lock.active = false;
                                            const outline = this.drawTextBorder(pname, b.name);

                                            const name = lesson.name;
                                            const richText = titleNode.getComponent(cc.RichText);
                                            if ( !richText.fontSizeBase ) {
                                                richText.fontSizeBase = richText.fontSize;
                                            }
                                            richText.fontSize = richText.fontSizeBase;
                                            if (name.length > 14) {
                                                richText.fontSize = richText.fontSizeBase * 0.7;
                                            }
                                            richText.font = cc.find("Canvas/res/font/BRLNSDB").getComponent(cc.Label).font;

                                            titleNode.getComponent(cc.RichText).string = `<outline align=top color=${outline}
                                            width=4>${name}</outline>`;

                                            const pos = exchangeNodePos(b, titleNode);
                                            titleNode.x = pos.x;
                                            titleNode.y = pos.y;
                                            titleNode.parent = b;

                                            // delayCall(1, () => {

                                            //     console.log('idx: ', idx);
                                            //     console.log("传入按钮名2：", name);

                                            //     titleNode.getComponent(cc.RichText).string = `<outline align=top color=${outline}
                                            //     width=4>${name}</outline>`;
                                            //     console.log("显示按钮名2：", titleNode.getComponent(cc.RichText).string);

                                            // })
                                        }

                                    });
                                    ctx.UnitViewData = list;
                                    ctx.currentDataset = list;
                                }
                                resolve();
                            });

                        },
                        exit: () => {
                            // console.log('exit UnitView stage');
                        },
                        invoke: {
                            src: (ctx, event) => {
                            }
                        },
                    },
                }
            };

            const operationMachine = createMachine(operationState);

            this.gameMachineService = interpret(operationMachine).onTransition((state) => {
                console.log(1, state);
            });

        });

    }
    setStateContextData({ rows, buttonsKey }) {
        const buttons = buttonsKey;
        buttons.forEach((b: any) => {
            b.getComponent(cc.Button).interactable = false;
        });
        rows.forEach((item, idx) => {
            if (!buttons[idx]) {
                return;
            }
            (buttons[idx] as any).getComponent(cc.Button).interactable = true;
            (buttons[idx] as any).getComponent(cc.Button).dataIndex = idx;
            (buttons[idx] as any).getComponent(cc.Button).dataMeta = item;
            const [_, action, index] = (buttons[idx] as any).name.split('@');
            (buttons[idx] as any).off(cc.Node.EventType.TOUCH_START);
            (buttons[idx] as any).on(cc.Node.EventType.TOUCH_START, function () {
                this.gameMachineService.send(action, item)
            }, this, true)
        });
    }

}
