import { Cat } from "./Cat";
import { Item } from "./Item";
import { delayCall, getSprNode, playAudio } from "./util";


/**
 * 单词对像
 */
export class Word extends Item {

    private _audioUrl: string;

    private _audioClip: cc.AudioClip;

    private _initScale = 1;

    /**间隔 */
    private _spacing = 20;

    private _nodeArr = [];

    private _cat: Cat;

    get nodeArr() {
        return this._nodeArr;
    }

    set audioUrl(audioUrl: string) {
        this._audioUrl = audioUrl

        //音频地址存在，则加载音频
        if (audioUrl && audioUrl != "") {
            cc.assetManager.loadRemote(this._audioUrl, (err, audioClip) => {

                this._audioClip = audioClip;
            });
        }
    }

    get audioUrl() {
        return this._audioUrl;
    }

    constructor(cat: Cat) {
        super();

        this._cat = cat;
    }

    buildWordNode(fontColor: string) {

        let valArr = this.data;

        let length = 0;

        //计算字母总长度
        for (let i = 0; i < valArr.length; ++i) {

            length += valArr[i].length;

        }


        let resName = "";

        if (length == 1) {
            resName = "card_1";
        }
        else if (length < 4) {
            resName = "card_2";
        }
        else {
            resName = "card_3";
        }

        this.node = getSprNode(resName);
        //设置不可点击
        this.canTouch = false;

        let color = new cc.Color();
        color.fromHEX(fontColor);

        let font = cc.find('Canvas/res/font/MuliBold_YzEVy').getComponent(cc.Label).font;


        for (let i = 0; i < valArr.length; ++i) {
            const labelNode = new cc.Node();
            labelNode.color = color;
            const label = labelNode.addComponent(cc.Label);
            label.lineHeight = 90;
            label.fontSize = 90;
            label.font = font;
            label.string = valArr[i];

            labelNode.parent = this.node;
            labelNode.y = 0;

            this._nodeArr.push(labelNode);
        }

        this._initScale = this.node.scale;
    }

    /**
     * 卡片点击事件处理
     * @param callback 
     */
    click(callback = null) {

        //动画时长
        let tweenDuration = 0.6;

        const twinkle = (node) => {
            cc.tween(node)
                .to(tweenDuration / 2, { scale: this._initScale * 1.5 })
                .to(tweenDuration / 2, { scale: this._initScale })
                .call(() => {

                })
                .start();
        };

        //播放动画
        twinkle(this.node);

        //播放音频
        if (this._audioClip) {

            playAudio(this._audioClip, () => {

            });
        }


        if (callback) {

            //获取音频时长
            let duration = this.getAudioDuration();

            //回调延迟时间
            let timeout = tweenDuration;

            //如果音频时长大于动画时长，则等音频播放完成后，再执行回待函数
            if (duration > tweenDuration) {
                timeout = duration;
            }

            console.log(timeout, duration)

            delayCall(timeout + 1, callback);
        }

    }

    getAudioDuration() {
        //获取音频时长
        let duration = this._audioClip == null ? 0 : this._audioClip.duration;

        return duration;
    }

    resetPosition() {

        let nodeArr = this._nodeArr;

        let tW = 0;

        for (let i = 0; i < nodeArr.length; ++i) {
            tW += nodeArr[i].width;
        }

        tW += (nodeArr.length - 1) * this._spacing;

        let startX = - tW / 2;

        for (let i = 0; i < nodeArr.length; ++i) {

            nodeArr[i].x = startX + nodeArr[i].width / 2;
            startX += nodeArr[i].width + this._spacing;
        }
    }

}

export class WordGroup extends Item {
    private _wordArr = [];

    get wordArr() {
        return this._wordArr;
    }

    show() {

    }
}

/**
 * 单词区域对象
 */
export class WordArea extends WordGroup {

    private _equalNode;


    get equalNode() {
        return this._equalNode;
    }

    addWord(word: Word) {
        if (word) {
            this.wordArr.push(word);

            word.node.parent = this.node;
        }
    }

    /**
     * 显示单词信息
     * @param callback 
     */
    show(callback = null) {

        let width = this.node.width;

        let spacing = 25;

        let x = -width / 2;

        let len = this.wordArr.length;

        if(len > 3){
            spacing = 8;
        }

        //循环显示卡片
        for (let i = 0; i < len - 1; ++i) {

            let word = this.wordArr[i];

            x += word.node.width / 2;

            word.node.x = x;

            x += word.node.width / 2 + spacing;

            word.node.zIndex = 10 + i;

            //不是最后一个，添加“+”号
            if (i < len - 2) {
                let plusNode = getSprNode("plus");

                x += plusNode.width / 2;
                plusNode.x = x;
                plusNode.parent = this.node;

                x += plusNode.width / 2 + spacing;
            }
        }


        //获取“=”号精灵
        let equal = getSprNode("equal");
        x += equal.width / 2;
        equal.x = x;
        equal.parent = this.node;
        equal.active = false;
        this._equalNode = equal;
        x += equal.width / 2 + spacing;

        //最后一个单词
        let word = this.wordArr[len - 1];
        x += word.node.width / 2;
        word.node.x = x;
        word.node.zIndex = 99;

        for (let i = 0; i < this.wordArr.length; ++i) {
            this.wordArr[i].resetPosition();
        }

        if (callback) {
            callback();
        }
    }
}

