<template>
  <div class="apply-container" :class="{ mobile: isMobile }">
    <div class="banner" :class="{ tablet: isTablet, mobile: isMobile && !isTablet }">
      <div class="slogan" @click="handleTestDate">
        {{ t('AwardApply.slogan') }}
      </div>
      <div class="title poppins-medium" @click="handleTestComplete">
        {{ t('AwardApply.applicationForm') }}
      </div>
      <div class="form-header" v-if="!isCompleted && !isExpired && !isMobile && !isTablet">
        <div class="form-title poppins-bold">
          {{ t('AwardApply.emailVerification') }}
        </div>
        <div class="desc">{{ t('AwardApply.aidaUsersOnly') }}</div>
      </div>
      <div class="steps-container" v-if="(isMobile || isTablet) && !isCompleted && !isExpired">
        <Step v-model="step" />
      </div>
    </div>
    <div
      class="success-wrapper"
      v-if="isCompleted || isExpired"
      :class="{ mobile: isMobile, tablet: isTablet }"
    >
      <Success
        class="success-container"
        :class="{ mobile: isMobile, tablet: isTablet }"
        :isExpired="isExpired"
      />
      <div
        class="step-btn back"
        v-show="(isCompleted || isExpired) && (isMobile || isTablet)"
        @click="handleBackToIntroduction"
      >
        {{ t('AwardApply.backToIntroduction') }}
      </div>
    </div>
    <div
      class="form-container"
      v-if="!isCompleted && !isExpired"
      :class="{ mobile: isMobile, tablet: isTablet }"
    >
      <div class="form-header" v-if="showStep(0)">
        <div class="form-title poppins-bold">
          {{ t('AwardApply.emailVerification') }}
        </div>
        <div class="desc">{{ t('AwardApply.aidaUsersOnly') }}</div>
      </div>
      <div class="form-content">
        <a-form
          name="form"
          ref="formRef"
          layout="vertical"
          :model="form"
          :rules="rulesRef"
          autocomplete="off"
        >
          <div class="email-box full-row" v-show="showStep(0)">
            <a-form-item name="email" required :label="t('AwardApply.emailAddress')">
              <div class="email-wrapper flex align-center">
                <a-input v-model:value="form.email" />
                <div
                  v-if="!hasValidEmail"
                  class="code-btn"
                  :class="{ disabled: isCountingDown }"
                  @click="handleSendCode"
                >
                  {{ isCountingDown ? formatCountdown(countdown) : t('AwardApply.sendCode') }}
                </div>
                <img
                  v-if="hasValidEmail"
                  src="@/assets/images/award/checked.png"
                  alt=""
                  class="checked-icon"
                />
              </div>
              <div class="tips">
                {{ t('AwardApply.pleaseUseRegisteredEmail') }}
              </div>
            </a-form-item>
          </div>
          <div
            v-if="isMobile || isTablet"
            class="email-box verify-box full-row"
            v-show="showStep(0)"
          >
            <a-form-item name="verify" required :label="t('AwardApply.verifyCode')">
              <div class="email-wrapper flex align-center">
                <a-input
                  v-model:value="mobileVerifyCode"
                  :placeholder="t('AwardApply.verifyPlaceholder')"
                />
                <div class="code-btn" @click="handleVerifyCode">
                  {{ t('AwardApply.verify') }}
                </div>
                <img
                  v-if="hasValidEmail"
                  src="@/assets/images/award/checked.png"
                  alt=""
                  class="checked-icon"
                />
              </div>
            </a-form-item>
          </div>
          <div v-show="showStep(1)" class="form-row full-row" :class="{ mobile: isMobile }">
            <div class="form-title poppins-bold">
              {{ t('AwardApply.personalInformation') }}
            </div>
            <div class="desc">{{ t('AwardApply.tellUsAboutYourself') }}</div>
          </div>
          <div v-show="showStep(1)" class="user-info flex">
            <template v-for="item in formKeys" :key="item.key">
              <a-form-item
                v-if="item.key !== 'email'"
                :required="item.required"
                :label="getFieldLabel(item.key)"
                :name="item.key"
              >
                <a-input
                  v-if="item.type === 'input'"
                  :disabled="readOnly"
                  v-model:value="form[item.key]"
                />
                <div class="select-container" v-if="item.type === 'select'">
                  <a-select
                    :disabled="readOnly"
                    v-model:value="form[item.key]"
                    :options="getGenderOptions()"
                  >
                    <template #suffixIcon>
                      <!-- <img
                          class="arrow-down-icon"
                          src="@/assets/images/award/arrow_down.svg"
                        /> -->
                    </template>
                  </a-select>
                  <div class="arrow-wrapper flex flex-center">
                    <img class="arrow-down-icon" src="@/assets/images/award/arrow_down.svg" />
                  </div>
                </div>
              </a-form-item>
            </template>
          </div>
          <template v-if="showStep(2)">
            <div class="form-row full-row">
              <div class="form-title poppins-bold">
                {{ t('AwardApply.designInformation') }}
              </div>
              <div class="desc">
                {{ t('AwardApply.shareYourCreativeVision') }}
              </div>
            </div>
            <a-form-item
              class="full-row design-title"
              name="designTitle"
              :label="t('AwardApply.designTitle')"
              required
            >
              <a-input v-model:value="form.designTitle" :disabled="readOnly" />
            </a-form-item>
            <a-form-item
              class="full-row design-desc"
              name="designDescription"
              :label="t('AwardApply.designDescription')"
              required
            >
              <a-textarea
                class="textarea"
                :disabled="readOnly"
                v-model:value="form.designDescription"
                :placeholder="t('AwardApply.designDescriptionPlaceholder')"
              />
            </a-form-item>
            <div class="form-row full-row">
              <div class="form-title poppins-bold">
                {{ t('AwardApply.submissionFiles') }}
              </div>
              <div class="desc">
                {{ t('AwardApply.uploadYourDesignMaterials') }}
              </div>
            </div>
            <div class="information full-row">
              <div class="information-title flex align-center">
                <div class="point"></div>
                <div class="text poppins-bold">
                  {{ t('AwardApply.submissionRequirements') }}
                </div>
              </div>
              <ul class="information-list flex space-between">
                <li class="information-item">
                  {{ t('AwardApply.pdfRequirement') }}
                </li>
                <div class="right">
                  <li class="information-item">
                    {{ t('AwardApply.rightContent.format') }}
                  </li>
                  <li class="information-item">
                    {{ t('AwardApply.rightContent.video') }}
                  </li>
                </div>
              </ul>
            </div>
            <div class="upload-container full-row">
              <a-form-item
                class="full-row"
                name="pdfPath"
                required
                :validate-trigger="[]"
                :label="t('AwardApply.uploadPdfTitle')"
              >
                <div>
                  <a-upload-dragger
                    v-model:fileList="pdfList"
                    :disabled="readOnly"
                    :maxCount="1"
                    :showUploadList="false"
                    @change="(info) => handleFileChange(info, 'pdf')"
                    :customRequest="handleUploadPdf"
                    :beforeUpload="beforeUploadPdf"
                    @remove="handleRemoveFile('pdf')"
                    accept=".pdf"
                  >
                    <img src="@/assets/images/award/upload.png" alt="" class="upload-icon" />
                    <p class="desc">
                      {{ t('AwardApply.clickToUploadPdf') }}
                    </p>
                    <p class="limit">
                      {{ t('AwardApply.pdfFileLimit') }}
                    </p>
                  </a-upload-dragger>
                  <!-- 自定义文件列表显示 -->
                  <div
                    v-if="pdfUploadStatus === 'success' && pdfList.length > 0"
                    class="custom-upload-list flex align-center space-between"
                  >
                    <div class="flex align-center">
                      <SvgIcon name="CFile" />
                      {{ pdfList[0]?.name }}
                    </div>
                    <div @click="handleRemoveFile('pdf')" class="delete-file" title="delete file">
                      <SvgIcon name="CDelete" color="red" />
                    </div>
                  </div>
                </div>
                <div
                  v-show="pdfUploadStatus === 'uploading' || pdfUploadStatus === 'success'"
                  class="uploading-container"
                >
                  <UploadStatus :status="pdfUploadStatus" type="pdf" />
                  <div class="progress-bar-container" v-if="pdfUploadStatus === 'uploading'">
                    <div class="progress-bar" :style="{ width: `${uploadProgressPdf}%` }"></div>
                  </div>
                </div>
              </a-form-item>
            </div>
            <div class="upload-container full-row">
              <a-form-item
                class="full-row"
                name="videoPath"
                required
                :validate-trigger="[]"
                :label="t('AwardApply.uploadVideoTitle')"
              >
                <div>
                  <a-upload-dragger
                    v-model:fileList="videoList"
                    :disabled="readOnly"
                    :maxCount="1"
                    :showUploadList="false"
                    @change="(info) => handleFileChange(info, 'video')"
                    :customRequest="handleUploadVideo"
                    :beforeUpload="beforeUploadVideo"
                    @remove="handleRemoveFile('video')"
                    accept=".mp4"
                  >
                    <img
                      src="@/assets/images/award/upload_video_icon.png"
                      alt=""
                      class="upload-icon"
                    />
                    <p class="desc">
                      {{ t('AwardApply.clickToUploadVideo') }}
                    </p>
                    <p class="limit">
                      {{ t('AwardApply.videoFileLimit') }}
                    </p>
                  </a-upload-dragger>
                  <!-- 自定义文件列表显示 -->
                  <div
                    v-if="videoUploadStatus === 'success' && videoList.length > 0"
                    class="custom-upload-list flex align-center space-between"
                  >
                    <div class="flex align-center">
                      <SvgIcon name="CFile" />
                      {{ videoList[0]?.name }}
                    </div>
                    <div @click="handleRemoveFile('video')" class="delete-file" title="delete file">
                      <SvgIcon name="CDelete" color="red" />
                    </div>
                  </div>
                </div>
                <div
                  v-show="videoUploadStatus === 'success' || videoUploadStatus === 'uploading'"
                  class="uploading-container"
                >
                  <UploadStatus :status="videoUploadStatus" type="video" />
                  <div class="progress-bar-container" v-if="videoUploadStatus === 'uploading'">
                    <div class="progress-bar" :style="{ width: `${uploadProgressVideo}%` }"></div>
                  </div>
                </div>
              </a-form-item>
            </div>
          </template>
        </a-form>
        <div
          class="conditions"
          :class="{ mobile: isMobile, tablet: isTablet }"
          v-show="showStep(3)"
        >
          <div class="confitions-title poppins-bold">
            {{ t('AwardApply.termsAndConditions') }}
          </div>
          <div class="condition-list flex flex-col">
            <div
              class="condition-item flex align-center"
              v-for="item in conditionsList"
              :key="item.id"
            >
              <a-checkbox v-model:checked="item.check" />
              <span>
                {{ t('AwardApply.' + item.translationKey) }}
                <span class="required" v-if="item.required"> * </span>
              </span>
            </div>
          </div>
        </div>

        <div class="submit-container" v-if="showStep(3)">
          <div class="submit-btn poppins-bold" @click="handleSubmitForm">
            {{ t('AwardApply.submitYourDesign') }}
          </div>
          <div class="desc">
            {{ t('AwardApply.unfinishedFormTip') }}
          </div>
        </div>
      </div>
      <div v-if="(isMobile || isTablet) && step < 3" class="step-container">
        <div class="step-btn" @click="handleNextStep">
          {{ t('AwardApply.nextStep') }}
        </div>
        <div class="step-tips">{{ t('AwardApply.stepTips') }}</div>
      </div>
    </div>
    <a-modal
      v-model:visible="showModal"
      :footer="null"
      :maskClosable="false"
      :closable="false"
      wrapClassName="code-modal"
      forceRender
      :keyboard="false"
      :style="{ top: '29.3rem' }"
    >
      <div class="verify-container flex flex-col align-center">
        <img src="@/assets/images/award/close.svg" class="close-icon" @click="handleCloseModal" />
        <div class="title poppins-bold">{{ t('AwardApply.checkYourEmail') }}</div>
        <div class="desc">
          {{ t('AwardApply.enterSixDigitCode') }}
          <br />
          <span class="email-verify">{{ form.email }}</span>
        </div>
        <div class="code-box">
          <VerifycationCodeInput :ct="emailCode" @sendCaptcha="setVerifyCode" />
        </div>
        <div class="verify-btn" @click="handleVerifyCode">
          {{ t('AwardApply.verify') }}
        </div>
        <div class="cutdown" :class="{ disabled: isCountingDown }" @click="handleSendCode">
          {{
            isCountingDown
              ? `${t('AwardApply.resendCodeIn')} ${formatCountdown(countdown)}`
              : t('AwardApply.resendCode')
          }}
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted, onMounted, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { debounce } from 'lodash-es'
import type { Rule } from 'ant-design-vue/es/form'
import { message, Upload } from 'ant-design-vue'
import { Https } from '@/utils/request'
import { useRoute } from 'vue-router'
import type { UploadChangeParam } from 'ant-design-vue'
import { useIsMobile, useIsTablet } from '@/utils/isMobile'
import VerifycationCodeInput from './components/VerificationCodeInput.vue'
import UploadStatus from './components/UploadStatus.vue'
import Success from './components/Success.vue'
import Step from './components/Step.vue'

