<!-- eslint-disable no-console -->
<script setup lang="ts">
import { NButton, NTag } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import PageHeader from '@/components/common/page-header.vue'
import { PublishStatus } from '@/enum/business'
import { useDict } from '@/hooks/business/useDict'
import { useRouterPush } from '@/hooks/common/router'

import {
  fetchDeleteActivity,
  fetchGetActivityDetail,
  fetchGetQuestionList,
  fetchGetTeamListByGroupId,
  fetchUpdateActivity,
  fetchUpdatePublishStatus,
  fetchUpdateQuestion,
  fetchUpdateTeamList,
} from '@/service/api/competition'
import BasicInfoCard from './modules/BasicInfoCard.vue'
import QuestionConfigCard from './modules/QuestionConfigCard.vue'
import SideMenu from './modules/SideMenu.vue'

import TeamListCard from './modules/TeamListCard.vue'

const { options: publishStatusDict } = useDict('publish_status')

const { routerBack } = useRouterPush()

const route = useRoute()

const activeEditModule = ref<string | null>(null) // 'basic' | 'team' | 'question'

const currentGroupId = ref(0)
const basicInfoCardRef = ref()
const teamListCardRef = ref()
const questionConfigCardRef = ref()

/** 规范化路由 Query 的 Id 字段为字符串 */
const competitionId = computed<string>(() => {
  const q = route.query.Id
  const v = Array.isArray(q) ? q[0] : q
  return (v ?? '') as string
})

/** 基础信息数据 */
const basicInfo = ref<Api.Competition.ActivityDetail>({
  Id: 0,
  RoomID: 0,
  Name: '',
  StartTime: '',
  EndTime: '',
  Teams: 0,
  TeamGroupNumber: 0,
  PublishStatus: 0,
  BackgroundImg: '',
  CreatedTime: '',
})

/** 队伍列表 */
const teamList = ref<Array<Api.Competition.TeamListRecord>>([])

/** 题目配置 */
const questionsList = ref<Array<Api.Competition.QuestionListRecord>>([])

/** 监听竞赛ID变化并拉取详情 */
watch(competitionId, async (val: string) => {
  if (val) {
    const id = Number(val)
    /** 并行获取详情数据 */
    await getActivityDetail(id)
    await getQuestionList(id)
  }
}, { immediate: true })

/** 获取活动基础详情 */
async function getActivityDetail(id: number) {
  const { response, error } = await fetchGetActivityDetail(id)
  if (!error) {
    basicInfo.value = response?.data?.data || {}
    // eslint-disable-next-line no-console
    console.log('获取活动基础详情', response.data.data)
  }
}

/** 点击分组 */
async function handleChangeGroup(id: number) {
  currentGroupId.value = id
  // 拉取当前分组的队伍列表
  await fetchTeamListByGroupId(id)
}

/** 根据组id查询队伍列表 */
async function fetchTeamListByGroupId(GroupID: number) {
  const { data, error } = await fetchGetTeamListByGroupId(GroupID)
  if (!error) {
    teamList.value = data?.data || []
    // eslint-disable-next-line no-console
    console.log('获取队伍列表', data?.data || [])
  }
}

/** 获取活动题目列表 */
async function getQuestionList(id: number) {
  const { data, error } = await fetchGetQuestionList(id, 3)
  if (!error) {
    questionsList.value = data?.data || []
    // eslint-disable-next-line no-console
    console.log('获取题目列表', data?.data || [])
  }
}

// 点击编辑模块
/** 请求编辑模块 */
function handleRequestEdit(moduleName: string) {
  if (basicInfo.value.PublishStatus === PublishStatus.Processing || basicInfo.value.PublishStatus === PublishStatus.Finished || basicInfo.value.PublishStatus === PublishStatus.Published) {
    window.$message?.warning('已发布、进行中或已结束的赛事无法编辑')
    return
  }
  if (activeEditModule.value && activeEditModule.value !== moduleName) {
    window.$message?.warning('请先保存或取消当前正在编辑的模块')
    return
  }
  activeEditModule.value = moduleName
}

