<template>
  <el-select
    v-model="selectedId"
    placeholder="请选择租户"
    clearable
    filterable
    remote
    reserve-keyword
    :remote-method="remoteSearch"
    :loading="loading"
    size="small"
    style="width: 220px"
    @change="handleChange"
  >
    <el-option
      v-for="item in tenantOptions"
      :key="item.id"
      :label="`[${item.tenantCode}] ${item.tenantName}`"
      :value="item.id"
    />
  </el-select>
</template>

<script>
import { tenantList } from '@/api/tenant/tenant'

export default {
  name: 'TenantSelect',
  props: {
    value: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      selectedId: this.value,
      tenantOptions: [],
      loading: false,
      searchTimer: null
    }
  },
  watch: {
    value(val) {
      this.selectedId = val
    }
  },
  mounted() {
    this.fetchList()
  },
  methods: {
    handleChange(val) {
      this.$emit('input', val)
      this.$emit('change', val)
    },
    remoteSearch(query) {
      if (this.searchTimer) clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.fetchList(query)
      }, 300)
    },
    fetchList(query) {
      this.loading = true
      const params = {}
      if (query) {
        params.tenantCode = query
        params.tenantName = query
      }
      tenantList(params)
        .then(res => {
          this.tenantOptions = res.data || res.rows || []
        })
        .catch(() => {
          this.tenantOptions = []
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>
