var tagInput = {
    isInited: false,
    init: init,
    bindEvent: bindEvent,
    addTag: addTag,
    removeTag: removeTag
};
tagInput.init();

function init() {
    var that = this;
    if (that.isInited) return;
    that.isInited = true;
    // 请修改这一行代码,保存class为js-input的输入框的dom元素引用
    that.input = null;
    that.input = document.getElementsByClassName("js-input")[0];
    that.bindEvent();
}

function bindEvent() {
    var that = this;
    var input = that.input;
    if (!input) return;
    input.addEventListener('keydown', function (event) {
        // 请修改这一行代码,判断用户是否按了回车键
        var isEnter = false;
        // 请修改这一行代码,判断用户是否按了删除键
        var isDelete = false;

        let code = Number(event.keyCode);
        if (code == 13) {
            isEnter = true;
        } else if (code == 8) {
            isDelete = true;
        }
        
        (isEnter || isDelete) && event.preventDefault();
        isEnter && that.addTag();
        isDelete && that.removeTag();
    });
    input.parentNode.addEventListener('click', function () {
        input.focus();
    });
}

function addTag() {
    let value = this.input.value.trim();
    if (value == null || value == "") {
        this.input.value = "";
        return;
    }
    let tagList = document.querySelector(".tag-input");
    let tag = document.createElement("span");
    tag.innerText = value;
    tag.classList.add("tag");
    tagList.insertBefore(tag, this.input);
    this.input.value = "";
}

function removeTag() {
    let value = this.input.value;
    if (value == null || value == "") {
        let tarDom = document.getElementsByClassName("tag-input")[0];
        let tagList = tarDom.querySelectorAll("span");
        let index = tagList.length - 1;
        if (index > -1) {
            tarDom.removeChild(tagList[index]);
        }
        console.log(tagList);
    } else {
        value = value.slice(0, value.length - 1);
        this.input.value = value;
        console.log(value);
    }
}