const { ccclass, property } = cc._decorator;

@ccclass
export default class middleLayer extends cc.Component {

    syllabus_id;
    getData(callBack) {
        const uri = 'syllabus/v1/getdata';
        const data = {
            syllabusid: this.syllabus_id
        };

        console.log("this.syllabus_id: ", this.syllabus_id);
        console.log("this.baseUrl: ", this.baseUrl);

        console.log('data = ' + JSON.stringify(data));
        this.callNetworkApiGet(uri, data, callBack);
    }

    role;
    baseUrl;
    homework_id;
    token;
    onHomeworkFinish(callBack) {
        if (this.role == 'teacher') {
            return;
        }

        const uri = 'app_source/v1/student/homework/finished';
        const data = {
            syllabus_id: this.syllabus_id,
            homework_id: this.homework_id,
            token: this.token,
            score: 0
        };
        console.log('data = ' + JSON.stringify(data));
        this.callNetworkApiPost(uri, data, callBack);

        if (this.homework_id == -1) {
            return;
        }

        const btnBg = cc.find('middleLayer/btnBg');
        btnBg.active = true;
    }

    callNetworkApiGet(uri, data, callBack) {
        let queryStr = '?';
        for (const key in data) {
            if (Object.hasOwnProperty.call(data, key)) {
                const value = data[key];
                queryStr += `${key}=${value}`;
            }
        }
        const xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                const responseData = JSON.parse(xhr.responseText);
                callBack(JSON.parse(responseData.data));
            }
        };
        const url = `${this.baseUrl}${uri}${queryStr}`;
        console.log('url = ' + url);
        xhr.open('GET', url, true);
        xhr.send();
    }

    callNetworkApiPost(uri, data, callBack) {
        const xhr = new XMLHttpRequest();
        const url = `${this.baseUrl}${uri}`;
        xhr.open("POST", url, true);
        xhr.setRequestHeader('content-type', 'application/json');
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4) {
                callBack(JSON.parse(xhr.responseText));
            }
        }
        xhr.send(JSON.stringify(data));
    }

    start() {
        this.node.zIndex = 9999;
        this.showWaitingLetters();
        cc.game.addPersistRootNode(this.node);
        this.initListener();
        const jsonStr = this.callNativeFunction({ name: 'loadScene', value: '' });
        const {
            sceneName,
            version,
            bondleUrl,
            token,
            baseUrl,
            homework_id,
            syllabus_id,
            role
        } = JSON.parse(jsonStr);

        this.baseUrl = baseUrl;
        this.token = token;
        this.homework_id = homework_id;
        this.syllabus_id = syllabus_id;
        this.role = role;

        cc.assetManager.loadBundle(bondleUrl, { version: version }, (err, bundle) => {
            if (err) {
                return console.error(err);
            }
            bundle.loadScene(sceneName, (err, scene) => {
                this.hideWaitingLetters();
                cc.director.runScene(scene);
            });
        });
    }

    initListener() {
        const exitBtn = this.node.getChildByName('ExitBtn');
        exitBtn.on('click', () => {
            const sprite = exitBtn.getChildByName('sprite');
            cc.tween(sprite)
                .to(0.1, { scaleX: 0.9, scaleY: 1.1 })
                .to(0.1, { scaleX: 1.1, scaleY: 0.9 })
                .to(0.1, { scaleX: 1, scaleY: 1 })
                .call(() => {
                    cc.game.removePersistRootNode(this.node);
                    cc.director.loadScene("emptyScene", () => {
                        this.callNativeFunction({ name: 'exit', value: '' });
                    });
                })
                .start();
        });

        const btnLast = cc.find('middleLayer/btnBg/btnLast');
        btnLast['canClick'] = true;
        btnLast.on('click', () => {
            if (!btnLast['canClick']) {
                return;
            }
            btnLast['canClick'] = false;
            cc.tween(btnLast)
                .to(0.1, { scaleX: 0.9, scaleY: 1.1 })
                .to(0.1, { scaleX: 1.1, scaleY: 0.9 })
                .to(0.1, { scaleX: 1, scaleY: 1 })
                .call(() => {
                    btnLast['canClick'] = true;
                    const paramStr = JSON.stringify({});
                    if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
                        return jsb.reflection.callStaticMethod('CocosMng', 'previousPage:', paramStr);
                    } else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
                        return jsb.reflection.callStaticMethod('com/iplayabc/cocos/AppActivity', 'previousPage', '(Ljava/lang/String;)Ljava/lang/String;', paramStr);
                    } else {
                        console.error('非源生环境');
                    }
                })
                .start();
        });

        const btnNext = cc.find('middleLayer/btnBg/btnNext');
        btnNext['canClick'] = true;
        btnNext.on('click', () => {
            if (!btnNext['canClick']) {
                return;
            }
            btnNext['canClick'] = false;
            cc.tween(btnNext)
                .to(0.1, { scaleX: 0.9, scaleY: 1.1 })
                .to(0.1, { scaleX: 1.1, scaleY: 0.9 })
                .to(0.1, { scaleX: 1, scaleY: 1 })
                .call(() => {
                    btnNext['canClick'] = true;
                    const paramStr = JSON.stringify({});
                    if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
                        return jsb.reflection.callStaticMethod('CocosMng', 'nextPage:', paramStr);
                    } else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
                        return jsb.reflection.callStaticMethod('com/iplayabc/cocos/AppActivity', 'nextPage', '(Ljava/lang/String;)Ljava/lang/String;', paramStr);
                    } else {
                        console.error('非源生环境');
                    }
                })
                .start();
        });
    }

    callNativeFunction(param) {
        const paramStr = JSON.stringify(param);
        if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
            return jsb.reflection.callStaticMethod('CocosMng', 'cocosWithNativeProtocol:', paramStr);
        } else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
            return jsb.reflection.callStaticMethod('com/iplayabc/cocos/AppActivity', 'cocosWithNativeProtocol', '(Ljava/lang/String;)Ljava/lang/String;', paramStr);
        } else {
            throw ('非源生环境');
        }
    }

    showWaitingLetters() {
        const colorList = this.getRainbowColorList();
        const layout = cc.find('middleLayer/layout');
        layout.active = true;
        const str = 'Now Loading...';
        str.split('').forEach((word, idx) => {
            const node = new cc.Node();
            const label = node.addComponent(cc.Label);
            label.string = word;
            node.parent = layout;
            node.color = colorList[idx];
            cc.tween(node)
                .delay(idx / 4)
                .by(0.3, { y: 50 }, { easing: 'sineOut' })
                .by(0.3, { y: -50 }, { easing: 'sineIn' })
                .delay((str.length - idx) / 4)
                .union()
                .repeatForever()
                .start();
        });
        const totalWidth = layout.children.reduce((width, node, idx) => {
            return width + node.width;
        }, 0);
        layout.width = totalWidth;
    }

    hideWaitingLetters() {
        const layout = cc.find('middleLayer/layout');
        layout.active = false;
    }


    logList = null;
    showLog(str) {
        if (!this.logList) {
            this.logList = [];
        }
        this.logList.push(str);
        console.log(str);

        if (this.logList.length == 1) {
            this.showOneLog();
        }
    }
    showOneLog() {
        const str = this.logList[0];
        if (str === undefined) {
            return;
        }
        const node = new cc.Node();
        node.anchorX = 0.5;
        const label = node.addComponent(cc.RichText);
        label.string = `<outline color=black width=3>${str}</outline>`;
        label.maxWidth = this.node.width / 2;
        node.x = this.node.width / 4;
        node.y = -this.node.height / 2;
        node.parent = this.node;
        cc.tween(node)
            .to(5, { y: this.node.height })
            .removeSelf()
            .start();
        setTimeout(() => {
            this.logList.shift();
            this.showOneLog();
        }, 1000);
    }

    getRainbowColorList() {
        return [
            cc.color(255, 0, 0),
            cc.color(255, 128, 0),
            cc.color(255, 255, 0),

            cc.color(255, 255, 0),

            cc.color(128, 255, 0),
            cc.color(0, 255, 0),
            cc.color(0, 255, 128),
            cc.color(0, 255, 255),
            cc.color(0, 128, 255),
            cc.color(0, 0, 255),
            cc.color(128, 0, 255),

            cc.color(255, 0, 255),
            cc.color(255, 0, 128),
            cc.color(255, 0, 0),
        ];
    }
}
