<template>
  <div class="user-autocomplete">
    <el-select v-model="searchType" style="width: 120px">
      <el-option label="用户名" value="username"></el-option>
      <el-option label="手机号" value="mobile"></el-option>
      <el-option label="邮箱" value="email"></el-option>
      <el-option label="昵称" value="nickname"></el-option>
    </el-select>
    <el-select
      placeholder="搜索"
      filterable
      remote
      style="width: 100%"
      :remote-method="fetchUserList"
      :loading="loading"
      @change="handleChange"
      clearable
      v-bind="$attrs"
      v-on="$listeners"
    >
      <el-option :label="user.realname || user.nickname" :value="user.id" v-for="user in userList" :key="user.id">
        <div style="display: flex">
          <span>
            {{ user.realname || user.nickname }}
            <template v-if="user.mobile">(手机号：{{ user.mobile }})</template>
          </span>
          <span class="t1" v-if="user.email">邮箱：{{ user.email }}</span>
          <span class="t1" v-else>ID：{{ user.id }}</span>
        </div>
      </el-option>
    </el-select>
  </div>
</template>

<script>
import { userSearch } from '@/api/base'

export default {
  data() {
    return {
      searchType: 'nickname',
      userList: [],
      loading: false
    }
  },
  methods: {
    fetchUserList(searchValue) {
      const params = {}
      params[this.searchType] = searchValue
      this.loading = true
      userSearch(params)
        .then(response => {
          this.userList = response.data.items
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleChange(userId) {
      const user = this.userList.find(user => user.id === userId)
      this.$emit('change', userId, user)
    }
  }
}
</script>

<style lang="scss">
.user-autocomplete {
  display: flex;
  .el-select + .el-select {
    margin-left: 10px;
  }
  .t1 {
    color: #8492a6;
    font-size: 13px;
    margin: 0 20px 0 10px;
  }
}
</style>
