<template>
  <div class="app-right-aside">
    <ul>
      <li>
        <div class="text hover-text">报名<br />咨询</div>
        <div class="hover">
          <div class="enroll_cont">
            <h5>{{ t('aside.apply') }}</h5>
            <div class="p">
              <input
                v-model="formInfo.name"
                type="text"
                class="custom-input"
                :class="{ 'input-error': errors.name }"
                :placeholder="t('aside.name')"
                @input="errors.name = ''" />
              <div v-if="errors.name" class="error-message">{{ errors.name }}</div>
            </div>
            <div class="p">
              <input
                v-model="formInfo.phone"
                type="text"
                class="custom-input"
                :class="{ 'input-error': errors.phone }"
                :placeholder="t('aside.phone')"
                @input="errors.phone = ''" />
              <div v-if="errors.phone" class="error-message">{{ errors.phone }}</div>
            </div>
            <div class="p">
              <select v-model="formInfo.projectId" class="custom-select" :class="{ 'input-error': errors.projectId }">
                <option :value="item.value" v-for="(item, index) in projectList" :key="index">{{ item.label }}</option>
              </select>
              <span class="icon el-icon-arrow-down"></span>
              <div v-if="errors.projectId" class="error-message">{{ errors.projectId }}</div>
            </div>
            <div class="p code-input-wrapper">
              <div class="code-input-container">
                <input
                  v-model="sendCodeValue"
                  type="text"
                  class="custom-input code-input"
                  :class="{ 'input-error': errors.code }"
                  :placeholder="t('aside.code')"
                  @input="errors.code = ''" />
                <button class="custom-button code-button" :disabled="isBtnDisabled" @click="getSendCode">
                  {{ countdown > 0 ? `${countdown}s` : t('aside.codeBtn') }}
                </button>
              </div>
              <div v-if="errors.code" class="error-message">{{ errors.code }}</div>
            </div>
            <div class="p">
              <button class="custom-button submit-button" @click="submitEnroll">{{ t('aside.formBtn') }}</button>
              <div v-if="successMessage" class="success-message">{{ successMessage }}</div>
            </div>
          </div>
        </div>
      </li>
      <li>
        <div class="text">技术<br />客服</div>
        <div class="hover">
          <img
            src="https://zws-imgs-pub.ezijing.com/static/public/d2d9945d598e81c3b58aff5ce927a78a.jpg"
            width="150px" />
        </div>
      </li>
      <li @click="showDownloadPopup">
        <div class="text">APP</div>
      </li>
      <li>
        <div class="text">小程序</div>
        <div class="hover">
          <img src="https://webapp-pub.ezijing.com/www/pc/next/qrcode_weapp.png" width="150px" />
        </div>
      </li>
      <li>
        <div class="text">公众号</div>
        <div class="hover">
          <img
            src="https://zws-imgs-pub.ezijing.com/static/public/d2d9945d598e81c3b58aff5ce927a78a.jpg"
            width="150px" />
        </div>
      </li>
      <li @click="scrollToTop">
        <div class="text">回到<br />顶部</div>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { sendCode, checkCode, submitApplicationForm } from '@/api/index'
import { useStore } from '@/composables/useStore'
const { visibleAppDownloadPopup } = useStore()

const showDownloadPopup = () => {
  visibleAppDownloadPopup.value = true
}
const MOBILE_REG = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/

const { t } = useI18n()
const route = useRoute()

const sendCodeValue = ref('')
const isBtnDisabled = ref(false)
const countdown = ref(0)
const countdownTimer = ref(null)
const successMessage = ref('')

const formInfo = reactive({
  name: '',
  phone: '',
  projectId: '',
})

const errors = reactive({
  name: '',
  phone: '',
  projectId: '',
  code: '',
})

const projectListMap = computed(() => [
  { label: t('aside.project1'), value: '1012' },
  { label: t('aside.project5'), value: '1006' },
  { label: t('aside.project6'), value: '1005' },
  { label: t('aside.project8'), value: '1021' },
  { label: t('aside.project3'), value: '1008' },
  { label: t('aside.project10'), value: '1018' },
  { label: t('aside.project12'), value: '1020' },
])

