<template>
  <div class="px-[30px] py-5 user-info min-h-full flex flex-col">
    <!-- 标签页切换 -->
    <el-form>
      <!-- 查询进度区域 -->
      <div class="border-b border-br pb-5">
        <span class="text-2xl font-medium">查询报名进度</span>
      </div>
      <!-- 查询表单 -->
      <el-card class="!border-none mb-6" shadow="never">
        <el-form
          :model="queryForm"
          :rules="queryRules"
          ref="queryFormRef"
          label-width="100px"
          class="mt-4"
        >
          <el-form-item label="身份证号" prop="idCard">
            <el-input
              v-model="queryForm.idCard"
              placeholder="请输入18位身份证号"
              maxlength="18"
              @input="handleIdCardInput"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuerySubmit" :loading="isQueryLoading">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <!-- 进度展示区域 -->
      <div v-if="submission" class="border-b border-br pb-5">
        <span class="text-2xl font-medium">注册状态</span>
      </div>
      <el-card
        v-if="submission"
        class="!border-none mb-4 flex-1"
        shadow="never"
      >
        <div class="status-info mt-4">
          <!-- 步骤条展示 -->
          <div class="mb-6">
            <div class="text-tx-secondary text-sm mb-4">状态进度</div>
            <el-steps
              :active="activeStep"
              finish-status="success"
              class="w-full"
              style="text-align: left"
            >
              <el-step
                v-for="(step, index) in statusConfig.steps"
                :key="index"
                :title="stepTitles[index]"
                :description="getStepDescription(index)"
                :status="getStepStatus(index)"
              />
            </el-steps>
          </div>
          <!-- 显示拒绝原因 -->
          <div v-if="rejectionReason" class="text-danger mt-4">
            <i class="el-icon-error mr-2"></i>
            拒绝原因：{{ rejectionReason }}
          </div>
        </div>
      </el-card>
    </el-form>

    <!-- 查询进度弹窗（保持全局可访问） -->
    <el-dialog
      v-model="isQueryDialogOpen"
      title="查询报名进度"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="queryForm"
        :rules="queryRules"
        ref="queryFormRef"
        label-width="100px"
        class="mt-4"
      >
        <el-form-item label="身份证号" prop="idCard">
          <el-input
            v-model="queryForm.idCard"
            placeholder="请输入18位身份证号"
            maxlength="18"
            @input="handleIdCardInput"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isQueryDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="handleQuerySubmit" :loading="isQueryLoading">
          查询
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, computed, onMounted, ref, unref } from 'vue'
import { ElButton, ElMessage, ElForm, ElFormItem, ElInput, ElDialog, ElTabs, ElTabPane } from 'element-plus'
import {
  getEnrollmentProcessStatus
} from '@/api/enrollment'
import { useRoute } from 'vue-router'

const activeTab = ref('enroll') // 默认显示报名页面
const route = useRoute()
// 步骤标题与后端状态对应
const stepTitles = ['报名', '缴费', '等待录取']
const submission = ref(false) // 提交状态
const rejectionReason = ref('') // 拒绝原因
// 查询相关状态
const isQueryDialogOpen = ref(false) // 查询弹窗显示状态
const isQueryLoading = ref(false) // 查询加载状态
const queryFormRef = ref<InstanceType<typeof ElForm> | null>(null) // 查询表单引用
// 查询表单数据
const queryForm = reactive({
  idCard: ''
})

// 查询表单校验规则
const queryRules = reactive({
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: '请输入有效的18位身份证号',
      trigger: 'blur'
    }
  ]
})

// 学生信息数据
const studentData = reactive({
  baseInfo: {
    name: '',
    gender: 0,
    idCard: '',
    birthday: '',
    nationality: '',
    phone: '',
    email: '',
    homeAddress: '',
    nativePlace: '',
    invitationCode: '',
    politicalStatus: 0,
    previousSchool: '',
    schoolType: '',
    graduationYear: 2025,
    emergencyContact: '',
    emergencyPhone: '',
    relationship: ''
  }
})

// 状态配置
const statusConfig = reactive({
  steps: [
    { completed: false, time: 0, status: 0 }, // 报名
    { completed: false, time: 0, status: 0 }, // 缴费
    { completed: false, time: 0, status: 0 }, // 等待录取通知
  ],
  applicationNumber: '' // 报名编号
})

// 格式化时间戳为日期
const formatTime = (timestamp: number) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleDateString()
}

// 获取步骤描述
const getStepDescription = (index: number) => {
  const step = statusConfig.steps[index]
  const timeStr = formatTime(step.time)
  if (index === 0) {
    return step.completed ? `已完成${timeStr}` : '状态异常'
  } else if (index === 1) {
    if (step.status === 0) return '未缴费'
    if (step.status === 1) return `已缴费 ${timeStr}`
  } else if (index === 2) {
    if (step.status === 0) return '等待录取通知'
    if (step.status === 1) return `录取通知已发送 ${timeStr}`
    if (step.status === 2) return `未录取 ${timeStr}`
  } 
  return ''
}

// 处理身份证输入
const handleIdCardInput = () => {
  let idCardStr = String(queryForm.idCard || '')
  idCardStr = idCardStr.replace(/[^0-9Xx]/g, '')
  idCardStr = idCardStr.toUpperCase()
  if (idCardStr.length > 18) {
    idCardStr = idCardStr.slice(0, 18)
  }
  queryForm.idCard = idCardStr
}

