<template>
    <div class="menuInRow">
        <template v-if="showData.length>0">
            <div class="showMenu" v-menuInRow="getMenuNum">
                <div v-for="(item,index) in showData" :key="'show'+index" @click.prevent="clickDom(item,index,'show')" class="menuItem" :class="[index >= (surplusNum>0?num:num)?'display_none':'',currentClick == ('show'+index)?'color_red':'']">
                    <slot name="menuItem" v-if="data.length>0" :row="item">
                        <div v-html="item[prop.name]"></div>
                    </slot>
                    <div v-else v-html="getItemName(item,index,'show')"></div>
                </div>
            </div>
            <div v-if="surplusNum>0" class="hideMenu">
                <el-dropdown>
                    <span class="el-dropdown-link">
                        更多<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item v-for="(item,index) in hideData" :key="'hide'+index" :class="currentClick == ('hide'+index)?'color_red':''" @click.native.prevent="clickDom(item,index,'hide')">
                            <slot name="menuItem" v-if="data.length>0" :row="item">
                                <div v-html="item[prop.name]"></div>
                            </slot>
                            <div v-else v-html="getItemName(item,index,'hide')"></div>
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </template>
        <template v-if="data.length == 0">
            <div v-getChildData class="showMenu" v-showDom="'show'" style="display:none">
                <slot></slot>
            </div>
            <div v-if="surplusNum>0" class="hideMenu">
                <el-dropdown>
                    <span class="el-dropdown-link">
                        更多<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown" class="dropdownMenu" v-showDom="'hide'">
                        <slot></slot>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </template>
    </div>
</template>

