<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
            <span>分类管理 - {{ categoryInfo?.category_name || '加载中...' }}</span>
          </div>
          <el-button type="primary" @click="openBatchSetCategoryDialog">
            移入应用
          </el-button>
        </div>
      </template>

      <!-- 分类信息 -->
      <div v-if="categoryInfo" style="margin-bottom: 20px; padding: 15px; background-color: #f5f7fa; border-radius: 4px;">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="分类名称">
            <el-tag>{{ categoryInfo.category_name }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="应用数量">
            <el-tag type="info">{{ categoryInfo.app_count }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 应用列表 -->
      <div style="margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center;">
        <span style="font-weight: bold;">分类下的应用 ({{ apps.length }} 个)</span>
        <div>
          <el-button 
            type="danger" 
            size="small" 
            @click="openBatchRemoveCategoryDialog"
            :disabled="selectedApps.length === 0"
          >
            批量移除分类 (已选 {{ selectedApps.length }})
          </el-button>
        </div>
      </div>

      <el-table 
        :data="apps" 
        v-loading="appsLoading"
        stripe
        border
        @selection-change="handleAppSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="app_name" label="应用名称" min-width="150" />
        <el-table-column prop="app_id" label="App ID" min-width="220" />
        <el-table-column prop="protocol_type" label="协议类型" width="120">
          <template #default="scope">
            <el-tag :type="protocolTagType(scope.row.protocol_type)">
              {{ scope.row.protocol_type === 'NONE' ? '无' : scope.row.protocol_type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button 
              type="danger" 
              link 
              size="small"
              @click="handleRemoveAppFromCategory(scope.row)"
            >
              移出分类
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="apps.length === 0 && !appsLoading" 
           style="padding: 20px; text-align: center; color: #909399;">
        该分类下暂无应用
      </div>
    </el-card>

    <!-- 批量设置分类对话框 -->
    <el-dialog v-model="batchSetCategoryDialogVisible" title="批量设置分类" width="800px">
      <el-form label-width="120px">
        <el-form-item label="选择应用来源">
          <el-select 
            v-model="batchSetCategoryForm.source_category_id" 
            placeholder="选择应用来源"
            filterable
            style="width: 100%"
            @change="handleSourceCategoryChange"
          >
            <el-option
              label="未分类"
              :value="0"
            />
            <el-option
              v-for="cat in allCategories"
              :key="cat.category_id"
              :label="cat.category_name"
              :value="cat.category_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="应用列表">
          <div style="max-height: 300px; overflow-y: auto; border: 1px solid #dcdfe6; border-radius: 4px; padding: 10px;">
            <el-table 
              :data="availableAppsForBatch" 
              v-loading="batchAppsLoading"
              stripe
              border
              max-height="280"
              @selection-change="handleBatchAppSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="app_name" label="应用名称" min-width="150" />
              <el-table-column prop="app_id" label="App ID" min-width="220" />
              <el-table-column prop="category_name" label="当前分类" width="120">
                <template #default="scope">
                  <el-tag v-if="scope.row.category_name" type="info">{{ scope.row.category_name }}</el-tag>
                  <el-tag v-else type="warning">未分类</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <div v-if="availableAppsForBatch.length === 0 && !batchAppsLoading" 
                 style="padding: 20px; text-align: center; color: #909399;">
              暂无应用
            </div>
          </div>
        </el-form-item>
        <el-form-item label="已选应用">
          <span style="color: #409eff; font-weight: bold;">{{ batchSelectedApps.length }} 个应用</span>
        </el-form-item>
        <el-form-item label="管理员密码" required>
          <el-input 
            v-model="batchSetCategoryForm.password" 
            type="password"
            placeholder="请输入管理员密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchSetCategoryDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleBatchSetCategory" 
          :loading="batchUpdating"
          :disabled="batchSelectedApps.length === 0 || !batchSetCategoryForm.password"
        >
          确定 ({{ batchSelectedApps.length }} 个应用)
        </el-button>
      </template>
    </el-dialog>

    <!-- 批量移除分类对话框 -->
    <el-dialog v-model="batchRemoveCategoryDialogVisible" title="批量移除分类" width="500px">
      <el-form label-width="120px">
        <el-form-item label="已选应用">
          <span>{{ selectedApps.length }} 个应用</span>
        </el-form-item>
        <el-alert
          type="warning"
          :closable="false"
          style="margin-bottom: 20px;"
        >
          <template #title>
            <div>
              <p>确定要将这 {{ selectedApps.length }} 个应用从分类中移除吗？</p>
            </div>
          </template>
        </el-alert>
        <el-form-item label="管理员密码" required>
          <el-input 
            v-model="batchRemoveCategoryForm.password" 
            type="password"
            placeholder="请输入管理员密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchRemoveCategoryDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleBatchRemoveCategory" :loading="batchUpdating">
          确定移除
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { 
  getCategories,
  getCategoryApps,
  batchUpdateAppCategory,
  getApps,
  CategoryStats,
  Application,
} from '../../../api/apps'

const router = useRouter()
const route = useRoute()

const categoryId = computed(() => Number(route.params.id))

const protocolTagType = (p: string) => {
  if (p === 'OIDC') return 'success'
  if (p === 'NONE') return 'info'
  return 'warning'
}

// 数据
const categoryInfo = ref<CategoryStats | null>(null)
const apps = ref<Application[]>([])
const appsLoading = ref(false)
const allCategories = ref<CategoryStats[]>([])

// 选中的应用
const selectedApps = ref<Application[]>([])

// 对话框状态
const batchSetCategoryDialogVisible = ref(false)
const batchRemoveCategoryDialogVisible = ref(false)
const batchUpdating = ref(false)

const batchSetCategoryForm = reactive({
  source_category_id: undefined as number | undefined,
  password: ''
})

const batchRemoveCategoryForm = reactive({
  password: ''
})

// 批量设置分类用的应用列表
const availableAppsForBatch = ref<Application[]>([])
const batchAppsLoading = ref(false)
const batchSelectedApps = ref<Application[]>([])

// 获取分类信息
const fetchCategoryInfo = async () => {
  try {
    const res = await getCategories('')
    const category = res.data.find(c => c.category_id === categoryId.value)
    if (category) {
      categoryInfo.value = category
    }
    allCategories.value = res.data
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '获取分类信息失败')
  }
}

// 获取分类下的应用列表
const fetchCategoryApps = async () => {
  appsLoading.value = true
  try {
    const res = await getCategoryApps(categoryId.value, 0, 1000)
    apps.value = res.data.items || []
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '获取应用列表失败')
    apps.value = []
  } finally {
    appsLoading.value = false
  }
}

// 处理应用选择变化
const handleAppSelectionChange = (selection: Application[]) => {
  selectedApps.value = selection
}

// 返回
const goBack = () => {
  router.push({ name: 'AppCategories' })
}

// 打开批量设置分类对话框
const openBatchSetCategoryDialog = () => {
  batchSetCategoryForm.source_category_id = undefined
  batchSetCategoryForm.password = ''
  batchSelectedApps.value = []
  availableAppsForBatch.value = []
  batchSetCategoryDialogVisible.value = true
}

// 处理应用来源分类变化
const handleSourceCategoryChange = async () => {
  if (batchSetCategoryForm.source_category_id === undefined) {
    availableAppsForBatch.value = []
    batchSelectedApps.value = []
    return
  }
  
  batchAppsLoading.value = true
  try {
    const catId = batchSetCategoryForm.source_category_id === 0 ? 0 : batchSetCategoryForm.source_category_id
    const res = await getApps(0, 1000, '', catId)
    availableAppsForBatch.value = res.data.items
    batchSelectedApps.value = []
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '获取应用列表失败')
  } finally {
    batchAppsLoading.value = false
  }
}

// 处理批量应用选择变化
const handleBatchAppSelectionChange = (selection: Application[]) => {
  batchSelectedApps.value = selection
}

// 打开批量移除分类对话框
const openBatchRemoveCategoryDialog = () => {
  if (selectedApps.value.length === 0) {
    ElMessage.warning('请先选择要移除分类的应用')
    return
  }
  batchRemoveCategoryForm.password = ''
  batchRemoveCategoryDialogVisible.value = true
}

// 单个应用移出分类
const handleRemoveAppFromCategory = async (app: Application) => {
  try {
    await ElMessageBox.confirm(
      `确定要将应用 "${app.app_name}" 从分类中移除吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const passwordResult = await ElMessageBox.prompt(
      '请输入管理员密码',
      '验证',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'password',
        inputPlaceholder: '请输入管理员密码'
      }
    )
    
    if (!passwordResult.value) {
      return
    }
    
    batchUpdating.value = true
    try {
      await batchUpdateAppCategory({
        app_ids: [app.id],
        category_id: null,
        password: passwordResult.value as string
      })
      ElMessage.success('移除成功')
      fetchCategoryApps()
      fetchCategoryInfo()
    } catch (error: any) {
      ElMessage.error(error.response?.data?.detail || '移除失败')
    } finally {
      batchUpdating.value = false
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.detail || '操作失败')
    }
  }
}

// 批量设置分类
const handleBatchSetCategory = async () => {
  if (!batchSetCategoryForm.password) {
    ElMessage.warning('请输入管理员密码')
    return
  }

  if (batchSelectedApps.value.length === 0) {
    ElMessage.warning('请先选择要设置分类的应用')
    return
  }

  batchUpdating.value = true
  try {
    await batchUpdateAppCategory({
      app_ids: batchSelectedApps.value.map(app => app.id),
      category_id: categoryId.value,
      password: batchSetCategoryForm.password
    })
    ElMessage.success('批量设置成功')
    batchSetCategoryDialogVisible.value = false
    fetchCategoryApps()
    fetchCategoryInfo()
    batchSelectedApps.value = []
    availableAppsForBatch.value = []
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '批量设置失败')
  } finally {
    batchUpdating.value = false
  }
}

// 批量移除分类
const handleBatchRemoveCategory = async () => {
  if (!batchRemoveCategoryForm.password) {
    ElMessage.warning('请输入管理员密码')
    return
  }

  if (selectedApps.value.length === 0) {
    ElMessage.warning('请先选择要移除分类的应用')
    return
  }

  batchUpdating.value = true
  try {
    await batchUpdateAppCategory({
      app_ids: selectedApps.value.map(app => app.id),
      category_id: null,
      password: batchRemoveCategoryForm.password
    })
    ElMessage.success('批量移除成功')
    batchRemoveCategoryDialogVisible.value = false
    fetchCategoryApps()
    fetchCategoryInfo()
    selectedApps.value = []
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '批量移除失败')
  } finally {
    batchUpdating.value = false
  }
}

onMounted(() => {
  fetchCategoryInfo()
  fetchCategoryApps()
})
</script>

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

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