# Login2 & Register2 组件文档

企业级登录注册组件，支持多种认证方式、灵活配置、完整的用户流程管理。

## 📋 目录

- [特性](#特性)
- [快速开始](#快速开始)
- [核心概念](#核心概念)
- [组件 API](#组件-api)
  - [Login2](#login2)
  - [Register2](#register2)
- [配置指南](#配置指南)
  - [登录方式配置](#登录方式配置)
  - [注册验证方式](#注册验证方式)
  - [UI 配置](#ui-配置)
- [认证流程](#认证流程)
  - [邮箱登录](#邮箱登录)
  - [手机登录](#手机登录)
  - [第三方登录](#第三方登录)
  - [忘记密码](#忘记密码)
- [高级功能](#高级功能)
  - [分步骤登录](#分步骤登录)
  - [验证码登录](#验证码登录)
  - [多步骤注册](#多步骤注册)
  - [邮件链接验证](#邮件链接验证)
- [国际化](#国际化)
- [样式定制](#样式定制)
- [最佳实践](#最佳实践)
- [常见问题](#常见问题)

---

## ✨ 特性

### 🔐 多种认证方式
- **邮箱认证**：密码登录、验证码登录、邮件链接注册
- **手机认证**：密码登录、验证码登录、短信验证注册
- **第三方登录**：Google、Facebook、Apple（扩展支持更多平台）

### 🎯 灵活配置
- **动态排序**：通过配置数组控制登录方式的显示顺序
- **验证方式切换**：邮箱/手机支持密码和验证码无缝切换
- **分步骤登录**：可选的两步登录流程，提升安全性
- **UI 定制**：支持主题色、Logo、标题、副标题等完整定制

### 📱 完整的用户流程
- **注册流程**：邮件验证码、邮件链接、短信验证码、无验证注册
- **登录流程**：密码登录、验证码登录、第三方登录
- **密码找回**：邮箱/手机验证码验证 + 重置密码
- **错误处理**：账号已注册、验证失败、链接过期等场景

### 🌍 国际化支持
- 内置中英文支持
- 可扩展的国际化机制
- 自动检测用户语言环境

### 📦 Lowcode 支持
- 完整的 Alibaba Lowcode Engine 集成
- 可视化配置所有属性
- 预设代码片段（Snippets）

---

## 🚀 快速开始

### 安装

```bash
npm install @pisell/materials
# or
pnpm add @pisell/materials
```

### 基础使用

#### 邮箱登录（密码）

```tsx
import { Login2 } from '@pisell/materials';

function App() {
  return (
    <Login2
      config={{
        loginMethods: [
          {
            type: 'email',
            verificationMethods: ['password']
          }
        ],
        ui: {
          title: 'Welcome back',
          subtitle: 'Log in to your account'
        }
      }}
      onLogin={(data, method) => {
        console.log('Login success:', data);
        // data = { account: 'user@example.com', password: '***', remember_me: true }
      }}
    />
  );
}
```

#### 邮箱注册（验证码）

```tsx
import { Register2 } from '@pisell/materials';

function App() {
  return (
    <Register2
      config={{
        email: {
          enable_email: true,
          registration_verification: 'verification_code'
        },
        ui: {
          title: 'Create your account',
          subtitle: 'Get started in seconds'
        }
      }}
      onRegister={(data, method) => {
        console.log('Register success:', data);
        // data = { account: 'user@example.com', password: '***', verificationCode: '1234' }
      }}
    />
  );
}
```

---

## 🧩 核心概念

### 登录方式（Login Methods）

Login2 组件通过 `loginMethods` 数组统一管理所有登录方式：

```typescript
loginMethods: [
  { type: 'email', verificationMethods: ['password', 'verification_code'] },
  { type: 'phone', verificationMethods: ['verification_code'] },
  { type: 'google', clientId: 'your-client-id' },
  { type: 'facebook', appId: 'your-app-id' },
  { type: 'apple', clientId: 'your-client-id' }
]
```

**关键点**：
- 数组顺序决定显示顺序
- 第一项为默认显示的主登录方式
- 其他项在 "OR" 分隔符下方显示

### 验证方式（Verification Methods）

邮箱和手机登录支持两种验证方式：

- **password**：传统密码登录
- **verification_code**：验证码登录（一次性验证码）

用户可以在同一个登录方式下切换不同的验证方式。

### 注册验证（Registration Verification）

Register2 组件支持四种注册验证方式：

- **verification_code**：邮箱/短信验证码（推荐）
- **verification_link**：邮件链接验证（仅邮箱）
- **none**：无需验证直接注册（不推荐）

---

## 📚 组件 API

### Login2

#### Props

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| config | `Login2Config` | 必填 | 登录组件配置 |
| onLogin | `(data, method, channel?) => void` | - | 登录成功回调 |
| onOAuthLogin | `(provider, data) => void` | - | 第三方登录回调 |
| onSendVerificationCode | `(account, method) => void` | - | 发送验证码回调 |
| onForgotPassword | `(account, method) => void` | - | 忘记密码回调 |

#### Login2Config

```typescript
interface Login2Config {
  // 登录方式配置（推荐）
  loginMethods?: LoginMethodItem[]
  
  // UI 配置
  ui?: {
    logo?: string
    title?: string
    subtitle?: string
    desc?: string
    themeColor?: string
    showTabs?: boolean
    formLabels?: {
      email?: { show?: boolean; text?: string }
      phone?: { show?: boolean; text?: string }
      password?: { show?: boolean; text?: string }
      verificationCode?: { show?: boolean; text?: string }
    }
  }
  
  // 渠道标识（用于区分不同来源的登录请求）
  channel?: string
}
```

#### LoginMethodItem

```typescript
// 邮箱登录
interface EmailLoginMethod {
  type: 'email'
  verificationMethods: Array<'password' | 'verification_code'>
  stepByStep?: boolean  // 是否启用分步骤登录
}

// 手机登录
interface PhoneLoginMethod {
  type: 'phone'
  verificationMethods: Array<'password' | 'verification_code'>
  stepByStep?: boolean
}

// Google 登录
interface GoogleLoginMethod {
  type: 'google'
  clientId?: string
}

// Facebook 登录
interface FacebookLoginMethod {
  type: 'facebook'
  appId?: string
}

// Apple 登录
interface AppleLoginMethod {
  type: 'apple'
  clientId?: string
}

type LoginMethodItem = 
  | EmailLoginMethod 
  | PhoneLoginMethod 
  | GoogleLoginMethod 
  | FacebookLoginMethod 
  | AppleLoginMethod
```

---

### Register2

#### Props

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| config | `Register2Config` | 必填 | 注册组件配置 |
| onRegister | `(data, method, channel?) => void` | - | 注册成功回调 |
| onOAuthLogin | `(provider, data) => void` | - | 第三方登录回调 |
| onSendVerificationCode | `(account, method) => void` | - | 发送验证码回调 |
| onGoToLogin | `() => void` | - | 跳转登录回调 |
| onEmailLinkExpired | `() => void` | - | 邮件链接过期回调 |

#### Register2Config

```typescript
interface Register2Config {
  // 邮箱认证配置
  email?: {
    enable_email?: boolean
    registration_verification?: 'verification_code' | 'verification_link' | 'none'
  }
  
  // 手机认证配置
  phone?: {
    enable_phone_number?: boolean
    registration_verification?: 'verification_code' | 'none'
  }
  
  // 第三方登录配置
  oauth?: {
    google?: { enabled?: boolean; client_id?: string }
    facebook?: { enabled?: boolean; app_id?: string }
    apple?: { enabled?: boolean; client_id?: string }
  }
  
  // 默认认证方式
  defaultAuthMethod?: 'email' | 'phone'
  
  // UI 配置
  ui?: {
    logo?: string
    title?: string
    subtitle?: string
    desc?: string
    themeColor?: string
    formLabels?: {
      email?: { show?: boolean; text?: string }
      phone?: { show?: boolean; text?: string }
      password?: { show?: boolean; text?: string }
      verificationCode?: { show?: boolean; text?: string }
    }
  }
  
  // 渠道标识
  channel?: string
  
  // 邮件链接验证（从邮件链接打开时使用）
  emailLinkVerification?: {
    enabled: boolean
    code: string
  }
}
```

---

## ⚙️ 配置指南

### 登录方式配置

#### 1. 邮箱为主，密码优先，支持验证码切换

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'email',
        verificationMethods: ['password', 'verification_code']
      },
      { type: 'google', clientId: 'xxx' }
    ]
  }}
/>
```

**效果**：
- 主表单显示：Email + Password 输入框
- 底部显示切换按钮：📧 Email code to your email
- OR 分隔符
- Continue with Google 按钮

#### 2. 手机为主，验证码优先

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'phone',
        verificationMethods: ['verification_code', 'password']
      }
    ]
  }}
/>
```

**效果**：
- 主表单显示：Phone + Verification Code 输入框
- 底部显示切换按钮：🔑 Password login

#### 3. 多种方式混合

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'email',
        verificationMethods: ['password', 'verification_code'],
        stepByStep: true  // 启用分步骤登录
      },
      { type: 'google', clientId: 'your-google-client-id' },
      { type: 'facebook', appId: 'your-facebook-app-id' },
      {
        type: 'phone',
        verificationMethods: ['verification_code']
      }
    ]
  }}
/>
```

**效果**：
- 主表单：邮箱分步骤密码登录（先输入邮箱，再输入密码）
- 底部显示：Email code / Continue with Google / Continue with Facebook / Login with phone number

#### 4. 纯第三方登录

```tsx
<Login2
  config={{
    loginMethods: [
      { type: 'google', clientId: 'xxx' },
      { type: 'apple', clientId: 'xxx' },
      { type: 'facebook', appId: 'xxx' }
    ]
  }}
/>
```

**效果**：
- 仅显示三个第三方登录按钮
- 不显示任何输入框

---

### 注册验证方式

#### 1. 邮箱验证码注册（推荐）

```tsx
<Register2
  config={{
    email: {
      enable_email: true,
      registration_verification: 'verification_code'
    }
  }}
/>
```

**流程**：
1. 用户输入邮箱
2. 点击 "Continue" → 发送验证码
3. 显示 "Check your email" 页面，输入 4 位验证码
4. 验证成功 → 显示 "验证成功" 提示（1.5 秒）
5. 自动跳转到 "Set Password" 页面
6. 设置密码 → 完成注册

#### 2. 邮件链接注册

```tsx
<Register2
  config={{
    email: {
      enable_email: true,
      registration_verification: 'verification_link'
    }
  }}
/>
```

**流程**：
1. 用户输入邮箱
2. 点击 "Continue" → 发送验证链接
3. 显示 "Verify your email" 页面（等待用户点击邮件链接）
4. 用户在邮箱中点击链接 → 打开带 `code` 参数的页面
5. 组件自动验证 → 显示 "Verifying..." 页面
6. 验证成功 → 跳转到 "Set Password" 页面
7. 设置密码 → 完成注册

**使用验证链接时的配置**：

```tsx
// 从邮件链接打开时
const urlParams = new URLSearchParams(window.location.search);
const verificationCode = urlParams.get('code');

<Register2
  config={{
    email: {
      enable_email: true,
      registration_verification: 'verification_link'
    },
    emailLinkVerification: verificationCode ? {
      enabled: true,
      code: verificationCode
    } : undefined
  }}
/>
```

#### 3. 手机短信验证注册

```tsx
<Register2
  config={{
    phone: {
      enable_phone_number: true,
      registration_verification: 'verification_code'
    },
    defaultAuthMethod: 'phone'
  }}
/>
```

**流程**：
1. 用户选择国家/地区，输入手机号
2. 点击 "Continue" → 发送短信验证码
3. 显示 "Check your message" 页面，输入 4 位验证码
4. 验证成功 → 跳转到 "Set Password" 页面
5. 设置密码 → 完成注册

#### 4. 无验证注册（不推荐）

```tsx
<Register2
  config={{
    email: {
      enable_email: true,
      registration_verification: 'none'
    }
  }}
/>
```

**流程**：
1. 用户输入邮箱和密码
2. 点击 "Continue" → 直接注册
3. 完成注册

**⚠️ 安全提示**：此模式跳过验证，不推荐在生产环境使用。

#### 5. 混合注册方式

```tsx
<Register2
  config={{
    email: {
      enable_email: true,
      registration_verification: 'verification_code'
    },
    phone: {
      enable_phone_number: true,
      registration_verification: 'verification_code'
    },
    oauth: {
      google: { enabled: true, client_id: 'xxx' }
    }
  }}
/>
```

**效果**：
- 主表单：邮箱注册
- 底部显示：Register with phone（点击切换到手机注册）
- OR 分隔符
- Continue with Google 按钮

---

### UI 配置

#### 完整的 UI 定制示例

```tsx
<Login2
  config={{
    loginMethods: [
      { type: 'email', verificationMethods: ['password'] }
    ],
    ui: {
      logo: 'https://your-domain.com/logo.png',
      title: 'Welcome back',
      subtitle: 'Log in to your account',
      desc: 'Enter your credentials to access your account',
      themeColor: '#7F56D9',  // 主题紫色
      formLabels: {
        email: {
          show: true,
          text: 'Email Address'
        },
        password: {
          show: true,
          text: 'Your Password'
        }
      }
    }
  }}
/>
```

#### 表单标签配置

隐藏标签或自定义标签文本：

```tsx
ui: {
  formLabels: {
    email: {
      show: false  // 隐藏 Email 标签
    },
    password: {
      show: true,
      text: 'Enter Password'  // 自定义密码标签
    },
    verificationCode: {
      show: true,
      text: 'Verification Code (4 digits)'
    }
  }
}
```

---

## 🔄 认证流程

### 邮箱登录

#### 密码登录（单步）

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'email',
        verificationMethods: ['password']
      }
    ]
  }}
  onLogin={async (data, method) => {
    // data = { account: 'user@example.com', password: '***', remember_me: true }
    // method = 'email'
    const response = await loginAPI(data);
    if (response.success) {
      // 登录成功，跳转到首页
      window.location.href = '/dashboard';
    }
  }}
/>
```

**API 调用**：
```typescript
registerAndLogin.emailPasswordLogin({
  email: 'user@example.com',
  password: 'SecurePassword123!'
})
```

#### 密码登录（分步骤）

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'email',
        verificationMethods: ['password'],
        stepByStep: true  // ✅ 启用分步骤
      }
    ]
  }}
/>
```

**用户流程**：
1. **第一步**：输入邮箱 → 点击 "Continue with email"
2. **第二步**：显示已输入的邮箱（只读） → 输入密码 → 点击 "Log in"
3. 点击 "Back" 可返回第一步修改邮箱

**使用场景**：
- 提升安全性（分步输入）
- 更好的移动端体验
- 与某些身份验证服务（如 Auth0）保持一致的用户体验

#### 验证码登录（固定两步）

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'email',
        verificationMethods: ['verification_code']
      }
    ]
  }}
  onLogin={async (data, method) => {
    // data = { account: 'user@example.com', verification_code: '1234' }
    // method = 'email'
  }}
/>
```

**用户流程**：
1. **第一步**：输入邮箱 → 点击 "Continue with email"
2. 自动发送验证码到邮箱
3. **第二步**：显示 "Check your email" 页面 → 输入 4 位验证码 → 点击 "Log in"

**API 调用**：
```typescript
// 第一步：发送验证码
registerAndLogin.sendEmailVerificationCode({
  type: 'email',
  target: 'user@example.com',
  purpose: 'login'
})

// 第二步：验证并登录
registerAndLogin.emailCodeLogin({
  email: 'user@example.com',
  code: '1234'
})
```

**⚠️ 注意**：验证码登录始终是两步流程，不受 `stepByStep` 配置影响。

---

### 手机登录

#### 手机号密码登录

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'phone',
        verificationMethods: ['password']
      }
    ]
  }}
  onLogin={async (data, method) => {
    // data = { account: '+8613800138000', password: '***', remember_me: true }
    // method = 'phone'
  }}
/>
```

**API 调用**：
```typescript
registerAndLogin.phonePasswordLogin({
  phone: '+8613800138000',
  password: 'SecurePassword123!'
})
```

#### 手机号验证码登录

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'phone',
        verificationMethods: ['verification_code']
      }
    ]
  }}
/>
```

**用户流程**：
1. 选择国家/地区，输入手机号
2. 点击 "Continue with phone"
3. 自动发送短信验证码
4. 输入 4 位验证码 → 点击 "Log in"

**API 调用**：
```typescript
// 第一步：发送短信验证码
registerAndLogin.sendSmsLoginCode({
  phone: '+8613800138000',
  country_calling_code: '+86'
})

// 第二步：验证并登录
registerAndLogin.phoneCodeLogin({
  phone: '+8613800138000',
  country_calling_code: '+86',
  code: '1234'
})
```

---

### 第三方登录

#### Google 登录

```tsx
<Login2
  config={{
    loginMethods: [
      { type: 'google', clientId: 'your-google-client-id.apps.googleusercontent.com' }
    ]
  }}
  onOAuthLogin={(provider, data) => {
    console.log('OAuth provider:', provider); // 'google'
    console.log('OAuth data:', data);
    // 处理 Google 登录回调
  }}
/>
```

#### 混合第三方登录

```tsx
<Login2
  config={{
    loginMethods: [
      { type: 'email', verificationMethods: ['password'] },
      { type: 'google', clientId: 'xxx' },
      { type: 'facebook', appId: 'xxx' },
      { type: 'apple', clientId: 'xxx' }
    ]
  }}
/>
```

**显示效果**：
- 主表单：Email + Password
- OR 分隔符
- Continue with Google 按钮
- Continue with Facebook 按钮
- Continue with Apple 按钮

---

### 忘记密码

#### 邮箱找回密码

```tsx
<Login2
  config={{
    loginMethods: [
      { type: 'email', verificationMethods: ['password'] }
    ]
  }}
  onForgotPassword={(account, method) => {
    console.log('Forgot password for:', account); // 'user@example.com'
    console.log('Method:', method); // 'email'
  }}
/>
```

**用户流程**：
1. 在登录页点击 "Forgot password" 链接
2. **确认邮箱页面**：显示预填的邮箱（如果有） → 点击 "Send verification code"
3. 发送验证码到邮箱
4. **输入验证码页面**：输入 4 位验证码 → 点击 "Verify"
5. 验证成功
6. **设置新密码页面**：输入新密码 → 点击 "Continue"
7. 密码重置成功 → 返回登录页

**API 调用**：
```typescript
// 第一步：发送验证码
registerAndLogin.sendEmailVerificationCode({
  type: 'email',
  target: 'user@example.com',
  purpose: 'password_reset'
})

// 第二步：验证验证码
registerAndLogin.verifyCode({
  type: 'email',
  target: 'user@example.com',
  code: '1234',
  purpose: 'password_reset'
})

// 第三步：重置密码
registerAndLogin.resetPassword({
  type: 'email',
  account: 'user@example.com',
  newPassword: 'NewSecurePassword123!',
  verificationCode: '1234'
})
```

#### 手机找回密码

```tsx
<Login2
  config={{
    loginMethods: [
      { type: 'phone', verificationMethods: ['password'] }
    ]
  }}
/>
```

**用户流程**：
1. 在登录页点击 "Forgot password"
2. **确认手机号页面**：选择国家/地区，输入手机号 → 点击 "Send verification code"
3. 发送短信验证码
4. **输入验证码页面**：输入 4 位验证码 → 点击 "Verify"
5. 验证成功
6. **设置新密码页面**：输入新密码 → 点击 "Continue"
7. 密码重置成功 → 返回登录页

**API 调用**：
```typescript
// 第一步：发送短信验证码
registerAndLogin.sendSmsVerificationCode({
  phone: '+8613800138000',
  country_calling_code: '+86',
  purpose: 'password_reset'
})

// 第二步：验证验证码
registerAndLogin.verifyCode({
  type: 'phone',
  target: '+8613800138000',
  code: '1234',
  purpose: 'password_reset'
})

// 第三步：重置密码
registerAndLogin.resetPassword({
  type: 'phone',
  account: '+8613800138000',
  newPassword: 'NewSecurePassword123!',
  verificationCode: '1234'
})
```

---

## 🚀 高级功能

### 分步骤登录

分步骤登录将密码登录分为两步：先输入账号，再输入密码。这种方式在某些场景下可以提升用户体验和安全性。

#### 启用分步骤登录

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'email',
        verificationMethods: ['password'],
        stepByStep: true  // ✅ 启用
      }
    ]
  }}
/>
```

#### 与验证码切换结合

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'email',
        verificationMethods: ['password', 'verification_code'],
        stepByStep: true  // 仅对密码登录生效
      }
    ]
  }}
/>
```

**行为说明**：
- **密码登录**：分两步（先输入邮箱 → 再输入密码）
- **验证码登录**：固定两步（输入邮箱 → 输入验证码）

#### 分步骤登录的优势

1. **更好的焦点管理**：每个步骤只有一个主要输入框
2. **适配移动端**：减少页面滚动，提升填写体验
3. **灵活的错误处理**：在第一步就可以验证账号是否存在
4. **一致的用户体验**：与主流身份验证服务（如 Auth0）保持一致

---

### 验证码登录

验证码登录提供了更安全的无密码登录体验。

#### 邮箱验证码登录

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'email',
        verificationMethods: ['verification_code']
      }
    ]
  }}