<script>
async function menuInRowFun(el,binding,childNodes){
  el.style.whiteSpace = 'nowrap';
//   el.style.width = 'calc(100% - 60px)'
  var el_width = el.clientWidth
  
  var width = 0
  var num = 0
  var surplusNum = 0
  async function getElementWidthWithMargin(element) {
    const rect = await element.getBoundingClientRect();
    return rect.width;
  }
//   var widths = []
  for(var i = 0;i<childNodes.length;i++){
    let childWidth = await getElementWidthWithMargin(childNodes[i])
    // widths.push(childWidth)
    width += childWidth
    if(width >el_width){
      break;
    }
    num ++
  }
  surplusNum = childNodes.length - num
  binding.value(num,surplusNum)
//   el.style.width = width - widths[num-1] - 20 + 'px'
}
function uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random()*16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  }
function getMenuItem(el, binding,vnode){
    var that = vnode.context
    var childNodes = el.childNodes
    var data = []
    for(var i = 0;i<childNodes.length;i++){
        var child = childNodes[i]
        var display = child.style.display
        var name = child.getAttribute('name')
        if(name != 'menuInRowItem'){
            continue;
        }
        var value = child.getAttribute('value')
        var highlight = child.getAttribute('highlight')
        var key = child.getAttribute('key')
        if(!key){
            key = uuid(32)
            child.setAttribute('key',key)
        }
        var label = child.outerHTML
        data.push(
            {
                value:value,
                highlight:highlight,
                name:label,
                key:key
            }
        )
    }
    that.showData = data
    // binding.value(data)
}
export default {
    directives:{
        showDom:{
            bind(el, binding,vnode){
                
            },
        },
        getChildData:{
            bind(el, binding,vnode){
                getMenuItem(el, binding,vnode)
                // console.log(that.showData)
            },
            // componentUpdated(el, binding,vnode) {  
            //     getMenuItem(el, binding,vnode)
            // },
        },
        menuInRow:{
            bind(el, binding,vnode) {  
                var that = vnode.context
                var childNodes = el.childNodes
                that.$nextTick(()=>{
                    menuInRowFun(el, binding,childNodes)
                    window.addEventListener('resize',()=>{
                       that.$commonJS.debounce( menuInRowFun(el, binding,childNodes),1000)
                    })
                })
                
            },  
            // 如果需要，可以在更新时再次执行逻辑  
            // componentUpdated(el, binding,vnode) {  
            //     menuInRowFun(el, binding)
            // },  
            unbind(el) {
                var eventListener = window.eventListeners_
                if(!eventListener){
                return false
                }
                const listeners = eventListener.resize
                if(listeners){
                window.removeEventListener("resize");
                }
                
            },
        }
    },
  components: {},
  props: {
    data:{
        type:Array,
        default:()=>{
            return []
        }
    },
    prop:{
        type:String,
        default:'name'
    },
    value:{
        type:[Number,String],
        default:0
    }
  },
  data() {
    return {
        config:{
            num:0,
            surplusNum:0,
        },
        num:0,
        surplusNum:0,
        showData:this.data,
        hideData:[],
        currentClick:null
    };
  },
  watch: {},
  computed: {},
  created() {},
  mounted() {
  },
  methods: {
    getMenuNum(num,surplusNum){
        this.num=num||0,
        this.surplusNum=surplusNum||0
        // this.showData = this.getShowData()
        this.hideData = this.getHideData()
        if(!this.currentClick){
            var value = Number(this.value)
            if(value >= num){
                value = value - num
                this.currentClick = 'hide'+value
            }else{
                this.currentClick = 'show'+value
            }
        }
    },
    getShowData(){
        if(this.surplusNum==0){
            return this.data
        }else{
            return this.data.slice(0, this.num)
        }
    },
    getHideData(){
        if(this.surplusNum==0){
            return []
        }
        return this.showData.slice(-this.surplusNum)
    },
    clickDom(item,index,type){
        if(item.highlight){
            this.currentClick = type+index
        }
        
        if(this.data.length>0){
            this.$emit('click',item)
        }else{
            this.$emit('click',item.value)
        }
        
    },
    clickChild(e){
        this.$emit('click',e)
    },
    getItemName(item,index,type){
        var sign = type+index
        if(sign == this.currentClick){
            if(!item.clickName){
                var style = 'color: red;';
                item.clickName = this.addStyleToHtmlTags(item.name, style);
            }
            return item.clickName
        }
        return item.name
    },
    addStyleToHtmlTags(htmlString, styleString) {
        // 创建一个临时的容器元素
        var tempDiv = document.createElement('div');
        // 将HTML字符串设置为容器的innerHTML
        tempDiv.innerHTML = htmlString.trim();
    
        // 遍历容器中的所有元素
        Array.from(tempDiv.getElementsByTagName('*')).forEach(function(element) {
            // 如果元素已经有style属性，则添加新的样式到现有样式中
            if (element.style) {
                element.style.cssText += ';' + styleString;
            } else {
                // 否则，直接设置style属性
                element.setAttribute('style', styleString);
            }
        });
    
        // 返回修改后的HTML字符串（注意：这将不包含外部容器的标签）
        return tempDiv.innerHTML;
    }
  },
};
</script>
<style lang="scss" scoped>
.menuInRow{
    display:flex;
    align-items: center;
    width:calc(100% - 40px);
    padding:5px 20px;
    border-top:1px solid #e6e6e6;
    overflow:hidden;
    .showMenu{
        display:flex;
        align-items: center;
        width:calc(100% - 60px);
    }
    .menuItem{
        cursor: pointer;
        // margin:0 10px;
        padding:5px 10px;
        min-width:fit-content
    }
    .hideMenu{
        padding-left:10px;
        width:50px;
        min-width:50px;
        background:white;
        cursor: pointer;
    }
}
.display_none{
    opacity: 0;
    pointer-events: none;
}
.color_red>*,.color_red{
    color:red !important;
}
.dropdownMenu>*{
    width: 200px;
    min-width: 200px;
    line-height: 1em;
    padding: 5px 10px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow:ellipsis;
    border-bottom: 1px solid #e6e6e6;
    cursor: pointer;
    &:last-child{
        border-bottom:none;
    }
}
</style>