<template>
  <PageCard>
    <template #toolbar-left>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索应用名称 / AgentID"
        clearable
        style="width: 260px"
      />
    </template>
    <template #toolbar-right>
      <el-button type="primary" @click="openCreate">新增应用</el-button>
    </template>

    <el-table :data="pagedApps" class="sino-table" @row-click="handleRowClick">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="appName" label="应用名称" />
      <el-table-column prop="agentId" label="AgentID" />
      <el-table-column prop="secret" label="Secret">
        <template #default="{ row }">
          <span v-if="row.secret">••••••••</span>
          <span v-else class="text-secondary">-</span>
        </template>
      </el-table-column>
      <el-table-column prop="sessionArchiveEnabled" label="会话存档" width="120">
        <template #default="{ row }">
          <el-tag :type="row.sessionArchiveEnabled === 1 ? 'success' : 'info'" size="small">
            {{ row.sessionArchiveEnabled === 1 ? '已开启' : '未开启' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <template #pagination>
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="filteredApps.length"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        background
      />
    </template>

    <el-dialog v-model="dialogVisible" title="新增应用" width="520px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="应用名称"><el-input v-model="form.appName" /></el-form-item>
        <el-form-item label="AgentID"><el-input v-model="form.agentId" /></el-form-item>
        <el-form-item label="Secret"><el-input v-model="form.secret" type="password" show-password /></el-form-item>
        <el-form-item label="会话存档">
          <el-switch v-model="form.sessionArchiveEnabled" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

    <el-drawer v-model="drawerVisible" title="应用详情" size="420px">
      <div class="drawer-body">
        <div class="drawer-actions">
          <el-button size="small" type="primary" @click="initAccounts(currentApp!)">初始化账号</el-button>
        </div>
        <el-form :model="drawerForm" label-width="100px">
          <el-form-item label="应用名称"><el-input v-model="drawerForm.appName" /></el-form-item>
          <el-form-item label="AgentID"><el-input v-model="drawerForm.agentId" /></el-form-item>
          <el-form-item label="Secret"><el-input v-model="drawerForm.secret" type="password" show-password /></el-form-item>
          <el-form-item label="会话存档">
            <el-switch v-model="drawerForm.sessionArchiveEnabled" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="drawer-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="saveDrawer">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </PageCard>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import PageCard from '@/components/PageCard.vue'

interface AppItem {
  id: number
  appName: string
  agentId: string
  secret: string
  sessionArchiveEnabled: number
  status: number
}

const apps = ref<AppItem[]>([
  { id: 1, appName: '会话存档应用', agentId: '1000002', secret: 'xxx', sessionArchiveEnabled: 1, status: 1 },
  { id: 2, appName: '消息推送应用', agentId: '1000005', secret: 'xxx', sessionArchiveEnabled: 0, status: 1 },
])

const searchKeyword = ref('')
const page = ref(1)
const pageSize = ref(10)

const filteredApps = computed(() => {
  const kw = searchKeyword.value.trim().toLowerCase()
  if (!kw) return apps.value
  return apps.value.filter(
    (item) =>
      item.appName.toLowerCase().includes(kw) ||
      item.agentId.toLowerCase().includes(kw)
  )
})

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

const dialogVisible = ref(false)
const form = reactive({
  appName: '',
  agentId: '',
  secret: '',
  sessionArchiveEnabled: 0,
})

const drawerVisible = ref(false)
const currentApp = ref<AppItem | null>(null)
const drawerForm = reactive({
  appName: '',
  agentId: '',
  secret: '',
  sessionArchiveEnabled: 0,
})

function resetForm() {
  form.appName = ''
  form.agentId = ''
  form.secret = ''
  form.sessionArchiveEnabled = 0
}

function fillDrawerForm(app: AppItem) {
  drawerForm.appName = app.appName
  drawerForm.agentId = app.agentId
  drawerForm.secret = app.secret
  drawerForm.sessionArchiveEnabled = app.sessionArchiveEnabled
}

function openCreate() {
  resetForm()
  dialogVisible.value = true
}

function handleRowClick(row: AppItem) {
  currentApp.value = row
  fillDrawerForm(row)
  drawerVisible.value = true
}

function save() {
  apps.value.push({
    id: Date.now(),
    appName: form.appName || '未命名应用',
    agentId: form.agentId,
    secret: form.secret,
    sessionArchiveEnabled: form.sessionArchiveEnabled,
    status: 1,
  })
  ElMessage.success('创建成功')
  dialogVisible.value = false
}

function saveDrawer() {
  if (!currentApp.value) return
  const idx = apps.value.findIndex((a) => a.id === currentApp.value!.id)
  if (idx >= 0) {
    apps.value[idx] = {
      ...currentApp.value,
      appName: drawerForm.appName,
      agentId: drawerForm.agentId,
      secret: drawerForm.secret,
      sessionArchiveEnabled: drawerForm.sessionArchiveEnabled,
    }
  }
  ElMessage.success('更新成功')
  drawerVisible.value = false
}

function initAccounts(app: AppItem) {
  ElMessage.info(`开始初始化账号：${app.appName}`)
}
</script>

<style scoped>
.text-secondary {
  color: #94a3b8;
}
.drawer-body {
  padding: 20px;
}
.drawer-actions {
  margin-bottom: 20px;
}
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  width: 100%;
}
</style>
