<template>
    <div v-clickoutside="handleCloseSearch" ref="searchBox" class="searchBox" @click="$emit('update:popperVisible', true); $refs.searchBox.classList.add('is-focus'); $refs.input.focus()">
        <div class="searchBox__left">
            <template>
                <div v-clickoutside="handleUnSelect" ref="tagBox" class="filter__condition">
                    <el-tag
                        v-for="(item,index) in logRetrival.selectedPolicyArray"
                        :key="index"
                        :ref="'tagCss' + index"
                        class="tagCss"
                        effect="dark"
                        type="info"
                        closable
                        data-selected="false"
                        @click.native.stop="$event => tagClick($event, item, index)"
                        @keydown.native.delete="event => deleteSelectedTag(event, item, index)"
                        @close.stop="resetSearchStatus(); logRetrival.handleClose(item, index); $nextTick(() => togglePoint())"
                    >
                        <span class="tagCss--text">
                            <template v-if="item.type == 'input'||item.type == 'datetime'||item.type == 'datetimerange'||item.type == 'selectInput'">
                                {{ item.label }}:{{ item.conditionLabel }}{{ toConvert(item.value, logRetrival.statics[logRetrival.treeSelectField[item.prop]] || logRetrival.statics[item.prop == 'event_level' ? 'rule_level' : item.prop], 'dataId', logRetrival.treeSelectField[item.prop] ? 'label' : 'dataName') }}
                            </template>
                            <template v-if="item.type == 'select'">{{ item.label }}:{{ item.valueList.dataName }}</template>
                        </span>
                    </el-tag>
                    <el-tag
                        v-if="showMore"
                        class="tag__point"
                        effect="dark"
                        type="info"
                    >
                        <span class="tag__point__item" v-for="item in 3" :key="item"></span>
                    </el-tag>
                </div>
                <el-input
                    ref="input"
                    v-model="searchVal"
                    placeholder="请选择查询策略"
                    @keypress.native="$event => $event.preventDefault()"
                    @keydown.native.delete="deleteTagInfo"
                ></el-input>
            </template>
        </div>
        <div class="searchBox__right">
            <i class="el-icon-search" @click.stop="$emit('search')"></i>
        </div>
        <el-popover v-model="popperVisible" :visible-arrow="false" placement="bottom-start" trigger="manual" popper-class="searchBox__popper">
            <div class="scroll__box">
                <el-scrollbar wrap-style="overflow-x: hidden;">
                    <el-row class="step__box" @click.native="popperItemClick">
                        <template v-if="step == 1">
                            <div class="step__header" @click.stop="logRetrival.cfgKeyFieldOper">
                                <i class="el-icon-setting" style="color: "></i>关键字配置
                            </div>
                            <div
                                class="step__item"
                                v-for="item in logRetrival.keyword[0].conditions"
                                :key="item.fieldNote"
                                :data-key="item.fieldNote"
                                :data-label="item.fieldName"
                            >
                                {{ item.fieldName }}
                            </div>
                        </template>
                        <template v-else-if="step == 2">
                            <div
                                class="step__item"
                                v-for="item in logRetrival.statics.conditionType"
                                :key="item.value"
                                :data-condition="item.value"
                                :data-condition-label="item.label"
                            >
                                {{ item.label }}
                            </div>
                        </template>
                        <div v-else-if="step == 3" style="position: fixed; width: 150px">
                            <manager-tree-select
                                v-if="item_child.fieldNote != 'event_group' && logRetrival.treeSelectField[item_child.fieldNote]"
                                :ref="item_child.fieldNote"
                                v-model="item_child.itemValue"
                                class="logManagerTreeSelect"
                                :multiple="false"
                                :data="logRetrival.statics[logRetrival.treeSelectField[item_child.fieldNote]] || []"
                                @clear="item_child.itemValue = []; $refs[item_child.fieldNote].filterText = ''"
                                @change="formChange(item_child.itemValue.join(','), item_child)"
                            />

                            <el-tree-select
                                class="logManagerTreeSelect"
                                v-else-if="item_child.fieldNote == 'event_group'"
                                :value="selectedEventGroup"
                                key-name="label"
                                @clear="$refs['eventGroupTree'][0].setCheckedKeys([]); logRetrival.eventGroupFilterText = ''; selectedEventGroup = []; item_child.itemValue = []; logRetrival.conditionKeywordInput(item_child.itemValue.join(','), item_child)"
                            >
                                <div class="filter-input" style="padding:0 15px 8px;">
                                    <el-input v-model="logRetrival.eventGroupFilterText" placeholder="输入关键字进行过滤" />
                                </div>
                                <el-tree
                                    ref="eventGroupTree"
                                    v-model="item_child.itemValue"
                                    :filter-node-method="logRetrival.filterNode"
                                    node-key="dataId"
                                    :data="logRetrival.statics.eventGroupTree"
                                    show-checkbox
                                    :multiple="false"
                                    :check-strictly="true"
                                    accordion
                                    highlight-current
                                    @check-change="(val, selectedNode, selectedLeaf) => eventGroupChange(val, selectedNode, selectedLeaf, item_child)"
                                />
                            </el-tree-select>

                            <template v-else-if="item_child.fieldType == 3">
                                <el-date-picker
                                    :key="item_child.itemCondition == '12' ? 'datetimerange' : 'datetime'"
                                    v-model="item_child.itemValue"
                                    :type="item_child.itemCondition == '12' ? 'datetimerange' : 'datetime'"
                                    placeholder="选择日期时间"
                                    format="yyyy-MM-dd HH:mm:ss"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    @change="formChange(item_child.itemValue, item_child)"
                                >
                                </el-date-picker>
                            </template>

                            <el-select
                                v-else-if="logRetrival.selectFiledNote.includes(item_child.fieldNote)"
                                v-model="item_child.itemValue"
                                @change="formChange(String(item_child.itemValue), item_child)"
                                filterable
                                clearable
                            >
                                <template v-if="['rule_level', 'event_level'].includes(item_child.fieldNote)">
                                    <el-option v-for="ruleItem in logRetrival.statics.rule_level" :key="ruleItem.dataId" :label="ruleItem.dataName" :value="ruleItem.dataId" />
                                </template>
                                <template v-else>
                                    <el-option v-for="item in logRetrival.statics[item_child.fieldNote]" :key="item.dataId" :label="item.dataName" :value="item.dataId" />
                                </template>
                            </el-select>

                            <el-input v-else v-model="item_child.itemValue" @keyup.native.enter="formChange(item_child.itemValue, item_child)" />
                        </div>
                        <template v-else-if="step == 4">
                            <el-select
                                v-model="logRetrival.queryForm.indexId"
                                filterable
                                @change="val => {
                                    logRetrival.getKeyFieldsData(val, '日志类型', 'indexId', 'select');
                                    handleUnSelect()
                                }"
                            >
                                <el-option
                                    v-for="item_child in logRetrival.logTypeList"
                                    :key="item_child.indexId"
                                    :label="item_child.indexName"
                                    :value="item_child.indexId"
                                />
                            </el-select>
                        </template>
                    </el-row>
                </el-scrollbar>
            </div>
            <span slot="reference" style="position: absolute; left: 0; bottom: 0"></span>
        </el-popover>
    </div>
