<template>
  <view class="multi-select-dropdown">
    <!-- 触发按钮 -->
    <view class="dropdown-trigger" @click.stop="toggleDropdown">
      <slot name="trigger" :selectedItems="selectedItems">
        <text class="trigger-text">{{ displayText }}</text>
        <text class="iconfont icon-arrow-down" :class="{ 'rotate': isOpen }"></text>
      </slot>
    </view>
    
    <!-- 遮罩层 -->
    <view class="dropdown-mask" v-show="isOpen" @click.stop="closeDropdown"></view>
    
    <!-- 下拉内容 - 修改为底部弹出 -->
    <view class="dropdown-content bottom-popup" v-show="isOpen">
      <!-- 搜索框（可选） -->
      <view class="search-box" v-if="searchable">
        <input 
          class="search-input" 
          placeholder="搜索" 
          v-model="searchText"
          @input="handleSearch"
        />
      </view>
      
      <!-- 选项列表 -->
      <scroll-view scroll-y class="options-list">
        <view 
          class="option-item" 
          v-for="item in filteredOptions" 
          :key="item[valueKey]"
          @click.stop="toggleOption(item)"
        >
          <view class="checkbox" :class="{ 'checked': isSelected(item) }"></view>
          <text class="option-label">{{ item[labelKey] }}</text>
        </view>
      </scroll-view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
       <view class="button reset" @click.stop="closeDropdown">取消</view>
        <view class="button confirm" @click.stop="confirmSelection">确定</view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'MultiSelectDropdown',
  props: {
    // 选项列表
    options: {
      type: Array,
      default: () => []
    },
    // 已选中的值
    value: {
      type: Array,
      default: () => []
    },
    // 选项文本的key
    labelKey: {
      type: String,
      default: 'label'
    },
    // 选项值的key
    valueKey: {
      type: String,
      default: 'value'
    },
    // 占位文本
    placeholder: {
      type: String,
      default: '请选择'
    },
    // 是否可搜索
    searchable: {
      type: Boolean,
      default: false
    },
    // 最大选择数量
    maxSelect: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      isOpen: false,
      selectedItems: [...this.value],
      searchText: '',
      filteredOptions: []
    }
  },
  computed: {
    displayText() {
      if (this.selectedItems.length === 0) {
        return this.placeholder
      }
      
      if (this.selectedItems.length === this.options.length) {
        return '已选择全部'
      }
      
      // 显示选中的前2项，超过则显示数量
      const selectedLabels = this.options
        .filter(option => this.selectedItems.includes(option[this.valueKey]))
        .map(option => option[this.labelKey])
      
      if (selectedLabels.length <= 2) {
        return selectedLabels.join('、')
      } else {
        return `已选择${selectedLabels.length}项`
      }
    }
  },
  watch: {
    options: {
      immediate: true,
      handler(newVal) {
        this.filteredOptions = [...newVal]
      }
    },
    value(newVal) {
      this.selectedItems = [...newVal]
	  console.log('this.selectedItems',this.selectedItems);
    }
  },
  methods: {
    toggleDropdown() {
      if (this.isOpen) {
        this.closeDropdown()
      } else {
        this.openDropdown()
      }
    },
    openDropdown() {
      this.isOpen = true
	  this.selectedItems = [...this.value]
      // 禁止页面滚动
      document.body.style.overflow = 'hidden'
    },
    closeDropdown() {
	  console.log('this.selectedItems',this.selectedItems);
      this.isOpen = false
      this.searchText = ''
      this.filteredOptions = [...this.options]
	  // if(this.selectedItems.includes('-1')){
		 //  this.selectedItems = []
		 //  console.log(' this.selectedItems', this.selectedItems);
	  // }
      // 恢复页面滚动
      document.body.style.overflow = ''
    },
	toggleOption(item) {
	  const value = item[this.valueKey]
	  const index = this.selectedItems.indexOf(value)
	  
	  if (value === '-1') { // 处理"全部"选项
	    if (index === -1) {
	      // 选中全部
	      this.selectedItems = this.options.map(option => option[this.valueKey])
	    } else {
	      // 取消选中全部
	      this.selectedItems = []
	    }
	    return
	  }
	  
	  if (index === -1) {
	    // 检查是否超过最大选择数量
	    if (this.maxSelect && this.selectedItems.length >= this.maxSelect) {
	      uni.showToast({
	        title: `最多选择${this.maxSelect}项`,
	        icon: 'none'
	      })
	      return
	    }
	    this.selectedItems.push(value)
	    
	    // 如果选中了所有非"全部"选项，自动选中"全部"
	    const allNonAllOptions = this.options
	      .filter(option => option[this.valueKey] !== '-1')
	      .map(option => option[this.valueKey])
	    const allSelected = allNonAllOptions.every(val => this.selectedItems.includes(val))
	    if (allSelected && this.options.some(opt => opt[this.valueKey] === '-1')) {
	      this.selectedItems.push('-1')
	    }
	  } else {
	    this.selectedItems.splice(index, 1)
	    
	    // 如果取消选中了任意选项，确保取消选中"全部"
	    const allIndex = this.selectedItems.indexOf('-1')
	    if (allIndex !== -1) {
	      this.selectedItems.splice(allIndex, 1)
	    }
	  }
	},
   
	isSelected(item) {
	  if (item[this.valueKey] === '-1') {
	    // 对于"全部"选项，检查是否所有非"全部"选项都被选中
	    const allNonAllOptions = this.options
	      .filter(option => option[this.valueKey] !== '-1')
	      .map(option => option[this.valueKey])
	    return allNonAllOptions.length > 0 && 
	           allNonAllOptions.every(val => this.selectedItems.includes(val))
	  }
	  return this.selectedItems.includes(item[this.valueKey])
	},
    handleSearch() {
      if (!this.searchText) {
        this.filteredOptions = [...this.options]
        return
      }
      
      this.filteredOptions = this.options.filter(option => 
        option[this.labelKey].toLowerCase().includes(this.searchText.toLowerCase())
      )
    },
    resetSelection() {
      this.selectedItems = []
	  // this.closeDropdown()
    },
    confirmSelection() {
      this.$emit('input', [...this.selectedItems])
      this.$emit('change', [...this.selectedItems])
      this.closeDropdown()
    }
  }
}
</script>

