<template>
  <div>
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
      <h2>应用管理</h2>
      <div style="display:flex;gap:12px;align-items:center">
        <el-select
          v-model="tenantFilter"
          filterable
          remote
          clearable
          placeholder="筛选租户"
          :remote-method="searchTenants"
          :loading="tenantLoading"
          style="width:200px"
          @change="onTenantChange"
        >
          <el-option
            v-for="t in tenantOptions"
            :key="t.id"
            :label="t.nickname || t.username"
            :value="t.id"
          />
        </el-select>
        <el-input v-model="search" placeholder="搜索应用名称 / AppKey" style="width:280px" clearable @clear="loadApps" @keyup.enter="loadApps">
          <template #prefix><el-icon><Search /></el-icon></template>
        </el-input>
      </div>
    </div>

    <el-table :data="apps" v-loading="loading" border stripe>
      <el-table-column prop="appKey" label="AppKey" width="220" />
      <el-table-column prop="name" label="应用名称" min-width="160" />
      <el-table-column prop="packageName" label="包名" min-width="160" />
      <el-table-column label="租户" width="180" show-overflow-tooltip>
        <template #default="{ row }">{{ row.tenantName || row.tenantId }}</template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">{{ formatTime(row.createdAt) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="$router.push(`/apps/${row.appKey}`)">
            详情
          </el-button>
          <el-button link type="warning" @click="openTransfer(row)">
            转移
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Transfer Dialog -->
    <el-dialog v-model="showTransfer" title="转移应用到其他租户" width="480px">
      <el-form label-width="80px">
        <el-form-item label="应用">
          <span>{{ transferTarget?.name }} ({{ transferTarget?.appKey }})</span>
        </el-form-item>
        <el-form-item label="当前租户">
          <span>{{ transferTarget?.tenantName || transferTarget?.tenantId }}</span>
        </el-form-item>
        <el-form-item label="目标租户">
          <el-select
            v-model="transferTenantId"
            filterable
            remote
            clearable
            placeholder="搜索目标租户"
            :remote-method="searchTransferTenants"
            :loading="transferTenantLoading"
            style="width:100%"
          >
            <el-option
              v-for="t in transferTenantOptions"
              :key="t.id"
              :label="`${t.nickname || t.username} (${t.username})`"
              :value="t.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showTransfer = false">取消</el-button>
        <el-button type="primary" :loading="transferring" :disabled="!transferTenantId" @click="doTransfer">确认转移</el-button>
      </template>
    </el-dialog>

    <el-pagination style="margin-top:16px"
      :current-page="page + 1" :page-size="size" :total="total"
      layout="prev, pager, next" @current-change="(p: number) => { page = p - 1; loadApps() }" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { opsApi, type AppItem, type TenantItem } from '@/api/ops'
import { formatTime } from '@/utils/date'

const apps = ref<AppItem[]>([])
const loading = ref(false)
const search = ref('')
const tenantFilter = ref('')
const page = ref(0)
const size = ref(20)
const total = ref(0)

const tenantOptions = ref<TenantItem[]>([])
const tenantLoading = ref(false)

async function searchTenants(keyword: string) {
  if (!keyword) { tenantOptions.value = []; return }
  tenantLoading.value = true
  try {
    const res = await opsApi.listTenants(keyword, 0, 20)
    tenantOptions.value = res.data.data.content
  } catch {
    tenantOptions.value = []
  } finally {
    tenantLoading.value = false
  }
}

function onTenantChange() {
  page.value = 0
  loadApps()
}

async function loadApps() {
  loading.value = true
  try {
    const res = await opsApi.listApps(search.value, tenantFilter.value, page.value, size.value)
    apps.value = res.data.data.content
    total.value = res.data.data.total
  } catch {
    apps.value = []
  } finally {
    loading.value = false
  }
}

// Transfer
const showTransfer = ref(false)
const transferTarget = ref<AppItem | null>(null)
const transferTenantId = ref('')
const transferTenantOptions = ref<TenantItem[]>([])
const transferTenantLoading = ref(false)
const transferring = ref(false)

function openTransfer(row: AppItem) {
  transferTarget.value = row
  transferTenantId.value = ''
  transferTenantOptions.value = []
  showTransfer.value = true
}

async function searchTransferTenants(keyword: string) {
  if (!keyword) { transferTenantOptions.value = []; return }
  transferTenantLoading.value = true
  try {
    const res = await opsApi.listTenants(keyword, 0, 20)
    transferTenantOptions.value = res.data.data.content
  } catch {
    transferTenantOptions.value = []
  } finally {
    transferTenantLoading.value = false
  }
}

async function doTransfer() {
  if (!transferTarget.value || !transferTenantId.value) return
  const target = transferTenantOptions.value.find(t => t.id === transferTenantId.value)
  const targetLabel = target ? `${target.nickname || target.username} (${target.username})` : transferTenantId.value
  try {
    await ElMessageBox.confirm(
      `确认将应用「${transferTarget.value.name}」转移到「${targetLabel}」？此操作立即生效。`,
      '确认转移',
      { type: 'warning', confirmButtonText: '确认转移', cancelButtonText: '取消' }
    )
  } catch {
    return
  }
  transferring.value = true
  try {
    await opsApi.transferApp(transferTarget.value.appKey, transferTenantId.value)
    ElMessage.success('转移成功')
    showTransfer.value = false
    await loadApps()
  } catch {
    ElMessage.error('转移失败')
  } finally {
    transferring.value = false
  }
}

onMounted(loadApps)
</script>
