<template>
  <!-- 登录弹窗 — 使用登录页 step1&2 的样式，弹窗形式 -->
  <Teleport to="body">
    <div v-if="visible" class="login-dialog-overlay" @click.self="handleClose">
      <div class="login-dialog-box">
        <!-- 关闭按钮 -->
        <div class="login-dialog-box__close" @click="handleClose">
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M5 5L15 15M15 5L5 15" stroke="#999" stroke-width="1.8" stroke-linecap="round"/>
          </svg>
        </div>

        <!-- Logo -->
        <div class="login-dialog-box__logo-row">
          <img src="@/assets/images/logo.png" alt="">
        </div>

        <div class="login-dialog-box__form-wrap">
          <!-- 步骤一：输入手机号发送验证码 -->
          <template v-if="step === 1">
            <div class="login-dialog-box__heading">
              <h2 class="login-dialog-box__title">手机号登录/注册</h2>
              <p class="login-dialog-box__subtitle">未注册用户验证后将自动注册并登录</p>
            </div>
            <!-- 手机号输入组 -->
            <div class="login-dialog-box__phone-row">
              <!-- 手机图标 -->
              <div class="login-dialog-box__phone-icon">
                <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <rect x="4.5" y="2" width="9" height="14" rx="1.5" stroke="#0F6B66" stroke-width="1.5"/>
                  <line x1="9" y1="2" x2="9" y2="3.5" stroke="#0F6B66" stroke-width="1.5" stroke-linecap="round"/>
                </svg>
              </div>
              <!-- 国家码标签 -->
              <span class="login-dialog-box__country-label">中国 +86</span>
              <!-- 下拉箭头 -->
              <div class="login-dialog-box__country-chevron">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M6 8L10 12L14 8" stroke="#6F8586" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </div>
              <!-- 分隔线 -->
              <div class="login-dialog-box__input-divider"></div>
              <!-- 手机号输入框 -->
              <input v-model="phone" type="tel" class="login-dialog-box__phone-input" placeholder="请输入手机号码" maxlength="11" />
            </div>
            <!-- 发送验证码按钮 -->
            <button class="login-dialog-box__send-btn" :disabled="!canSend" @click="handleSendCode">发送验证码</button>
          </template>

          <!-- 步骤二：输入验证码登录 -->
          <template v-if="step === 2">
            <div class="login-dialog-box__heading">
              <h2 class="login-dialog-box__title">请输入验证码</h2>
              <p class="login-dialog-box__subtitle dflex"><span class="dib">短信验证码已发送至 +86{{ phone }} </span><span class="fw600 ml5 dib cursor-po mlauto" @click="handleChangePhone">修改手机号</span></p>
            </div>
            <!-- OTP 输入框 -->
            <div class="login-dialog-box__otp-wrap" @click="focusOtpInput">
              <input ref="otpInputRef" v-model="otpValue" type="text" inputmode="numeric" class="login-dialog-box__otp-hidden-input" maxlength="6" :disabled="isLoggingIn" @input="handleOtpInput" />
              <div v-for="(_, idx) in 6" :key="idx" class="login-dialog-box__otp-box" :class="{ 'login-dialog-box__otp-box--active': idx === otpValue.length && !isLoggingIn, 'login-dialog-box__otp-box--filled': idx < otpValue.length }">
                <span v-if="idx < otpValue.length" class="login-dialog-box__otp-digit">{{ otpValue[idx] }}</span>
                <span v-else-if="idx === otpValue.length && !isLoggingIn" class="login-dialog-box__otp-cursor"></span>
              </div>
            </div>
            <!-- 状态提示 -->
            <p v-if="smsStatusMsg" class="login-dialog-box__sms-status" :class="{ 'login-dialog-box__sms-status--error': smsStatusIsError }">{{ smsStatusMsg }}</p>
            <!-- 重新发送 / 登录中按钮 -->
            <button class="login-dialog-box__status-btn" :disabled="isLoggingIn || countdown > 0" @click="handleResendCode">
              <template v-if="isLoggingIn"><span class="login-dialog-box__spinner"></span><span>登录中</span></template>
              <template v-else-if="countdown > 0">{{ countdown }} 秒后可继续发送</template>
              <template v-else>再次发送验证码</template>
            </button>
          </template>

          <!-- 协议勾选（步骤一二通用） -->
          <div class="login-dialog-box__agreement">
            <div class="login-dialog-box__checkbox" :class="{ 'login-dialog-box__checkbox--checked': agreedTerms }" @click="agreedTerms = !agreedTerms">
              <span v-if="agreedTerms" class="login-dialog-box__check-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="0.13rem" height="0.13rem"><path stroke="currentColor" fill="currentColor" d="M77.248 415.04a64 64 0 0 1 90.496 0l226.304 226.304L846.528 188.8a64 64 0 1 1 90.56 90.496l-543.04 543.04-316.8-316.8a64 64 0 0 1 0-90.496"></path></svg></span>
            </div>
            <span class="login-dialog-box__agreement-text">登录即表示同意</span>
            <span class="login-dialog-box__agreement-link" @click="openAgreement('ae8065i3')">《用户协议》</span>
            <span class="login-dialog-box__agreement-text">与</span>
            <span class="login-dialog-box__agreement-link" @click="openAgreement('hf8375i8')">《隐私政策》</span>
          </div>
        </div>
      </div>
    </div>
  </Teleport>

  <!-- 协议预览弹窗 -->
  <AgreementPreviewDialog v-model="showAgreementDialog" :code="agreementCode" />
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { sendSmsCode, smsLogin } from '@/api/auth'
import AgreementPreviewDialog from '@/components/tools/AgreementPreviewDialog.vue'

const store = useStore()
const router = useRouter()