const projectList = computed(() => {
  if (route.path === '/internationalDegree') {
    return projectListMap.value.slice(0, 7)
  } else if (route.path === '/studyAbroad') {
    return projectListMap.value.slice(-4)
  } else {
    return projectListMap.value
  }
})

// 清除所有错误信息
const clearErrors = (clearSuccess = false) => {
  errors.name = ''
  errors.phone = ''
  errors.projectId = ''
  errors.code = ''
  if (clearSuccess) {
    successMessage.value = ''
  }
}

// 返回顶部功能
const scrollToTop = () => {
  if (process.client) {
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    })
  }
}

// 组件卸载时清理定时器
onBeforeUnmount(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
})

// 监听路由变化
watch(
  () => route.path,
  (newPath) => {
    if (newPath === '/studyAbroad') {
      formInfo.projectId = '1018'
    } else {
      formInfo.projectId = '1012'
    }
  },
  { immediate: true },
)

const submitEnroll = async () => {
  // 清除之前的错误信息
  clearErrors()

  // 验证表单字段
  let hasError = false

  if (!formInfo.name) {
    errors.name = '请输入姓名'
    hasError = true
  }

  if (!formInfo.phone) {
    errors.phone = '请输入手机号'
    hasError = true
  } else if (!MOBILE_REG.test(formInfo.phone)) {
    errors.phone = '手机号格式错误'
    hasError = true
  }

  if (!formInfo.projectId) {
    errors.projectId = '请选择项目'
    hasError = true
  }

  if (!sendCodeValue.value) {
    errors.code = '请输入验证码'
    hasError = true
  }

  if (hasError) {
    return
  }

  try {
    await checkSendcode()
    await enrollQuery()
    // 清空表单和错误信息
    formInfo.name = ''
    formInfo.phone = ''
    formInfo.projectId = route.path === '/studyAbroad' ? '1018' : '1012'
    sendCodeValue.value = ''
    clearErrors(true)
    successMessage.value = '报名成功'

    // 3秒后清除成功提示
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
  } catch (err) {
    if (err && err.type === 'checkcode') {
      errors.code = err.msg || '验证码错误'
    } else {
      errors.code = err.msg || '报名提交失败'
    }
  }
}

const enrollQuery = async () => {
  const params = {
    channel: process.client ? localStorage.getItem('channel_num') || 10000 : 10000,
    project_id: formInfo.projectId === '9999' ? '1016' : formInfo.projectId,
    name: formInfo.name,
    phone: formInfo.phone,
  }

  try {
    const res = await submitApplicationForm(params)
    if (res && res.status === 200 && res.error === 0) {
      return {
        type: 'enroll',
        state: 'success',
      }
    } else {
      throw {
        type: 'enroll',
        state: 'fail',
        msg: res.message || '报名提交失败',
      }
    }
  } catch (error) {
    throw error
  }
}

const getSendCode = async () => {
  // 清除之前的错误信息
  errors.phone = ''
  errors.code = ''

  if (!formInfo.phone) {
    errors.phone = '手机号不能为空'
    return
  }

  if (!MOBILE_REG.test(formInfo.phone)) {
    errors.phone = '手机号格式错误'
    return
  }

  try {
    const param = {
      account: formInfo.phone,
      service: 'ezijing.com',
    }
    const res = await sendCode(param)
    btnDisabledTimer()
    if (res && res.code === 0) {
      successMessage.value = '验证码已发送，请注意查收'
      setTimeout(() => {
        successMessage.value = ''
      }, 3000)
    } else {
      errors.code = '获取验证码失败，请稍后再试'
    }
  } catch (error) {
    errors.code = '获取验证码失败，请稍后再试'
  }
}

const checkSendcode = async () => {
  const checkCodeParam = {
    account: formInfo.phone,
    code: sendCodeValue.value,
    countryCode: 86,
  }

  try {
    const res = await checkCode(checkCodeParam)
    if (res && res.code === 0) {
      return {
        type: 'checked',
        state: 'success',
      }
    } else {
      throw {
        type: 'checked',
        state: 'fail',
        msg: res.msg || '验证码检测失败',
      }
    }
  } catch (error) {
    throw error
  }
}

