<script setup lang="ts">
import { NButton, NModal, NStep, NSteps } from 'naive-ui'
import { computed, onMounted, ref, useTemplateRef, watch } from 'vue'
import { useDict } from '@/hooks/business/useDict'
import { fetchCreateCompetition, fetchGetRoomList } from '@/service/api/competition'
/** 房间相关接口 */
import BasicInfo from './modules/BasicInfo.vue'

import GroupManagement from './modules/GroupManagement.vue'
// import HardwareBinding from './modules/HardwareBinding.vue'
import QuestionConfig from './modules/QuestionConfig.vue'

const props = defineProps<{
  show: boolean
}>()

const emit = defineEmits<{
  (e: 'update:show', visible: boolean): void
  (e: 'success'): void
}>()

const { options: roundTypeOptions } = useDict('round_type')
const { options: scoreTypeOptions } = useDict('score_type')

const currentStep = ref<number>(1)
/** 房间列表 */
const roomListOptions = ref<{ label: string, value: number }[]>([])

// Reset step when modal opens
watch(() => props.show, (val) => {
  if (val) {
    currentStep.value = 1
  }
})

const competitionData = ref({
  name: '阅读之星年度总决赛', // 竞赛名称
  startTime: null as string | null, // 竞赛开始时间
  endTime: null as string | null, // 竞赛结束时间
  groupCount: 10, // 组别数量
  teamCount: 4, // 每组队伍数量
  poster: '', // 竞赛海报
  roomId: null, // 关联场地AP
  subTitle: '星·辞海遨游', // 活动口号或副标题
  extraTimeContent: '每道题额外时间10秒', // 加时赛的规则
  activityContent: '<p>本轮环节共有4道题目,分别是“<strong>诗词理解</strong>”、“<strong>联想对对碰</strong>”、“<strong>逆向接诗句</strong>”、“<strong>情景猜诗句</strong>”</p><p>阅读完题目介绍，主持人点击“<strong>开始作答</strong>”后均在答题本田字格上作答</p><p><br></p><p> “<strong>诗词理解</strong>” 根据题目选择正确答案</p><p> “<strong>联想对对碰</strong>” 根据关键信息写出完整诗句</p><p> “<strong>逆向接诗句</strong>” 根据关键信息写出关联诗句</p><p> “<strong>情景猜诗句</strong>” 根据情景写出关联诗句</p><p><br></p><p>答题倒计时结束后，界面自动跳转到下一题</p>',
  rounds: [ // 赛题包配置
    {
      id: 'round_default',
      name: '星·辞海遨游',
      roundType: roundTypeOptions.value?.[0]?.value || 0,
      questions: Array.from({ length: 10 }).map(() => ({
        value: null,
        score: 5,
        time: 30,
        title: '第1题',
        scoreType: scoreTypeOptions.value?.[0]?.value || 0,
      })),
    },
  ],
  // 名单录入
  groupManagement: [], // 组别管理
  isPublic: true, // 是否公开
})

const steps = [
  { title: '基础设置', component: BasicInfo },
  { title: '名单录入', component: GroupManagement },
  // { title: '硬件绑定', component: HardwareBinding },
  { title: '题目配置', component: QuestionConfig },
]

const currentComponent = computed(() => steps[currentStep.value - 1]?.component)
const stepComponentRef = useTemplateRef('stepComponentRef')

function handleClose() {
  emit('update:show', false)
}

async function nextStep() {
  // 校验当前步骤
  const componentInstance = stepComponentRef.value
  if (componentInstance && typeof componentInstance.validate === 'function') {
    const isValid = componentInstance.validate()
    if (!isValid)
      return
  }

  if (currentStep.value < 3) {
    currentStep.value++
  }
  else { // 最后一步 数据提交
    // 提交表单
    await submitForm()
  }
}

async function submitForm() {
  const { name, startTime, endTime, groupCount, teamCount, poster, rounds, groupManagement, roomId, subTitle, extraTimeContent, activityContent } = competitionData.value

  if (!startTime || !endTime) {
    window.$message?.error('请完善比赛时间')
    return
  }

  // 活动基础信息
  const roomParams = {
    id: 0,
    name,
    startTime,
    endTime,
    teams: groupCount * teamCount,
    teamGroupNumber: teamCount,
    createdTime: startTime,
    roomID: roomId || 0,
    backgroundImg: poster,
    publishStatus: 0,
    ActivityTitle: subTitle,
    ActivityContent: activityContent,
    ExtraTimeContent: extraTimeContent,
  }
  const teamParams: Api.Competition.CreateTeamListRequest[] = []

  // 遍历组别管理
  groupManagement.forEach((group: any) => {
    // 遍历队伍
    (group as any).teams.forEach((team: any, index: number) => {
      teamParams.push({
        ...team,
        id: 0,
        mainId: 0,
        number: `${group.id}-${index + 1}`,
        name: team.name,
        penSerial: `${group.id}-${index + 1}`,
        nameList: `${index + 1}-${team.name}`,
        schoolName: team.name,
        teamGroupId: 0,
      })
    })
  })

  const questionParams: Api.Competition.CreateQuestionRequest[] = []

  // 遍历赛题包配置
  rounds.forEach((round: any) => {
    // 遍历题目
    round.questions.forEach((question: any, index: number) => {
      questionParams.push({
        id: 0,
        activityID: 0,
        questionID: question.QuestionID,
        questionIndex: index,
        actitvityQuestionName: question.ActitvityQuestionName || '',
        questionTime: question.QuestionTime,
        questionRule: question.QuestionRule,
        uiType: question.UIType,
        point: question.Point,
        templateID: question.TemplateID,
        roundType: round.roundType,
        questionSubTitle: question.ActitvityQuestionName || '',
      })
    })
  })

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

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

  // eslint-disable-next-line no-console
  console.log(questionParams, 'questionParams')

  const { error } = await fetchCreateCompetition({
    actMain: roomParams,
    teams: teamParams,
    questions: questionParams,
  })

  if (!error) {
    window.$message?.success('比赛发布成功')
    emit('success')
    emit('update:show', false)
  }
}

