import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import Attributes from "../script/Attributes";
import { callNetworkApiGet, callNetworkApiPost, jumpToCourseWare, buttonOnClick, jumpToBundle, delayCall } 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();
        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)
        });
    }

    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() {

        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();
            }
        }

        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 label =  titleNode.addComponent(cc.Label);
                            label.string = name;
                            label.fontSize = richText.fontSize;
                            label.font = richText.font;

                        });


                        callNetworkApiGet('/api/syllabus/v1/tree', { pid }, (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)
                                console.log('UnitView', list);

                                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 });
                                    // console.log("===liu3===unlock_syllabuses==", this.kidInfo.unlock_syllabuses);
                                    // console.log("===liu3===lesson.id==", lesson.id);
                                    // console.log("===liu3===index==", index);
                                    if (this.kidInfo && this.kidInfo.unlock_syllabuses?.includes(lesson.id+"") && (index-0) % 3 === 0) {
                                        lock.active = false;
                                        const { parent } = b;
                                        const pa = parent.getComponent('Attributes');
                                        const { outline } = pa.attrMap;

                                        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;

                                        console.log('idx: ', idx);
                                        console.log("传入按钮名1：", name);
                                        // titleNode.getComponent(cc.Label).string = `<outline align=top color=${outline}
                                        // width=4>${name}</outline>`;
                                        titleNode.getComponent(cc.Label).string = name;

                                        console.log("显示按钮名1：", titleNode.getComponent(cc.Label).string);


                                        // 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;
                            }
                        });

                    },
                    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)
        });
    }

}