</template>

<script>
export default {
    inject: ['logRetrival'],
    props: {
        popperVisible: {
            type: Boolean,
            default: false
        }
    },
    watch: {
        popperVisible() {
            this.togglePoint()
        },
        'logRetrival.selectedPolicyArray'(val) {
            if (val.length == 1) this.showMore = false
        }
    },
    mounted() {
        // 监听输入法事件来过滤输入法输入的内容
        let val = ''
        this.$refs.input.$el.addEventListener('compositionstart', e => {
            val = e.target.value
        })
        this.$refs.input.$el.addEventListener('compositionend', e => {
            this.searchVal = val
        })
    },
    data() {
        return {
            searchVal: '',
            step: 1,
            curTag: {
                key: '',
                value: '',
                label: '',
                condition: '',
                conditionLabel: ''
            },
            item_child: {},
            showMore: false,
        }
    },
    methods: {
        // 判断标签是否超出容器高度
        togglePoint() {
            if (this.$refs.tagBox.clientHeight > 32 && Array.from(this.$refs.searchBox.classList).indexOf('is-focus') == -1) this.showMore = true
            else this.showMore = false
        },
        // 查询框高度重置，弹窗隐藏
        handleCloseSearch(e) {
            this.$emit('update:popperVisible', false)
            this.$refs.searchBox.classList.remove('is-focus')
            this.item_child.itemValue = ''
            this.item_child.itemCondition = null
            this.item_child.conditionLabel = null
            this.resetSearchStatus()
        },
        // 标签重置为未选中状态
        handleUnSelect(e) {
            // if (Array.from(e.target.classList).includes('tagCss--text')) return
            let ele = document.querySelector('.tagCss.is-focus') || document.querySelector('.tagCss.is-selected')
            if (ele) {
                ele.classList.remove('is-focus', 'is-selected')
                ele.dataset.selected = 'false'
            }
        },
        // 重置新增搜索条件状态
        resetSearchStatus() {
            this.searchVal = ''
            this.step = 1
            this.curTag = {
                key: '',
                value: '',
                label: '',
                condition: '',
                conditionLabel: ''
            }
            this.item_child = {}
        },
        toConvert(input = '', source, keyName, valueName) {
            if (!(source instanceof Array) || !source.length || !input) return input
            if (source[0].children) {
                source = this.recursiveArray(source)
            }
            for (const e of source) {
                if (e[keyName] == input) {
                    return e[valueName]
                }
            }
            return input
        },
        recursiveArray(list) {
            let source = [];
            list.forEach((el) => {
                source.push(el);
                if (el.children) {
                    let childList = this.recursiveArray(el.children);
                    source.push(...childList);
                }
            });
            return source;
        },
        // 已选标签条件修改
        tagClick(event, item, index) {
            this.resetSearchStatus()
            let element = this.$refs['tagCss' + index][0].$el
            let { selected } = element.dataset
            if (selected == 'false') {
                this.handleUnSelect(event)
                element.dataset.selected = 'true'
                element.classList.add('is-focus')
            } else if (selected == 'true') {
                Object.keys(this.curTag).forEach(key => {
                    this.curTag[key] = item[key] || ''
                })
                if (item.conditionLabel) {
                    this.curTag.condition = this.logRetrival.statics.conditionType.find(el => el.label == item.conditionLabel).value
                }
                this.curTag.key = item.prop
                element.classList.add('is-selected')
                // 日志类型字段
                if (item.prop == 'indexId') {
                    this.step = 4
                    this.$nextTick(() => this.$emit('update:popperVisible', true))
                    return
                }
                element.setAttribute('contenteditable', true)
                element.focus()
                let selection = window.getSelection()
                selection.collapse(element, 1)
                this.$emit('update:popperVisible', false)
            }
        },
        // 删除修改已选择的条件
        deleteSelectedTag(event, item, index) {
            let { key, value, conditionLabel } = this.curTag
            let element = this.$refs['tagCss' + index][0].$el
            let selection = window.getSelection()
            if (value) {
                this.item_child = this.logRetrival.keyword[0].conditions.filter(el => {
                    return el.fieldNote == key
                })[0]
                if (Object.keys(this.item_child).length) {
                    this.item_child.itemValue = this.item_child.itemValue instanceof Array ? [] :''
                }
                item.value = ''
                this.curTag.value = ''
                this.step = 3
            } else if (conditionLabel) {
                item.conditionLabel = ''
                this.curTag.condition = ''
                this.curTag.conditionLabel = ''
                this.step = 2
            }
            // 光标至于尾部
            selection.collapse(element, 1)
            this.$emit('update:popperVisible', true)
            event.preventDefault()
        },
        // 点击key，condition行时保存属性
        popperItemClick(event) {
            let target = event.target
            if (target.dataset.key) {
                this.curTag.key = target.dataset.key
                this.curTag.label = target.dataset.label
                this.searchVal += target.dataset.label
                this.item_child = this.logRetrival.keyword[0].conditions.filter(el => {
                    return el.fieldNote == this.curTag.key
                })[0]
                this.step = 2
                this.$refs.input.focus()
            } else if (target.dataset.condition) {
                this.curTag.condition = this.item_child.itemCondition = target.dataset.condition
                this.curTag.conditionLabel = this.item_child.conditionLabel = target.dataset.conditionLabel
                // 判断新增还是修改状态
                let ele = document.querySelector('.tagCss.is-focus') || document.querySelector('.tagCss.is-selected')
                if (ele) {
                    // 修改
                    let label = ele.textContent.substring(0, ele.textContent.indexOf(':')).trim()
                    let item = this.logRetrival.selectedPolicyArray.find(el => el.label == label)
                    item.conditionLabel = target.dataset.conditionLabel
                    // 保存prop值，在修改时formChange步骤，直接修改，有问题
                    // this.curTag.key = item.prop
                    // this.curTag.label = item.label
                } else {
                    // 新增
                    this.searchVal += target.dataset.conditionLabel
                }
                this.step = 3
            }
        },
        // 事件分组
        eventGroupChange(val, selectedNode, selectedLeaf, item_child) {
            if (selectedNode) {
                if (this.selectedEventGroup.length != 0) {
                    this.$refs["eventGroupTree"][0].setChecked(
                        this.selectedEventGroup[0].dataId,
                        false
                    );
                    this.selectedEventGroup = [];
                    item_child.itemValue = [];
                }
                this.selectedEventGroup = [{ dataId: val.dataId, label: val.label }];
                item_child.itemValue = [val.dataId];                
                this.formChange(item_child.itemValue.join(","), item_child);
            }
        },
        // 表单字段值改变，增加/修改标签
        formChange(val, item) {
            Object.keys(item).forEach(key => {
                if(this.curTag[key]) item[key] = this.curTag[key]
            })
            // 判断新增还是修改状态
            let ele = document.querySelector('.tagCss.is-focus') || document.querySelector('.tagCss.is-selected')
            if (ele) {
                // 修改
                let label = ele.textContent.substring(0, ele.textContent.indexOf(':')).trim()
                let searchItem = this.logRetrival.keyword[0].conditions.find(el => el.fieldName == label)
                let findItem = this.logRetrival.selectedPolicyArray.find(el => el.label == label)
                findItem.value = val
                searchItem.conditionLabel = item.conditionLabel
                searchItem.itemCondition = item.itemCondition
                searchItem.itemValue = item.itemValue
                
                ele.classList.remove('is-focus', 'is-selected')
                ele.dataset.selected = 'false'
            } else {
                // 新增
                this.logRetrival.conditionKeywordInput(val, item)
                this.searchVal = ''
            }
            this.item_child = {}
            this.$emit('update:popperVisible', false)
            this.$nextTick(() => {
                this.step = 1
                this.$emit('update:popperVisible', true)
            })
        },
        // 删除新增的查询条件
        deleteTagInfo(event) {
            let { key, label, condition, conditionLabel } = this.curTag
            if (condition) {
                this.curTag.condition = ''
                this.curTag.conditionLabel = ''
                this.searchVal = this.searchVal.replace(conditionLabel, '')
                this.step = 2
            } else if (key) {
                this.curTag.key = ''
                this.curTag.label = ''
                this.searchVal = this.searchVal.replace(label, '')
                this.step = 1
            }
            if (condition || key) {
                event.preventDefault()
            }
            this.$nextTick(() => {
                this.$emit('update:popperVisible', true)
            })
        }
    }
}
</script>

