<template>
    <div :class="bem({focus: focus, light})">
        <Popover
            :visible.sync="visableOptions"
            trigger="click"
            :arrow="false"
            :popoverClass="bem('options')"
        >
            <GdInput
                :class="bem('input')"
                @keypress.enter="search"
                @keydown.esc="closeOptions"
                @compositionstart="flag = true"
                @compositionend="flag = false"
                @keydown.down.up="changeSelectSuggest"
                @input="onInput"
                @blur="onBlur"
                placeholder="搜索海量模板"
                @focus="onFocue"
                :value="value"
                ref="searchInput"
            >
                <Icon name="search" slot="append" @click.native="onClickIcon"/>
            </GdInput>
            <template slot="content">
                <div @click.stop>
                    <p  v-if="!!hotsData.length" :class="bem('title')">热搜</p>

                    <ul
                        v-if="!!hotsData.length"
                        @mouseleave="hotIndex = null"
                    >
                        <li
                            v-for="(item, i) in hotsData"
                            @mousemove="hotIndex = i"
                            @click="() => selectOption(item, 'hot')"
                            :class="bem('option', { active: i === hotIndex })"
                            :key="item">
                            <b v-html="keywordLight(item)"/>
                            <span :class="bem('hot-icon')" v-if="i < 3"/>
                        </li>
                    </ul>

                    <div
                        v-if="!!historys.length"
                        :class="bem('title')">
                        <p>历史记录</p>
                        <p
                            :class="bem('clear-history')"
                            @click.stop="clearHistory"
                        >清空</p>
                    </div>
                    <ul
                        v-if="!!historys.length"
                        :class="bem('historys')"
                        @mouseleave="historyIndex = null"
                    >
                        <li
                            v-for="(item, i) in historys"
                            @mousemove="historyIndex = i"
                            @click="() => selectOption(item, 'history')"
                            :class="bem('option', { active: i === historyIndex })"
                            :key="item.timestamp">
                            <b v-html="item.search_word"/>
                            <span :class="bem('del-btn')" v-if="i === historyIndex" @click.stop="delHistory(item)"/>
                        </li>
                    </ul>
                </div>

                <!-- <ul
                    @mouseleave="otpionIndex = null"
                    v-show="options.length"
                >
                    <li
                        v-for="(item, i) in options"
                        @mouseenter="otpionIndex = i"
                        :class="bem('option', { active: i === otpionIndex })"
                        @click="() => selectOption(item)"
                        :key="item">
                        <b v-html="keywordLight(item)"/>
                    </li>
                </ul> -->
                <div style="width: 100%;"/>
            </template>
        </Popover>
    </div>
</template>

<script>
import Popover from '../Popover';
import Input from '../Input';
import Icon from '../Icon';
import { createComponentName, componentMixin } from '../_utils/component.js';


