<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import DataTablePage from '@/components/DataTablePage.vue'
import {
  getModelList,
  getTrainedModels,
  deleteModel,
  deleteTrainedModel,
  mergeModel,
  exportModelUrl,
} from '@/api/modules/model'
import { MODEL_TYPE_MAP, PURPOSE_MAP, MODEL_SOURCE_MAP } from '@/constants'
import type { ModelItem, TrainedModel } from '@/types'

const router = useRouter()

type TabKey = 'config' | 'trained'
const activeTab = ref<TabKey>('config')

const loading = ref(false)
const configList = ref<ModelItem[]>([])
const trainedList = ref<TrainedModel[]>([])



async function loadConfig() {
  loading.value = true
  try {
    configList.value = (await getModelList()) || []
  } catch {
    // ignore
  } finally {
    loading.value = false
  }
}

async function loadTrained() {
  loading.value = true
  try {
    const res = await getTrainedModels()
    trainedList.value = res?.models || []
  } catch {
    // ignore
  } finally {
    loading.value = false
  }
}

function loadData() {
  if (activeTab.value === 'config') loadConfig()
  else loadTrained()
}

/** 删除配置模型 */
async function handleDeleteConfig(row: any) {
  await deleteModel(row.id)
  ElMessage.success('删除成功')
}



/** 删除 LoRA 权重 */
async function handleDeleteWeight(row: any) {
  await ElMessageBox.confirm(
    `确定要删除模型 "${row.name}" 的权重文件吗？合并模型不受影响。`,
    '确认删除',
    { type: 'warning' },
  )
  await deleteTrainedModel(row.name, 'lora')
  ElMessage.success('权重已删除')
  loadTrained()
}

/** 合并权重 */
async function handleMerge(row: any) {
  await router.push({
    path: '/model-manage/merge',
    query: {
      model: row.name,
      method: row.train_methods?.[0]?.name || 'lora',
    },
  })
}

/** 导出 */
function handleExport(row: any) {
  window.open(exportModelUrl(row.name), '_blank')
}

function editModel(row: any) {
  router.push(`/model-manage/${row.id}/edit`)
}

function handleCreateClick() {
  if (activeTab.value === 'config') {
    router.push('/model-manage/create')
  }
}

function handleRefresh() {
  if (activeTab.value === 'config') {
    loadConfig()
  } else {
    loadTrained()
  }
}

watch(activeTab, () => {
  loadData()
})

onMounted(loadData)
</script>

<template>
  <div class="model-manage-page" style="height: 100%;">
    <!-- 配置模型列表 -->
    <DataTablePage
      v-if="activeTab === 'config'"
      title=""
      :data="configList"
      :loading="loading"
      searchable
      :search-fields="['name', 'description']"
      create-text="添加模型"
      @create="handleCreateClick"
      :delete-fn="handleDeleteConfig"
      row-key="id"
      @refresh="loadConfig"
    >
      <template #title>
        <div class="capsule-tabs">
          <button class="capsule-tab-item active" @click="activeTab = 'config'">配置模型</button>
          <button class="capsule-tab-item" @click="activeTab = 'trained'">训练模型</button>
        </div>
      </template>
      <template #columns>
        <el-table-column label="模型名称" prop="name" align="center" />
        <el-table-column label="模型类型" align="center" width="140">
          <template #default="{ row }">
            <el-tag type="primary" size="small">
              {{ MODEL_TYPE_MAP[row.type] || row.type || '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用途" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="(PURPOSE_MAP[row.purpose]?.type || 'info') as any" size="small">
              {{ PURPOSE_MAP[row.purpose]?.text || row.purpose || '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="模型来源" align="center" width="110">
          <template #default="{ row }">
            {{ MODEL_SOURCE_MAP[row.model_source] || row.model_source || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" show-overflow-tooltip>
          <template #default="{ row }">{{ row.description || '-' }}</template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="180">
          <template #default="{ row }">
            {{ row.create_time ? new Date(row.create_time).toLocaleString('zh-CN') : '-' }}
          </template>
        </el-table-column>
      </template>
      <template #actions="{ row }">
        <el-button type="primary" link size="small" @click="editModel(row)">编辑</el-button>
        <el-button type="danger" link size="small" @click="handleDeleteConfig(row)">删除</el-button>
      </template>
    </DataTablePage>

    <!-- 训练模型列表 -->
    <DataTablePage
      v-else
      title=""
      :data="trainedList"
      :loading="loading"
      searchable
      :search-fields="['name']"
      row-key="name"
      @refresh="loadTrained"
    >
      <template #title>
        <div class="capsule-tabs">
          <button class="capsule-tab-item" @click="activeTab = 'config'">配置模型</button>
          <button class="capsule-tab-item active" @click="activeTab = 'trained'">训练模型</button>
        </div>
      </template>
      <template #columns>
        <el-table-column label="模型名称" prop="name" align="center" />
        <el-table-column label="训练方法" align="center">
          <template #default="{ row }">
            {{ row.train_methods?.[0]?.name || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="基座模型" align="center" show-overflow-tooltip>
          <template #default="{ row }">{{ row.base_model_path || '-' }}</template>
        </el-table-column>
        <el-table-column label="合并状态" align="center" width="110">
          <template #default="{ row }">
            <el-tag v-if="row.merging" type="warning" size="small">合并中</el-tag>
            <el-tag v-else-if="row.merged" type="success" size="small">已合并</el-tag>
            <el-tag v-else type="info" size="small">未合并</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="180">
          <template #default="{ row }">
            {{ row.create_time ? new Date(row.create_time).toLocaleString('zh-CN') : '-' }}
          </template>
        </el-table-column>
      </template>
      <template #actions="{ row }">
        <div class="action-buttons">
          <el-button
            v-if="!row.merged && !row.merging"
            type="primary"
            link
            size="small"
            @click="handleMerge(row)"
          >
            <i class="fa fa-code-fork" style="margin-right: 4px" />合并权重
          </el-button>
          <el-button
            v-else-if="row.merging"
            type="info"
            link
            size="small"
            :loading="true"
            disabled
          >
            合并中
          </el-button>
          <el-button type="warning" link size="small" @click="handleDeleteWeight(row)">
            <i class="fa fa-eraser" style="margin-right: 4px" />删除权重
          </el-button>
          <el-button
            v-if="row.merged"
            type="success"
            link
            size="small"
            @click="handleExport(row)"
          >
            <i class="fa fa-download" style="margin-right: 4px" />导出
          </el-button>

        </div>
      </template>
    </DataTablePage>
  </div>
</template>

<style scoped lang="scss">

/* 胶囊切换栏样式 */
.capsule-tabs {
  display: flex;
  background: #f1f5f9;
  padding: 3px;
  border-radius: 8px;
  gap: 2px;
  border: 1px solid #e2e8f0;
}

.capsule-tab-item {
  border: 0;
  background: transparent;
  padding: 6px 20px;
  font-size: 13px;
  font-weight: 500;
  color: #64748b;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.2s ease;
  outline: none;

  &:hover {
    color: #1e293b;
  }

  &.active {
    background: #fff;
    color: #4f46e5;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06), 0 1px 2px rgba(0, 0, 0, 0.04);
    font-weight: 600;
  }
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}
</style>
