/**
 * useRequest Hook 使用示例
 * 
 * 此文件展示了如何在React Native项目中使用useRequest hook
 */

import { useEffect, useState } from 'react';
import { View, Text, Button, ActivityIndicator } from 'react-native';
import { useRequest } from './useRequest';

// ===== 示例1: 基础GET请求 =====
export function BasicGetExample() {
  const { get } = useRequest();
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  const fetchUserInfo = async () => {
    setLoading(true);
    try {
      const result = await get('/api/user/info');
      setData(result);
    } catch (error) {
      // 错误已经在useRequest中处理，这里可以添加额外的错误逻辑
      console.error('获取用户信息失败:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <View>
      <Button title="获取用户信息" onPress={fetchUserInfo} />
      {loading && <ActivityIndicator />}
      {data && <Text>{JSON.stringify(data, null, 2)}</Text>}
    </View>
  );
}

// ===== 示例2: POST请求 =====
export function PostExample() {
  const { post } = useRequest();
  const [loading, setLoading] = useState(false);

  const submitForm = async () => {
    setLoading(true);
    try {
      const result = await post('/api/user/update', {
        name: '张三',
        email: 'zhangsan@example.com',
      });
      console.log('更新成功:', result);
    } catch (error) {
      console.error('更新失败:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <View>
      <Button title="提交表单" onPress={submitForm} disabled={loading} />
    </View>
  );
}

// ===== 示例3: 带查询参数的GET请求 =====
export function GetWithParamsExample() {
  const { get } = useRequest();

  const fetchList = async () => {
    try {
      // 使用searchParams传递查询参数
      const result = await get('/api/products', {
        searchParams: {
          page: 1,
          pageSize: 10,
          category: 'electronics',
        },
      });
      console.log('产品列表:', result);
    } catch (error) {
      console.error('获取列表失败:', error);
    }
  };

  useEffect(() => {
    fetchList();
  }, []);

  return <View />;
}

// ===== 示例4: 跳过认证的请求（登录接口）=====
export function LoginExample() {
  const { post } = useRequest();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = async () => {
    try {
      // 登录接口不需要token，使用skipAuth
      const result = await post<{ token: string }>(
        '/api/auth/login',
        { username, password },
        { skipAuth: true }
      );
      
      // 登录成功后保存token
      if (result.token) {
        const { setToken } = await import('./useRequest');
        setToken(result.token);
        console.log('登录成功');
      }
    } catch (error) {
      console.error('登录失败:', error);
    }
  };

  return (
    <View>
      <Button title="登录" onPress={handleLogin} />
    </View>
  );
}

// ===== 示例5: 自定义错误处理 =====
export function CustomErrorHandlingExample() {
  const { get } = useRequest();

  const fetchDataWithCustomError = async () => {
    try {
      // 跳过全局错误处理，使用自定义错误处理
      const result = await get('/api/risky-operation', {
        skipErrorHandler: true,
      });
      console.log('操作成功:', result);
    } catch (error) {
      // 自定义错误处理逻辑
      console.error('这是自定义的错误处理:', error);
      // 可以显示自定义的错误提示
    }
  };

  return (
    <View>
      <Button title="执行操作" onPress={fetchDataWithCustomError} />
    </View>
  );
}

// ===== 示例6: 配合React Query使用 =====
import { useQuery } from '@tanstack/react-query';

export function WithReactQueryExample() {
  const { get } = useRequest();

  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ['userInfo'],
    queryFn: () => get('/api/user/info'),
  });

  return (
    <View>
      {isLoading && <ActivityIndicator />}
      {error && <Text>加载失败</Text>}
      {data && <Text>{JSON.stringify(data, null, 2)}</Text>}
      <Button title="刷新" onPress={() => refetch()} />
    </View>
  );
}

// ===== 示例7: PUT和DELETE请求 =====
export function UpdateDeleteExample() {
  const { put, delete: del } = useRequest();

  const updateUser = async (userId: number) => {
    try {
      await put(`/api/user/${userId}`, {
        name: '李四',
        age: 25,
      });
      console.log('更新成功');
    } catch (error) {
      console.error('更新失败:', error);
    }
  };

  const deleteUser = async (userId: number) => {
    try {
      await del(`/api/user/${userId}`);
      console.log('删除成功');
    } catch (error) {
      console.error('删除失败:', error);
    }
  };

  return (
    <View>
      <Button title="更新用户" onPress={() => updateUser(1)} />
      <Button title="删除用户" onPress={() => deleteUser(1)} />
    </View>
  );
}

// ===== 示例8: 文件上传 =====
export function FileUploadExample() {
  const { post } = useRequest();

  const uploadFile = async (file: File) => {
    try {
      const formData = new FormData();
      formData.append('file', file);

      const result = await post('/api/upload', formData, {
        headers: {
          // FormData会自动设置Content-Type
          'Content-Type': 'multipart/form-data',
        },
      });
      console.log('上传成功:', result);
    } catch (error) {
      console.error('上传失败:', error);
    }
  };

  return <View />;
}

// ===== 示例9: 直接使用http实例 =====
import { http } from './useRequest';

export async function DirectHttpExample() {
  try {
    // 直接使用导出的http实例
    const result = await http.get('api/quick-request').json();
    console.log('快速请求结果:', result);
  } catch (error) {
    console.error('请求失败:', error);
  }
}

// ===== 示例10: Token管理 =====
import { getToken, setToken, removeToken } from './useRequest';

export function TokenManagementExample() {
  const handleLoginSuccess = (token: string) => {
    // 保存token
    setToken(token);
    console.log('Token已保存');
  };

  const checkToken = () => {
    // 获取当前token
    const currentToken = getToken();
    console.log('当前token:', currentToken);
  };

  const handleLogout = () => {
    // 清除token
    removeToken();
    console.log('Token已清除');
  };

  return (
    <View>
      <Button title="登录" onPress={() => handleLoginSuccess('mock-token-123')} />
      <Button title="检查Token" onPress={checkToken} />
      <Button title="登出" onPress={handleLogout} />
    </View>
  );
}
