<script setup lang="ts">
import {
  NBreadcrumb,
  NBreadcrumbItem,
  NButton,
  NCard,
  NCheckbox,
  NEmpty,
  NImage,
  NInput,
  NPagination,
  NTag,
} from 'naive-ui'
import { computed, ref, watch } from 'vue'
import SvgIcon from '@/components/custom/svg-icon.vue'
import { fetchDeleteQuestionLibrary, fetchDisableQuestionLibrary, fetchGetQuestionLibraryListAll } from '@/service/api/question'
import QuestionDrawer from './QuestionDrawer.vue'

const props = defineProps<{
  currentCategory: any
}>()

const questionList = ref<any[]>([])
const loading = ref(false)

const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  onChange: (page: number) => {
    pagination.value.page = page
    if (props.currentCategory?.Id) {
      fetchData(props.currentCategory.Id)
    }
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.value.pageSize = pageSize
    pagination.value.page = 1
    if (props.currentCategory?.Id) {
      fetchData(props.currentCategory.Id)
    }
  },
})

const searchText = ref('')
const showQuestionModal = ref(false)
const questionOperation = ref<'add' | 'edit'>('add')
const currentQuestion = ref<any>(null)

// 批量选择
const selectedQuestionIds = ref<number[]>([])

// 全选状态
const isAllSelected = computed(() => {
  return questionList.value.length > 0 && selectedQuestionIds.value.length === questionList.value.length
})

// 半选状态
const isIndeterminate = computed(() => {
  return selectedQuestionIds.value.length > 0 && selectedQuestionIds.value.length < questionList.value.length
})

function handleSelectAll(checked: boolean) {
  if (checked) {
    selectedQuestionIds.value = questionList.value.map(q => q.Id)
  }
  else {
    selectedQuestionIds.value = []
  }
}

function handleSelect(id: number, checked: boolean) {
  if (checked) {
    selectedQuestionIds.value.push(id)
  }
  else {
    selectedQuestionIds.value = selectedQuestionIds.value.filter(v => v !== id)
  }
}

function handleBatchDelete() {
  if (selectedQuestionIds.value.length === 0) {
    window?.$message?.warning('请先选择要删除的题目')
    return
  }

  window?.$dialog?.warning({
    title: '批量删除警告',
    content: `确定要删除选中的 ${selectedQuestionIds.value.length} 道题目吗？此操作无法撤销。`,
    positiveText: '确定删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { error } = await fetchDeleteQuestionLibrary(selectedQuestionIds.value)
      if (!error) {
        window?.$message?.success('批量删除成功')
        selectedQuestionIds.value = []
        if (props.currentCategory?.Id) {
          fetchData(props.currentCategory.Id)
        }
      }
      else {
        window?.$message?.error('批量删除失败')
      }
    },
  })
}

async function handleBatchDisable(disabled: boolean) {
  if (selectedQuestionIds.value.length === 0) {
    window?.$message?.warning('请先选择要操作的题目')
    return
  }

  const payload = selectedQuestionIds.value.map(id => ({
    id,
    Id: id,
    IsDisabled: disabled,
  }))

  const { error } = await fetchDisableQuestionLibrary(payload)
  if (!error) {
    window?.$message?.success(`批量${disabled ? '禁用' : '启用'}成功`)
    selectedQuestionIds.value = []
    if (props.currentCategory?.Id) {
      fetchData(props.currentCategory.Id)
    }
  }
  else {
    window?.$message?.error(`批量${disabled ? '禁用' : '启用'}失败`)
  }
}

const hasCategory = computed(() => {
  return !!props.currentCategory
})

watch(() => props.currentCategory, (newVal) => {
  if (newVal && newVal.Id) {
    pagination.value.page = 1
    searchText.value = ''
    fetchData(newVal.Id)
  }
  else {
    questionList.value = []
  }
}, { immediate: true })