/** 点击取消编辑 */
function handleCancelEdit() {
  activeEditModule.value = null
  // Refresh data to reset forms
  if (competitionId.value) {
    const id = Number(competitionId.value)
    getActivityDetail(id)
    getQuestionList(id)
    if (currentGroupId.value)
      fetchTeamListByGroupId(currentGroupId.value)
  }
}

/** 点击保存基础信息 */
async function handleSaveBasic() {
  const basicForm = basicInfoCardRef.value?.form
  if (!basicForm)
    return

  const params: Api.Competition.ActivityDetail = {
    ...basicInfo.value,
    ...basicForm,
  }
  // eslint-disable-next-line no-console
  console.log('基础信息保存参数', params)
  const { error } = await fetchUpdateActivity(params)
  if (!error) {
    window.$message?.success('基础信息保存成功')
    activeEditModule.value = null
    getActivityDetail(Number(competitionId.value))
  }
}

/** 点击保存队伍信息 */
async function handleSaveTeam() {
  const teams = teamListCardRef.value?.localTeams
  if (!teams)
    return

  const params: Api.Competition.CreateTeamListRequest[] = teams.map((t: Api.Competition.TeamListRecord) => ({
    id: t.Id,
    mainId: t.MainId,
    number: t.Number,
    name: t.Name,
    penSerial: t.PenSerial,
    nameList: t.NameList,
    schoolName: t.SchoolName,
    teamGroupId: t.TeamGroupId,
    headImg: t.HeadImg,
  }))
  // eslint-disable-next-line no-console
  console.log('新增队伍信息的params', params)
  const { error } = await fetchUpdateTeamList(params)
  if (!error) {
    window.$message?.success('队伍信息保存成功')
    activeEditModule.value = null
    if (currentGroupId.value)
      fetchTeamListByGroupId(currentGroupId.value)
  }
}

/** 点击保存题目配置 */
async function handleSaveQuestion() {
  const component = questionConfigCardRef.value
  if (!component)
    return

  const valid = await component.validate()
  if (!valid)
    return

  const modelValue = component.modelValue
  console.log('原始题目配置', modelValue)
  // 扁平化题目配置，将 rounds 中的 questions 合并到 flatQuestions 中
  const flatQuestions: Api.Competition.QuestionListRecord[] = []
  modelValue.rounds.forEach((r: any) => {
    r.questions.forEach((q: any, index: number) => {
      flatQuestions.push({
        ActitvityQuestionName: q.ActitvityQuestionName || '',
        ActivityID: Number(competitionId.value),
        ID: q.ID || 0,
        Point: q.Point,
        QuestionID: q.QuestionID ? Number(q.QuestionID) : 0,
        QuestionIndex: index,
        QuestionRule: q.QuestionRule ? Number(q.QuestionRule) : 0,
        QuestionSubTitle: '',
        QuestionTime: q.QuestionTime,
        RoundType: Number(r.roundType),
        TemplateID: q.TemplateID || 0,
        UIType: q.UIType,
      })
    })
  })

  // 根据 questionID 降序排序 (例如: 54455 -> 55544)
  // flatQuestions.sort((a, b) => Number(b.QuestionID) - Number(a.QuestionID))

  // 重新计算 questionIndex
  flatQuestions.forEach((item, index) => {
    item.QuestionIndex = index
  })

  // eslint-disable-next-line no-console
  console.log('新增题目配置的params', flatQuestions)
  const { error } = await fetchUpdateQuestion(flatQuestions)
  if (!error) {
    window.$message?.success('题目配置保存成功')
    activeEditModule.value = null
    getQuestionList(Number(competitionId.value))
  }
}

/** 删除赛事 */
async function handleDelete() {
  window.$dialog?.warning({
    title: '删除确认',
    content: '确定要删除该赛事吗？此操作无法撤销。',
    positiveText: '确定删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { error } = await fetchDeleteActivity(Number(competitionId.value))
      if (!error) {
        window.$message?.success('删除成功')
        routerBack()
      }
    },
  })
}