/>
```

**流程详解**：

1. **输入邮箱页面**：
   - 用户输入邮箱
   - 点击 "Continue with email"
   - 自动调用 `sendEmailVerificationCode` 发送验证码

2. **验证码输入页面**：
   - 显示 "Check your email" 标题
   - 显示 "We sent a verification code to user@example.com" 描述
   - 4 个独立的验证码输入框（自动聚焦、自动跳转）
   - "Didn't receive the email?" 重发链接（60秒倒计时）
   - "Log in" 按钮（输入完毕自动启用）

3. **自动提交**：
   - 输入第 4 位验证码后自动提交
   - 验证成功 → 触发 `onLogin` 回调

#### 手机验证码登录

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'phone',
        verificationMethods: ['verification_code']
      }
    ]
  }}
/>
```

**流程详解**：

1. **输入手机号页面**：
   - 用户选择国家/地区（自动检测默认值）
   - 输入手机号
   - 点击 "Continue with phone"
   - 自动调用 `sendSmsLoginCode` 发送短信验证码

2. **验证码输入页面**：
   - 显示 "Check your message" 标题
   - 显示 "We sent a verification code to +86 138****0000" 描述
   - 4 个独立的验证码输入框
   - "Didn't receive the message?" 重发链接（60秒倒计时）
   - "Log in" 按钮

