<template>
  <div class="world-book-list-drawer">
    <!-- 操作按钮 -->
    <div class="actions-bar">
      <el-upload
        :show-file-list="false"
        :before-upload="handleImport"
        accept=".json"
      >
        <el-button type="success" :icon="Upload">导入世界书</el-button>
      </el-upload>
      <el-button type="primary" :icon="Plus" @click="handleCreate">
        创建世界书
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" @submit.prevent="handleSearch">
        <el-form-item label="世界书名称">
          <el-input
            v-model="searchForm.bookName"
            placeholder="搜索世界书"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="类型">
          <el-select
            v-model="searchForm.isGlobal"
            placeholder="全部"
            clearable
            @change="handleSearch"
          >
            <el-option label="全局" :value="true" />
            <el-option label="非全局" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 世界书列表 -->
    <el-card class="list-card">
      <el-table
        v-loading="loading"
        :data="worldBooks"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="bookName" label="世界书名称" min-width="200" />
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isGlobal ? 'success' : 'info'">
              {{ row.isGlobal ? '全局' : '非全局' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="条目数" width="100">
          <template #default="{ row }">
            {{ row.entryCount || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="关联角色" width="120">
          <template #default="{ row }">
            {{ row.linkedChars?.length || 0 }} 个
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handleDuplicate(row)"
            >
              复制
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="handleExport(row)"
            >
              导出
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSearch"
          @current-change="handleSearch"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, inject } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload } from '@element-plus/icons-vue'
import * as worldInfoApi from '@/api/worldInfo'
import type { WorldBook } from '@/types/worldInfo'
import { defineAsyncComponent } from 'vue'

const drawerNavigate = inject<any>('drawerNavigate')

const loading = ref(false)
const worldBooks = ref<WorldBook[]>([])
const total = ref(0)

const searchForm = ref({
  page: 1,
  pageSize: 20,
  bookName: '',
  isGlobal: undefined as boolean | undefined,
})

// 加载世界书列表
async function loadWorldBooks() {
  loading.value = true
  try {
    const res = await worldInfoApi.getWorldBookList(searchForm.value) as any
    worldBooks.value = res.data?.list || []
    total.value = res.data?.total || 0
  } catch (error) {
    ElMessage.error('加载世界书列表失败')
  } finally {
    loading.value = false
  }
}

// 暴露刷新方法给父组件
defineExpose({
  refresh: loadWorldBooks
})

// 搜索
function handleSearch() {
  searchForm.value.page = 1
  loadWorldBooks()
}

// 重置
function handleReset() {
  searchForm.value = {
    page: 1,
    pageSize: 20,
    bookName: '',
    isGlobal: undefined,
  }
  loadWorldBooks()
}

// 创建世界书
function handleCreate() {
  const WorldBookEdit = defineAsyncComponent(() => import('./WorldBookEdit.vue'))
  drawerNavigate({
    component: WorldBookEdit,
    props: { mode: 'create' },
    title: '创建世界书',
  })
}

// 编辑世界书
function handleEdit(row: WorldBook) {
  const WorldBookEdit = defineAsyncComponent(() => import('./WorldBookEdit.vue'))
  drawerNavigate({
    component: WorldBookEdit,
    props: { bookId: row.id, mode: 'edit' },
    title: `编辑世界书 - ${row.bookName}`,
  })
}

// 复制世界书
async function handleDuplicate(row: WorldBook) {
  try {
    await ElMessageBox.confirm(
      `确定要复制世界书"${row.bookName}"吗？`,
      '提示',
      { type: 'warning' }
    )
    await worldInfoApi.duplicateWorldBook(row.id)
    ElMessage.success('复制成功')
    loadWorldBooks()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('复制失败')
    }
  }
}

// 导出世界书
async function handleExport(row: WorldBook) {
  try {
    await worldInfoApi.downloadWorldBookJSON(row.id)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 删除世界书
async function handleDelete(row: WorldBook) {
  try {
    await ElMessageBox.confirm(
      `确定要删除世界书"${row.bookName}"吗？此操作不可恢复！`,
      '警告',
      { type: 'warning' }
    )
    await worldInfoApi.deleteWorldBook(row.id)
    ElMessage.success('删除成功')
    loadWorldBooks()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 导入世界书
async function handleImport(file: File) {
  try {
    await worldInfoApi.importWorldBook(file)
    ElMessage.success('导入成功')
    loadWorldBooks()
  } catch (error) {
    ElMessage.error('导入失败')
  }
  return false
}

// 格式化日期
function formatDate(date: string) {
  return new Date(date).toLocaleString('zh-CN')
}

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

<style scoped lang="scss">
.world-book-list-drawer {
  .actions-bar {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
  }

  .search-card {
    margin-bottom: 16px;
  }

  .list-card {
    .pagination {
      margin-top: 16px;
      display: flex;
      justify-content: center;
    }
  }
}
</style>
