<template>
  <el-dialog
    v-model="visible"
    width="480px"
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    class="login-dialog"
    @close="handleClose"
  >
    <div class="login-page">
      <h1 class="login-title">欢迎使用Offer派</h1>

      <div class="login-form">
        <el-input
          v-model="phone"
          placeholder="输入手机号"
          size="large"
          class="login-input mt20"
        />
        <div class="code-row mt12 mb12">
          <el-input
            v-model="code"
            placeholder="输入验证码"
            size="large"
            class="login-input"
          />
          <el-button
            class="send-code-btn"
            :disabled="countdown > 0"
            @click="sendCode"
          >
            {{ countdown > 0 ? countdownText : '发送验证码' }}
          </el-button>
        </div>

        <el-button
          type="primary"
          size="large"
          class="login-btn h50 border-ra20"
          @click="handleLogin"
        >
          登录
        </el-button>

      </div>
    </div>
  </el-dialog>
</template>

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

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

const phone = ref('')
const code = ref('')
const countdown = ref(0)
let timer: ReturnType<typeof setInterval> | null = null

/** 倒计时显示文本，格式 m:ss */
const countdownText = computed(() => {
  const m = Math.floor(countdown.value / 60)
  const s = countdown.value % 60
  return `${m}:${s.toString().padStart(2, '0')}`
})

const visible = computed({
  get: () => store.state.showLogin,
  set: (val: boolean) => {
    if (!val) store.dispatch('closeLogin')
  },
})

//发送验证码
async function sendCode() {
  if (!phone.value) {
    ElMessage.warning('请输入手机号')
    return
  }
  try {
    const res = await sendSmsCode(phone.value)
    if (res.code === '0' && res.data === true) {
      ElMessage.success('验证码已发送')
      countdown.value = 300
      timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0 && timer) {
          clearInterval(timer)
          timer = null
        }
      }, 1000)
    } else {
      ElMessage.error(res.msg || '验证码发送失败')
    }
  } catch {
    // 错误已在 request 拦截器中统一处理
  }
}

/**
 * 登录流程：
 * 1. 调 smsLogin 接口，后端成功会 Set-Cookie: Token=xxx
 * 2. Cookie 自动保持登录状态，不再存 localStorage
 * 3. 关闭弹窗，跳转到登录前想去的页面
 */
async function handleLogin() {
  if (!phone.value || !code.value) {
    ElMessage.warning('请输入手机号和验证码')
    return
  }
  try {
    const res = await smsLogin(phone.value, code.value)
    if (res.code !== '0') {
      ElMessage.error(res.msg || '登录失败')
      return
    }

    // 登录成功，Cookie Token 已由后端 Set-Cookie 写入
    ElMessage.success(`欢迎回来，${res.data?.nick || ''}`)

    // 清除验证码倒计时，登录成功后解除发送限制
    if (timer) {
      clearInterval(timer)
      timer = null
    }
    countdown.value = 0

    store.commit('SET_AUTHENTICATED', true)

    const redirect = store.state.loginRedirect
    store.dispatch('closeLogin')
    if (redirect) {
      router.push(redirect)
    }
  } catch {
    // 错误已在 request 拦截器中统一处理
  }
}

function handleClose() {
  store.dispatch('closeLogin')
}
</script>
