<template>
  <el-select
    v-model="selectedId"
    placeholder="选择租户"
    clearable
    filterable
    size="small"
    style="width: 160px"
    @change="handleChange"
  >
    <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: 'InlineTenantSelector',
  data() {
    return {
      tenantList: [],
      selectedId: null
    }
  },
  created() {
    // 从Vuex恢复上次选择
    const saved = this.$store.getters.selectedCompanyId
    if (saved) {
      this.selectedId = saved
    }
    this.loadTenants()
  },
  methods: {
    loadTenants() {
      tenantList().then(response => {
        this.tenantList = response.rows || response.data || []
      }).catch(() => {
        this.tenantList = []
      })
    },
    handleChange(val) {
      this.$store.dispatch('tenant/setCompanyId', val)
      this.$emit('change', val)
    }
  }
}
</script>