3. **自动提交**：
   - 输入第 4 位验证码后自动提交
   - 验证成功 → 触发 `onLogin` 回调

#### 验证码与密码切换

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'email',
        verificationMethods: ['password', 'verification_code']
        // 第一项为默认，第二项在底部显示切换按钮
      }
    ]
  }}
/>
```

**默认显示密码登录**：
- 主表单：Email + Password
- 底部显示：📧 Email code to your email（点击切换到验证码登录）

**点击切换后**：
- 主表单：Email（仅邮箱输入框）
- 按钮：Continue with email（不再是 "Log in"）
- 底部显示：🔑 Password login（点击切换回密码登录）

---

### 多步骤注册

Register2 组件内置完整的多步骤注册流程。

#### 邮箱验证码注册流程

```tsx
<Register2
  config={{
    email: {
      enable_email: true,
      registration_verification: 'verification_code'
    }
  }}
  onRegister={(data, method) => {
    // data = {
    //   account: 'user@example.com',
    //   password: 'SecurePassword123!',
    //   verificationCode: '1234'
    // }
  }}
  onSendVerificationCode={(account, method) => {
    console.log('Verification code sent to:', account);
  }}
/>
```

**完整步骤**：

1. **初始表单**（`INITIAL`）
   - 用户输入邮箱
   - 点击 "Continue"
   - 调用 `sendEmailVerificationCode({ purpose: 'register' })`
   - 如果返回 `code: 409` → 跳转到 "Already Registered" 页面
   - 如果返回 `code: 200` → 跳转到验证码输入页面

2. **输入验证码**（`INPUT_VERIFICATION_CODE`）
   - 显示 "Check your email" 标题
   - 输入 4 位验证码
   - 点击 "Continue" 或自动提交
   - 调用 `verifyEmailCode({ purpose: 'register' })`
   - 验证成功 → 跳转到验证成功页面

3. **验证成功**（`VERIFICATION_SUCCESS`）
   - 显示 ✅ "Verification successful" 提示
   - 1.5 秒后自动跳转到设置密码页面

4. **设置密码**（`SET_PASSWORD`）
   - 显示 "Please enter the new password" 标题
   - 输入密码
   - 点击 "Continue"
   - 调用 `register()` API
   - 注册成功 → 触发 `onRegister` 回调

5. **异常流程：邮箱已注册**（`EMAIL_ALREADY_REGISTERED`）
   - 显示 "This email is already registered" 提示
   - 提供 "Log in" 链接
   - 提供返回按钮

#### 手机验证码注册流程

```tsx
<Register2
  config={{
    phone: {
      enable_phone_number: true,
      registration_verification: 'verification_code'
    },
    defaultAuthMethod: 'phone'
  }}
