<template>
  <el-select
    v-model="selectedCompanyId"
    placeholder="选择租户"
    clearable
    filterable
    size="small"
    class="tenant-selector"
    @change="handleTenantChange"
  >
    <el-option
      v-for="item in tenantList"
      :key="item.id"
      :label="item.tenantName"
      :value="item.id"
    />
  </el-select>
</template>

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

export default {
  name: 'TenantSelector',
  data() {
    return {
      tenantList: [],
      selectedCompanyId: null
    }
  },
  created() {
    this.loadTenants()
    // 从Vuex恢复上次选择
    const saved = this.$store.getters.selectedCompanyId
    if (saved) {
      this.selectedCompanyId = saved
    }
  },
  methods: {
    loadTenants() {
      tenantList().then(response => {
        this.tenantList = response.rows || response.data || []
      }).catch(() => {
        this.tenantList = []
      })
    },
    handleTenantChange(val) {
      this.$store.dispatch('tenant/setCompanyId', val)
    }
  }
}
</script>

<style lang="scss" scoped>
.tenant-selector {
  width: 180px;
  margin-right: 10px;
  ::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
}
</style>