<style lang="scss" scoped>
    .searchBox {
        width: 254px;
        height: 34px;
        overflow: hidden;
        border: 1px solid #CDCDCD;
        background-color: #fff;
        padding-right: 10px;
        display: flex;
        position: absolute;
        right: 160px;
        z-index: 11;
        .tag__point {
            position: absolute;
            top: 50%;
            right: 20%;
            transform: translateY(-50%);
            cursor: pointer;
            &__item {
                display: inline-block;
                vertical-align: middle;
                width: 4px;
                height: 4px;
                border-radius: 4px;
                background: #ffffff;
                font-style: normal;
                &:not(:first-child) {
                    margin-left: 4px;
                }
            }
        }
        .tagCss {
            &.is-selected {
                background-color: #ffffff;
                color: #000000;
                height: auto;
                & .tagCss--text {
                    overflow: visible;
                    white-space: pre-wrap;
                }
                ::v-deep .el-tag__close {
                    display: none;
                }
            }
            &.is-focus {
                border-color: #006EFF;
            }
        }
        &.is-focus {
            border-color: #006EFF;
            height: auto;
            overflow: visible;
        }
        &--placeholder {
            font-size: 12px;
            font-weight: 400;
            color: #BFBFBF;
        }
        &__left {
            flex: 1;
            & > div {
                float: left;
            }
            .filter__condition {
                overflow: hidden;
                .tagCss {
                    margin: 4px 6px;
                    max-width: 200px;
                    &--text {
                        max-width: 150px;
                        display: inline-block;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }
                    ::v-deep .el-tag__close {
                        transform: scale(.8) translateY(-50%);
                    }
                }
            }
            
            ::v-deep .el-input {
                width: 150px;
                input {
                    border: none;
                    background: #fff;
                    cursor: default;
                }
            }
        }
        &__right {
            padding-top: 4px;
            i {
                font-size: 12px;
                color: #888888;
                cursor: pointer;
            }
        }
    }
</style>

<style lang="scss">
    .searchBox__popper {
        .el-scrollbar {
            height: 100%;
        }
        .scroll__box {
            min-width: 150px;
            height: 250px;
            overflow: hidden;
            display: inline-block;
        }
        .step__box {
            font-size: 12px;
            font-weight: 400;
            & > div {
                margin-bottom: 10px;
            }
        }
        .step__header {
            cursor: pointer;
            color: #579BFA;
        }
        .step__item {
            color: #000000;
            cursor: pointer;
            &:hover {
                color: #579BFA;
            }
        }
    }
</style>