// 提交查询
const handleQuerySubmit = async () => {
  const formRef = unref(queryFormRef)
  if (!formRef) return

  try {
    await formRef.validate()
    isQueryLoading.value = true

    const data = await getEnrollmentProcessStatus(queryForm)
    const statusRes = data.data

    if (statusRes) {
      isQueryDialogOpen.value = false
      submission.value = true

      statusConfig.applicationNumber = statusRes.applicationNumber || ''
      rejectionReason.value = statusRes.rejectionReason || ''

      statusConfig.steps[0] = {
        completed: statusRes.applicationNumber ? true : false,
        time: statusRes.applicationTime || 0,
        status: statusRes.applicationTime > 0 ? 1 : 0
      }
      statusConfig.steps[1] = {
        completed: statusRes.approvalStatus === 1,
        time: statusRes.approvalTime || 0,
        status: statusRes.approvalStatus || 0
      }
      statusConfig.steps[2] = {
        completed: statusRes.admissionStatus === 6,
        time: statusRes.admissionTime || 0,
        status: statusRes.admissionStatus || 0
      }

      ElMessage.success('查询成功')
    } else {
      ElMessage.info('未查询到相关报名记录')
      resetStatusConfig()
    }
  } catch (error) {
    console.error('查询进度失败：', error)
    ElMessage.error('查询失败，请稍后重试')
  } finally {
    isQueryLoading.value = false
  }
}

// 加载流程状态
const loadProcessStatus = async (idCard?: string) => {
  const cardNo = idCard || studentData.baseInfo.idCard
  if (!cardNo || typeof cardNo !== 'string') return

  try {
    const statusRes = await getEnrollmentProcessStatus(cardNo)
    if (statusRes) {
      submission.value = true
      statusConfig.applicationNumber = statusRes.data.applicationNumber || ''
      rejectionReason.value = statusRes.data.rejectionReason || ''

      statusConfig.steps[0] = {
        completed: statusRes.data.applicationNumber ? true : false,
        time: statusRes.data.applicationTime || 0,
        status: statusRes.data.applicationTime > 0 ? 1 : 0
      }
      statusConfig.steps[1] = {
        completed: statusRes.data.approvalStatus === 1,
        time: statusRes.data.approvalTime || 0,
        status: statusRes.data.approvalStatus || 0
      }
      statusConfig.steps[2] = {
        completed: statusRes.data.admissionStatus === 1,
        time: statusRes.data.admissionTime || 0,
        status: statusRes.data.admissionStatus || 0
      }
    }
  } catch (error) {
    console.error('刷新状态失败：', error)
  }
}

// 重置状态配置
const resetStatusConfig = () => {
  statusConfig.steps = [
    { completed: false, time: 0, status: 0 },
    { completed: false, time: 0, status: 0 },
    { completed: false, time: 0, status: 0 }
  ]
  statusConfig.applicationNumber = ''
  rejectionReason.value = ''
  submission.value = false
  const graduationYear = studentData.baseInfo.graduationYear
  Object.assign(studentData.baseInfo, {
    name: '',
    gender: 0,
    idCard: '',
    birthday: '',
    nationality: '',
    phone: '',
    email: '',
    homeAddress: '',
    nativePlace: '',
    politicalStatus: 0,
    previousSchool: '',
    schoolType: '',
    graduationYear,
    emergencyContact: '',
    emergencyPhone: '',
    relationship: ''
  })
}

// 动态推导当前激活的步骤
const activeStep = computed(() => {
  if (
    statusConfig.steps[1].status === 2 ||
    statusConfig.steps[2].status === 2
  ) {
    return statusConfig.steps[1].status === 2 ? 1 : 2
  }

  const count = completedStepCount.value
  return count >= statusConfig.steps.length
    ? statusConfig.steps.length - 1
    : count
})

// 获取步骤状态
const getStepStatus = (index: number) => {
  if (statusConfig.steps[index].completed) {
    return 'finish'
  }

  if (
    (index === 1 && statusConfig.steps[index].status === 2) ||
    (index === 2 && statusConfig.steps[index].status === 2)
  ) {
    return 'error'
  }

  return index === activeStep.value ? 'process' : 'wait'
}

// 计算已完成的步骤数量
const completedStepCount = computed(() => {
  return statusConfig.steps.filter((step) => step.completed).length
})

// 页面加载时初始化
onMounted(() => {
  // 新增：从路由参数获取身份证号并自动查询
  const idCardFromRoute = route.query.idCard as string
  if (idCardFromRoute) {
    queryForm.idCard = idCardFromRoute
    // 延迟执行避免表单验证时机问题
    setTimeout(() => {
      handleQuerySubmit()
    }, 100)
  } else {
    const idCard = studentData.baseInfo.idCard
    if (idCard && typeof idCard === 'string') {
      loadProcessStatus(idCard)
    }
  }
})
</script>
<style lang="scss" scoped>
.el-dialog__body {
  padding: 20px;
}
.el-form-item {
  margin-bottom: 20px;
}
.el-tabs {
  margin-bottom: 20px;
}
</style>