// ==================== 弹窗显隐控制 ====================
/** 弹窗可见性，绑定 store.state.showLogin */
const visible = computed(() => store.state.showLogin)

// ==================== 登录步骤 ====================
/** 当前步骤：1=输入手机号 2=输入验证码 */
const step = ref(1)
/** 手机号 */
const phone = ref('')
/** OTP 验证码值 */
const otpValue = ref('')
/** 是否已勾选协议 */
const agreedTerms = ref(true)
/** 倒计时秒数 */
const countdown = ref(0)
let countdownTimer: ReturnType<typeof setInterval> | null = null
/** 是否正在登录中 */
const isLoggingIn = ref(false)
/** 验证码状态提示文字 */
const smsStatusMsg = ref('')
/** 是否为错误样式 */
const smsStatusIsError = ref(false)
/** OTP 输入框引用 */
const otpInputRef = ref<HTMLInputElement | null>(null)
/** 协议弹窗状态 */
const showAgreementDialog = ref(false)
const agreementCode = ref('')

/** 发送按钮是否可用（手机号11位 + 勾选协议） */
const canSend = computed(() => phone.value.length === 11 && agreedTerms.value)

// ==================== 弹窗打开时重置状态 ====================
watch(visible, (val) => {
  if (val) {
    step.value = 1
    phone.value = ''
    otpValue.value = ''
    countdown.value = 0
    smsStatusMsg.value = ''
    smsStatusIsError.value = false
    isLoggingIn.value = false
    if (countdownTimer) { clearInterval(countdownTimer); countdownTimer = null }
  }
})

// ==================== 方法 ====================

/** 关闭弹窗 */
function handleClose() {
  store.dispatch('closeLogin')
}

/** 打开协议预览 */
function openAgreement(code: string) {
  agreementCode.value = code
  showAgreementDialog.value = true
}

/** 聚焦 OTP 隐藏输入框 */
function focusOtpInput() {
  otpInputRef.value?.focus()
}

/** 修改手机号 — 回到步骤一 */
function handleChangePhone() {
  step.value = 1
  phone.value = ''
  otpValue.value = ''
  countdown.value = 0
  smsStatusMsg.value = ''
  smsStatusIsError.value = false
  isLoggingIn.value = false
  if (countdownTimer) { clearInterval(countdownTimer); countdownTimer = null }
}

/** 开始60秒倒计时 */
function startCountdown() {
  countdown.value = 60
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0 && countdownTimer) { clearInterval(countdownTimer); countdownTimer = null }
  }, 1000)
}

/** 步骤一：发送验证码 */
async function handleSendCode() {
  if (!phone.value) { ElMessage.warning('请输入手机号'); return }
  if (!agreedTerms.value) { ElMessage.warning('请先同意用户协议与隐私政策'); return }
  try {
    const res = await sendSmsCode(phone.value)
    if (res.code === '0') {
      smsStatusMsg.value = '验证码发送成功，请输入'
      smsStatusIsError.value = false
      step.value = 2
      startCountdown()
      nextTick(() => focusOtpInput())
    } else if (res.msg && res.msg.includes('请勿重复发送')) {
      smsStatusMsg.value = '验证码还在有效期内，请输入'
      smsStatusIsError.value = false
      step.value = 2
      startCountdown()
      nextTick(() => focusOtpInput())
    } else {
      smsStatusMsg.value = res.msg || '验证码发送失败'
      smsStatusIsError.value = true
    }
  } catch (err: any) {
    const msg = err?.response?.data?.msg || '验证码发送失败'
    smsStatusMsg.value = msg
    smsStatusIsError.value = true
  }
}

/** OTP 输入处理 — 6位自动登录 */
function handleOtpInput() {
  otpValue.value = otpValue.value.replace(/\D/g, '').slice(0, 6)
  if (otpValue.value.length === 6) { handleLogin() }
}

/** 步骤二：再次发送验证码 */
async function handleResendCode() {
  if (isLoggingIn.value || countdown.value > 0) return
  try {
    const res = await sendSmsCode(phone.value)
    if (res.code === '0') {
      smsStatusMsg.value = '验证码发送成功，请输入'
      smsStatusIsError.value = false
      otpValue.value = ''
      startCountdown()
      nextTick(() => focusOtpInput())
    } else if (res.msg && res.msg.includes('请勿重复发送')) {
      smsStatusMsg.value = '验证码还在有效期内，请输入'
      smsStatusIsError.value = false
    } else {
      smsStatusMsg.value = res.msg || '验证码发送失败'
      smsStatusIsError.value = true
    }
  } catch (err: any) {
    const msg = err?.response?.data?.msg || '验证码发送失败'
    smsStatusMsg.value = msg
    smsStatusIsError.value = true
  }
}

/** 登录接口调用 */
async function handleLogin() {
  isLoggingIn.value = true
  try {
    const res = await smsLogin(phone.value, otpValue.value)
    if (res.code !== '0') {
      smsStatusMsg.value = '验证码有误，请重新输入'
      smsStatusIsError.value = true
      otpValue.value = ''
      isLoggingIn.value = false
      nextTick(() => focusOtpInput())
      return
    }

    // 登录成功
    ElMessage.success(`欢迎回来，${res.data?.nick || ''}`)
    if (countdownTimer) { clearInterval(countdownTimer); countdownTimer = null }
    countdown.value = 0
    store.commit('SET_AUTHENTICATED', true)

    // 关闭弹窗并跳转
    const redirect = store.state.loginRedirect
    store.dispatch('closeLogin')
    if (redirect) {
      router.push(redirect)
    }
  } catch {
    smsStatusMsg.value = '验证码有误，请重新输入'
    smsStatusIsError.value = true
    otpValue.value = ''
    isLoggingIn.value = false
    nextTick(() => focusOtpInput())
  }
}
</script>