const router = useRouter()
const { isMobile } = useIsMobile()
const { isTablet } = useIsTablet()

const step = ref(0)
const showStep = (val: number) => {
  if (!isMobile.value && !isTablet.value) {
    return true
  } else {
    return step.value === val
  }
}

// 是否晚于2026年7月15日
const date = ref('2026-07-15')
const isExpired = computed(() => {
  const now = new Date()
  const targetDate = new Date(date.value)
  return now > targetDate
})

const { t } = useI18n()
const route = useRoute()
const isCompleted = ref(false)

let dateClick = 0
const handleTestDate = () => {
  dateClick++
  if (dateClick % 2 === 0) {
    date.value = date.value === '2026-07-15' ? '2026-01-15' : '2026-07-15'
  }
}
let completeClick = 0
const handleTestComplete = () => {
  completeClick++
  if (completeClick % 4 === 0) {
    isCompleted.value = !isCompleted.value
  }
}

const readOnly = computed(() => {
  if (route.query.id && !hasValidEmail.value) {
    return true
  }

  return false
})
const formRef = ref(null)
const form = ref({
  email: '',
  firstName: '',
  lastName: '',
  gender: '',
  occupation: '',
  age: '',
  countryRegionCity: '',
  phoneNumber: '',
  portfolioUrl: '',
  // code: '',
  designTitle: '',
  designDescription: '',
  pdfPath: '',
  videoPath: '',
  videoDuration: 0,
  secureToken: ''
})
const hasValidEmail = computed(() => {
  return !!form.value.secureToken
})