<style lang="scss" scoped>
.multi-select-dropdown {
  position: relative;
  display: inline-block;
  
  .dropdown-trigger {
    display: flex;
    align-items: center;
    padding: 0 20rpx;
    height: 60rpx;
    border-radius: 8rpx;
    box-sizing: border-box;
    
    .trigger-text {
      font-size: 28rpx;
      color: #333;
      margin-right: 10rpx;
      max-width: 200rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .icon-arrow-down {
      font-size: 24rpx;
      color: #666;
      transition: transform 0.3s;
      
      &.rotate {
        transform: rotate(180deg);
      }
    }
  }
  
  .dropdown-content {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #fff;
    border-radius: 16rpx 16rpx 0 0;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
    z-index: 110;
    transform: translateY(100%);
    transition: transform 0.3s ease;
    
    &.bottom-popup {
      transform: translateY(0);
    }
    
    .search-box {
      padding: 20rpx;
      border-bottom: 1rpx solid #eee;
      
      .search-input {
        width: 100%;
        height: 60rpx;
        padding: 0 20rpx;
        background-color: #f5f5f5;
        border-radius: 8rpx;
        font-size: 26rpx;
      }
    }
    
    .options-list {
      max-height: 60vh;
      padding: 10rpx 0;
      
      .option-item {
        display: flex;
        align-items: center;
        padding: 20rpx;
        
        &:active {
          background-color: #f5f5f5;
        }
        
        .checkbox {
          width: 30rpx;
          height: 30rpx;
          border: 2rpx solid #ccc;
          border-radius: 4rpx;
          margin-right: 15rpx;
          position: relative;
          
          &.checked {
            background-color: #2A36AD;
            border-color: #2A36AD;
            
            &::after {
              content: '';
              position: absolute;
              left: 8rpx;
              top: 3rpx;
              width: 12rpx;
              height: 18rpx;
              border: solid white;
              border-width: 0 2rpx 2rpx 0;
              transform: rotate(45deg);
            }
          }
        }
        
        .option-label {
          font-size: 28rpx;
          color: #333;
        }
      }
    }
    
    .action-buttons {
      display: flex;
      justify-content: space-between;
      padding: 20rpx;
      border-top: 1rpx solid #eee;
      
      .button {
        width: 30%;
        height: 60rpx;
        line-height: 60rpx;
        text-align: center;
        border-radius: 60rpx;
        font-size: 28rpx;
        padding: 20rpx ;
        &.reset {
          // margin-right: 20rpx;
          color: #666;
		  border: 1rpx solid #666;
        }
        
        &.confirm {
          background-color: #2A36AD;
          color: #fff;
        }
      }
    }
  }
  
  .dropdown-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 100;
  }
}
</style>