import { asyncDelay, exchangeNodePos, getSprNode, onHomeworkFinish, onHomeworkStart, playAudio } from "../script/util_hy14_pipei";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_hy14_pipei";
import Game, { imageZize, ItemJigsaw, OptionJigsaw } from "./Game_hy14_pipei";
import pg from "./pg_hy14_pipei";

const { ccclass, property } = cc._decorator;

@ccclass
export default class PuzzleJigsaw extends MyCocosSceneComponent {

    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();
        this.initListener();
    }
    @property(cc.Node)
    layout_sort: cc.Node = null;



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

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

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


    private initListener() {

        pg.event.on("layer_record_score", (score) => {
        });

        pg.event.on('npc_voice_play_voice_end', () => {

        })
        pg.event.emit('npc_layer_back_init', this.data)


        pg.event.on('layer_ending_touch_replay', () => {
            this.replay();
        })
        pg.event.on('layer_coin_show_coin_end', () => {
            // pg.event.emit('layer_ending_show', { coin: 3 })
            this.sendData(3).then(() => {
                const midd = cc.find('middleLayer');
                if (!midd) return this.log("no middleLayer");
                let middleLayer = midd.getComponent('middleLayer');
                middleLayer.saveGolds(3); // 保存金币数量；num 是获得金币的数量，数字类型；
                middleLayer.goNextPage();  // 跳转到下一页
            })

        })
        pg.event.on("gameOver", () => { this.gameOver() })
        cc.find("ScrollView", this.node).on("scroll-began", this.onScroll, this);
    }

    sendData(score) {
        return new Promise(res => {
            let upData: any = {
                word_count: this.data.word_count || 0,
                sentence_count: this.data.sentence_count || 0,
                zi_count: this.data.zi_count || 0,
                score: score || 0,
            };
            let recordList = pg.hw.getRecord();
            if (recordList && recordList.length > 0) {
                upData.recordList = recordList
            }
            const middleLayer = cc.find('middleLayer').getComponent('middleLayer');
            console.log('upload->' + JSON.stringify(upData))
            middleLayer.onHomeworkFinish(upData, () => {
                res('');
            })
        })
    }
    replay() {
        this.initData();
        this.initView();
    }

    initData() {
        Game.getIns().init(this.data);
        Game.getIns().reset();
        this.cardBgs = [];
        this.isOver = false;
    }
    initView() {

        this.checked = false;
        this.cards = [];
        this.currentCards = [];
        this.cardBgs = [];

        //自动创建卡片
        let itembg = this.layout_sort;
        // let itembg = cc.find("itembg", this.node);
        pg.view.setNetImg(itembg, Game.getIns().image, { w: imageZize.width, h: imageZize.height }, false).then((data: any) => {
            Game.getIns().changepoints(data);
            itembg.width = imageZize.width;
            itembg.height = imageZize.height;
            this.creaetPosPic();
            itembg.x = -itembg.width / 2;
        });
        this.createCrads();
    }

    protected update(dt: number): void {

    }
    private onScroll() {
        this.playLocalAudio("huadong");
    }
    //根据两点获取距离
    private getDistance(p1, p2) {
        let temp = p1.sub(p2);
        let dis = Math.abs(temp.mag());
        return dis;
    }
    private getDistances(p1, p2) {
        //转换世界坐标查看距离
        let ps2 = p2.convertToWorldSpaceAR(cc.v2(0, 0));
        let ps1 = p1.convertToWorldSpaceAR(cc.v2(0, 0));
        let temp = ps1.sub(ps2);
        let dis = Math.abs(temp.mag());
        return dis;
    }
    private rectCollect(A, B) {
        let AP = A.convertToWorldSpaceAR(cc.v2(0, 0));
        let BP = B.convertToWorldSpaceAR(cc.v2(0, 0));
        if (Math.abs(AP.x - BP.x) < A.width + B.width
            && Math.abs(AP.y - BP.y) < A.height + B.height) return true;
        return false;
    }

    private currentCards: cc.Node[];
    //开始游戏
    startGame() {
        Game.getIns().reset();
        this.nextPage();
    }
    nextPage() {

    }

    //创建卡片
    private cards: cc.Node[];
    private cardBgs: cc.Node[];
    createCrads() {
        this.layout_sort.removeAllChildren();



        this.layout_op.removeAllChildren();
        let op = Game.getIns().opdata;
        let item = this.item_op;
        // let item = cc.instantiate(this.item_op);
        item.active = true;
        // item.parent = this.layout_op;
        op.forEach((dt, idx) => {
            // if (idx % 8 == 0) {
            // }
            // let id = idx % 8;
            let ch = item.children[idx];
            // this.log(id)
            if (!ch) return;
            ch.active = true;
            let desc = cc.find("desc", ch);
            let img = cc.find("img", ch);
            let node;
            if (dt.pic_url && dt.pic_url != "") {
                pg.view.setNetImg(img, dt.pic_url, { w: 200, h: 150 });
                desc.getComponent(cc.Label).string = "";
                img.active = true;
                desc.active = false;
                node = img;
            } else {
                desc.getComponent(cc.Label).string = dt.text;
                img.active = false;
                desc.active = true;
                node = desc;
            }
            let data: any = {};
            data.text = dt.text;
            data.audio = dt.audio_url || "";
            data.index = dt.index;
            data.parent = ch;
            data.x = node.x;
            data.y = node.y;
            node.data = data;


            node.on(cc.Node.EventType.TOUCH_START, this.onItemTouchStart, this);
            node.on(cc.Node.EventType.TOUCH_MOVE, this.onItemTouchMove, this);
            node.on(cc.Node.EventType.TOUCH_END, this.onItemTouchEnd, this);
            node.on(cc.Node.EventType.TOUCH_CANCEL, this.onItemTouchCancel, this);
            ch.getComponent(cc.Layout).enabled = false;
            let stone1 = cc.find("stone1", ch);
            this.stSction(stone1);
        })
        let size = cc.view.getCanvasSize();
        let scale = (size.width / size.height) / (1920 / 1080);
        let oplen = scale > 1.2 ? 5 : 4;
        if (op.length > oplen) {
            cc.find("ScrollView", this.node).getComponent(cc.ScrollView).enabled = false;
            this.layout_op.getComponent(cc.Layout).enabled = true;
            let x = 0;
            if (op.length > 12) x = 7680;
            else if (op.length > 8) x = 5760;
            else if (op.length > oplen) x = 3840;
            let bottom = cc.find("bottom", this.node);
            cc.tween(bottom).repeatForever(cc.tween().by(20, { x: -x })
                .call(() => { bottom.x = -960 * scale; }))
                .start();
        }
    }
    private creaetPosPic() {
        let pos = Game.getIns().pointsArr;
        pos.forEach((li, idx) => {
            let item = cc.instantiate(this.item);
            this.layout_sort.addChild(item);
            item.x = li.x;
            item.y = li.y;
            item.active = true;
            // let desc = cc.find("desc", item);
            // desc.getComponent(cc.Label).string = li.text;
            this.cardBgs.push(item);
            let data = li;
            item.data = data;
            item.width = li.width;
            item.height = li.height;
        })
    }

    private stSction(node) {
        cc.tween(node).repeatForever(cc.tween().by(1, { y: 10 }).by(1, { y: -10 })).start();

    }
    private setTouchPos(e) {
        let location = e.getLocation();
        let size = cc.view.getCanvasSize();
        let scale = (size.width / size.height) / (1920 / 1080);
        if (scale > 1) {
            let width = size.width / size.height * 1080;
            let pos = location.sub(cc.v2(width / 2, 1080 / 2))
            e.target.setPosition(pos)
        } else {
            let height = size.height / size.width * 1920;
            let pos = location.sub(cc.v2(1920 / 2, height / 2))
            e.target.setPosition(pos)
        }
    }
    // checkSuccess(target, data) {
    //     let itemBg = this.cardBgs.find((bg) => {
    //         // let dis = this.getDistances(target.getPosition(), bg.getPosition());
    //         let dis = this.getDistances(target, bg);
    //         // if (dis < 100 && bg.sortId == data.id) {
    //         if (dis < 100 && cc.find("n/img", bg)) {
    //             return bg;
    //         }
    //         return null;
    //     })
    //     return itemBg && itemBg.sortId == data.id
    // }

    onItemTouchCancel(e) {
        let target: cc.Node = e.target;
        let data = target.data;
        target.parent = data.parent;
        target.setPosition(data.x, data.y);
        let stone1 = cc.find("stone1", data.parent);
        this.stSction(stone1);
    }
    onItemTouchStart(e) {
        let target: cc.Node = e.target;
        let data = target.data;
        //已经成功的方块要拒绝掉
        // if (this.checkSuccess(target, data)) return;
        target.parent = this.node;
        target.scale = 1;
        this.setTouchPos(e);

        let stone1 = cc.find("stone1", data.parent);
        stone1.y = 0;
        cc.Tween.stopAllByTarget(stone1);
        // target.startPos = target.getPosition();
    }
    onItemTouchMove(e) {
        let target: cc.Node = e.target;
        let data = target.data;
        //已经成功的方块要拒绝掉
        // if (this.checkSuccess(target, data)) return;
        this.setTouchPos(e);
    }
    onItemTouchEnd(e) {
        let target: cc.Node = e.target;
        let data = target.data;

        //已经成功的方块要拒绝掉
        // if (this.checkSuccess(target, data)) return;
        let itemBg = this.cardBgs.find((bg) => {
            // let dis = this.getDistances(target.getPosition(), bg.getPosition());
            let dis = this.getDistances(target, bg);
            // if (dis < 100 && bg.sortId == data.id) {
            if (dis < 100 && bg.data.index == data.index) {
                return bg;
            }
            return null;
        })
        //检测是否在区域内
        if (!itemBg) {
            target.parent = data.parent;
            target.setPosition(data.x, data.y);
            // this.playLocalAudio("error");
            this.playLocalAudio("error");
            let stone1 = cc.find("stone1", data.parent);
            this.stSction(stone1);
            return;
        }

        target.parent = data.parent;
        target.setPosition(data.x, data.y);
        target.active = false;

        let layer_candy = cc.find("layer_candy", itemBg);
        layer_candy.active = true;
        if (itemBg.data.pic_url && itemBg.data.pic_url != "") {
            let img = cc.find("img", itemBg);
            pg.view.setNetImg(img, itemBg.data.pic_url, { w: itemBg.data.width, h: itemBg.data.height });

        } else {
            let desc = cc.find("desc", itemBg);
            desc.getComponent(cc.Label).string = data.text;
        }


        this.playLocalAudio("right").then(async () => {
            await asyncDelay(0.1);
            pg.audio.playAudioByUrl(data.audio).then(async () => {
                if (this.checkRoundEnd()) {
                    await asyncDelay(0.5);
                    pg.event.emit("gameOver");
                }
            });
        });
    }
    private cleanLayoutSort() {
        this.cardBgs.forEach((item) => {
            let img = cc.find("img", item);
            if (img) {
                img.parent = null;
                img.destroy();
            }
        })
    }
    private checkRoundEnd() {
        let count = 0;
        this.cardBgs.forEach((item) => {
            let desc = cc.find("desc", item);
            if (desc.getComponent(cc.Label).string != "") count++
        })
        return count == this.cardBgs.length;
    }
    checked: boolean;
    checkFull() {
        if (!this.currentCards) return;
        if (!this.cards) return;
        if (this.currentCards.length != this.cards.length) return false;
        return this.currentCards.every(card => !!card);
    }
    private isOver = false;
    gameOver() {
        if (this.isOver) return;
        this.isOver = true;
        this.log("over  ~~~~~~~~~~~~~~")
        pg.event.once('layer_right_show_excellent_end', () => {
            pg.event.emit('layer_coin_show_coin', 3)   //1 2 3硬币数量
        })
        pg.event.emit("layer_right_show_excellent");
    }


    playLocalAudio(audioName) {
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            const id = cc.audioEngine.playEffect(audio.clip, false);
            cc.audioEngine.setFinishCallback(id, () => {
                resolve(id);
            });
        })
    }
}


