<template>
  <div class="tenant-list">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>租户管理</span>
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon> 新建租户
          </el-button>
        </div>
      </template>
      
      <div class="filter-bar">
        <el-input 
          v-model="keyword" 
          placeholder="搜索租户名称/编码/域名" 
          style="width: 300px;"
          clearable
          @keyup.enter="fetchTenants"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select v-model="statusFilter" placeholder="状态" clearable style="width: 120px;">
          <el-option label="启用" value="active" />
          <el-option label="禁用" value="inactive" />
        </el-select>
        
        <el-button type="primary" @click="fetchTenants">查询</el-button>
      </div>
      
      <el-table :data="tenants" v-loading="loading" style="width: 100%;">
        <el-table-column prop="code" label="编码" width="100" />
        <el-table-column prop="name" label="名称" width="150" />
        <el-table-column prop="domain" label="域名" />
        <el-table-column prop="industry" label="行业" width="120">
          <template #default="{ row }">
            {{ getIndustryLabel(row.industry) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'" size="small">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="config_count" label="配置项" width="80" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="$router.push(`/tenants/${row.id}`)">详情</el-button>
            <el-button type="primary" link @click="$router.push(`/tenants/${row.id}/configs`)">配置</el-button>
            <el-button type="primary" link @click="$router.push(`/tenants/${row.id}/features`)">功能</el-button>
            <el-button 
              :type="row.status === 'active' ? 'warning' : 'success'" 
              link 
              @click="toggleStatus(row)"
            >
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="fetchTenants"
          @current-change="fetchTenants"
        />
      </div>
    </el-card>
    
    <!-- 新建租户对话框 -->
    <el-dialog v-model="createDialogVisible" title="新建租户" width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="租户编码" prop="code">
          <el-input v-model="form.code" placeholder="英文小写，如：hua" />
        </el-form-item>
        <el-form-item label="租户名称" prop="name">
          <el-input v-model="form.name" placeholder="如：华尔倍丽" />
        </el-form-item>
        <el-form-item label="域名" prop="domain">
          <el-input v-model="form.domain" placeholder="如：hua.ireborn.com.cn" />
        </el-form-item>
        <el-form-item label="行业" prop="industry">
          <el-select v-model="form.industry" style="width: 100%;">
            <el-option label="轻医美" value="medical_beauty" />
            <el-option label="宠物" value="pet" />
            <el-option label="教育" value="education" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contact_name">
          <el-input v-model="form.contact_name" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contact_phone">
          <el-input v-model="form.contact_phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleCreate">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import api from '@/api'

const loading = ref(false)
const tenants = ref([])
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)
const keyword = ref('')
const statusFilter = ref('')

const createDialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref()

const form = reactive({
  code: '',
  name: '',
  domain: '',
  industry: 'medical_beauty',
  contact_name: '',
  contact_phone: ''
})

const rules = {
  code: [
    { required: true, message: '请输入租户编码', trigger: 'blur' },
    { pattern: /^[a-z0-9_]+$/, message: '只能包含小写字母、数字和下划线', trigger: 'blur' }
  ],
  name: [{ required: true, message: '请输入租户名称', trigger: 'blur' }],
  domain: [{ required: true, message: '请输入域名', trigger: 'blur' }],
  industry: [{ required: true, message: '请选择行业', trigger: 'change' }]
}

function getIndustryLabel(industry) {
  const map = {
    medical_beauty: '轻医美',
    pet: '宠物',
    education: '教育',
    other: '其他'
  }
  return map[industry] || industry
}

async function fetchTenants() {
  loading.value = true
  try {
    const res = await api.tenants.list({
      page: page.value,
      page_size: pageSize.value,
      keyword: keyword.value || undefined,
      status: statusFilter.value || undefined
    })
    tenants.value = res.items
    total.value = res.total
  } finally {
    loading.value = false
  }
}

function showCreateDialog() {
  Object.assign(form, {
    code: '',
    name: '',
    domain: '',
    industry: 'medical_beauty',
    contact_name: '',
    contact_phone: ''
  })
  createDialogVisible.value = true
}

async function handleCreate() {
  await formRef.value.validate()
  
  submitting.value = true
  try {
    await api.tenants.create(form)
    ElMessage.success('租户创建成功')
    createDialogVisible.value = false
    fetchTenants()
  } finally {
    submitting.value = false
  }
}

async function toggleStatus(tenant) {
  const action = tenant.status === 'active' ? '禁用' : '启用'
  
  await ElMessageBox.confirm(`确定要${action}租户 ${tenant.name} 吗？`, '提示', {
    type: 'warning'
  })
  
  try {
    if (tenant.status === 'active') {
      await api.tenants.disable(tenant.id)
    } else {
      await api.tenants.enable(tenant.id)
    }
    ElMessage.success(`${action}成功`)
    fetchTenants()
  } catch (e) {
    // 错误已在拦截器处理
  }
}

onMounted(() => {
  fetchTenants()
})
</script>

<style lang="scss" scoped>
.tenant-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .filter-bar {
    display: flex;
    gap: 12px;
    margin-bottom: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

