<template>
  <div class="login-page">
    <div class="login-header">
      <div class="logo">🛵</div>
      <h1>电动车租赁</h1>
      <p>骑手端</p>
    </div>
    
    <div class="login-form">
      <el-tabs v-model="loginType" class="login-tabs">
        <el-tab-pane label="手机号登录" name="phone">
          <el-form ref="phoneFormRef" :model="phoneForm" :rules="phoneRules">
            <el-form-item prop="phone">
              <el-input
                v-model="phoneForm.phone"
                placeholder="请输入手机号"
                size="large"
                :prefix-icon="Phone"
              />
            </el-form-item>
            <el-form-item prop="code">
              <el-input
                v-model="phoneForm.code"
                placeholder="请输入验证码"
                size="large"
                :prefix-icon="Lock"
                style="width: 60%"
              >
                <template #append>
                  <el-button @click="sendCode" :disabled="codeTimer > 0">
                    {{ codeTimer > 0 ? `${codeTimer}s` : '获取验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="密码登录" name="password">
          <el-form ref="pwdFormRef" :model="pwdForm" :rules="pwdRules">
            <el-form-item prop="phone">
              <el-input
                v-model="pwdForm.phone"
                placeholder="请输入手机号"
                size="large"
                :prefix-icon="Phone"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="pwdForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      
      <el-button type="primary" size="large" :loading="loading" class="login-btn" @click="handleLogin">
        登录
      </el-button>
      
      <div class="demo-hint">
        <p>演示账号：13800138000 / 123456</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Phone, Lock } from '@element-plus/icons-vue'
import request from '../utils/request'

const router = useRouter()
const loginType = ref('password')
const loading = ref(false)
const codeTimer = ref(0)

const phoneFormRef = ref()
const pwdFormRef = ref()

const phoneForm = ref({
  phone: '13800138000',
  code: '123456'
})

const pwdForm = ref({
  phone: '13800138000',
  password: '123456'
})

const phoneRules = {
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const pwdRules = {
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 发送验证码
const sendCode = () => {
  if (!phoneForm.value.phone) {
    ElMessage.warning('请输入手机号')
    return
  }
  // 模拟发送验证码
  ElMessage.success('验证码已发送')
  codeTimer.value = 60
  const timer = setInterval(() => {
    codeTimer.value--
    if (codeTimer.value <= 0) clearInterval(timer)
  }, 1000)
}

// 登录
const handleLogin = async () => {
  try {
    let formRef = loginType.value === 'phone' ? phoneFormRef.value : pwdFormRef.value
    await formRef.validate()
    loading.value = true

    // 使用密码登录
    const res = await request.post('/customers/login', {
      phone: pwdForm.value.phone,
      password: pwdForm.value.password
    }).catch(async () => {
      // 如果没有专门的登录接口，尝试用手机号查找客户
      const customers = await request.get('/customers')
      if (customers.success && customers.data) {
        const customer = customers.data.find(c => c.phone === pwdForm.value.phone)
        if (customer) {
          return { success: true, data: customer }
        }
      }
      throw new Error('登录失败')
    })

    if (res.success && res.data) {
      const customer = res.data
      const token = btoa(`${customer._id}:${Date.now()}`)
      localStorage.setItem('customer_token', token)
      localStorage.setItem('customer_info', JSON.stringify(customer))
      localStorage.setItem('customer_id', customer._id)
      ElMessage.success('登录成功')
      await nextTick()
      router.push('/')
    } else {
      ElMessage.error(res.message || '登录失败')
    }
  } catch (e) {
    // 如果API不存在，使用本地模拟登录
    if (pwdForm.value.phone === '13800138000' && pwdForm.value.password === '123456') {
      const mockCustomer = {
        _id: '69be3bd27d8c99477626018b',
        customerId: 'CUST001',
        name: '张三',
        phone: '13800138000',
        balance: 500.00,
        totalRentals: 5,
        creditScore: 100
      }
      const token = btoa(`${mockCustomer._id}:${Date.now()}`)
      localStorage.setItem('customer_token', token)
      localStorage.setItem('customer_info', JSON.stringify(mockCustomer))
      localStorage.setItem('customer_id', mockCustomer._id)
      ElMessage.success('登录成功（演示模式）')
      await nextTick()
      router.push('/')
    } else {
      ElMessage.error('手机号或密码错误')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background: #F7F7F7;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-header {
  text-align: center;
  color: #1A1A1A;
  margin-bottom: 40px;
}

.logo {
  font-size: 64px;
  margin-bottom: 10px;
}

.login-header h1 {
  font-size: 28px;
  margin-bottom: 8px;
  font-weight: 600;
  color: #1A1A1A;
}

.login-header p {
  font-size: 13px;
  color: #B2B2B2;
}

.login-form {
  width: 100%;
  max-width: 360px;
  background: #fff;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
}

.login-tabs :deep(.el-tabs__header) {
  margin-bottom: 20px;
}

.login-tabs :deep(.el-tabs__item) {
  font-size: 15px;
  color: #B2B2B2;
}

.login-tabs :deep(.el-tabs__item.is-active) {
  color: #FF6B00;
}

.login-tabs :deep(.el-tabs__active-bar) {
  background-color: #FF6B00;
}

.login-tabs :deep(.el-input__wrapper) {
  border-radius: 12px;
}

.login-btn {
  width: 100%;
  background: #FF6B00;
  border-color: #FF6B00;
  font-size: 18px;
  border-radius: 12px;
  margin-top: 20px;
  height: 48px;
}

.demo-hint {
  text-align: center;
  color: #B2B2B2;
  font-size: 12px;
  margin-top: 20px;
}
</style>
