import { asyncDelay, onHomeworkFinish } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import EventMgr from '../script/EventMgr'
const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {
    @property({ type: cc.Node, displayName: "翻页容器" })
    pageContainer: cc.Node = null

    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        this._imageResList.push({ url: this.data.pic_url });
        this._imageResList.push({ url: this.data.pic_url_2 });
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
        this._audioResList.push({ url: this.data.audio_url });
    }

    addPreloadAnima() {

    }

    onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
    }

    _cantouch = null;
    initData() {
        // 所有全局变量 默认都是null 
        this._cantouch = true;
    }

    initView() {
        this.initBg();
        this.initPic();
        this.initBtn();
    }

    initBg() {
        const bgNode = cc.find('Canvas/bg');
        bgNode.scale = this._mapScaleMax;
    }

    currentPageIndex = 1;
    captureJs = null;
    currentFlipBeizerNode = null;
    initPic() {
        const frame = cc.find('Canvas/pageFrame')
        const page = cc.find('Canvas/page');
        const canvas = cc.find('Canvas')

        canvas.on("myMoveStart", ()=> {
            this.flipPage(2,1);
        })
        
        canvas.on("myMoveEnd", ()=> {
            if(this.currentFlipBeizerNode) {
                this.currentFlipBeizerNode.destroy();
                this.currentFlipBeizerNode = null;
            }
            
        })

        canvas.on("myTouchMoving", (x)=> {
            let p = ((canvas.width - x) * 180) / canvas.width
            if(this.currentFlipBeizerNode) {
                this.currentFlipBeizerNode.toAngle(p)
            }
        })
        this.initBezierSize();
        this.captureJs = this.pageContainer.getComponent("CaptureNative");
        

    }

    initBezierSize() {
        const deviceWidth = cc.find("Canvas").width;
        const deviceHeight = cc.find("Canvas").height;

        const _page = cc.find('Canvas/page');
        const mask = cc.find('mask', _page);
        const bezier = cc.find('bezier', mask);
        const page = cc.find('page', bezier);

        _page.width = mask.width = bezier.width = page.width = deviceWidth;
        _page.height = mask.height = bezier.height = page.height = deviceHeight;
    }
    setBezierContainer(node) {
        const page = cc.find('Canvas/page');
        
        // 把当前模板节点进行复制 用于创建多个页
        let bezierNode = cc.instantiate(page);

        // 找到书的页
        const pic = cc.find('mask/bezier/page', bezierNode);

        // 此处加载本地图片
        const texture = node.getComponent(cc.Sprite).spriteFrame._texture;

        // 把页码存在节点data中，在接收到翻页消息时判断哪页执行动画 - 在shader/scripts/page.ts中有用到
        // bezierNode.data = {'page': i};

        // 将翻页纹理上面的这一层放上图片、 背面的纹理在page/mask/bezier/page的属性检查器上可以设置
        pic.getComponent('bezier-render').textureList[0] = texture;
        pic.getComponent('bezier-render').textureList[1] = texture;
        pic.getComponent('bezier-render').init();

        const scriptPage = bezierNode.getComponent("page");
        bezierNode.toAngle = (angle) => {
            scriptPage.pageToAngle(angle);
        }
        // 显示
        bezierNode.active = true;
        return bezierNode;
    }

    async flipPage(index, nextIndex) {
        const picNode = await this.captureJs.capture(this.pageContainer);
        const bezierNode = this.setBezierContainer(picNode)
        bezierNode.parent = cc.find("Canvas/BezierContainer");
        const pc = cc.find("Canvas/pageFrame");
        const len = pc.children.length;
        pc.children[index].active = false;
        pc.children[nextIndex].active = true;
        this.currentFlipBeizerNode = bezierNode;
    }

    initBtn() {
        const bottomPart = cc.find('Canvas/bottomPart');
        bottomPart.zIndex = 5; // 提高层级

        bottomPart.x = bottomPart.parent.width / 2;
        bottomPart.y = -bottomPart.parent.height / 2;

        const leftBtnNode = bottomPart.getChildByName('btn_left');
        //节点中添加了button组件 则可以添加click事件监听
        leftBtnNode.on('click', () => {
            if (!this._cantouch) {
                return;
            }
            if (this.currentPageIndex == 0) {
                return;
            }
            // 页码-1 需要让上一页执行从 左-右 动画
            this.currentPageIndex--;
            EventMgr.emit('page_to_right', this.currentPageIndex);
        })

        const rightBtnNode = bottomPart.getChildByName('btn_right');
        //节点中添加了button组件 则可以添加click事件监听
        rightBtnNode.on('click', () => {
            if (!this._cantouch) {
                return;
            }
            if (this.currentPageIndex == 5) {
                return;
            }

            // 当前页执行从 右-左 动画
            EventMgr.emit('page_to_left', this.currentPageIndex)
            this.currentPageIndex++;
        })
    }

    loadNetImg (url) {
		return new Promise((resolve, reject) => {
			cc.loader.load({ url }, (err, texture) => {
				if (err && !texture) return resolve(pg.logger.w('loading loadRes warn-> ' + texture));
				resolve(texture);
			});
		})
	}
}