// 验证码输入组件引用
const codeInputRef = ref()
const emailCode = ref(['', '', '', '', '', ''])

const isValidEmail = (email) => {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  return emailRegex.test(email)
}
const validEmail = (rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject(t('AwardApply.pleaseInputEmail'))
  }
  if (!isValidEmail(value)) {
    return Promise.reject(t('AwardApply.pleaseInputValidEmail'))
  }
  return Promise.resolve()
}
const validateNumber = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject(t('AwardApply.pleaseInputAge'))
  }
  if (!Number.isInteger(Number(value))) {
    return Promise.reject(t('AwardApply.pleaseInputDigits'))
  }
  return Promise.resolve()
}

const validatePhone = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject(t('AwardApply.pleaseInputPhoneNumber'))
  }
  const phoneRegex = /^[\+]?[1-9][\d]{0,15}$/
  if (!phoneRegex.test(value)) {
    return Promise.reject(t('AwardApply.pleaseInputValidPhone'))
  }
  return Promise.resolve()
}

const validateVerificationCode = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject(t('AwardApply.pleaseEnterCompleteCode'))
  }
  const codeRegex = /^\d{6}$/
  if (!codeRegex.test(value)) {
    return Promise.reject(t('AwardApply.pleaseEnterCompleteCode'))
  }
  return Promise.resolve()
}
const rulesRef = {
  email: [{ required: true, validator: validEmail }],
  firstName: [
    {
      required: true,
      message: t('AwardApply.pleaseInputFirstName'),
      trigger: 'blur'
    }
  ],
  lastName: [
    {
      required: true,
      message: t('AwardApply.pleaseInputLastName'),
      trigger: 'blur'
    }
  ],
  gender: [
    {
      required: true,
      message: t('AwardApply.pleaseSelectGender'),
      trigger: 'blur'
    }
  ],
  occupation: [
    {
      required: true,
      message: t('AwardApply.pleaseInputOccupation'),
      trigger: 'blur'
    }
  ],
  age: [{ required: true, message: t('AwardApply.pleaseInputAge'), trigger: 'blur' }],
  countryRegionCity: [
    {
      required: true,
      message: t('AwardApply.pleaseInputCountry'),
      trigger: 'blur'
    }
  ],
  phoneNumber: [{ required: true, validator: validatePhone, trigger: 'blur' }],

  designTitle: [
    {
      required: true,
      message: t('AwardApply.pleaseInputDesignTitle'),
      trigger: 'blur'
    }
  ],
  designDescription: [
    {
      required: true,
      message: t('AwardApply.pleaseInputDesignDescription'),
      trigger: 'blur'
    }
  ],
  pdfPath: [{ required: true, message: t('AwardApply.pleaseUploadPdf'), trigger: 'null' }],
  videoPath: [
    {
      required: true,
      message: t('AwardApply.pleaseUploadVideo'),
      trigger: 'null'
    }
  ]
}