/** 立即发布 */
async function handlePublish() {
  window.$dialog?.info({
    title: '发布确认',
    content: '确定要立即发布该赛事吗？发布后将对外可见。',
    positiveText: '立即发布',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { error } = await fetchUpdatePublishStatus(Number(competitionId.value), PublishStatus.Published)
      if (!error) {
        window.$message?.success('发布成功')
        getActivityDetail(Number(competitionId.value))
      }
    },
  })
}

const publishStatusLabel = computed(() => {
  if (!publishStatusDict.value)
    return ''
  return publishStatusDict.value.find((item: any) => item.value === basicInfo.value.PublishStatus)?.label || ''
})

const isUnpublished = computed(() => basicInfo.value.PublishStatus === PublishStatus.Unpublished)
// const isPublished = computed(() => basicInfo.value.PublishStatus === PublishStatus.Published)
const statusConfig = computed(() => {
  const status = basicInfo.value.PublishStatus
  switch (status) {
    case PublishStatus.Unpublished:
      return { bgClass: 'bg-unpublished-100 text-unpublished-600' }
    case PublishStatus.Published:
      return { bgClass: 'bg-published-100 text-published-600' }
    case PublishStatus.Processing:
      return { bgClass: 'bg-processing-100 text-processing-600' }
    case PublishStatus.Finished:
      return { bgClass: 'bg-finished-100 text-finished-600' }
    default:
      return { bgClass: 'bg-unpublished-100 text-unpublished-600' }
  }
})
</script>

<template>
  <div class="h-full flex flex-col overflow-hidden bg-gray-50/50">
    <!-- 顶部 Header -->
    <PageHeader>
      <div class="flex items-center gap-2">
        <span class="text-sm text-gray-500">状态:</span>
        <NTag size="small" :bordered="false" :class="statusConfig.bgClass">
          {{ publishStatusLabel }}
        </NTag>
      </div>
      <template #action>
        <NButton v-if="isUnpublished" type="error" secondary @click="handleDelete">
          <template #icon>
            <icon-ic:baseline-delete-forever class="text-3xl" />
          </template>
          删除赛事
        </NButton>
        <NButton v-if="isUnpublished" type="primary" @click="handlePublish">
          <template #icon>
            <icon-ic:round-publish class="text-3xl" />
          </template>
          立即发布
        </NButton>
      </template>
    </PageHeader>

    <!-- 主内容区 -->
    <div class="flex flex-1 gap-4 overflow-hidden p-4">
      <!-- 左侧分组导航 -->
      <div class="h-full w-64 flex flex-col flex-shrink-0 overflow-hidden rounded-xl bg-white shadow-sm">
        <SideMenu :activity-id="competitionId" :disabled="!!activeEditModule" @change="handleChangeGroup" />
      </div>

      <!-- 右侧主要内容区 -->
      <div class="h-full flex flex-col flex-1 overflow-hidden">
        <!-- 滚动内容区 -->
        <div class="no-scrollbar flex flex-col flex-1 gap-4 overflow-y-auto">
          <BasicInfoCard
            ref="basicInfoCardRef" :is-edit="activeEditModule === 'basic'" :base-info="basicInfo"
            :publish-status="basicInfo.PublishStatus" @enter-edit="handleRequestEdit('basic')" @save="handleSaveBasic"
            @cancel="handleCancelEdit"
          />
          <TeamListCard
            ref="teamListCardRef" :is-edit="activeEditModule === 'team'" :teams="teamList"
            :publish-status="basicInfo.PublishStatus" :current-group-id="currentGroupId"
            @enter-edit="handleRequestEdit('team')" @save="handleSaveTeam" @cancel="handleCancelEdit"
          />
          <QuestionConfigCard
            ref="questionConfigCardRef" :is-edit="activeEditModule === 'question'"
            :publish-status="basicInfo.PublishStatus" :questions="questionsList"
            @enter-edit="handleRequestEdit('question')" @save="handleSaveQuestion" @cancel="handleCancelEdit"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.no-scrollbar::-webkit-scrollbar {
  display: none;
}

.no-scrollbar {
  -ms-overflow-style: none;
  scrollbar-width: none;
}
</style>
