<template>
  <view class="project-select-container">
    <!-- 搜索输入框 -->
    <input
      v-model="searchKeyword"
      :placeholder="`搜索项目名称、编码或编号...`"
      class="search-input"
      clearable
    />
    
    <!-- 选择器组件 -->
    <uni-data-select
      v-model="innerValue"
      :localdata="filteredOptions"
      :placeholder="placeholder"
      :clear="clear"
      :filterable="false" 
      @change="onChange"
    />
  </view>
</template>

<script>
import { listProject } from '@/api/oa/project'

export default {
  name: 'OaProjectSelect',
  props: {
    value: [String, Number],
    placeholder: {
      type: String,
      default: '请选择项目'
    },
    clear: {
      type: Boolean,
      default: true
    },
    filterable: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      allProjects: [],  // 存储所有项目原始数据
      innerValue: this.value,
      searchKeyword: ''  // 搜索关键词
    }
  },
  computed: {
    // 根据搜索关键词过滤项目
    filteredOptions() {
      if (!this.searchKeyword) {
        // 如果没有搜索关键词，返回所有项目
        return this.allProjects.map(item => ({
          text: item.projectName,
          value: item.projectId
        }))
      }
      
      // 转换关键词为小写，方便不区分大小写搜索
      const keyword = this.searchKeyword.toLowerCase()
      
      // 过滤出匹配的项目
      return this.allProjects
        .filter(item => {
          // 检查项目名称、编码、编号是否包含关键词
          const matchesName = item.projectName?.toLowerCase().includes(keyword)
          const matchesCode = item.projectCode?.toLowerCase().includes(keyword)
          const matchesNum = item.projectNum?.toString().toLowerCase().includes(keyword)
          
          return matchesName || matchesCode || matchesNum
        })
        .map(item => ({
          text: item.projectName,
          value: item.projectId
        }))
    }
  },
  watch: {
    value(val) {
      this.innerValue = val
    },
    innerValue(val) {
      this.$emit('input', val)
      this.$emit('update:value', val)
      this.$emit('change', val)
    }
  },
  mounted() {
    this.getProjectOptions()
  },
  methods: {
    // 获取所有项目数据
    getProjectOptions() {
      listProject().then(res => {
        // 保存原始数据，用于搜索过滤
        this.allProjects = res.rows || []
      })
    },
    onChange(val) {
      this.innerValue = val
    }
  }
}
</script>

<style scoped>
.project-select-container {
  width: 100%;
}

.search-input {
  width: 100%;
  padding: 8px 12px;
  margin-bottom: 8px;
  border: 1px solid #eee;
  border-radius: 4px;
  font-size: 14px;
}
</style>
