<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>应用分类管理</span>
          <el-button type="primary" @click="openCreateDialog">创建分类</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar" style="margin-bottom: 20px;">
        <el-input
          v-model="searchQuery"
          placeholder="搜索分类名称"
          clearable
          style="width: 300px;"
          @clear="fetchCategories"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>

      <!-- 分类列表 -->
      <el-table 
        :data="categories" 
        v-loading="loading" 
        stripe 
        border
        style="width: 100%"
      >
        <el-table-column prop="category_name" label="分类名称" min-width="200">
          <template #default="scope">
            <el-tag>{{ scope.row.category_name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="app_count" label="应用数量" width="120" align="center">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.app_count }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="goToCategoryDetail(scope.row)">
              管理
            </el-button>
            <el-button type="primary" link @click="openEditDialog(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="openDeleteDialog(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="categories.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无分类数据" />
      </div>
    </el-card>

    <!-- 创建/编辑分类对话框 -->
    <el-dialog 
      v-model="categoryDialogVisible" 
      :title="categoryIsEdit ? '编辑分类' : '创建分类'" 
      width="500px"
    >
      <el-form :model="categoryForm" label-width="100px">
        <el-form-item label="分类名称" required>
          <el-input 
            v-model="categoryForm.name" 
            placeholder="请输入分类名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="分类描述">
          <el-input 
            v-model="categoryForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入分类描述（选填）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item v-if="categoryIsEdit" label="密码验证" required>
          <el-input 
            v-model="categoryForm.password" 
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCategorySubmit" :loading="categorySaving">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 删除对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="删除分类" width="500px">
      <el-alert
        type="error"
        :closable="false"
        style="margin-bottom: 20px;"
      >
        <template #title>
          <div>
            <p>确定要删除分类 <strong>{{ deleteForm.category_name }}</strong> 吗？</p>
            <p style="margin-top: 10px; font-size: 12px; color: #f56c6c;">
              <strong>注意：</strong>该分类下有 {{ deleteForm.app_count }} 个应用，请先移出这些应用后才能删除分类。
            </p>
          </div>
        </template>
      </el-alert>
      <el-form :model="deleteForm" label-width="120px">
        <el-form-item label="验证码" required>
          <div style="display: flex; gap: 10px;">
            <el-input 
              v-model="deleteForm.verification_code" 
              placeholder="请输入手机验证码"
              maxlength="6"
            />
            <el-button 
              @click="sendVerificationCode" 
              :disabled="cooldown > 0"
            >
              {{ cooldown > 0 ? `${cooldown}秒后重试` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button 
          type="danger" 
          @click="handleDelete" 
          :loading="deleting"
          :disabled="deleteForm.app_count > 0"
        >
          确定删除
        </el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { 
  getCategories, 
  deleteCategory,
  getPresetCategories,
  createPresetCategory,
  updatePresetCategory,
  CategoryStats,
  AppCategoryCreate,
} from '../../../api/apps'
import { sendImportVerificationCode } from '../../../api/mapping'

const router = useRouter()

// 数据
const categories = ref<CategoryStats[]>([])
const loading = ref(false)
const searchQuery = ref('')

// 对话框状态
const categoryDialogVisible = ref(false)
const categoryIsEdit = ref(false)
const categorySaving = ref(false)
const currentCategoryId = ref<number | null>(null)
const categoryForm = reactive<AppCategoryCreate & { password?: string }>({
  name: '',
  description: '',
  password: ''
})

const deleteDialogVisible = ref(false)
const deleting = ref(false)

const deleteForm = reactive({
  category_id: 0,
  category_name: '',
  app_count: 0,
  verification_code: ''
})

// 验证码倒计时
const cooldown = ref(0)
let timer: any = null

// 获取分类列表
const fetchCategories = async () => {
  loading.value = true
  try {
    const res = await getCategories(searchQuery.value)
    categories.value = res.data
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  fetchCategories()
}

// 跳转到分类详情页面
const goToCategoryDetail = (row: CategoryStats) => {
  router.push({
    name: 'CategoryDetail',
    params: { id: row.category_id }
  })
}

// 打开创建分类对话框
const openCreateDialog = () => {
  categoryIsEdit.value = false
  currentCategoryId.value = null
  categoryForm.name = ''
  categoryForm.description = ''
  categoryForm.password = ''
  categoryDialogVisible.value = true
}

// 打开编辑分类对话框
const openEditDialog = (row: CategoryStats) => {
  categoryIsEdit.value = true
  currentCategoryId.value = row.category_id
  // 需要获取分类详情
  getPresetCategories().then(res => {
    const cat = res.data.find(c => c.id === row.category_id)
    if (cat) {
      categoryForm.name = cat.name
      categoryForm.description = cat.description || ''
      categoryForm.password = ''
      categoryDialogVisible.value = true
    }
  })
}

// 提交分类（创建/更新）
const handleCategorySubmit = async () => {
  if (!categoryForm.name?.trim()) {
    ElMessage.warning('请输入分类名称')
    return
  }

  // 编辑时需要密码验证
  if (categoryIsEdit.value && !categoryForm.password?.trim()) {
    ElMessage.warning('请输入密码')
    return
  }

  categorySaving.value = true
  try {
    if (categoryIsEdit.value && currentCategoryId.value) {
      // 编辑时传递密码
      await updatePresetCategory(currentCategoryId.value, {
        name: categoryForm.name,
        description: categoryForm.description,
        password: categoryForm.password
      })
      ElMessage.success('更新成功')
    } else {
      // 创建时不需要密码
      await createPresetCategory({
        name: categoryForm.name,
        description: categoryForm.description
      })
      ElMessage.success('创建成功')
    }
    categoryDialogVisible.value = false
    fetchCategories()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '操作失败')
  } finally {
    categorySaving.value = false
  }
}


// 打开删除对话框
const openDeleteDialog = (row: CategoryStats) => {
  deleteForm.category_id = row.category_id
  deleteForm.category_name = row.category_name
  deleteForm.app_count = row.app_count
  deleteForm.verification_code = ''
  deleteDialogVisible.value = true
}


// 发送验证码
const sendVerificationCode = async () => {
  try {
    await sendImportVerificationCode()
    ElMessage.success('验证码已发送')
    cooldown.value = 60
    timer = setInterval(() => {
      cooldown.value--
      if (cooldown.value <= 0) {
        clearInterval(timer)
        timer = null
      }
    }, 1000)
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '发送验证码失败')
  }
}


// 删除
const handleDelete = async () => {
  if (deleteForm.app_count > 0) {
    ElMessage.warning('请先移出该分类下的所有应用后再删除分类')
    return
  }
  
  if (!deleteForm.verification_code) {
    ElMessage.warning('请输入验证码')
    return
  }

  deleting.value = true
  try {
    const res = await deleteCategory(deleteForm.category_id, deleteForm.verification_code)
    ElMessage.success(res.data.message)
    deleteDialogVisible.value = false
    fetchCategories()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '删除失败')
  } finally {
    deleting.value = false
  }
}


onMounted(() => {
  fetchCategories()
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.search-bar {
  margin-bottom: 20px;
}

.empty-state {
  margin-top: 40px;
}
</style>