async function fetchData(id: number) {
  loading.value = true
  const { data, error } = await fetchGetQuestionLibraryListAll({
    questionId: id,
    pageIndex: pagination.value.page,
    pageSizes: pagination.value.pageSize,
    keyWords: searchText.value,
  })
  if (!error) {
    questionList.value = data?.data?.QuestionListDetailList || []
    pagination.value.itemCount = data?.data?.TotalNum || 0
  }
  loading.value = false
}

function handleSearch() {
  pagination.value.page = 1
  if (props.currentCategory?.Id) {
    fetchData(props.currentCategory.Id)
  }
}

function handleAddQuestion() {
  if (!props.currentCategory) {
    window?.$message?.warning('请先选择一个分类')
    return
  }
  questionOperation.value = 'add'
  currentQuestion.value = null
  showQuestionModal.value = true
}

function handleEditQuestion(id: number) {
  const question = questionList.value.find(q => q.Id === id)
  if (question) {
    questionOperation.value = 'edit'
    currentQuestion.value = question
    showQuestionModal.value = true
  }
}

function handleDeleteQuestion(id: number) {
  window?.$dialog?.warning({
    title: '警告',
    content: '确定要删除这道题目吗？此操作无法撤销。',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { error } = await fetchDeleteQuestionLibrary([id])
      if (!error) {
        window?.$message?.success('删除成功')
        if (props.currentCategory?.Id) {
          fetchData(props.currentCategory.Id)
        }
      }
      else {
        window?.$message?.error('删除失败')
      }
    },
  })
}

function onDrawerSuccess() {
  showQuestionModal.value = false
  if (props.currentCategory?.Id) {
    fetchData(props.currentCategory.Id)
  }
}
</script>