/>
```

**流程与邮箱类似**：
1. 用户输入手机号 → 发送短信验证码 (`sendSmsRegisterCode`)
2. 输入验证码 → 验证 (`verifySmsCode`)
3. 验证成功 → 设置密码 → 注册完成

---

### 邮件链接验证

邮件链接验证提供了一种无需输入验证码的注册方式。

#### 发起注册

```tsx
<Register2
  config={{
    email: {
      enable_email: true,
      registration_verification: 'verification_link'
    }
  }}
/>
```

**用户操作**：
1. 用户输入邮箱
2. 点击 "Continue"
3. 调用 `sendEmailRegisterLink({ email: 'user@example.com' })`
4. 跳转到 "Verify your email" 等待页面

**等待页面**（`WAIT_EMAIL_LINK`）：
- 显示 "Verify your email" 标题
- 显示 "We sent a verification link to user@example.com" 描述
- 显示用户邮箱（可编辑按钮）
- "Didn't receive a link?" 重发链接（60秒倒计时）
- 返回按钮

#### 从邮件打开

用户在邮箱中收到验证邮件，点击链接后：

```
https://your-app.com/register?code=abc123xyz
```

在你的应用中：

```tsx
import { Register2 } from '@pisell/materials';

function RegisterPage() {
  // 从 URL 获取 code 参数
  const urlParams = new URLSearchParams(window.location.search);
  const verificationCode = urlParams.get('code');

  return (
    <Register2
      config={{
        email: {
          enable_email: true,
          registration_verification: 'verification_link'
        },
        emailLinkVerification: verificationCode ? {
          enabled: true,
          code: verificationCode
        } : undefined
      }}
      onRegister={(data, method) => {
        console.log('Registration complete:', data);
        // 跳转到登录页或首页
      }}
      onEmailLinkExpired={() => {
        // 链接过期，返回注册页
        window.location.href = '/register';
      }}
    />
  );
}
```

**自动验证流程**：

1. **验证中**（`VERIFYING_EMAIL_LINK`）
   - 显示 "Verifying..." 加载动画
   - 自动调用 `verifyEmailLink({ code })`

2. **验证成功**
   - 跳转到 "Set Password" 页面
   - 用户设置密码后完成注册

3. **链接过期**（`EMAIL_LINK_EXPIRED`）
   - 显示 "Verification link expired" 提示
   - 显示 "The link you followed has expired. Please request a new one." 描述
   - "Back to Registration" 按钮 → 触发 `onEmailLinkExpired` 回调

4. **链接已使用**（`EMAIL_LINK_ALREADY_USED`）
   - 显示 "Verification link already used" 提示
   - 显示 "This link has already been used to verify your email." 描述
   - "Log in" 按钮 → 触发 `onGoToLogin` 回调

---

## 🌍 国际化

组件内置多语言支持，自动检测用户语言环境。

### 支持的语言

- `en-US`：英语（默认）
- `zh-CN`：简体中文
- `zh-HK`：繁体中文（香港）

### 自动语言检测

组件会按以下顺序检测语言：
1. 浏览器语言设置（`navigator.language`）
2. Intl API 推荐语言
3. 默认使用英语

### 关键文本键

#### 通用文本

| 键名 | 英文 | 中文 |
|------|------|------|
| `pisell-login2-or` | OR | OR |
| `pisell-login2-back` | Back | 返回 |
| `pisell-login2-continue` | Continue | 继续 |
| `pisell-login2-resend` | Resend | 重新发送 |

#### 登录相关

| 键名 | 英文 | 中文 |
|------|------|------|
| `pisell-login2-login-button` | Log in | 登录 |
| `pisell-login2-forgot-password` | Forgot password | 忘记密码 |
| `pisell-login2-remember-me` | Remember me | 记住我 |
| `pisell-login2-switch-to-email` | Login with email | 邮箱登录 |
| `pisell-login2-switch-to-phone` | Login with phone number | 手机登录 |
| `pisell-login2-switch-to-password` | Password login | 密码登录 |
| `pisell-login2-switch-to-email-code` | Email code to your email | 邮箱验证码登录 |
| `pisell-login2-switch-to-sms-code` | SMS code to your phone | 短信验证码登录 |

#### 注册相关

| 键名 | 英文 | 中文 |
|------|------|------|
| `pisell-register2-already-have-account` | Already have an account? | 已有账号？ |
| `pisell-register2-login-link` | Log in | 登录 |
| `pisell-register2-register-with-phone` | Register with phone | 手机号注册 |
| `pisell-register2-register-with-email` | Register with email | 邮箱注册 |

#### 验证码相关

| 键名 | 英文 | 中文 |
|------|------|------|
| `pisell-login2-check-email-title` | Check your email | 查看您的邮件 |
| `pisell-login2-check-email-desc` | We sent a verification code to | 我们已向以下邮箱发送验证码 |
| `pisell-login2-check-phone-title` | Check your message | 查看您的短信 |
| `pisell-login2-check-phone-desc` | We sent a verification code to | 我们已向以下号码发送验证码 |
| `pisell-login2-no-email-received` | Didn't receive the email? | 没有收到邮件？ |
| `pisell-login2-no-message-received` | Didn't receive the message? | 没有收到短信？ |

#### 忘记密码相关

| 键名 | 英文 | 中文 |
|------|------|------|
| `pisell-forgot-password-title` | Forgot password | 忘记密码 |
| `pisell-forgot-password-desc` | Please confirm your email address | 请确认您的邮箱地址 |
| `pisell-forgot-password-desc-phone` | Please confirm your phone number | 请确认您的手机号 |
| `pisell-forgot-password-send-code` | Send verification code | 发送验证码 |
| `pisell-forgot-password-verify` | Verify | 验证 |

### 扩展国际化

如需添加新语言或自定义文本：

```typescript
import { locales } from '@pisell/utils';
import localeTexts from '@pisell/materials/src/pro/Login2.0/locales';

