<template>
  <el-select
    v-model="selectedValue"
    :multiple="multiple"
    filterable
    remote
    :remote-method="handleSearch"
    :loading="loading"
    :placeholder="placeholder"
    style="width: 100%"
    @change="handleChange"
    :clearable="clearable"
  >
    <el-option
      v-for="user in filteredUsers"
      :key="user.userId"
      :label="`${user.nickName}（${user.dept && user.dept.deptName ? user.dept.deptName : '无部门'}）`"
      :value="user.userId"
    >
      <span>{{ user.nickName }}</span>
      <span style="color: #999; font-size: 12px; margin-left: 8px;">{{ user.dept && user.dept.deptName ? user.dept.deptName : '无部门' }}</span>
    </el-option>
  </el-select>
</template>

<script>
import { selectUser } from '@/api/system/user'

export default {
  name: 'UserSelect',
  props: {
    value: {
      type: [String, Number, Array],
      default: null
    },
    multiple: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请选择用户'
    },
    clearable: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      userList: [],
      loading: false,
      searchKeyword: '',
      filteredUsers: []
    }
  },
  computed: {
    selectedValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
        this.$emit('change', val)
      }
    }
  },
  watch: {
    searchKeyword(val) {
      this.filterUsers(val)
    }
  },
  created() {
    this.fetchUsers()
  },
  methods: {
    fetchUsers() {
      this.loading = true
      selectUser({}).then(res => {
        this.userList = res.data || res.rows || []
        this.filteredUsers = this.userList
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleSearch(query) {
      this.searchKeyword = query
    },
    filterUsers(keyword) {
      if (!keyword) {
        this.filteredUsers = this.userList
      } else {
        const lower = keyword.toLowerCase()
        this.filteredUsers = this.userList.filter(user => {
          return (
            (user.nickName && user.nickName.toLowerCase().includes(lower)) ||
            (user.dept && user.dept.deptName && user.dept.deptName.toLowerCase().includes(lower))
          )
        })
      }
    },
    handleChange(val) {
      this.$emit('input', val)
      this.$emit('change', val)
    }
  }
}
</script>

<style scoped>
</style>
