<template>
  <view class="custom-picker-overlay" v-if="visible" @tap="handleOverlayTap">
    <view class="custom-picker-container" @tap.stop="">
      <!-- 头部 -->
      <view class="picker-header">
        <view class="picker-cancel" @tap="handleCancel">取消</view>
        <view class="picker-title">{{ title || '请选择' }}</view>
        <view class="picker-confirm" @tap="handleConfirm">确定</view>
      </view>

      <!-- 搜索框 -->
      <view class="search-container" v-if="searchable">
        <view class="search-box">
          <text class="iconfont icon-sousuo search-icon"></text>
          <input class="search-input" v-model="searchValue" placeholder="搜索..." placeholder-class="search-placeholder"
            @input="handleSearch" />
          <text class="clear-icon" v-if="searchValue" @tap="clearSearch">×</text>
        </view>
      </view>

      <!-- 选项列表 -->
      <scroll-view class="options-container" scroll-y="true">
        <view class="options-list">
          <view class="option-item" v-for="(item, index) in filteredOptions" :key="index"
            :class="{ 'selected': isSelected(item) }" @tap="handleSelect(item, index)">
            <view class="option-content">
              <view class="option-text" v-html="highlightText(getDisplayText(item))"></view>
              <view class="option-check" v-if="isSelected(item)">✓</view>
            </view>
          </view>

          <!-- 无数据提示 -->
          <view class="no-data" v-if="filteredOptions.length === 0">
            <text>{{ searchValue ? '暂无匹配数据' : '暂无数据' }}</text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
  export default {
    name: 'CustomPicker',
    props: {
      // 是否显示选择器
      visible: {
        type: Boolean,
        default: false
      },
      // 选择器标题
      title: {
        type: String,
        default: '请选择'
      },
      // 选项数据
      options: {
        type: Array,
        default: () => []
      },
      // 显示字段名
      displayKey: {
        type: String,
        default: 'label'
      },
      // 值字段名
      valueKey: {
        type: String,
        default: 'value'
      },
      // 当前选中值
      value: {
        type: [String, Number, Object],
        default: ''
      },
      // 是否可搜索
      searchable: {
        type: Boolean,
        default: true
      },
      // 是否多选
      multiple: {
        type: Boolean,
        default: false
      },
      // 自定义过滤函数
      filterMethod: {
        type: Function,
        default: null
      }
    },

    data() {
      return {
        searchValue: '', // 搜索关键词
        selectedValue: null, // 当前选中值
        selectedValues: [] // 多选时的选中值数组
      }
    },

    computed: {
      // 过滤后的选项
      filteredOptions() {
        if (!this.searchValue) {
          return this.options
        }

        // 使用自定义过滤方法
        if (this.filterMethod) {
          return this.options.filter(item => this.filterMethod(this.searchValue, item))
        }

        // 默认过滤逻辑
        const keyword = this.searchValue.toLowerCase()
        return this.options.filter(item => {
          const text = this.getDisplayText(item).toLowerCase()
          return text.includes(keyword)
        })
      }
    },

    watch: {
      visible(newVal) {
        if (newVal) {
          this.initSelectedValue()
        } else {
          this.searchValue = ''
        }
      },

      value: {
        handler(newVal) {
          this.initSelectedValue()
        },
        immediate: true
      }
    },

    methods: {
      // 初始化选中值
      initSelectedValue() {
        if (this.multiple) {
          //  debugger
          this.selectedValues = Array.isArray(this.value) ? [...this.value] : []
        } else {
          this.selectedValue = this.value
        }
      },

      // 获取显示文本
      getDisplayText(item) {
        if (typeof item === 'string') {
          return item
        }
        return item[this.displayKey] || item.label || item.name || String(item)
      },



      // 获取项目值
      getItemValue(item) {
        if (typeof item === 'string' || typeof item === 'number') {
          return item
        }
        return item[this.valueKey] || item.value || item
      },

      // 判断是否选中
      isSelected(item) {
        const itemValue = this.getItemValue(item)
        if (this.multiple) {
          return this.selectedValues.some(val => {
            const compareValue = this.getItemValue(val)
            return compareValue === itemValue
          })
        } else {
          const compareValue = this.getItemValue(this.selectedValue)
          return compareValue === itemValue
        }
      },

      // 处理选择
      handleSelect(item, index) {
        if (this.multiple) {
          const itemValue = this.getItemValue(item)
          const existIndex = this.selectedValues.findIndex(val => {
            const compareValue = this.getItemValue(val)
            return compareValue === itemValue
          })

          if (existIndex > -1) {
            // 取消选择
            this.selectedValues.splice(existIndex, 1)
          } else {
            // 添加选择
            this.selectedValues.push(item)
          }
        } else {
          this.selectedValue = item
          // 单选模式下，选择后自动确认
          this.$nextTick(() => {
            this.handleConfirm()
          })
        }
      },

      // 搜索处理
      handleSearch(e) {
        this.searchValue = e.detail.value
      },

      // 清空搜索
      clearSearch() {
        this.searchValue = ''
      },

      // 高亮搜索关键词
      highlightText(text) {
        if (!this.searchValue) {
          return text
        }
        const keyword = this.searchValue
        const regex = new RegExp(`(${keyword})`, 'gi')
        return text.replace(regex, '<span class="highlight">$1</span>')
      },

      // 确认选择
      handleConfirm() {
        //debugger
        let result
        if (this.multiple) {
          result = {
            selectedItems: [...this.selectedValues],
            selectedValues: this.selectedValues.map(item => this.getItemValue(item))
          }
        } else {
          result = {
            selectedItem: this.selectedValue,
            selectedValue: this.getItemValue(this.selectedValue),
            selectedIndex: this.options.findIndex(option => {
              return this.getItemValue(option) === this.getItemValue(this.selectedValue)
            })
          }
        }

        this.$emit('confirm', result)
        this.$emit('change', result)
        this.hide()
      },

      // 取消选择
      handleCancel() {
        this.$emit('cancel')
        this.hide()
      },

      // 隐藏选择器
      hide() {
        this.$emit('update:visible', false)
      },

      // 处理遮罩点击
      handleOverlayTap() {
        this.handleCancel()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .custom-picker-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 99999;
    display: flex;
    align-items: flex-end;
  }

  .custom-picker-container {
    width: 100%;
    max-height: 80vh;
    background-color: #fff;
    border-radius: 24rpx 24rpx 0 0;
    display: flex;
    flex-direction: column;
  }

  .picker-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;

    .picker-cancel {
      font-size: 32rpx;
      color: #999;
    }

    .picker-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }

    .picker-confirm {
      font-size: 32rpx;
      color: #12b792;
      font-weight: 600;
    }
  }

  .search-container {
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #f5f5f5;
  }

  .search-box {
    position: relative;
    display: flex;
    align-items: center;
    background-color: #f8f8f8;
    border-radius: 24rpx;
    padding: 0 30rpx;
    height: 72rpx;

    .search-icon {
      font-size: 28rpx;
      color: #999;
      margin-right: 20rpx;
    }

    .search-input {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      height: 100%;
    }

    .search-placeholder {
      color: #999;
      font-size: 28rpx;
    }

    .clear-icon {
      font-size: 36rpx;
      color: #ccc;
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      background-color: #ddd;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 20rpx;
    }
  }

  .options-container {
    flex: 1;
    max-height: 600rpx;
  }

  .options-list {
    padding: 0 30rpx;
  }

  .option-item {
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    &.selected {
      .option-content {
        .option-text {
          color: #12b792;
        }

        .option-check {
          color: #12b792;
        }
      }
    }
  }

  .option-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .option-text {
    font-size: 28rpx;
    color: #333;
    flex: 1;

    :deep(.highlight) {
      background-color: #fff2e8;
      color: #ff6b35;
      font-weight: 600;
    }
  }

  .option-check {
    font-size: 32rpx;
    font-weight: 600;
    margin-left: 20rpx;
  }

  .no-data {
    padding: 100rpx 0;
    text-align: center;

    text {
      font-size: 28rpx;
      color: #999;
    }
  }

  // 动画效果
  .custom-picker-container {
    animation: slideUp 0.3s ease-out;
  }

  @keyframes slideUp {
    from {
      transform: translateY(100%);
    }

    to {
      transform: translateY(0);
    }
  }
</style>