// 添加新语言
const customLocale = {
  'ja-JP': {
    'pisell-login2-login-button': 'ログイン',
    // ... 其他文本
  }
};

// 初始化
locales.init({ ...localeTexts, ...customLocale }, 'ja-JP');
```

---

## 🎨 样式定制

### 使用主题色

通过 `ui.themeColor` 自定义主题色：

```tsx
<Login2
  config={{
    loginMethods: [
      { type: 'email', verificationMethods: ['password'] }
    ],
    ui: {
      themeColor: '#7F56D9'  // 紫色主题
    }
  }}
/>
```

**影响的元素**：
- 主按钮背景色
- 链接文本颜色
- 复选框选中颜色
- Loading 动画颜色

### 自定义 CSS 类名

组件使用 BEM 命名规范，可以通过 CSS 覆盖样式：

```less
// 自定义登录按钮样式
.login2-submit-button {
  height: 48px !important;
  border-radius: 12px !important;
  font-size: 18px !important;
}

// 自定义输入框样式
.login2-input {
  border-radius: 8px !important;
  border-color: #D0D5DD !important;
}

// 自定义标题样式
.login2-title {
  font-size: 32px !important;
  font-weight: 700 !important;
  color: #101828 !important;
}
```

### 主要 CSS 类名

| 类名 | 说明 |
|------|------|
| `.login2-container` | 容器 |
| `.login2-header` | 头部区域 |
| `.login2-logo` | Logo |
| `.login2-title` | 标题 |
| `.login2-subtitle` | 副标题 |
| `.login2-desc` | 描述 |
| `.login2-form` | 表单 |
| `.login2-input` | 输入框 |
| `.login2-submit-button` | 提交按钮 |
| `.login2-divider` | OR 分隔符 |
| `.login2-switch-options` | 切换选项区域 |
| `.login2-switch-option-button` | 切换按钮 |
| `.login2-oauth-button` | 第三方登录按钮 |
| `.login2-back-button` | 返回按钮 |
| `.login2-account-display` | 账号显示框（分步骤登录） |

### 响应式设计

组件已内置响应式设计，适配以下屏幕尺寸：

```less
// 移动端（< 768px）
@media (max-width: 767px) {
  .login2-container {
    width: 100%;
    padding: 20px;
  }
  
  .login2-title {
    font-size: 24px;
  }
}