<template>
  <div class="h-full flex flex-col flex-1 overflow-hidden bg-white">
    <!-- 分类面包屑导航 -->
    <div class="flex flex-col gap-4 border-b border-gray-100 px-6 py-4">
      <NBreadcrumb>
        <NBreadcrumbItem>题库全集</NBreadcrumbItem>
        <NBreadcrumbItem v-if="currentCategory && currentCategory.level === 1">
          {{ currentCategory.name }}
        </NBreadcrumbItem>
      </NBreadcrumb>

      <div class="flex items-center justify-between">
        <h1 class="m-0 text-xl text-gray-800 font-bold">
          {{ currentCategory ? currentCategory.name : '' }}
        </h1>
      </div>

      <!-- 搜索框 -->
      <div v-if="currentCategory" class="mt-2 flex items-center justify-between">
        <div class="flex items-center gap-3">
          <NCheckbox :checked="isAllSelected" :indeterminate="isIndeterminate" @update:checked="handleSelectAll">
            全选 ({{ selectedQuestionIds.length }})
          </NCheckbox>
          <NInput v-model:value="searchText" placeholder="输入题目关键字在当前分类下搜索..." class="!w-80" @keyup.enter="handleSearch">
            <template #prefix>
              <SvgIcon icon="carbon:search" class="text-gray-400" />
            </template>
          </NInput>
        </div>

        <div class="flex gap-3">
          <NButton
            v-if="selectedQuestionIds.length > 0" type="warning" secondary
            @click="() => handleBatchDisable(true)"
          >
            <template #icon>
              <SvgIcon icon="carbon:view-off" />
            </template>
            批量禁用
          </NButton>
          <NButton
            v-if="selectedQuestionIds.length > 0" type="success" secondary
            @click="() => handleBatchDisable(false)"
          >
            <template #icon>
              <SvgIcon icon="carbon:view" />
            </template>
            批量启用
          </NButton>
          <NButton v-if="selectedQuestionIds.length > 0" type="error" secondary @click="handleBatchDelete">
            <template #icon>
              <SvgIcon icon="carbon:trash-can" />
            </template>
            批量删除 ({{ selectedQuestionIds.length }})
          </NButton>
          <NButton type="primary" @click="handleAddQuestion">
            <template #icon>
              <SvgIcon icon="carbon:add" />
            </template>
            新增题目
          </NButton>
        </div>
      </div>
    </div>

    <!-- 题目列表区域 -->
    <div class="flex-1 overflow-y-auto bg-gray-50/50 p-6">
      <template v-if="!hasCategory">
        <div class="h-full flex flex-col items-center justify-center text-gray-400">
          <NEmpty description="暂无数据">
            <template #extra>
              请从左侧选择一个分类以管理题目数据
            </template>
          </NEmpty>
        </div>
      </template>

      <template v-else-if="questionList.length === 0">
        <div class="mt-20 flex justify-center">
          <NEmpty description="该分类下暂无题目" />
        </div>
      </template>

      <!-- 题目列表 -->
      <template v-else>
        <div class="grid grid-cols-1 gap-4 lg:grid-cols-2">
          <NCard
            v-for="q in questionList" :key="q.Id" size="small" hoverable class="rounded-xl transition-all" :class="{
              'ring-2 ring-primary-500 bg-primary-50': selectedQuestionIds.includes(q.Id),
              'opacity-50 grayscale': q.IsDisabled === 1,
            }" @click="handleSelect(q.Id, !selectedQuestionIds.includes(q.Id))"
          >
            <template #header>
              <div class="flex items-center gap-2" @click.stop>
                <NCheckbox
                  :checked="selectedQuestionIds.includes(q.Id)"
                  @update:checked="(val) => handleSelect(q.Id, val)"
                />
                <NTag size="small" type="primary" :bordered="false">
                  ID: {{ q.Id }}
                </NTag>
                <NTag size="small" :type="q.IsGood === 1 ? 'info' : 'default'" :bordered="false">
                  {{ q.IsGood === 1 ? '优先' : '随机' }}
                </NTag>
                <NTag v-if="q.IsDisabled" size="small" type="error" :bordered="false">
                  已禁用
                </NTag>
              </div>
            </template>
            <template #header-extra>
              <!-- <span class="text-xs text-gray-400 font-mono">{{ q.score }} PTS / {{ q.time }} S</span> -->
            </template>

            <div class="py-2 text-base text-gray-700 font-medium" v-html="q.Name" />

            <!-- 图片展示 -->
            <div v-if="q.ImageUrl" class="mb-2">
              <NImage :src="q.ImageUrl" width="100" class="block rounded-lg" />
            </div>

            <!-- 标准答案 -->
            <div class="mt-3 border border-green-100 rounded-lg bg-green-50 p-3">
              <div class="mb-1 text-xs text-green-600 font-bold tracking-wider uppercase">
                STANDARD ANSWER
              </div>
              <div class="text-green-800 font-bold">
                {{ q.Answer }}
              </div>
            </div>

            <!-- 操作按钮 -->
            <template #action>
              <div class="flex justify-end gap-2" @click.stop>
                <NButton size="tiny" quaternary type="primary" @click="handleEditQuestion(q.Id)">
                  <template #icon>
                    <SvgIcon icon="carbon:edit" />
                  </template>
                </NButton>
                <NButton size="tiny" quaternary type="error" @click="handleDeleteQuestion(q.Id)">
                  <template #icon>
                    <SvgIcon icon="carbon:trash-can" />
                  </template>
                </NButton>
              </div>
            </template>
          </NCard>
        </div>
        <div class="mt-4 flex justify-end">
          <NPagination
            v-model:page="pagination.page" v-model:page-size="pagination.pageSize"
            :item-count="pagination.itemCount" :page-sizes="pagination.pageSizes" show-size-picker
            @update:page="pagination.onChange" @update:page-size="pagination.onUpdatePageSize"
          >
            <template #prefix="{ itemCount }">
              共 {{ itemCount }} 项
            </template>
          </NPagination>
        </div>
      </template>
    </div>

    <QuestionDrawer
      v-model:show="showQuestionModal"
      :operation="questionOperation"
      :question-data="currentQuestion"
      :current-category="currentCategory"
      @success="onDrawerSuccess"
    />
  </div>
</template>

<style lang="scss" scoped>
:deep(.n-card__content) {
  img {
    height: 100px !important;
    width: 100px !important;
    object-fit: contain;
  }
}
</style>
