<template>
  <div class="login-container">
    <van-form @submit="handleSubmit">
      <van-field
        v-model="form.tel"
        name="手机号"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '请填写手机号' }, { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' }]"
      />
      
      <van-field
        v-model="form.vcode"
        center
        clearable
        name="验证码"
        label="验证码"
        placeholder="请输入验证码"
        :rules="[{ required: true, message: '请填写验证码' }]"
      >
        <template #button>
          <van-button
            size="small"
            :disabled="countdown > 0"
            @click="sendSms"
            native-type="button"
          >
            {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
          </van-button>
        </template>
      </van-field>

      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          立即登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showSuccessToast, showFailToast } from 'vant';
import { getTokenApi, sendSmsApi, verifySmsApi } from '@/common/apis/ab98';
import { useAb98UserStore } from '@/pinia/stores/ab98-user';
import { useWxStore } from '@/pinia/stores/wx';

const userStore = useAb98UserStore();
const wxStore = useWxStore();
const router = useRouter()

const form = ref({
  tel: '',
  vcode: ''
})

const countdown = ref(0)
const loading = ref(true)
let timer: number | null = null

onMounted(async () => {
  try {
    const { data } = await getTokenApi('ab98_app')
    if (data.token) {
      userStore.setToken(data.token)
    } else {
      showFailToast('令牌获取失败')
    }
  } catch (err) {
    showFailToast('网络异常，请重试')
  } finally {
    loading.value = false
  }
})

const sendSms = async () => {
  try {
    if (!/^1[3-9]\d{9}$/.test(form.value.tel)) {
      showFailToast('手机号格式错误')
      return
    }

    const { data } = await sendSmsApi(userStore.token, form.value.tel)
    if (data.success) {
      startCountdown()
      showSuccessToast('验证码已发送')
    } else {
      showFailToast(data.errMsg || '发送失败')
    }
  } catch (err) {
    showFailToast('请求异常，请稍后重试')
  }
}

const startCountdown = () => {
  countdown.value = 60
  timer = window.setInterval(() => {
    if (countdown.value <= 0 && timer) {
      window.clearInterval(timer)
      return
    }
    countdown.value--
  }, 1000)
}

const handleSubmit = async () => {
  try {
    const { data } = await verifySmsApi({
      token: userStore.token,
      tel: form.value.tel,
      vcode: form.value.vcode,
      userid: wxStore.userid
    })

    if (data.success) {
      userStore.setTel(form.value.tel)
      userStore.setUserInfo(data)
      userStore.setIsLogin(true)
      showSuccessToast('登录成功')
      router.push('/')
    } else {
      showFailToast('验证码错误')
    }
  } catch (err) {
    console.error(err)
    showFailToast('登录失败，请稍后重试')
  }
}
</script>

<style scoped>
.login-container {
  padding: 20px;
  margin-top: 30%;
}
</style>