<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { ContestJoinParams } from '../types'
import AppUpload from '@/components/base/AppUpload.vue'
import { pick } from 'lodash-es'
import { contestModeList } from '@/utils/dictionary'
import { useMapStore } from '@/stores/map'
import { useCountdown } from '@/composables/useCountdown'
import { joinContest, getStudentInfo, sendApplySMS } from '../api'

const { second, disabled, start } = useCountdown()
const countdownText = $computed(() => {
  return disabled.value ? `（${second.value}）秒` : '点击获取'
})
// 发送验证码
function sendSMS() {
  start()
  sendApplySMS({ competition_id: form.competition_id, mobile: form.mobile }).catch(() => {
    stop()
  })
}
const router = useRouter()
const route = useRoute()

// 性别
const genderList = useMapStore().getMapValuesByKey('system_gender')
// 证件类型
const systemIdTypeList = useMapStore().getMapValuesByKey('system_id_type')

function fetchStudentInfo() {
  getStudentInfo().then(res => {
    const { student = {}, specialty = {}, org = {}, classes = [] } = res.data
    const [studentClass = {}] = classes
    Object.assign(form, {
      student_name: student.name,
      gender: student.gender.toString(),
      id_type: student.id_type.toString(),
      id_number: student.id_number,
      mobile: student.mobile,
      org_name: org.name,
      province_name: student.info?.province_name,
      city_name: student.info?.city_name,
      county_name: student.info?.county_name,
      specialty_name: specialty.name,
      class_name: studentClass.name
    })
  })
}
onMounted(fetchStudentInfo)

const formRef = $ref<FormInstance>()
const form = reactive({
  name: route.query.name as string,
  competition_id: route.query.id as string,
  mode: '1',
  student_name: '',
  gender: '1',
  id_type: '1',
  id_number: '',
  mobile: '',
  org_name: '',
  province_name: '',
  city_name: '',
  county_name: '',
  specialty_name: '',
  grade: '',
  class_name: '',
  teacher_name: '',
  picture: '',
  sms_code: '',
  protocol: false
})
const checkProtocol = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请确认'))
  } else {
    callback()
  }
}
const rules = ref<FormRules>({
  name: [{ required: true, message: '请输入实验指导书名称', trigger: 'blur' }],
  grade: [{ required: true, message: '请输入年级' }],
  teacher_name: [{ required: true, message: '请输入指导教师' }],
  picture: [{ required: true, message: '请上传证件照' }],
  sms_code: [{ required: true, message: '请输入验证码' }],
  protocol: [{ validator: checkProtocol, trigger: 'change' }]
})

let dialogVisible = $ref(false)

// 提交
function handleSubmit() {
  formRef?.validate().then(handleJoin)
}
// 报名
function handleJoin() {
  const params: ContestJoinParams = pick(form, [
    'competition_id',
    'mode',
    'picture',
    'grade',
    'teacher_name',
    'sms_code'
  ])
  joinContest(params).then(() => {
    dialogVisible = true
  })
}
function handleCancel() {
  router.replace('/student/contest')
}
</script>

<template>
  <AppCard title="大赛报名">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="124px" style="width: 600px; margin: 0 auto">
      <el-form-item label="报名赛项">
        <el-input v-model="form.name" disabled />
      </el-form-item>
      <el-form-item label="参赛形式" prop="mode">
        <el-radio-group v-model="form.mode">
          <el-radio v-for="item in contestModeList" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="form.student_name" disabled />
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="form.gender" disabled>
          <el-radio v-for="item in genderList" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="证件类型">
        <el-radio-group v-model="form.id_type" disabled>
          <el-radio v-for="item in systemIdTypeList" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="证件号码">
        <el-input v-model="form.id_number" disabled />
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="form.mobile" disabled />
      </el-form-item>
      <el-form-item label="学校名称">
        <el-input v-model="form.org_name" disabled />
      </el-form-item>
      <el-form-item label="省">
        <el-input v-model="form.province_name" disabled />
      </el-form-item>
      <el-form-item label="市">
        <el-input v-model="form.city_name" disabled />
      </el-form-item>
      <el-form-item label="区/县">
        <el-input v-model="form.county_name" disabled />
      </el-form-item>
      <el-form-item label="专业名称">
        <el-input v-model="form.specialty_name" disabled />
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-input v-model="form.grade" />
      </el-form-item>
      <el-form-item label="班级">
        <el-input v-model="form.class_name" disabled />
      </el-form-item>
      <el-form-item label="指导教师" prop="teacher_name">
        <el-input v-model="form.teacher_name" />
      </el-form-item>
      <el-form-item label="证件照" prop="picture">
        <AppUpload v-model="form.picture" accept="image/*">
          <template #tip>证件照说明：请上传蓝底1寸或蓝底2寸证件照，照片大小控制在500kb以内。</template>
        </AppUpload>
      </el-form-item>
      <el-form-item label="验证码" prop="sms_code">
        <el-input v-model="form.sms_code">
          <template #append>
            <el-button type="primary" :disabled="disabled" @click="sendSMS">{{ countdownText }}</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="protocol">
        <el-checkbox label="我已确认上述信息输入无误，并对上述信息填写内容负责。" v-model="form.protocol" />
      </el-form-item>
      <el-row justify="center">
        <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
        <el-button round auto-insert-space @click="handleCancel">取消</el-button>
      </el-row>
    </el-form>
  </AppCard>
  <el-dialog title="报名成功" v-model="dialogVisible" :width="400" align-center center @closed="handleCancel">
    <el-result icon="success" title="您已经成功报名赛项！">
      <template #extra>
        <el-button type="primary" @click="handleCancel">确定</el-button>
      </template>
    </el-result>
  </el-dialog>
</template>