const genderOptions = [
  {
    label: 'Male',
    value: 'Male'
  },
  {
    label: 'Female',
    value: 'Female'
  },
  {
    label: 'Other',
    value: 'Other'
  }
]
const formKeys = ref([
  {
    label: 'First Name',
    required: true,
    type: 'input',
    key: 'firstName'
  },
  {
    label: 'Last Name',
    required: true,
    type: 'input',
    key: 'lastName'
  },
  {
    label: 'Gender',
    required: true,
    type: 'select',
    key: 'gender'
  },
  {
    label: 'Occupation',
    required: true,
    type: 'input',
    key: 'occupation'
  },
  {
    label: 'Age',
    required: true,
    type: 'input',
    key: 'age'
  },
  {
    label: 'Country/Region and City',
    required: true,
    type: 'input',
    key: 'countryRegionCity'
  },
  {
    label: 'Phone Number',
    required: true,
    type: 'input',
    key: 'phoneNumber'
  },

  {
    label: 'Portfoilo Website/Instagram(Optional)',
    required: false,
    type: 'input',
    key: 'portfolioUrl'
  }
])

const showModal = ref(false)
// 获取表单标签的翻译
const getFieldLabel = (key: string) => {
  const labelMap: Record<string, string> = {
    firstName: t('AwardApply.firstName'),
    lastName: t('AwardApply.lastName'),
    gender: t('AwardApply.gender'),
    occupation: t('AwardApply.occupation'),
    age: t('AwardApply.age'),
    countryRegionCity: t('AwardApply.countryRegionCity'),
    phoneNumber: t('AwardApply.phoneNumber'),
    portfolioUrl: t('AwardApply.portfolioUrl')
  }
  return labelMap[key] || key
}

// 获取性别选项的翻译
const getGenderOptions = () => {
  return [
    {
      label: t('AwardApply.male'),
      value: 'Male'
    },
    {
      label: t('AwardApply.female'),
      value: 'Female'
    },
    {
      label: t('AwardApply.other'),
      value: 'Other'
    }
  ]
}

// 倒计时相关状态
const countdown = ref(0)
const countdownTimer = ref<NodeJS.Timeout | null>(null)
const isCountingDown = ref(false)
const formatCountdown = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

const startCountdown = () => {
  countdown.value = 60
  isCountingDown.value = true

  countdownTimer.value = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearCountdown()
    }
  }, 1000)
}

const clearCountdown = () => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
    countdownTimer.value = null
  }
  countdown.value = 0
  isCountingDown.value = false
}

const handleSendCode = debounce(async () => {
  // 如果正在倒计时，不允许再次发送
  if (isCountingDown.value) {
    return
  }

  try {
    await formRef.value.validateFields(['email'])
    await Https.axiosGet(Https.httpUrls.checkEmail, {
      params: {
        email: form.value.email
      }
    })

    startCountdown()
    emailCode.value = ['', '', '', '', '', ''] // 重置验证码输入
    if (!isMobile.value && !isTablet.value) {
      showModal.value = true
    }
  } catch (error) {}
}, 300)

const verifyCode = ref(null)
const mobileVerifyCode = ref('')

const setVerifyCode = (value) => {
  verifyCode.value = value
}

const handleCloseModal = () => {
  showModal.value = false
}
const handleVerifyCode = async () => {
  // console.log(verifyCode.value)
  if (isMobile.value || isTablet.value) {
    await formRef.value.validateFields(['email'])
  }
  if (isMobile.value || isTablet.value) {
    verifyCode.value = mobileVerifyCode.value
  }
  if (verifyCode.value.length !== 6) {
    message.error(t('AwardApply.pleaseEnterCompleteCode'))
    return
  }
  Https.axiosGet(Https.httpUrls.checkOTP, {
    params: {
      email: form.value.email,
      code: verifyCode.value
    },
    fullData: true
  }).then((res) => {
    // console.log('coderes', res)

    form.value.secureToken = res.data.secureToken
    // form.value.secureToken = '123456'

    message.success(t('AwardApply.verificationSuccess'))
    showModal.value = false
  })
}

const handleSubmitForm = () => {
  if (!hasValidEmail.value) {
    message.error(t('AwardApply.pleaseVerifyEmailFirst'))
    return
  }
  const validCondition = conditionsList.value.filter((item) => item.required && !item.check)
  if (validCondition.length > 0) {
    message.error(t('AwardApply.pleaseCheckTerms'))
    return
  }
  formRef.value
    .validate()
    .then((res) => {
      // console.log(res)
      Https.axiosPost(Https.httpUrls.submitForm, form.value).then((res) => {
        // console.log('res', res)
        isCompleted.value = true
      })
    })
    .catch((err) => {
      console.error('handleSubmitForm错误', err)
      message.error(t('AwardApply.pleaseFillRequiredFields'))
    })
}

const pdfList = ref([])
const videoList = ref([])
const isUploadingPdf = ref(false)
const uploadProgressPdf = ref(0)
const isUploadingVideo = ref(false)
const uploadProgressVideo = ref(0)
const pdfUploadStatus = ref<'idle' | 'uploading' | 'success' | 'error'>('idle')
const videoUploadStatus = ref<'idle' | 'uploading' | 'success' | 'error'>('idle')

const chunkUploadState: Record<
  FileType,
  { uploadId: string | null; chunkSize: number; uploadedChunks: Set<number> }
> = {
  pdf: { uploadId: null, chunkSize: 0, uploadedChunks: new Set() },
  video: { uploadId: null, chunkSize: 0, uploadedChunks: new Set() }
}