// 平板（768px - 1024px）
@media (min-width: 768px) and (max-width: 1024px) {
  .login2-container {
    width: 360px;
  }
}

// 桌面（> 1024px）
@media (min-width: 1025px) {
  .login2-container {
    width: 360px;
  }
}
```

---

## 💡 最佳实践

### 1. 选择合适的登录方式

**推荐配置（企业应用）**：

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'email',
        verificationMethods: ['password', 'verification_code'],
        stepByStep: true
      },
      { type: 'google', clientId: 'xxx' },
      {
        type: 'phone',
        verificationMethods: ['verification_code']
      }
    ]
  }}
/>
```

**推荐理由**：
- 邮箱密码为主（用户习惯）
- 支持验证码切换（无密码登录）
- 分步骤提升安全性
- Google 作为快捷登录
- 手机号作为备选方案

**推荐配置（移动应用）**：

```tsx
<Login2
  config={{
    loginMethods: [
      {
        type: 'phone',
        verificationMethods: ['verification_code', 'password']
      },
      { type: 'apple', clientId: 'xxx' },
      { type: 'google', clientId: 'xxx' }
    ]
  }}
/>
```

**推荐理由**：
- 手机号为主（移动端用户习惯）
- 验证码登录更安全、更快捷
- Apple 登录在 iOS 上有优势
- Google 作为跨平台选项

