<template>
  <PageCard>
    <template #toolbar-left>
      <el-input
        v-model="searchText"
        placeholder="搜索租户编码 / 租户名称"
        clearable
        style="width: 260px"
        @keyup.enter="handleSearch"
      />
    </template>
    <template #toolbar-right>
      <el-button type="primary" @click="openCreateDialog">新增租户</el-button>
    </template>

    <el-table :data="pagedTenants" @row-click="openEditDrawer" class="sino-table">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="tenantCode" label="租户编码" min-width="160" />
      <el-table-column prop="tenantName" label="租户名称" min-width="160" />
      <el-table-column prop="inboundWebhookUrl" label="入站 Webhook" show-overflow-tooltip min-width="220" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <div class="status-cell" @click.stop>
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              inline-prompt
              active-text="启用"
              inactive-text="禁用"
              @change="(val: any) => handleStatusChange(row, val)"
            />
          </div>
        </template>
      </el-table-column>
    </el-table>

    <template #pagination>
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="totalCount"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </template>

    <!-- 新增租户弹窗 -->
    <el-dialog v-model="dialogVisible" title="新增租户" width="600px">
      <el-form :model="dialogForm" label-width="140px">
        <el-form-item label="租户编码">
          <el-input v-model="dialogForm.tenantCode" placeholder="租户编码" />
        </el-form-item>
        <el-form-item label="租户名称">
          <el-input v-model="dialogForm.tenantName" placeholder="租户名称" />
        </el-form-item>
        <el-form-item label="入站 Webhook">
          <el-input v-model="dialogForm.inboundWebhookUrl" placeholder="https://example.com/webhook" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="dialogForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
        <el-form-item label="初始化管理员">
          <el-checkbox v-model="dialogForm.createAdmin">同时创建租户管理员</el-checkbox>
        </el-form-item>
        <el-form-item v-if="dialogForm.createAdmin" label="管理员账号">
          <el-input v-model="dialogForm.initAdminUsername" placeholder="admin" />
        </el-form-item>
        <el-form-item v-if="dialogForm.createAdmin" label="初始密码">
          <el-input v-model="dialogForm.initAdminPassword" type="password" placeholder="初始密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 租户详情 / 编辑抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="480px">
      <el-form :model="drawerForm" label-width="120px" v-if="currentRow">
        <el-form-item label="租户编码">
          <el-input v-model="drawerForm.tenantCode" disabled />
        </el-form-item>
        <el-form-item label="租户名称">
          <el-input v-model="drawerForm.tenantName" placeholder="租户名称" />
        </el-form-item>
        <el-form-item label="入站 Webhook">
          <el-input v-model="drawerForm.inboundWebhookUrl" placeholder="https://example.com/webhook" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="drawerForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="drawer-footer">
          <el-button type="danger" plain @click="handleDrawerDelete">删除</el-button>
          <div class="drawer-actions">
            <el-button @click="drawerVisible = false">取消</el-button>
            <el-button type="primary" @click="handleDrawerSave">保存</el-button>
          </div>
        </div>
      </template>
    </el-drawer>
  </PageCard>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createTenant, deleteTenant, listTenants, updateTenant } from '@/api/account'
import PageCard from '@/components/PageCard.vue'