const btnDisabledTimer = () => {
  // 清除之前的定时器
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }

  isBtnDisabled.value = true
  countdown.value = 60
  countdownTimer.value = setInterval(() => {
    countdown.value--
    if (countdown.value < 1) {
      clearInterval(countdownTimer.value)
      countdownTimer.value = null
      isBtnDisabled.value = false
      countdown.value = 0
    }
  }, 1000)
}
</script>
<style lang="scss">
.app-right-aside {
  position: fixed;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: #ffffff;
  box-shadow: 0px 2px 16px 1px rgba(0, 0, 0, 0.12);
  border-radius: 12px;
  z-index: 1001;

  li {
    position: relative;
    width: 70px;
    height: 70px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    .hover-text {
      color: var(--main-color);
    }

    & + li {
      border-top: 1px solid #ededed;
    }
    &:hover {
      .text {
        color: #fff;
      }

      border-color: transparent;
      background-color: var(--main-color);
      .hover {
        display: block;
      }
    }
  }
  .hover {
    display: none;
    position: absolute;
    right: 100%;
    top: 50%;
    transform: translateY(-50%);
    border-radius: 12px;
    background-color: #fff;
    box-shadow: 0px 6px 12px 0px rgba(0, 0, 0, 0.1);
    padding: 10px;
  }

  .enroll_cont {
    padding: 10px;
    min-width: 260px;
    h5 {
      margin: 0 0 15px 0;
      font-size: 16px;
      font-weight: 600;
      color: #333;
      text-align: center;
    }

    .p {
      margin-bottom: 15px;
      position: relative;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .error-message {
      margin-top: 4px;
      font-size: 12px;
      color: #f56c6c;
      line-height: 1.5;
      min-height: 18px;
    }

    .success-message {
      margin-top: 4px;
      font-size: 12px;
      color: #67c23a;
      line-height: 1.5;
      min-height: 18px;
    }

    .custom-input {
      width: 100%;
      height: 40px;
      padding: 0 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      font-size: 14px;
      color: #606266;
      background-color: #fff;
      transition: border-color 0.2s;

      &::placeholder {
        color: #c0c4cc;
      }

      &:focus {
        outline: none;
        border-color: var(--main-color);
      }

      &:disabled {
        background-color: #f5f7fa;
        border-color: #e4e7ed;
        color: #c0c4cc;
        cursor: not-allowed;
      }

      &.input-error {
        border-color: #f56c6c;

        &:focus {
          border-color: #f56c6c;
        }
      }
    }

    .custom-select {
      width: 100%;
      height: 40px;
      padding: 0 30px 0 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      font-size: 14px;
      color: #606266;
      background-color: #fff;
      appearance: none;
      cursor: pointer;
      transition: border-color 0.2s;

      &:focus {
        outline: none;
        border-color: var(--main-color);
      }

      &.input-error {
        border-color: #f56c6c;

        &:focus {
          border-color: #f56c6c;
        }
      }
    }

    .icon {
      position: absolute;
      right: 15px;
      top: 50%;
      transform: translateY(-50%);
      pointer-events: none;
      color: #c0c4cc;

      &::before {
        content: '\25BC';
        font-size: 12px;
      }
    }

    .code-input-wrapper {
      .code-input-container {
        display: flex;
        gap: 10px;
      }

      .code-input {
        flex: 1;
      }

      .code-button {
        white-space: nowrap;
        padding: 0 15px;
        min-width: 100px;
      }
    }

    .custom-button {
      height: 40px;
      padding: 0 20px;
      border: 1px solid var(--main-color);
      border-radius: 4px;
      font-size: 14px;
      color: #fff;
      background-color: var(--main-color);
      cursor: pointer;
      transition: all 0.3s;

      &:hover:not(:disabled) {
        background-color: #98163a;
        border-color: #98163a;
      }

      &:active:not(:disabled) {
        background-color: #871232;
        border-color: #871232;
      }

      &:disabled {
        background-color: #c0c4cc;
        border-color: #c0c4cc;
        cursor: not-allowed;
        opacity: 0.6;
      }

      &.submit-button {
        width: 100%;
      }
    }
  }
}
</style>