### 2. 注册流程选择

**推荐配置（高安全性）**：

```tsx
<Register2
  config={{
    email: {
      enable_email: true,
      registration_verification: 'verification_code'
    },
    phone: {
      enable_phone_number: true,
      registration_verification: 'verification_code'
    }
  }}
/>
```

**推荐理由**：
- 验证码方式最安全
- 用户体验流畅（无需跳转邮箱）
- 实时验证，防止假邮箱/手机号

**推荐配置（快速注册）**：

```tsx
<Register2
  config={{
    email: {
      enable_email: true,
      registration_verification: 'verification_link'
    },
    oauth: {
      google: { enabled: true, client_id: 'xxx' }
    }
  }}
/>
```

**推荐理由**：
- 邮件链接方式简单（用户无需记忆验证码）
- Google 登录最快捷
- 适合非敏感应用

### 3. API 接口设计

#### 统一的响应格式

```typescript
interface ApiResponse<T = any> {
  code: number      // 200=成功, 400=失败, 401=未授权, 409=冲突
  message: string   // 错误或成功消息
  data?: T          // 可选的返回数据
}
```

#### 登录接口

```typescript
// 密码登录
POST /api/auth/login
{
  "type": "email" | "phone",
  "account": "user@example.com",
  "password": "***",
  "channel": "website"
}

// 验证码登录
POST /api/auth/login-with-code
{
  "type": "email" | "phone",
  "account": "user@example.com",
  "code": "1234",
  "channel": "website"
}

// 响应
{
  "code": 200,
  "message": "Login successful",
  "data": {
    "userId": "123",
    "token": "jwt-token",
    "user": { ... }
  }
}
```

#### 注册接口

```typescript
// 发送验证码
POST /api/auth/send-code
{
  "type": "email" | "phone",
  "target": "user@example.com",
  "purpose": "register" | "login" | "password_reset"
}

// 响应
{
  "code": 200 | 409,  // 409 = 账号已注册
  "message": "Code sent successfully"
}

// 注册
POST /api/auth/register
{
  "type": "email" | "phone",
  "account": "user@example.com",
  "password": "***",
  "verificationCode": "1234",
  "channel": "website"
}

// 响应
{
  "code": 200,
  "message": "Registration successful",
  "data": {
    "userId": "123",
    "token": "jwt-token"
  }
}
```

### 4. 错误处理

```tsx
<Login2
  config={{ ... }}
  onLogin={async (data, method) => {
    try {
      const response = await loginAPI(data);
      
      if (response.code === 200) {
        // 登录成功
        localStorage.setItem('token', response.data.token);
        window.location.href = '/dashboard';
      } else if (response.code === 401) {
        // 密码错误
        message.error('Invalid email or password');
      } else if (response.code === 404) {
        // 账号不存在
        message.error('Account not found. Please register first');
      } else {
        // 其他错误
        message.error(response.message || 'Login failed');
      }
    } catch (error) {
      console.error('Login error:', error);
      message.error('Network error. Please try again');
    }
  }}
/>
```

### 5. 使用 Channel 参数

```tsx
<Login2
  config={{
    loginMethods: [ ... ],
    channel: 'website'  // 或 'mobile_app', 'admin_panel' 等
  }}
  onLogin={(data, method, channel) => {
    // channel = 'website'
    // 可以根据 channel 调用不同的 API 端点
    if (channel === 'website') {
      return loginAPI('/api/web/login', data);
    } else if (channel === 'mobile_app') {
      return loginAPI('/api/mobile/login', data);
    }
  }}
/>
```

**使用场景**：
- 区分不同平台的登录请求
- 实现不同的认证策略
- 统计不同渠道的登录数据

### 6. 性能优化

```tsx
import React, { lazy, Suspense } from 'react';

// 懒加载组件
const Login2 = lazy(() => import('@pisell/materials').then(m => ({ default: m.Login2 })));

function LoginPage() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Login2 config={{ ... }} />
    </Suspense>
  );
}
```

---

## ❓ 常见问题

### Q1: 如何实现"记住我"功能？

A: 组件已内置 "Remember me" 选项，在 `onLogin` 回调中处理：

```tsx
onLogin={(data, method) => {
  if (data.remember_me) {
    // 使用 localStorage 持久化 token
    localStorage.setItem('token', response.token);
  } else {
    // 使用 sessionStorage，关闭浏览器后失效
    sessionStorage.setItem('token', response.token);
  }
}}
```

### Q2: 如何自定义表单验证规则？

A: 目前组件使用内置的验证规则。如需自定义，可以在 `onLogin` 或 `onRegister` 回调中添加额外验证：