export default {
    name: createComponentName('header-search'),
    components: {
        Popover,
        Icon,
        GdInput: Input,
    },
    mixins: [componentMixin],
    props: {
        options: {
            type: Array,
            default() {
                return [];
            }
        },
        light: {
            type: Boolean,
            default: false,
        },
        value: {
            type: [String, Number],
            required: true
        },
        searchHistory: {
            type: Array,
            default() {
                return [];
            }
        },
        hots: {
            type: Array,
            default() {
                return [];
            }
        }
    },
    data() {
        return {
            focus: false,
            otpionIndex: null,
            hotIndex: null,
            historyIndex: null,
            // 判断是否在输入法中输入状态
            flag: false,
            minWidth: 200,
            visableOptions: false,
            // hots: ['四川凉山森林大火', '做自己的锦鲤', '防忽悠指南', '整人方式合辑', '整人方式'],
            // searchHistory: ['公众号运营', '愚人节', '清明节思念', '童装换季促销', '公众号首图'],
        };
    },
    computed: {
        historys() {
            const unique = (arr) => {
                const res = new Map();
                return arr.filter((a) => !res.has(a.search_word) && res.set(a.search_word, 1));
            };
            return unique(this.searchHistory).filter((item, index) => index < 5).filter(item => item.search_word !== '');
        },
        hotsData() {
            return this.hots.filter((hot, index) => index < 5);
        },
    },
    methods: {
        delHistory(item) {
            this.$emit('del-history', item);
        },
        // 清除历史记录
        clearHistory() {
            this.$emit('clear-history');
        },

        keywordLight(label) {
            const keyword = this.value;
            const rStr = new RegExp(keyword, 'g');
            let html = label;
            if (keyword !== '' && label) {
                html = label.replace(rStr, text => `<span class="gd-header-search__keyword">${text}</span>`);
            }
            return html;
        },
        search() {
            if (this.otpionIndex !== null) {
                this.$emit('input', this.options[this.otpionIndex]);
            }
            else {
                this.$emit('input', this.value);
            }
            this.closeOptions();
            this.$emit('search', this.value);
        },
        onClickIcon() {
            this.closeOptions();
            this.$emit('search', this.value);
        },
        onInput(value) {
            if (value === this.value) return;
            this.visableOptions = false;
            // 用户清除 value 历史记录弹出
            if (value === '') this.visableOptions = true;
            this.$emit('input', value);
        },
        selectOption(key, type = 'select') {
            let emitKey;
            if (type === 'history') {
                emitKey = key.search_word;
            }
            else {
                emitKey = key;
            }
            this.closeOptions();
            this.$emit('input', emitKey);
            this.$emit('search', this.value);
        },
        onFocue() {
            this.focus = true;
            const searchInput = this.$refs.searchInput.$el;
            searchInput.style.border = '1px solid #005CF9';
            this.$emit('focus');
        },
        onBlur() {
            this.focus = false;
            const searchInput = this.$refs.searchInput.$el;
            searchInput.style.border = '1px solid #cccccc';
            this.$emit('blur');
        },
        changeSelectSuggest(e) {
            e.preventDefault();
            if (this.flag) return;
            let index = this.otpionIndex;

            if (index === null) {
                index = e.keyCode === 40 ? 0 : this.options.length - 1;
                this.otpionIndex = index;
                return;
            }

            index += e.keyCode === 40 ? 1 : -1;

            if (index < 0) {
                this.otpionIndex = this.options.length - 1;
            }
            else if (index === this.options.length) {
                this.otpionIndex = 0;
            }
            else {
                this.otpionIndex = index;
            }
        },
        closeOptions() {
            this.otpionIndex = null;
            this.visableOptions = false;
        },
    }
};
</script>

<style lang="less">

@import '../_styles/base.less';

@b: gd-header-search;

.@{b} {

    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    position: relative;


    &__content {
        margin: auto;
        margin-top: 22px;
    }

    & &__input {
        width: 260px;
        height: 36px;
        border-radius: 4px;
        background:#fff;
        color: #000;
        border: solid 1px #cccccc;
        outline: 0;
    }

    .@{icon} {
        cursor: pointer;
        color: #999999;
        font-size: 16px;
    }
}

    .@{b}__options {
        overflow-y: auto;
        margin-top: 2px;
        width: 260px;
    }

    ul {
        list-style: none;
        margin: 4px 0;
        padding: 0;
        b {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            width: 120px;
            font-weight: 400;
        }
    }

    li {
        cursor: pointer;
        list-style: none;

    }

    .@{b}__option {
        line-height: 38px;
        padding: 0 20px;
        font-size: 14px;
        color: #000;
        cursor: pointer;
        font-weight: bold;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;

        &--active {
            color: #000;
            background: #F0F3F4;
        }
    }

    .@{b}__keyword {
        font-weight: normal;
    }

    .@{b}__title {
        height: 41px;
        border-bottom: 1px solid #eee;
        padding: 0 20px;
        color: #999;
        font-size: 12px;
        line-height: 48px;
        margin: 0;
        display: flex;
        justify-content: space-between;
        p {
            margin: 0;
            height: 41px;
            display: inline-block;
        }
    }

    .@{b}__clear-history {
        cursor: pointer;
        &:hover {
            color: #000;
        }
    }

    .@{b}__historys {
        .@{b}__option {
            display: flex;
            justify-content: space-between;
            padding-right: 0px;
            span {
                font-weight: 400;
            }
        }
        .@{b}__del-btn {
            padding: 10px 20px;
            background: none;
            border: 0;
            box-sizing: border-box;
            height: 38px;

            &::before{
                content: "";
                display: inline-block;
                background: svg-load('../../assets/icons/close.svg', fill=#000);
                background-size: contain;
                margin: -22px 5px 0 0;
                height: 16px;
                width: 16px;
                vertical-align: middle;
            }
        }
    }
    .@{b}__hot-icon {
        background: none;
        border: 0;
        box-sizing: border-box;
        height: 38px;

        &::before{
            content: "";
            display: inline-block;
            background: svg-load('../../assets/icons/fir.svg', fill=#FF4343);
            background-size: contain;
            margin: 1px 5px 5px 2px;
            height: 14px;
            width: 14px;
            vertical-align: middle;
        }
    }



</style>
