<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'
import { listCompanyOptions } from '@/api/admin/sysCompany'

export default {
  name: 'InlineTenantSelector',
  props: {
    /** admin=总后台(/admin/company/options)，saas=租户总后台(/tenant/tenant/tenantList) */
    mode: {
      type: String,
      default: 'saas'
    }
  },
  data() {
    return {
      tenantList: [],
      selectedId: null
    }
  },
  created() {
    // 从Vuex恢复上次选择
    const saved = this.$store.getters.selectedCompanyId
    if (saved) {
      this.selectedId = saved
    }
    this.loadTenants()
  },
  methods: {
    loadTenants() {
      const loader = this.mode === 'admin'
        ? listCompanyOptions().then(response => response.data || [])
        : tenantList().then(response => response.rows || response.data || [])
      loader.then(list => {
        this.tenantList = list
      }).catch(() => {
        this.tenantList = []
      })
    },
    handleChange(val) {
      this.$store.dispatch('tenant/setTenantId', val)
      this.$emit('change', val)
    },
    reset() {
      this.selectedId = null
      this.$store.dispatch('tenant/setTenantId', null)
    }
  }
}
</script>