// 统一的文件上传前验证
// 获取视频时长
const getVideoDuration = (file: File): Promise<number> => {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video')
    video.preload = 'metadata'
    video.onloadedmetadata = () => {
      window.URL.revokeObjectURL(video.src)
      resolve(video.duration)
    }
    video.onerror = () => {
      window.URL.revokeObjectURL(video.src)
      reject(new Error('Failed to load video'))
    }
    video.src = window.URL.createObjectURL(file)
  })
}

const beforeUploadFile = async (type: FileType, file: File) => {
  if (!hasValidEmail.value) {
    message.error(t('AwardApply.pleaseVerifyEmailFirst'))
    return Upload.LIST_IGNORE
  }
  let maxSize: number
  let allowedExtensions: string[]
  let allowedMimeTypes: string[]
  let errorMessage: string

  if (type === 'pdf') {
    maxSize = 20 * 1024 * 1024 // 20MB
    allowedExtensions = ['pdf']
    allowedMimeTypes = ['application/pdf']
    errorMessage = t('AwardApply.uploadPdfOnly')
  } else if (type === 'video') {
    maxSize = 100 * 1024 * 1024 // 100MB
    allowedExtensions = ['mp4']
    allowedMimeTypes = ['video/mp4', 'video/quicktime']
    errorMessage = t('AwardApply.uploadVideoOnly')
  } else {
    return Upload.LIST_IGNORE
  }

  // 验证文件类型
  const fileExtension = file.name.split('.').pop()?.toLowerCase()
  const isValidType =
    allowedExtensions.includes(fileExtension || '') || allowedMimeTypes.includes(file.type)

  if (!isValidType) {
    message.error(errorMessage)

    return Upload.LIST_IGNORE
  }

  // 验证文件大小
  if (file.size > maxSize) {
    const sizeLimit = type === 'pdf' ? '20MB' : '100MB'
    message.error(t('AwardApply.fileSizeExceeds', { sizeLimit }))

    return Upload.LIST_IGNORE
  }

  // 验证视频时长
  let duration = 0
  if (type === 'video') {
    duration = await getVideoDuration(file)
    try {
      if (duration > 60) {
        message.error(t('AwardApply.videoDurationExceeds'))
        return Upload.LIST_IGNORE
      }
    } catch (error) {
      console.error('Failed to get video duration:', error)
    }
  }
  form.value.videoDuration = Math.ceil(duration)

  return true
}

// PDF文件上传前验证
const beforeUploadPdf = (file: File) => {
  return beforeUploadFile('pdf', file)
}

// Video文件上传前验证
const beforeUploadVideo = (file: File) => {
  return beforeUploadFile('video', file)
}

const initializeChunkUpload = async (type: FileType, file: File) => {
  const endpoint = type === 'pdf' ? Https.httpUrls.initPdfUpload : Https.httpUrls.initVideoUpload

  const data = await Https.axiosPost(endpoint, {
    fileName: file.name,
    fileSize: file.size,
    fileType: file.type,
    email: form.value.email,
    secureToken: form.value.secureToken
  })

  return {
    uploadId: data?.uploadId as string,
    chunkSize: data?.chunkSize as number
  }
}

const createFileChunks = (file: File, chunkSize: number) => {
  const chunks: Blob[] = []
  const totalChunks = Math.ceil(file.size / chunkSize)

  for (let i = 0; i < totalChunks; i++) {
    const start = i * chunkSize
    const end = Math.min(start + chunkSize, file.size)
    const chunk = file.slice(start, end)
    chunks.push(chunk)
  }

  return chunks
}

const updateUploadProgress = (type: FileType, uploadedCount: number, total: number) => {
  const percent = Math.round((uploadedCount / total) * 100)
  if (type === 'pdf') {
    uploadProgressPdf.value = percent
  } else {
    uploadProgressVideo.value = percent
  }
}

const uploadChunk = async (
  type: FileType,
  chunk: Blob,
  chunkIndex: number,
  totalChunks: number
) => {
  const endpoint = type === 'pdf' ? Https.httpUrls.uploadPDF : Https.httpUrls.uploadVideo

  const formData = new FormData()
  formData.append('chunk', chunk)
  formData.append('uploadId', chunkUploadState[type].uploadId || '')
  formData.append('chunkIndex', String(chunkIndex))
  formData.append('totalChunks', String(totalChunks))
  formData.append('secureToken', form.value.secureToken)

  await Https.axiosPost(endpoint, formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  })

  chunkUploadState[type].uploadedChunks.add(chunkIndex)
}

const completeChunkUpload = async (type: FileType, file: File) => {
  try {
    const endpoint =
      type === 'pdf' ? Https.httpUrls.uploadPDFComplete : Https.httpUrls.uploadVideoComplete

    return Https.axiosPost(endpoint, {
      uploadId: chunkUploadState[type].uploadId,
      email: form.value.email,
      fileName: file.name,
      secureToken: form.value.secureToken,
      totalSize: file.size
    })
  } catch (error) {
    console.log('complete错误', error)
  }
}

type FileType = 'pdf' | 'video'
const handleFileChange = (info: UploadChangeParam, type: FileType) => {
  const status = info.file.status

  if (status === 'done') {
    message.success(t('AwardApply.fileUploadedSuccess', { fileName: info.file.name }))
    if (type === 'pdf') {
      isUploadingPdf.value = false
      uploadProgressPdf.value = 0
      pdfUploadStatus.value = 'success'
      // 使用 customRequest 时需要手动更新 fileList
      pdfList.value = [
        {
          uid: info.file.uid,
          name: info.file.name,
          status: 'done',
          url: form.value.pdfPath
        }
      ]
    } else if (type === 'video') {
      isUploadingVideo.value = false
      uploadProgressVideo.value = 0
      videoUploadStatus.value = 'success'
      // 使用 customRequest 时需要手动更新 fileList
      videoList.value = [
        {
          uid: info.file.uid,
          name: info.file.name,
          status: 'done',
          url: form.value.videoPath
        }
      ]
    }
  } else if (status === 'error') {
    message.error(t('AwardApply.fileUploadFailed', { fileName: info.file.name }))
    if (type === 'pdf') {
      isUploadingPdf.value = false
      uploadProgressPdf.value = 0
      pdfUploadStatus.value = 'error'
    } else if (type === 'video') {
      isUploadingVideo.value = false
      uploadProgressVideo.value = 0
      videoUploadStatus.value = 'error'
    }
  }
}

