const MARK_BOX_ELEM_ID = 'mark_box',
    MARK_CONTAINER_ELEM_ID = 'mark-container',
    MARK_CHOOSE_CLASS = 'choose';
const TEMPLATE = `
    <div class="layui-card">
        <div class="layui-card-header">
            <div class="head-filter">
                <input class="layui-input" id="filter-input" name="filter" placeholder="输入关键词过滤标签。。。 ">
                    <i class="layui-icon layui-icon-search"></i>
                </input>
            </div>
        </div>
        <div class="layui-card-body" id="${MARK_BOX_ELEM_ID}"></div>
    </div>
`;

/**
 * 标签选择器对象
 */
class MarkerSelector {
    constructor(elemSelector) {
        /**
         * 绑定按钮的元素选择器
         */
        this.elemSelector = elemSelector;
        this.selected_data = [];
        this.okBtnThen = null;
        this.markTag = null;

        this.bindBtnEvent();
    }

    bindBtnEvent() {
        const _this = this;
        $(_this.elemSelector).off('click').on('click', function () {
            _this.show();
        });
    }

    show() {
        let _this = this;
        fetchMarks().then(data => _this.openLayer(data));
    }

    renderSelectData() {
        if (this.markTag) {
            for (let str of this.selected_data) {
                let arr = str.split('-');
                str = str.replace(arr[0] + '-', '');
                $(`#${MARK_BOX_ELEM_ID} .tag-item[data-id="${str}"]`).addClass(MARK_CHOOSE_CLASS);
            }
        }
    }

    callEvent() {
        this.okBtnThen && this.okBtnThen(this.selected_data);
    }

    onOkBtn(then) {
        this.okBtnThen = then;
    }


    /**
     * 渲染弹框
     * @param marks
     */
    openLayer(marks) {
        let _selector = this;
        layui.use(['layer', 'tag'], function () {
            let layer = layui.layer, tag = layui.tag;
            layer.open({
                type: 1,
                title: '选择置标标签',
                area: ['700px', '80%'],
                btn: ['确定', '取消'],
                content: TEMPLATE,
                success: function (layerObj, index) {
                    _selector.renderMarkType(marks, tag);
                    // 关键词过滤
                    $('#filter-input').on('keyup', function () {
                        showSearchMark($(this).val().trim());
                    });
                },
                yes: function (index) {
                    _selector.selected_data = [];
                    $(`#${MARK_BOX_ELEM_ID} .tag-item.${MARK_CHOOSE_CLASS}`).each((i, elem) => {
                        let type = $(elem).parent().data('markType')
                        _selector.selected_data.push(type + '-' + $(elem).data('id'))
                    })
                    _selector.callEvent();
                    layer.close(index);
                },
            });
        });
    }

    renderMarkType(markTypes, tag) {
        let _selector = this;
        layui.use(['tag'], function () {
            if (Array.isArray(markTypes)) {
                for (let type of markTypes) {
                    let elemId = MARK_CONTAINER_ELEM_ID + '-' + type.id;
                    let template = `<div class="type-item">
                        <fieldset class="layui-elem-field layui-field-title" style="margin-bottom: 0;height: 20px">
                            <legend>${type.markType}</legend>
                            <div class="btn-box">
                                <a href="javascript:void(0);" data-type="choose-all">全选</a>
                                <a href="javascript:void(0);" data-type="choose-clear">清空</a>
                                <a href="javascript:void(0);" data-type="box-slide">收起</a>
                            </div>
                        </fieldset>
                        <div class="mark-container" id="${elemId}"></div>
                    </div>`;
                    $(`#${MARK_BOX_ELEM_ID}`).append(template);

                    _selector.markTag = new MarkTag(tag, {
                        tagId: 'type-' + type.id,
                        container: '#' + elemId,
                        markType: type.id,
                        onClick: function (text, $elem) {
                        }
                    });
                    let marks = [];
                    if (type.markDefault) {
                        for (let val of type.markDefault.split(',')) {
                            marks.push({markType: type.markType, markValue: val})
                        }
                    }
                    _selector.markTag.setMarkData(marks);
                }
                _selector.renderSelectData();
                initMarkTypeTool();
            }
        });
    }
}

/**
 * 获取标签数据
 */
function fetchMarks() {
    return new Promise(((resolve, reject) => {
        Util.get('/mark/api/type/list', {}).then(res => {
            if (res.flag) {
                resolve && resolve(res.data)
            } else {
                showErrorMsg(res.msg)
            }
        }).catch(reject);
    }))
}


function initMarkTypeTool() {
    // 标签选中事件
    $('.mark-container .tag-item').on('click', function () {
        $(this).toggleClass(MARK_CHOOSE_CLASS);
    });
    // 工具按钮点击事件
    $('.type-item .btn-box a').on('click', function (event) {
        event.stopPropagation();
        let $root = $(this);
        let btnType = $root.data('type'), $tags = $root.parent().parent().parent().find('.tag-item');
        if (btnType === 'choose-all') {
            $tags.addClass(MARK_CHOOSE_CLASS);
        }
        if (btnType === 'choose-clear') {
            $tags.removeClass(MARK_CHOOSE_CLASS);
        }
        if (btnType === 'box-slide') {
            let $container = $root.parent().parent().next()
            $container.slideToggle(0);
            if ($container.is(':visible')) {
                $root.text('收起');
            } else {
                $root.text('展开');
            }
        }
    })
}

function showSearchMark(text) {
    let tagItems = $('#mark_box .tag-item'), tagBox = tagItems.parent().parent(),
        addBtn = $('#mark_box .button-new-tag');
    if (text) {
        // hide all
        tagItems.hide();
        addBtn.hide();
        tagBox.hide();

        // show choose
        tagItems.each((index, elem) => {
            let $elem = $(elem);
            if ($elem.text().includes(text)) {
                $elem.parent().parent().show();
                $elem.show()
            }
        })
    } else {
        // show all
        tagBox.show();
        tagItems.show();
        addBtn.show();
    }
}