<template>
  <view class="page">
    <!-- 顶部背景 -->
    <view class="header">
      <text class="title">声工坊</text>
      <text class="subtitle">让文字变成声音</text>
    </view>

    <!-- 登录表单 -->
    <view class="form-card">
      <text class="form-title">手机号登录</text>

      <!-- 手机号输入 -->
      <view class="input-group">
        <text class="input-label">手机号</text>
        <input
          v-model="phone"
          type="number"
          class="input"
          placeholder="请输入手机号"
          maxlength="11"
        />
      </view>

      <!-- 验证码输入 -->
      <view class="input-group">
        <text class="input-label">验证码</text>
        <view class="code-row">
          <input
            v-model="code"
            type="number"
            class="input code-input"
            placeholder="请输入验证码"
            maxlength="6"
          />
          <button
            class="code-btn"
            :disabled="countdown > 0 || !isPhoneValid"
            @click="handleSendCode"
          >
            <text class="code-btn-text">{{ countdown > 0 ? `${countdown}s` : '获取验证码' }}</text>
          </button>
        </view>
      </view>

      <!-- 登录按钮 -->
      <button class="login-btn" :disabled="!canLogin" @click="handleLogin">
        <text class="login-btn-text">登录</text>
      </button>

      <!-- 提示 -->
      <text class="tip">登录即表示同意《用户协议》和《隐私政策》</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onUnmounted } from 'vue';
import { useUserStore } from '../../store/user';

const userStore = useUserStore();

// 状态
const phone = ref('');
const code = ref('');
const countdown = ref(0);
const loading = ref(false);

let timer: number | null = null;

// 计算属性
const isPhoneValid = computed(() => /^1[3-9]\d{9}$/.test(phone.value));
// 开发环境免密登录：验证码可以为空
const canLogin = computed(() => isPhoneValid.value && !loading.value);

// 发送验证码
async function handleSendCode() {
  if (countdown.value > 0 || !isPhoneValid.value) return;

  try {
    loading.value = true;
    await userStore.sendCode(phone.value);
    uni.showToast({ title: '验证码已发送', icon: 'success' });

    // 开始倒计时
    countdown.value = 60;
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0 && timer) {
        clearInterval(timer);
        timer = null;
      }
    }, 1000) as unknown as number;
  } catch (error) {
    console.error('发送验证码失败:', error);
  } finally {
    loading.value = false;
  }
}

// 登录（开发环境免密）
async function handleLogin() {
  if (!canLogin.value) return;

  // 验证手机号格式
  if (!isPhoneValid.value) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
    return;
  }

  loading.value = true;
  try {
    // 开发环境下免密登录，验证码可为空
    const loginCode = code.value || '123456';
    await userStore.login(phone.value, loginCode);
    uni.showToast({ title: '登录成功', icon: 'success' });

    // 返回上一页或跳转首页
    const pages = getCurrentPages();
    if (pages.length > 1) {
      uni.navigateBack();
    } else {
      uni.switchTab({ url: '/pages/index/index' });
    }
  } catch (error: any) {
    console.error('登录失败:', error);
    uni.showToast({ 
      title: error.message || '登录失败，请重试', 
      icon: 'none' 
    });
  } finally {
    loading.value = false;
  }
}

// 组件卸载时清理定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
});
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: linear-gradient(180deg, #4f46e5 0%, #818cf8 50%, #f9fafb 50%);
}

.header {
  padding: 120rpx 32rpx 80rpx;
  text-align: center;
}

.title {
  display: block;
  font-size: 56rpx;
  font-weight: 700;
  color: #ffffff;
  margin-bottom: 16rpx;
}

.subtitle {
  display: block;
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
}

.form-card {
  background: #ffffff;
  margin: 0 32rpx;
  border-radius: 24rpx;
  padding: 48rpx 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.form-title {
  display: block;
  font-size: 36rpx;
  font-weight: 600;
  color: #1f2937;
  text-align: center;
  margin-bottom: 48rpx;
}

.input-group {
  margin-bottom: 32rpx;
}

.input-label {
  display: block;
  font-size: 26rpx;
  color: #6b7280;
  margin-bottom: 12rpx;
}

.input {
  width: 100%;
  height: 88rpx;
  background: #f9fafb;
  border-radius: 12rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #1f2937;
}

.code-row {
  display: flex;
  gap: 16rpx;
}

.code-input {
  flex: 1;
}

.code-btn {
  width: 200rpx;
  height: 88rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
  border-radius: 12rpx;
  border: none;
  padding: 0;
}

.code-btn::after {
  border: none;
}

.code-btn[disabled] {
  background: #e5e7eb;
  opacity: 0.6;
}

.code-btn-text {
  font-size: 26rpx;
  color: #ffffff;
}

.login-btn {
  width: 100%;
  height: 96rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  border-radius: 16rpx;
  border: none;
  margin-top: 48rpx;
}

.login-btn::after {
  border: none;
}

.login-btn[disabled] {
  background: #e5e7eb;
  opacity: 0.6;
}

.login-btn-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
}

.tip {
  display: block;
  font-size: 22rpx;
  color: #9ca3af;
  text-align: center;
  margin-top: 32rpx;
}
</style>