```tsx
onLogin={async (data, method) => {
  // 自定义验证
  if (data.password.length < 8) {
    message.error('Password must be at least 8 characters');
    return;
  }
  
  // 继续登录流程
  const response = await loginAPI(data);
  // ...
}}
```

### Q3: 验证码倒计时如何自定义？

A: 组件内置 60 秒倒计时，暂不支持自定义。如需修改，请在组件源码中调整 `countdown` 初始值。

### Q4: 如何实现"跳转到注册"功能？

A: 在 Register2 组件底部已内置"Already have an account? Log in"链接：

```tsx
<Register2
  config={{ ... }}
  onGoToLogin={() => {
    // 路由跳转
    window.location.href = '/login';
    // 或使用 React Router
    // navigate('/login');
  }}
/>
```

同理，在 Login2 组件中添加"跳转到注册"：

```tsx
<div className="login2-footer">
  <span>Don't have an account? </span>
  <a href="/register" className="login2-link">Sign up</a>
</div>
```

### Q5: 如何处理第三方登录回调？

A: 第三方登录通常涉及 OAuth 流程，需要后端配合：

```tsx
<Login2
  config={{
    loginMethods: [
      { type: 'google', clientId: 'your-google-client-id' }
    ]
  }}
  onOAuthLogin={(provider, data) => {
    // provider = 'google'
    // data 包含第三方返回的信息（如 access_token）
    
    // 发送到后端验证并创建/登录用户
    fetch('/api/auth/oauth/callback', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ provider, ...data })
    })
    .then(res => res.json())
    .then(result => {
      if (result.success) {
        localStorage.setItem('token', result.token);
        window.location.href = '/dashboard';
      }
    });
  }}
/>
```

### Q6: 手机号输入组件如何获取国家列表？

A: 组件会自动调用 `registerAndLogin.getCountries()` 方法。确保后端提供此接口：

```typescript
// API 返回格式
GET /api/countries
[
  {
    "name": "China",
    "code": "CN",
    "calling_code": "86",
    "currency_code": "CNY"
  },
  {
    "name": "United States",
    "code": "US",
    "calling_code": "1",
    "currency_code": "USD"
  },
  // ...
]
```

### Q7: 邮件链接验证的链接格式是什么？

A: 后端发送的验证邮件应包含如下格式的链接：

```
https://your-app.com/register?code=abc123xyz
```

或

```
https://your-app.com/verify-email?code=abc123xyz
```

组件会从 URL 中提取 `code` 参数并自动验证。

### Q8: 如何实现多语言切换？

A: 组件会自动检测浏览器语言。如需手动切换：

```tsx
import { locales } from '@pisell/utils';
import localeTexts from '@pisell/materials/src/pro/Login2.0/locales';

// 初始化为简体中文
locales.init(localeTexts, 'zh-CN');

// 切换到繁体中文
function switchToTraditionalChinese() {
  locales.init(localeTexts, 'zh-HK');
  window.location.reload();
}

// 切换到英文
function switchToEnglish() {
  locales.init(localeTexts, 'en-US');
  window.location.reload();
}
```

### Q9: 如何在 Lowcode 编辑器中使用？

A: 组件已完整集成 Alibaba Lowcode Engine，在编辑器中：

1. 从组件面板拖入 `Login2` 或 `Register2` 组件
2. 在右侧属性面板配置 `config` 对象
3. 使用"登录方式配置"面板添加和排序登录方式
4. 配置事件回调（onLogin、onRegister 等）
5. 预览和发布

### Q10: 组件宽度是否可以自定义？

A: 组件固定宽度为 360px（符合 Figma 设计稿）。如需调整，可以通过 CSS 覆盖：

```less
.login2-container {
  width: 400px !important;
}
```

**注意**：修改宽度可能影响内部元素的布局和间距，请谨慎调整。

---

## 📝 更新日志

### v1.0.3
- ✨ 新增分步骤登录功能
- ✨ 新增验证码登录固定两步流程
- ✨ 新增忘记密码完整流程
- ✨ 新增手机号输入组件 `PhoneInput`
- ✨ 新增自动检测用户国家/地区
- 🐛 修复验证码页面文案错误
- 🐛 修复 OR 切换选项显示逻辑
- 💄 优化邮件链接验证页面样式
- 📝 完善国际化文本

### v1.0.2
- ✨ 新增邮件链接注册验证流程
- ✨ 新增多步骤注册架构
- ✨ 新增 Channel 参数支持
- 🐛 修复注册流程状态管理问题
- 💄 优化验证码输入框样式
- 📝 完善文档和示例

### v1.0.1
- ✨ 新增 `loginMethods` 配置方式
- ✨ 新增验证方式切换功能
- 🐛 修复表单标签配置问题
- 💄 优化移动端适配
- 📝 新增最佳实践指南

### v1.0.0
- 🎉 首次发布
- ✨ 支持邮箱/手机/第三方登录
- ✨ 支持邮箱/手机注册
- ✨ 完整的国际化支持
- ✨ Lowcode Engine 集成

---

## 📞 技术支持

- **文档**: [完整文档](https://docs.pisell.com/components/login2)
- **示例**: [在线示例](https://demo.pisell.com/login2)
- **Figma**: 
  - [登录组件设计](https://www.figma.com/design/pM8Ho6d7kCMv9vIBvFHUlj/Pisell-2.0-Component-Library?node-id=11008-124601)
  - [注册组件设计](https://www.figma.com/design/pM8Ho6d7kCMv9vIBvFHUlj/Pisell-2.0-Component-Library?node-id=10144-4218)
- **GitHub**: [Issues](https://github.com/pisell/materials/issues)
- **Email**: support@pisell.com

---

## 📄 许可证

MIT License

---

**由 Pisell 团队用 ❤️ 打造**