function prevStep() {
  if (currentStep.value > 1) {
    currentStep.value -= 1
  }
}

function handleReset() {
  window.$dialog?.warning({
    title: '重置确认',
    content: '确定要重置当前步骤的数据吗？此操作无法撤销。',
    positiveText: '确定重置',
    negativeText: '取消',
    onPositiveClick: () => {
      const componentInstance = stepComponentRef.value
      if (componentInstance && typeof componentInstance.reset === 'function') {
        componentInstance.reset()
        window.$message?.success('重置成功')
      }
    },
  })
}

/** 获取房间列表 */
async function getRoomList() {
  const { data, error } = await fetchGetRoomList()
  if (data && !error) {
    const dataList = data.data || []
    const roomList = dataList.map(item => ({
      label: item.Name,
      value: item.ID,
    }))
    roomListOptions.value = roomList
  }
}

onMounted(() => {
  getRoomList()
})

watch(() => competitionData.value, (val) => {
  // eslint-disable-next-line no-console
  console.log(val, 'competitionData.value')
}, { deep: true })
</script>

<template>
  <NModal :show="show" :mask-closable="false" @update:show="handleClose">
    <div
      class="relative h-[90vh] max-h-[1080px] max-w-[95vw] w-[1380px] flex flex-col overflow-hidden rounded-[2rem] bg-white shadow-2xl transition-all"
    >
      <!-- Header -->
      <div class="flex items-center justify-between px-10 py-8">
        <!-- Logo & Title -->
        <div class="flex items-center gap-4">
          <div class="h-12 w-12 flex items-center justify-center rounded-xl bg-[#3B82F6] shadow-blue-500/30 shadow-lg">
            <div class="i-carbon-circle-dash text-2xl text-white" />
          </div>
          <div class="flex flex-col">
            <h2 class="m-0 text-xl text-gray-800 font-bold leading-none">
              比赛创建向导
            </h2>
            <span class="mt-1 text-xs text-gray-400 font-bold tracking-widest uppercase">
              Setup Configuration Wizard
            </span>
          </div>
        </div>

        <!-- Steps -->
        <div class="flex-1 px-20">
          <NSteps :current="currentStep" class="custom-steps" size="medium">
            <NStep v-for="(step, index) in steps" :key="index" :title="step.title" />
          </NSteps>
        </div>

        <!-- Close Button -->
        <div class="flex items-center gap-3">
          <NButton secondary type="warning" size="small" @click="handleReset">
            <template #icon>
              <icon-ic-baseline-refresh class="text-icon" />
            </template>
            重置当前步骤
          </NButton>
          <button
            class="h-10 w-10 flex items-center justify-center rounded-full text-gray-300 transition-colors hover:scale-110 hover:bg-gray-100 hover:text-gray-500"
            @click="handleClose"
          >
            <NButton
              type="primary" size="small"
              class="h-8 w-8 rounded-full text-gray-300 transition-colors hover:bg-gray-100 hover:text-gray-500"
            >
              <icon-ic-baseline-close class="text-icon" />
            </NButton>
          </button>
        </div>
      </div>

      <!-- Content -->
      <div class="flex-1 overflow-y-auto px-10">
        <div class="h-full">
          <KeepAlive>
            <component
              :is="currentComponent" ref="stepComponentRef" v-model="competitionData" :config="competitionData"
              :room-list-options="roomListOptions"
            />
          </KeepAlive>
        </div>
      </div>

      <!-- Footer -->
      <div class="flex items-center justify-between border-t border-gray-100 bg-gray-50/50 px-10 py-6">
        <NButton v-if="currentStep > 1" secondary type="primary" size="large" class="px-8 font-bold" @click="prevStep">
          <template #icon>
            <icon-ic-baseline-arrow-back class="text-icon" />
          </template>
          上一步
        </NButton>
        <div v-else />

        <NButton
          type="primary" size="large" class="px-10 text-lg font-bold shadow-blue-500/30 shadow-lg"
          @click="nextStep"
        >
          {{ currentStep === 3 ? '确认发布比赛' : '下一步' }}
          <template #icon>
            <icon-ic-baseline-arrow-forward v-if="currentStep < 4" class="text-icon" />
            <icon-ic-baseline-check v-else class="text-icon" />
          </template>
        </NButton>
      </div>
    </div>
  </NModal>
</template>
