const style = ``;
const STATE = {ready: 0, busy: 1}
const MARK_INSERT_TYPE = {
    ManagerInsert: 'ManagerInsert',
    FormInsert: 'FormInsert',
    FileUploadInsert: 'FileUploadInsert'
}

class MarkTag {
    constructor(tag, options) {
        this.tag = tag;
        this.tagId = options.tagId;
        this.container = options.container;
        this.addBtn = options.addBtn;
        this.changeAndSave = options.changeAndSave;
        this.removeBtn = options.removeBtn;
        this.onClick = options.onClick;
        this.markType = options.markType;
        this.markTypeStr = options.markTypeStr;
        this.insertType = options.insertType || MARK_INSERT_TYPE.ManagerInsert;
        this.state = STATE.busy;
        this.render();
    }

    render() {
        let {tagId, tag, container, addBtn, removeBtn, onClick, markType, changeAndSave} = this, _this = this;
        if (typeof container == 'string') {
            container = $(container);
        }
        $(container).addClass('layui-btn-container tag').attr('lay-filter', tagId)
        if (addBtn) {
            $(container).attr('lay-newTag', 'true');
        }
        if (removeBtn) {
            $(container).attr('lay-allowclose', 'true');
        }
        if (markType) {
            $(container).attr('data-mark-type', markType);
        }

        tag.render();
        tag.on(`add(${tagId})`, function ({text}) {
            let existTexts = tag.getItemElemsText(tagId);
            if (existTexts.includes(text.trim())) {
                layer.msg("标签已存在");
                return false;
            }
            changeAndSave && _this._saveTag(text.trim());
        });

        onClick && tag.on(`click(${tagId})`, ({text, elem}) => onClick(text, elem));
        this.state = STATE.ready;
    }

    getTextStr() {
        return this.tag.getItemElemsText(this.tagId).join(",");
    }

    setData(data) {
        this.state = STATE.busy;
        if (data) {
            let {tag, tagId} = this;
            data.split(',').forEach((item, index) => {
                tag.add(tagId, {
                    text: item,
                    id: index
                });
            });
            tag.render();
        }
        this.state = STATE.ready;
    }

    setMarkData(marks) {
        this.state = STATE.busy;
        if (Array.isArray(marks)) {
            let {tag, tagId} = this;
            for (let mark of marks) {
                tag.add(tagId, {
                    id: mark.markType + '-' + mark.markValue,
                    text: mark.markValue,
                });
            }
        }
        this.state = STATE.ready;
    }

    deleteTag(text) {
        let {tag, tagId, markType, insertType, markTypeStr} = this;
        let tags = this.getTextStr().split(',');
        let index = tags.findIndex(t=>t===text);
        tags.splice(index, 1);
        let data = {id: markType, markDefault: tags.join(','), insertType, markType: markTypeStr};
        saveRequest(data).then((res) => {
            if (res.flag) {
                tag.delete(tagId, markType + '-' + text);
            } else {
                showErrorMsg('标签删除失败');
                console.error(res.msg);
            }
        }).catch(err => {
            showErrorMsg('服务器异常');
            console.error(err);
        })
    }

    _saveTag(text) {
        let {state, markType, markTypeStr, insertType} = this, _this = this;
        if (state === STATE.ready) {
            let _text = this.getTextStr() + ',' + text;
            let data = {id: markType, markDefault: _text, insertType, markType: markTypeStr};
            let tagSelector = `button.tag-item[data-id="undefined"]`,
                close = $('<i class="layui-icon layui-unselect tag-close">&#x1006;</i>'),
                layId = markType + '-' + text;
            saveRequest(data).then((res) => {
                let $tagElem = $(tagSelector);
                if (!res.flag) {
                    $tagElem.remove();
                    showErrorMsg('标签保存失败');
                    console.error(res.msg);
                } else {
                    // 给新增的标签增加删除按钮
                    $tagElem.attr('lay-id', layId).attr('data-id', layId);
                    close.on('click', (event) => {
                        event.stopPropagation();
                        _this.deleteTag(text)
                    });
                    $tagElem.append(close);
                }
            }).catch((err) => {
                $(tagSelector).remove();
                showErrorMsg('服务器异常');
                console.error(err)
            })
        }
    }

    static getStaticTagHtml(data) {
        if (data) {
            let container = $(`<div class="layui-btn-container tag" style=""></div>`);
            data.split(',').forEach((item, index) => {
                container.append(`<button type="button" class="layui-btn layui-btn-primary layui-btn-xs layui-btn-radius tag-item" data-text="${item}" lay-id="${index}">${item}</button>`);
            });
            return container.html();
        }
    }
}

function saveRequest(data) {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: ctx + '/mark/api/type/save',
            data: data,
            type: 'post',
            headers: {'Content-type': 'application/x-www-form-urlencoded'},
            success: function (res) {
                resolve && resolve(res)
            },
            error: function (err) {
                reject && reject(err);
            },
        });
    })
}