export class Word2 extends Item {

    private _cat: Cat;

    private _audioUrl: string;

    private _audioClip: cc.AudioClip;

    constructor(cat: Cat, data) {
        super();

        this._cat = cat;

        this._data = data;
    }

    init() {
        this._audioUrl = this._data.audioUrl;

        //音频地址存在，则加载音频
        if (this._audioUrl && this._audioUrl != "") {
            cc.assetManager.loadRemote(this._audioUrl, (err, audioClip) => {

                this._audioClip = audioClip;
            });
        }

        this.buildNode();
    }

    private buildNode() {

        let font = cc.find('Canvas/res/font/MuliBold_YzEVy').getComponent(cc.Label).font;
        let color = new cc.Color();
        color.fromHEX(this._data.fontColor);
        console.log(this._data);

        const labelNode = new cc.Node();
        labelNode.active = false;
        labelNode.color = color;
        const label = labelNode.addComponent(cc.Label);
        label.lineHeight = 90;
        label.fontSize = 90;
        label.font = font;
        label.string = this._data.val;
        label._forceUpdateRenderData(true);

        labelNode.y = 0;
        labelNode.x = 0;
        this._node = labelNode;
    }

    /**
     * 卡片点击事件处理
     * @param callback 
     */
    click(callback = null) {

        //动画时长
        let tweenDuration = 0.6;

        const twinkle = (node) => {
            cc.tween(node)
                .to(tweenDuration / 2, { scale: 1.5 })
                .to(tweenDuration / 2, { scale: 1 })
                .call(() => {

                })
                .start();
        };

        this.node.active = true;

        //播放动画
        twinkle(this.node);

        //播放音频
        if (this._audioClip) {


            playAudio(this._audioClip, () => {

            });
        }


        if (callback) {

            //获取音频时长
            let duration = this.getAudioDuration();

            //回调延迟时间
            let timeout = tweenDuration;

            //如果音频时长大于动画时长，则等音频播放完成后，再执行回待函数
            if (duration > tweenDuration) {
                timeout = duration;
            }

            delayCall(timeout + 1, callback);
        }

    }

    getAudioDuration() {
        //获取音频时长
        let duration = this._audioClip == null ? 0 : this._audioClip.duration;

        return duration;
    }

    show() {
        this._node.opacity = 255;

    }

    hide() {
        this._node.opacity = 0;
    }
}

export class WordArea2 extends WordGroup {

    private _cat: Cat;

    card: cc.Node;

    constructor(cat: Cat, data) {
        super();

        this._cat = cat;

        this._node = cc.find("Canvas/center/word");

        this._data = data;
    }

    init() {

        let word = this._data[2];

        let length = word.val.length;

        let path = "card_3";

        if (length > 5) {
            path = "card_4";
        }

        this.card = cc.find(path, this._node);


        for (let i = 0; i < this._data.length; ++i) {

            let data = this._data[i];

            //如果是单词，修改字体颜色
            if (i == 2) {
                data.fontColor = "#231f20";
            }

            let word = new Word2(this._cat, data);
            word.init();

            word.node.parent = this.card;

            this.wordArr.push(word);
        }

    }

    show(callback = null) {
        this.card.active = true;

        //取最后一个单词节点的宽度
        let width = this.wordArr[2].node.getBoundingBox().width;
        console.log(width);
        let startX = - width / 2;

        for (let i = 0; i < this.wordArr.length - 1; ++i) {
            let node = this.wordArr[i].node;
            let width = node.getBoundingBox().width;
            node.x = startX + width / 2;
            startX += width;
        }

        callback && callback();
    }

    click(cb = null) {

        for (let i = 0; i < this.wordArr.length; ++i) {
            this.wordArr[i].hide();
        }

        const play2 = (index = 0) => {

            let word = this.wordArr[index];

            word.show();

            word.click(() => {

                if (index === this.wordArr.length - 1) {
                    cb && cb();
                }
                else {
                    word.hide();
                    play2(index + 1);
                }
            });
        };

        play2();
    }
}

/**
* 将给定的值拆成字母数组
* @param val 
* @returns 
*/
export function getLetterArr(val) {
    let arr = [];

    if (!val) {
        return arr;
    }

    for (let i = 0; i < val.length; ++i) {
        arr.push(val.charAt(i));
    }

    return arr;
}