const handleUploadFile = async (option: any, type: FileType) => {
  const file = option.file as File
  //

  if (!form.value.email) {
    message.error(t('AwardApply.pleaseInputEmail'))
    option.onError?.(new Error('Email required'))
    return
  }

  if (type === 'pdf') {
    isUploadingPdf.value = true
    uploadProgressPdf.value = 0
    pdfUploadStatus.value = 'uploading'
  } else {
    isUploadingVideo.value = true
    uploadProgressVideo.value = 0
    videoUploadStatus.value = 'uploading'
  }

  try {
    const { uploadId, chunkSize } = await initializeChunkUpload(type, file)
    chunkUploadState[type].uploadId = uploadId
    chunkUploadState[type].chunkSize = chunkSize
    chunkUploadState[type].uploadedChunks = new Set()

    const chunks = createFileChunks(file, chunkSize)
    for (let i = 0; i < chunks.length; i++) {
      await uploadChunk(type, chunks[i], i, chunks.length)
      updateUploadProgress(type, i + 1, chunks.length)
    }

    const res = await completeChunkUpload(type, file)

    if (type === 'pdf') {
      pdfUploadStatus.value = 'success'
      uploadProgressPdf.value = 100
      isUploadingPdf.value = false
      form.value.pdfPath = res.fileUrl
      form.value.pdfSize = file.size
      // 手动更新 fileList 以触发 itemRender 渲染
      pdfList.value = [
        {
          uid: file.uid || Date.now(),
          name: file.name,
          status: 'done',
          url: res.fileUrl
        }
      ]
    } else {
      videoUploadStatus.value = 'success'
      uploadProgressVideo.value = 100
      isUploadingVideo.value = false
      form.value.videoPath = res.fileUrl
      form.value.videoSize = file.size
      // 手动更新 fileList 以触发 itemRender 渲染
      videoList.value = [
        {
          uid: file.uid || Date.now(),
          name: file.name,
          status: 'done',
          url: res.fileUrl
        }
      ]
    }

    option.onSuccess?.({ uploadId }, option.file)
  } catch (error: any) {
    console.error('Upload error:', error)
    message.error(error?.message || t('AwardApply.uploadFailed'))
    option.onError?.(error)

    if (type === 'pdf') {
      isUploadingPdf.value = false
      uploadProgressPdf.value = 0
      pdfUploadStatus.value = 'error'
      pdfList.value = []
    } else {
      isUploadingVideo.value = false
      uploadProgressVideo.value = 0
      videoUploadStatus.value = 'error'
      videoList.value = []
    }
  }
}

// PDF上传处理
const handleUploadPdf = (option: any) => {
  return handleUploadFile(option, 'pdf')
}

// Video上传处理
const handleUploadVideo = (option: any) => {
  return handleUploadFile(option, 'video')
}

const handleRemoveFile = (type: 'video' | 'pdf') => {
  if (type === 'pdf') {
    form.value.pdfPath = ''
    pdfUploadStatus.value = 'idle'
    uploadProgressPdf.value = 0
  } else if (type === 'video') {
    form.value.videoPath = ''
    videoUploadStatus.value = 'idle'
    uploadProgressVideo.value = 0
  }
}

const conditionsList = ref([
  {
    check: false,
    required: true,
    text: '',
    translationKey: 'conditionFirst',
    id: 'first'
  },
  {
    check: false,
    required: true,
    text: '',
    translationKey: 'conditionSecond',
    id: 'second'
  },
  {
    check: false,
    required: true,
    text: '',
    translationKey: 'conditionThird',
    id: 'third'
  },
  {
    check: false,
    text: '',
    translationKey: 'conditionFourth',
    id: 'forth'
  }
])

const handleEchoForm = () => {
  Https.axiosGet(Https.httpUrls.getContestantByID + route.query.id).then((res) => {
    Object.assign(form.value, res)
  })
}

const handleNextStep = () => {
  if (step.value < 3) {
    step.value++
  }
}

const handleBackToIntroduction = () => {
  router.push('/')
}

onMounted(() => {
  if (route.query.id) {
    handleEchoForm()
  }
})
onUnmounted(() => {
  clearCountdown()
})
</script>

<style lang="less" scoped>
.poppins-bold {
  font-family: 'PoppinsBold';
  font-weight: 600;
}

.poppins-medium {
  font-family: 'PoppinsMedium';
  font-weight: 500;
}

