<template>
  <div class="login-page">
    <div class="login-box">
      <h1>管理后台</h1>
      <el-tabs v-model="activeTab" class="login-tabs">
        <el-tab-pane label="登录" name="login">
          <el-form ref="formRef" :model="form" :rules="rules" @submit.prevent="handleLogin">
            <el-form-item prop="username">
              <el-input v-model="form.username" placeholder="用户名" size="large" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="form.password" type="password" placeholder="密码" size="large" show-password @keyup.enter="handleLogin" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="large" :loading="loading" @click="handleLogin" style="width: 100%">
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="密码找回" name="reset">
          <el-form ref="resetFormRef" :model="resetForm" :rules="resetRules" @submit.prevent="handleReset">
            <el-form-item prop="mobile">
              <el-input v-model="resetForm.mobile" placeholder="手机号" size="large" maxlength="11" />
            </el-form-item>
            <el-form-item prop="code">
              <div class="code-row">
                <el-input v-model="resetForm.code" placeholder="验证码" size="large" maxlength="6" style="flex: 1" />
                <el-button size="large" :disabled="resetCountdown > 0" @click="handleResetSendCode">
                  {{ resetCountdown > 0 ? `${resetCountdown}s` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item prop="newPassword">
              <el-input v-model="resetForm.newPassword" type="password" placeholder="新密码（至少6位）" size="large" show-password />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="large" :loading="resetLoading" @click="handleReset" style="width: 100%">
                重置密码
              </el-button>
            </el-form-item>
          </el-form>
          <p class="tip">测试验证码：8888</p>
        </el-tab-pane>
        <el-tab-pane label="注册" name="register">
          <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" @submit.prevent="handleRegister">
            <el-form-item prop="mobile">
              <el-input v-model="registerForm.mobile" placeholder="手机号" size="large" maxlength="11" />
            </el-form-item>
            <el-form-item prop="code">
              <div class="code-row">
                <el-input v-model="registerForm.code" placeholder="验证码" size="large" maxlength="6" style="flex: 1" />
                <el-button size="large" :disabled="countdown > 0" @click="handleSendCode">
                  {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="registerForm.password" type="password" placeholder="密码（至少6位）" size="large" show-password />
            </el-form-item>
            <el-form-item>
              <el-input v-model="registerForm.username" placeholder="用户名（可选，默认手机号）" size="large" />
            </el-form-item>
            <el-form-item>
              <el-input v-model="registerForm.email" placeholder="邮箱（可选）" size="large" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="large" :loading="registerLoading" @click="handleRegister" style="width: 100%">
                注册
              </el-button>
            </el-form-item>
          </el-form>
          <p class="tip">测试验证码：8888</p>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login, sendCode, register, resetPassword, getMyPermissions } from '../api/admin'
import { useAuthStore } from '../stores/auth'

const router = useRouter()
const authStore = useAuthStore()

const formRef = ref(null)
const registerFormRef = ref(null)
const resetFormRef = ref(null)
const loading = ref(false)
const registerLoading = ref(false)
const resetLoading = ref(false)
const countdown = ref(0)
const resetCountdown = ref(0)
const activeTab = ref('login')

const form = reactive({
  username: '',
  password: ''
})

const registerForm = reactive({
  mobile: '',
  code: '',
  password: '',
  username: '',
  email: ''
})

const resetForm = reactive({
  mobile: '',
  code: '',
  newPassword: ''
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const registerRules = {
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' }
  ]
}

const resetRules = {
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  await formRef.value?.validate()
  loading.value = true
  try {
    const res = await login(form)
    authStore.setToken(res.token)
    authStore.setUser(res.user)
    try {
      const permRes = await getMyPermissions()
      authStore.setPermissions(permRes.permissions || [])
    } catch (_) {}
    ElMessage.success('登录成功')
    const redirect = router.currentRoute.value.query.redirect || '/'
    router.replace(redirect)
  } catch (e) {
    ElMessage.error(e.message)
  } finally {
    loading.value = false
  }
}

const handleSendCode = async () => {
  await registerFormRef.value?.validateField('mobile').catch(() => {})
  if (!registerForm.mobile || !/^1\d{10}$/.test(registerForm.mobile)) return
  try {
    await sendCode(registerForm.mobile)
    ElMessage.success('验证码已发送（测试请输入 8888）')
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) clearInterval(timer)
    }, 1000)
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message || '发送失败')
  }
}

const handleResetSendCode = async () => {
  await resetFormRef.value?.validateField('mobile').catch(() => {})
  if (!resetForm.mobile || !/^1\d{10}$/.test(resetForm.mobile)) return
  try {
    await sendCode(resetForm.mobile)
    ElMessage.success('验证码已发送（测试请输入 8888）')
    resetCountdown.value = 60
    const timer = setInterval(() => {
      resetCountdown.value--
      if (resetCountdown.value <= 0) clearInterval(timer)
    }, 1000)
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message || '发送失败')
  }
}

const handleReset = async () => {
  await resetFormRef.value?.validate()
  resetLoading.value = true
  try {
    await resetPassword({
      mobile: resetForm.mobile,
      code: resetForm.code,
      new_password: resetForm.newPassword
    })
    ElMessage.success('密码已重置，请登录')
    activeTab.value = 'login'
    form.username = resetForm.mobile
    resetForm.mobile = ''
    resetForm.code = ''
    resetForm.newPassword = ''
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message || '重置失败')
  } finally {
    resetLoading.value = false
  }
}

const handleRegister = async () => {
  await registerFormRef.value?.validate()
  registerLoading.value = true
  try {
    await register({
      mobile: registerForm.mobile,
      code: registerForm.code,
      password: registerForm.password,
      username: registerForm.username || undefined,
      email: registerForm.email || undefined
    })
    ElMessage.success('注册成功，请登录')
    activeTab.value = 'login'
    form.username = registerForm.username || registerForm.mobile
    registerForm.mobile = ''
    registerForm.code = ''
    registerForm.password = ''
    registerForm.username = ''
    registerForm.email = ''
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message || '注册失败')
  } finally {
    registerLoading.value = false
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.login-box {
  width: 400px;
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}
.login-box h1 {
  margin-bottom: 20px;
  text-align: center;
  font-size: 24px;
  color: #333;
}
.login-tabs {
  margin-top: 0;
}
.login-tabs :deep(.el-tabs__header) {
  margin-bottom: 20px;
}
.login-tabs :deep(.el-tabs__item) {
  font-size: 15px;
}
.login-tabs :deep(.el-tabs__nav-wrap::after) {
  display: none;
}
.code-row {
  display: flex;
  gap: 12px;
  width: 100%;
}
.tip {
  margin-top: -8px;
  font-size: 12px;
  color: #999;
  text-align: center;
}
</style>
