<template>
    <span :class="classes" @click="handleClick">
        <span v-if="value && value.length" :style="headStyle">
            <Scroller>
                <span ref="tagContent" :class="id">
                    <Tag 
                        v-for="(item, index) in value"
                        :key="index"
                        :size="size"
                        :closeable="clearable"
                        v-model="item.value"
                        @on-delete="handleRemove">
                        {{item.showValue != undefined ? item.showValue : item.label}}
                    </Tag>
                </span>
            </Scroller>
        </span>
        <span 
            v-if="!(value && value.length) && !filterable"
            :class="`${prefixCls}-placeholder`">
            {{placeholder}}
        </span>
        <input 
            v-if="filterable"
            type="text"
            v-model="query"
            ref="input"
            autocomplete="off"
            spellcheck="false"
            :disabled="disabled"
            :readonly="readonly"
            :placeholder="!(value && value.length) ? placeholder : ''"
            @keydown.delete="handleInputDelete"/>
        <span v-if="!showSlotSuffix" :class="`${prefixCls}-icon`">
            <Icon type="arrow-up" v-if="visible"/>
            <Icon type="arrow-down" v-else/>
        </span>
        <span v-else :class="`${prefixCls}-icon`">
            <slot name="suffix"></slot>
        </span>
    </span>
</template>
<script>
    import Input from '../input/'
    import Icon from '../icon/'
    import Tag from '../tag/'
    import Scroller from '../scroller'
    import Emitter from '../../../mixins/emitter'
    import { findComponentUpward, oneOf } from '../../../utils/assist'
    import Sortable from 'sortablejs'

    const now = Date.now()
    let seed = 0
    function getUuid () {
        return 'sortable_' + now + (seed++)
    }
    const prefixCls = 'yy-select-selection'
    export default {
        name: 'YYSelectHead',
        mixins: [ Emitter ],
        components: {
            Input,
            Icon,
            Tag,
            Scroller
        },
        props: {
            value: {
                type: String | Number | Array,
                default: []
            },
            size: {
                validator(value) {
                    return oneOf(value, ['small', 'large'])
                }
            },
            disabled: {
                type: Boolean,
                default: false
            },
            readonly: {
                type: Boolean,
                default: false
            },
            isFocused: {
                type: Boolean,
                default: false
            },
            clearable: {
                type: Boolean,
                default: false
            },
            filterable: {
                type: Boolean,
                default: false
            },
            placeholder: {
                type: String
            },
            maxHeight: Number
        },
        data() {
            return {
                prefixCls: prefixCls,
                query: '',
                showSlotSuffix: false,
                headStyle: {}
            }
        },
        computed: {
            classes() {
                return [
                    prefixCls,
                    {
                        [`${prefixCls}-disabled`]: this.disabled,
                        [`${prefixCls}-readonly`]: this.readonly,
                        [`${prefixCls}-focus`]: this.isFocused,
                    }
                ]
            },
            id() {
                return [
                    getUuid()
                ]
            },
            visible() {
                return findComponentUpward(this, 'YYSelect').dropVisible
            }
        },
        watch: {
            query (value) {
                if (value !== null) {
                    this.$emit('on-search', value)
                }
            },
            value () {
                // console.log(this.value, 'test')
                this.query = null
                this.headStyle = {}
                if (this.maxHeight) {
                    let tagContentHeight
                    if (this.$refs.tagContent) tagContentHeight = this.$refs.tagContent.offsetHeight
                    if (tagContentHeight > this.maxHeight) {
                        this.headStyle =  { height: this.maxHeight + 'px' }
                    }
                }
            }
        },
        methods: {
            handleClick(event) {
                if(this.disabled || this.readonly) return
                this.$emit('click')
                if (this.filterable && event.target === this.$el){
                    this.$refs.input.focus()
                }
            },
            handleRemove(value) {
                if(this.disabled || this.readonly) return
                this.dispatch('YYSelect', 'on-select-selected', {
                    value
                })
            },
            handleInputDelete () {
                if (this.value.length && this.query === '') {
                    this.handleRemove(this.value[this.value.length - 1].value)
                }
            },
            sortable() {
                this.$nextTick().then(()=>{
                    const wrapper = document.querySelector(`.${this.id}`)
                    const handle = `.${this.id} .yy-tag`
                    if(wrapper && handle) {
                        Sortable.create(wrapper, {
                            group: {
                                name: this.id,
                                pull: false,
                                put: true
                            },
                            handle: handle,
                            onUpdate:  (evt) => {
                                this.handleDragUpdate(evt)
                            },
                            animation: 150
                        })
                    }
                })
            },
            removeNode(node) { // 移除节点
                node.parentElement.removeChild(node)
            },
            insertNodeAt(fatherNode, node, position) { // 插入节点
                let refNode = position === 0 ? fatherNode.children[0] : fatherNode.children[position - 1].nextSibling
                fatherNode.insertBefore(node, refNode)
            },
            handleDragUpdate(evt, key) { // 更新数据的时候
                this.removeNode(evt.item)
                this.insertNodeAt(evt.from, evt.item, evt.oldIndex)
                this.$emit('on-change', evt.newIndex, evt.oldIndex)
            }
        },
        mounted() {
            this.showSlotSuffix = !!this.$slots.suffix
        }
    }
</script>