const tenants = ref<any[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const editingId = ref<number | null>(null)

const dialogForm = reactive({
  tenantCode: '',
  tenantName: '',
  inboundWebhookUrl: '',
  status: 1,
  createAdmin: true,
  initAdminUsername: 'admin',
  initAdminPassword: '',
})

const searchText = ref('')
const drawerVisible = ref(false)
const currentRow = ref<any>(null)
const page = ref(1)
const pageSize = ref(10)

const drawerForm = reactive({
  tenantCode: '',
  tenantName: '',
  inboundWebhookUrl: '',
  status: 1,
})

const filteredTenants = computed(() => {
  if (!searchText.value) return tenants.value
  const kw = searchText.value.toLowerCase()
  return tenants.value.filter(
    (t) =>
      (t.tenantCode || '').toLowerCase().includes(kw) ||
      (t.tenantName || '').toLowerCase().includes(kw)
  )
})

const totalCount = computed(() => filteredTenants.value.length)

const pagedTenants = computed(() => {
  const start = (page.value - 1) * pageSize.value
  return filteredTenants.value.slice(start, start + pageSize.value)
})

const drawerTitle = computed(() =>
  currentRow.value ? `编辑租户 - ${currentRow.value.tenantName}` : '租户详情'
)

function handleSearch() {
  page.value = 1
}

function handlePageChange(val: number) {
  page.value = val
}

function handleSizeChange(val: number) {
  pageSize.value = val
  page.value = 1
}

function resetDialogForm() {
  dialogForm.tenantCode = ''
  dialogForm.tenantName = ''
  dialogForm.inboundWebhookUrl = ''
  dialogForm.status = 1
  dialogForm.createAdmin = true
  dialogForm.initAdminUsername = 'admin'
  dialogForm.initAdminPassword = ''
}

function fillDialogForm(row: any) {
  dialogForm.tenantCode = row.tenantCode ?? ''
  dialogForm.tenantName = row.tenantName ?? ''
  dialogForm.inboundWebhookUrl = row.inboundWebhookUrl ?? ''
  dialogForm.status = row.status ?? 1
}

function resetDrawerForm() {
  drawerForm.tenantCode = ''
  drawerForm.tenantName = ''
  drawerForm.inboundWebhookUrl = ''
  drawerForm.status = 1
}

function fillDrawerForm(row: any) {
  drawerForm.tenantCode = row.tenantCode ?? ''
  drawerForm.tenantName = row.tenantName ?? ''
  drawerForm.inboundWebhookUrl = row.inboundWebhookUrl ?? ''
  drawerForm.status = row.status ?? 1
}

function openCreateDialog() {
  isEdit.value = false
  editingId.value = null
  resetDialogForm()
  dialogVisible.value = true
}

function openEditDialog(row: any) {
  isEdit.value = true
  editingId.value = row.id
  fillDialogForm(row)
  dialogVisible.value = true
}

function openEditDrawer(row: any) {
  currentRow.value = row
  fillDrawerForm(row)
  drawerVisible.value = true
}

async function loadTenants() {
  try {
    const res: any = await listTenants()
    tenants.value = res.data || []
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleSave() {
  if (!dialogForm.tenantCode || !dialogForm.tenantName) {
    ElMessage.warning('请填写租户编码和租户名称')
    return
  }
  try {
    if (isEdit.value && editingId.value != null) {
      await updateTenant(editingId.value, {
        tenantName: dialogForm.tenantName,
        inboundWebhookUrl: dialogForm.inboundWebhookUrl,
        status: dialogForm.status,
      })
      ElMessage.success('更新成功')
    } else {
      const payload: any = {
        tenantCode: dialogForm.tenantCode,
        tenantName: dialogForm.tenantName,
        inboundWebhookUrl: dialogForm.inboundWebhookUrl,
      }
      if (dialogForm.createAdmin) {
        if (!dialogForm.initAdminUsername || !dialogForm.initAdminPassword) {
          ElMessage.warning('请填写初始化管理员账号和密码')
          return
        }
        payload.initAdminUsername = dialogForm.initAdminUsername
        payload.initAdminPassword = dialogForm.initAdminPassword
      }
      await createTenant(payload)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    page.value = 1
    await loadTenants()
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleStatusChange(row: any, val: any) {
  try {
    await updateTenant(row.id, {
      tenantName: row.tenantName,
      inboundWebhookUrl: row.inboundWebhookUrl,
      status: val,
    })
    ElMessage.success('状态更新成功')
    await loadTenants()
  } catch (e: any) {
    ElMessage.error(e.message)
    await loadTenants()
  }
}

async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm(
      `确定删除租户「${row.tenantName}（${row.tenantCode}）」吗？`,
      '删除确认',
      { confirmButtonText: '删除', cancelButtonText: '取消', type: 'warning' }
    )
    await deleteTenant(row.id)
    ElMessage.success('删除成功')
    await loadTenants()
  } catch (e: any) {
    if (e !== 'cancel') {
      ElMessage.error(e.message || '删除失败')
    }
  }
}

async function handleDrawerSave() {
  if (!currentRow.value) return
  try {
    await updateTenant(currentRow.value.id, {
      tenantName: drawerForm.tenantName,
      inboundWebhookUrl: drawerForm.inboundWebhookUrl,
      status: drawerForm.status,
    })
    ElMessage.success('保存成功')
    drawerVisible.value = false
    await loadTenants()
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleDrawerDelete() {
  if (!currentRow.value) return
  await handleDelete(currentRow.value)
  drawerVisible.value = false
}

onMounted(loadTenants)
</script>

<style scoped>
.drawer-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.drawer-actions {
  display: flex;
  gap: 12px;
}
</style>