.full-row {
  width: 100%;
}
.arrow-down-icon {
  width: 2rem;
  height: 1rem;
}
.apply-container {
  min-height: calc(100% - 18rem);
  background-color: #f5f5f5;
  box-sizing: border-box;
}
.success-wrapper {
  padding-bottom: 3rem;
  .success-container {
    &.mobile {
      height: auto;
      top: initial;
      margin: 4rem 3.8rem 0;
      padding: 13.5rem 13.2rem;
    }
  }
  &.tablet {
    .step-btn {
      margin: 6rem 23.3rem 0;
    }
  }
}
.banner {
  height: 54.8rem;
  background: url('@/assets/images/award/form_bg.png') no-repeat;
  background-size: 100% 100%;
  text-align: center;
  padding: 12rem 21.4rem 0;
  position: relative;

  .slogan {
    color: #585858;
    font-family: 'ArialBold';
    font-weight: 700;
    font-size: 2.8rem;
    margin-bottom: 4rem;
  }

  .title {
    color: #c7342c;
    font-size: 8rem;
  }
  .form-header {
    width: calc(100% - 42.8rem);
    left: 21.4rem;
    bottom: 0;
    position: absolute;
  }
  .steps-container {
    height: 6.8rem;
    background-color: #fff;
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
  }
  &.mobile {
    height: 24.8rem;
    background: url('@/assets/images/mobile_version_background/banner_bg.png') no-repeat;
    background-size: 100% 100%;
    padding: 4.1rem 6rem 0;
    .slogan {
      font-size: 1.8rem;
      margin-bottom: 1.2rem;
    }
    .title {
      font-size: 4rem;
    }
  }
}
.form-header {
  height: 16.8rem;
  background-color: #fff;
  border-top-left-radius: 0.8rem;
  border-top-right-radius: 0.8rem;
  text-align: left;
  padding: 6rem 6rem 0;

  .form-title {
    color: #232323;
    font-size: 3rem;
    margin-bottom: 1rem;
  }

  .desc {
    color: #b10000;
    font-family: 'Instrument';
    font-weight: 500;
    font-size: 2.4rem;
  }
}

.form-row {
  margin-top: 12rem;
  margin-bottom: 6rem;
  &.mobile {
    margin-top: 0;
  }

  .form-title {
    color: #232323;
    font-size: 3rem;
    margin-bottom: 1rem;
  }

  .desc {
    color: #b10000;
    font-family: 'Instrument';
    font-weight: 500;
    font-size: 2.4rem;
  }
}

.form-container {
  padding: 0 21.4rem 12rem;
  background-color: #f5f5f5;

  .form-content {
    padding: 4rem 6rem 6rem;
    background-color: #fff;
    border-bottom-left-radius: 0.8rem;
    border-bottom-right-radius: 0.8rem;

    .ant-form {
      display: flex;
      flex-wrap: wrap;
      column-gap: 4rem;

      .user-info {
        flex-wrap: wrap;
        row-gap: 6rem;
        justify-content: space-between;
      }

      .ant-form-item {
        width: 66.5rem;
        margin-bottom: 0;

        &.full-row {
          width: 100%;
        }

        &.design-title {
          margin-bottom: 9rem;
        }

        :deep(label) {
          // display: none;
          flex-direction: row-reverse;
          color: #232323;

          &,
          &::before {
            font-family: 'Arial';
            font-weight: 400;
            font-size: 2rem;
          }
        }

        :deep(.ant-input),
        :deep(.ant-select-selector) {
          border: 0.2rem solid #d5d5d5;
          height: 6rem;
          border-radius: 0.8rem;
          font-family: 'Arial';
          font-weight: 400;
          font-size: 1.8rem;

          &.textarea {
            height: 20rem;
          }
          .ant-select-selection-search {
            height: 100%;
          }
          .ant-select-selection-item {
            line-height: 6rem;
          }
        }
        // :deep(.ant-select-arrow) {

        // 	justify-content: center;
        // 	display: flex;
        // 	align-items: center;
        // }
      }
    }
    .select-container {
      position: relative;
      .arrow-wrapper {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 6rem;
        height: 4rem;
        box-sizing: border-box;
        border-left: 0.1rem solid #d5d5d5;
        pointer-events: none;
      }
    }

    .email-box {
      :deep(.ant-input) {
        border: none !important;

        &:focus {
          box-shadow: none;
        }
      }

      .email-wrapper {
        border-radius: 0.8rem;
        border: 0.2rem solid #d5d5d5;
        position: relative;
        .checked-icon {
          position: absolute;
          right: -6rem;
          width: 4rem;
          height: 4rem;
        }
      }

      .code-btn {
        width: 13rem;
        height: 4rem;
        color: #585858;
        font-family: 'Arial';
        font-weight: 400;
        font-size: 1.8rem;
        line-height: 4rem;
        text-align: center;
        cursor: pointer;
        border-left: 0.1rem solid #d5d5d5;

        &.disabled {
          cursor: not-allowed;
          opacity: 0.6;
        }
      }
    }

    .tips {
      font-family: 'Arial';
      font-weight: 400;
      font-size: 1.6rem;
      color: #585858;
      margin-top: 1rem;
    }
  }
  &.mobile,
  &.tablet {
    margin-top: 4rem;
    .form-row {
      margin-top: 0;
    }
    .form-title {
      margin-top: 3rem;
    }
  }
  &.mobile:not(.tablet) {
    padding: 0 3.8rem 4rem;
    .form-header {
      padding: 3rem 3rem 0;
      height: auto;
      padding-bottom: 2.4rem;
    }
    .form-content {
      padding: 0 3rem 20rem;
      .verify-box {
        margin-top: 4rem;
      }
      .ant-form .ant-form-item {
        width: 100%;
      }
    }
  }
}

.step-btn {
  text-align: center;
  margin: 6rem 3rem 0;
  background-color: #454545;
  height: 5rem;
  border-radius: 0.8rem;
  color: #fff;
  line-height: 5rem;
  font-family: 'PoppinsBold';
  font-weight: 600;
  font-size: 2.4rem;
  cursor: pointer;
  &.back {
    margin: 6rem 6.6rem 0;
  }
}
.step-tips {
  text-align: center;
  margin-top: 2rem;
  font-family: 'Instrument';
  font-weight: 400;
  font-size: 1.8rem;
  color: #6d6d6d;
}

:deep(.ant-form-item-label) {
  padding: 0 0 1rem;
}

