import { asyncDelay, exchangeNodePos, getSprNode, onHomeworkFinish, onHomeworkStart, playAudio } from "../script/util_op_input";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_op_input";
import Game, { Item, Option } from "./Game_op_input";
import pg from "./pg_op_input";

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() {
        cc.macro.ENABLE_MULTI_TOUCH = false;
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initEvent();
    }
    @property(cc.Node)
    op_layout: cc.Node = null;

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

    // @property(cc.Node)
    // normal_layout: cc.Node = null;

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

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

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

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

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

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

    private audioId;
    private wordAudioId;

    initData() {
        Game.getIns().init(this.data);
        Game.getIns().reset();
        this.wordItams = [];
        this.audioId = -1;
    }
    initView() {
        this.startGame();

    }
    initEvent() {
        cc.find("btn_cat", this.node).on(cc.Node.EventType.TOUCH_END, this.onCat, this);
        cc.find("tips/icon", this.node).on(cc.Node.EventType.TOUCH_END, this.onWordAudio, this);
        // pg.event.on("startGame", () => { this.startGame() })
        // pg.event.on("nextPage", () => { this.nextPage() })
        pg.event.on("gameOver", () => { this.gameOver() })
    }
    private onCat() {
        let data = Game.getIns().getCurrentPage();
        let audioUrl = "";
        if (data.page % 2 == 0) {
            audioUrl = Game.getIns().twoWaitAudio;
        } else {
            audioUrl = Game.getIns().waitAudio;
        }
        if (this.audioId >= 0) cc.audioEngine.stopEffect(this.audioId);
        this.setMaoAni("begin");
        pg.audio.playAudioByUrl(audioUrl, (id) => {
            this.audioId = id;
        }).then(() => {
            this.setMaoAni("normal");
        });
    }
    private onWordAudio() {
        let data = Game.getIns().getCurrentPage();
        if (this.wordAudioId >= 0) cc.audioEngine.stopEffect(this.wordAudioId);
        this.setMaoAni("begin");
        pg.audio.playAudioByUrl(data.wordAudio, (id) => {
            this.wordAudioId = id;
        }).then(() => {
            this.setMaoAni("normal");
        });
    }
    //根据两点获取距离
    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() {
        this.setMaoAni("begin");
        let audioUrl = "";
        if (Game.getIns().roundCount == 2) audioUrl = Game.getIns().twoVectoringAudio;
        else audioUrl = Game.getIns().vectoringAudio;
        pg.audio.playAudioByUrl(audioUrl).then(() => {
            this.setMaoAni("normal");
        });;
        this.progressBar.getComponent(cc.ProgressBar).progress = 0;
        this.nextPage();
    }
    nextPage() {
        let data = Game.getIns().getCurrentPage();
        data.randomOptions();
        //自动创建卡片
        this.createCrads(data);
        this.showTop(data);
    }
    private showTop(data) {
        let img = cc.find("tips/img", this.node);
        let icon = cc.find("tips/icon", this.node);
        let pro_label = cc.find("pro_label", this.progressBar);
        if (Game.getIns().roundCount == 2) {
            img.active = false;
            icon.active = true;
            pro_label.getComponent(cc.Label).string = `Round 2`;
        } else {
            img.active = true;
            icon.active = false;
            pg.view.setNetImg(img, data.image, { w: 110, h: 110 });
            pro_label.getComponent(cc.Label).string = `Round 1`;
        }

    }
    //创建卡片
    private cards: cc.Node[];
    private wordItams: cc.Node[];
    createCrads(list) {
        this.wordItams = [];
        this.op_layout.removeAllChildren();
        this.word_layout.removeAllChildren();
        // this.normal_layout.removeAllChildren();
        // this.normal_layout.opacity = 0;
        this.word_layout.active = true;
        list.optionList.forEach((op) => {
            let item = cc.instantiate(this.op_item);
            let desc = cc.find("desc", item);
            desc.getComponent(cc.Label).string = op.text || "";
            item.y = 0;
            item.active = true;
            item.parent = this.op_layout;
            desc.data = op;
            item.data = op;
            desc.on(cc.Node.EventType.TOUCH_START, this.onItemTouchStart, this);
            desc.on(cc.Node.EventType.TOUCH_MOVE, this.onItemTouchMove, this);
            desc.on(cc.Node.EventType.TOUCH_END, this.onItemTouchEnd, this);
        })
        let wordStr = "";
        list.contentArr.forEach((data, idx) => {
            if (data.text && data.text != "") {
                let item = cc.instantiate(this.word_item);
                let word = cc.find("word", item);
                let line = cc.find("line", item);
                word.getComponent(cc.Label).string = data.text || "";
                line.active = data.block;
                word.active = !data.block;
                item.y = 0;
                item.active = true;
                item.parent = this.word_layout;
                item.data = data;
                item.errorCount = 0;
                this.wordItams.push(item);

                // let lable = cc.instantiate(this.nor_label);
                // lable.getComponent(cc.Label).string = data.text || "";
                // lable.parent = this.normal_layout;
                wordStr += data.text || "";
            }
        })
        this.nor_label.opacity = 0;
        this.nor_label.getComponent(cc.Label).string = wordStr;
        let len = this.word_layout.children.length
        if (len > 8) {
            let scale = len > 8 && len < 11 ? 0.9 : len <= 12 ? 0.8 : 0.75;
            let spx = len > 8 && len < 11 ? 20 : len <= 12 ? 10 : 0;
            this.word_layout.getComponent(cc.Layout).spacingX = spx;
            this.word_layout.children.forEach((ch) => {
                ch.scale = scale;
            })
        }
    }
    private setTouchPos(e) {
        let location = e.getLocation();
        let size = cc.view.getCanvasSize();
        let scale = (size.width / size.height) / (1280 / 720);
        if (scale > 1) {
            let width = size.width / size.height * 720;
            let pos = location.sub(cc.v2(width / 2, 720 / 2))
            e.target.setPosition(pos)
        } else {
            let height = size.height / size.width * 1280;
            let pos = location.sub(cc.v2(1280 / 2, height / 2))
            e.target.setPosition(pos)
        }
    }
    onItemTouchStart(e) {
        if (this.checkRoundOver()) return;
        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);
    }
    onItemTouchMove(e) {
        if (this.checkRoundOver()) return;
        let target: cc.Node = e.target;
        let data = target.data;
        //已经成功的方块要拒绝掉
        this.setTouchPos(e);
    }
    onItemTouchEnd(e) {
        if (this.checkRoundOver()) return;
        let target: cc.Node = e.target;
        let data = target.data;
        let itemBg = this.wordItams.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 < 80 && cc.find("line", bg).active) {
                return bg;
            }
            return null;
        })

        if (itemBg) {
            if (itemBg.data.text == data.text) {
                target.parent = null;
                target.destroy();
                this.moveRight(itemBg);
            } else {
                itemBg.errorCount++;
                if (itemBg.errorCount >= 3) {
                    this.errorThere(target, itemBg);
                    this.playLocalAudio("right", 0.6);
                    this.roundOver();
                } else {
                    this.playLocalAudio("error");
                    this.moveError(target, data);
                }
            }
        } else {
            this.playLocalAudio("error");
            this.moveError(target, data);
        }
    }
    private moveRight(item) {
        let word = cc.find("word", item);
        let line = cc.find("line", item);
        word.active = true;
        line.active = false;
        this.playLocalAudio("right", 0.6);
        this.roundOver();
    }
    private moveError(target, data) {
        this.op_layout.children.forEach((item) => {
            if (item.data.id == data.id) {
                target.parent = item;
                target.setPosition(0, 20);
            }
        })
    }
    private errorThere(target, itemBg) {
        this.op_layout.children.forEach((item) => {
            if (item.data.id == target.data.id) {
                target.parent = item;
                target.setPosition(0, 20);
            }
            if (item.data.text == itemBg.data.text) {
                let desc = cc.find("desc", item);
                desc.parent = null;
                desc.destroy();
            }
        })
        this.word_layout.children.forEach((item) => {
            if (item.data.text == itemBg.data.text) {
                let word = cc.find("word", item);
                let line = cc.find("line", item);
                word.active = true;
                line.active = false;

            }
        })
    }
    private roundOver() {
        if (this.checkRoundOver()) {
            cc.tween(this.nor_label)
                .delay(0.5).call(() => {
                    this.word_layout.active = false;
                    this.word_layout.removeAllChildren();
                })
                .to(0.1, { opacity: 255 }).delay(0.5).call(() => {
                    let data = Game.getIns().getCurrentPage();
                    pg.audio.playAudioByUrl(data.wordAudio).then(() => {
                        let pro = this.progressBar.getComponent(cc.ProgressBar);
                        let p = Game.getIns().page / Game.getIns().getTotalPageNum();
                        cc.tween(pro).to(1, { progress: p }).delay(1).call(() => {
                            let add = Game.getIns().addPage();
                            if (add) {
                                this.nextPage()
                            } else {
                                if (Game.getIns().roundCount == 1) {
                                    Game.getIns().roundCount = 2;
                                    Game.getIns().page = 1;
                                    this.startGame();
                                } else {
                                    this.goodJob.active = true;
                                    this.gameOver();
                                }
                            }
                        }).start();
                    })
                }).start();
        }
    }
    private checkRoundOver() {
        let count = 0;
        this.word_layout.children.forEach((item) => {
            let line = cc.find("line", item);
            if (!line.active) count++;
        })
        return count >= this.word_layout.children.length;
    }

    gameOver() {
        this.playLocalAudio("over").then(() => {
            let data: any = {};
            onHomeworkFinish(data);
        });
    }

    setMaoAni(aniName) {
        let mao_ske = cc.find("mao_ske", this.node);
        let ske = mao_ske.getComponent(dragonBones.ArmatureDisplay).playAnimation(aniName, 0);
    }
    playLocalAudio(audioName, volume = 1) {
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            cc.audioEngine.setEffectsVolume(volume);
            const id = cc.audioEngine.playEffect(audio.clip, false);
            cc.audioEngine.setFinishCallback(id, () => {
                cc.audioEngine.setEffectsVolume(1);
                resolve(id);
            });
        })
    }
}