.information {
  padding-left: 2.4rem;

  .information-title {
    font-size: 2.8rem;
    color: #232323;
    column-gap: 2.4rem;
    margin-bottom: 5rem;

    .point {
      width: 1.2rem;
      height: 1.2rem;
      border-radius: 50%;
      background-color: #c7342c;
    }
  }

  .information-list {
    padding-left: 2.4rem;
    column-gap: 4.8rem;

    .information-item {
      font-family: 'Arial';
      font-weight: 400;
      font-size: 2.4rem;
      color: #585858;
      position: relative;
      list-style: disc;
      // line-height: 3rem;
      white-space: pre-line;
    }
  }
}

.upload-container {
  margin-top: 6rem;
  position: relative;
  :deep(.ant-upload-drag) {
    height: 32rem;
    border-radius: 0.8rem;

    .ant-upload-btn {
      padding: 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-top: 5.89rem;

      .upload-icon {
        width: 12rem;
        height: 12rem;
      }

      .desc {
        color: #585858;
        font-family: 'Arial';
        font-weight: 400;
        font-size: 2.4rem;
        margin: 1rem 0 2rem;
      }

      .limit {
        color: #aaa;
        font-family: 'Arial';
        font-weight: 400;
        font-size: 1.8rem;
      }
    }
  }

  .uploading-container {
    height: 32rem;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 0.2rem dashed #d5d5d5;
    border-radius: 0.8rem;
    background-color: #fafafa;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;

    .uploading-text {
      color: #585858;
      font-family: 'Arial';
      font-weight: 400;
      font-size: 2.4rem;
    }
  }

  .progress-bar-container {
    width: 100%;
    height: 1rem;
    background-color: #f0f0f0;
    border-radius: 0.8rem;
    margin-top: 2rem;
    overflow: hidden;
    position: absolute;
    bottom: 0;

    .progress-bar {
      height: 100%;
      background-color: #c7342c;
      border-radius: 0.8rem;
      transition: width 0.3s ease;
    }
  }
}
.custom-upload-list {
  padding: 0.4rem 1rem;
  margin-top: 1rem;
  &:hover {
    background-color: #f5f5f5;
    border-radius: 0.4rem;
  }
  .c-svg {
    width: fit-content;
  }
  .delete-file {
    cursor: pointer;
  }
}
.conditions {
  margin-top: 12rem;
  &.mobile {
    margin-top: 3rem;
  }
  &-title {
    color: #232323;
    font-size: 3rem;
  }

  .condition-list {
    margin-top: 6rem;
    row-gap: 3rem;

    .condition-item {
      border: 0.2rem solid #d5d5d5;
      height: 6rem;
      line-height: 6rem;
      border-radius: 0.8rem;
      color: #585858;
      font-family: 'Arial';
      font-weight: 400;
      font-size: 1.8rem;
      padding-left: 1.5rem;
      column-gap: 2.5rem;
      .required {
        color: #c7342c;
      }
    }

    :deep(.ant-checkbox-wrapper) {
      line-height:initial;
      .ant-checkbox-inner {
        width: 2rem;
        height: 2rem;
        border: 0.2rem solid #585858 !important;
        border-radius: 0.4rem;
      }

      .ant-checkbox-checked .ant-checkbox-inner {
        background-color: #fff !important;
        border-color: #585858 !important;
      }

      .ant-checkbox-checked .ant-checkbox-inner::after {
        border-bottom: 0.2rem solid #585858;
        border-right: 0.2rem solid #585858;
        width: 0.65rem;
        height: 1rem;
        left: 21.895%;
      }
    }
  }
  &.mobile:not(.tablet) {
    .condition-list {
      .condition-item {
        align-items: flex-start;
        height: auto;
        min-height: 6rem;
        line-height: 2.4rem;
        padding: 2rem 1.5rem;
      }
    }
  }
}

.submit-container {
  margin-top: 12rem;

  .submit-btn {
    height: 5rem;
    background-color: #454545;
    border-radius: 0.8rem;
    color: #fff;
    line-height: 5rem;
    text-align: center;
    font-size: 1.6rem;
    cursor: pointer;
  }

  .desc {
    font-family: 'Instrument';
    font-weight: 400;
    font-size: 1.6rem;
    color: #6d6d6d;
    text-align: center;
    margin-top: 2rem;
  }
}

.verify-container {
  width: 60rem;
  height: 49.4rem;
  padding: 6rem 8.6rem;
  background-color: #fff;
  position: relative;

  .close-icon {
    position: absolute;
    width: 2.4rem;
    height: 2.4rem;
    top: 2rem;
    right: 2rem;
    cursor: pointer;
  }

  .title {
    color: #232323;

    font-size: 3rem;
    line-height: 5rem;
  }

  .desc {
    color: #585858;
    font-family: 'Arial';
    font-weight: 400;
    font-size: 1.6rem;
    line-height: 3.4rem;
    margin-top: 1.4rem;
    text-align: center;
    .email-verify {
      color: #232323;
      font-family: 'ArialBold';
      font-weight: 700;
      font-size: 1.6rem;
    }
  }

  .email {
    font-family: 'ArialBold';
    font-weight: 700;
    font-size: 1.6rem;
    line-height: 3rem;
    color: #232323;
  }

  .code-box {
    width: 100%;
    margin: 5rem 0;
  }

  .verify-btn {
    background-color: #232323;
    height: 4.2rem;
    border-radius: 8px;
    line-height: 4.2rem;
    width: 100%;
    color: #fff;
    text-align: center;
    font-family: 'ArialBold';
    font-weight: 700;
    font-size: 1.6rem;
    cursor: pointer;
  }

  .cutdown {
    font-family: 'Arial';
    font-weight: 400;
    font-size: 1.4rem;
    color: #585858;
    margin-top: 2rem;
    text-decoration: underline solid #585858;

    &:not(.disabled) {
      cursor: pointer;
    }

    &.disabled {
      cursor: not-allowed;
    }
  }
}
</style>
<style lang="less">
.code-modal {
  .ant-modal-content {
    padding: 0;
    &,
    .ant-modal-body {
      padding: 0;
    }
  }
}
</style>
