# 宁夏智慧养殖监管平台 API 设计文档

## 版本历史

| 版本 | 日期 | 作者 | 描述 |
|------|------|------|------|
| v1.0 | 2025-01-18 | 开发团队 | 初始版本 |
| v2.0 | 2025-01-19 | 开发团队 | 全面重构，增加多端支持和标准化规范 |

## 1. API 概述

### 1.1 设计原则

**RESTful 设计原则：**
- 使用标准HTTP方法（GET、POST、PUT、DELETE）
- 资源导向的URL设计
- 无状态通信
- 统一的响应格式
- 合理的HTTP状态码使用

**安全性原则：**
- JWT Token认证
- HTTPS加密传输
- 输入参数验证
- SQL注入防护
- 访问频率限制

**性能原则：**
- 分页查询支持
- 数据缓存机制
- 响应数据压缩
- 异步处理支持

### 1.2 基础信息

**基础URL：**
```
开发环境: http://localhost:5350/api
测试环境: https://test-api.nxxmdata.com/api
生产环境: https://api.nxxmdata.com/api
```

**API版本控制：**
- 当前版本：v1
- 版本控制方式：URL路径版本控制
- 示例：`/api/v1/farms`

**内容类型：**
- 请求：`application/json`
- 响应：`application/json`
- 字符编码：`UTF-8`

### 1.3 认证机制

**JWT Token认证：**
```http
Authorization: Bearer <token>
```

**Token获取：**
```http
POST /api/v1/auth/login
Content-Type: application/json

{
  "username": "admin",
  "password": "password123"
}
```

**Token刷新：**
```http
POST /api/v1/auth/refresh
Authorization: Bearer <refresh_token>
```

## 2. 通用规范

### 2.1 请求格式

**请求头规范：**
```http
Content-Type: application/json
Authorization: Bearer <token>
Accept: application/json
User-Agent: <client_info>
X-Request-ID: <unique_request_id>
```

**分页参数：**
```json
{
  "page": 1,
  "limit": 20,
  "sort": "created_at",
  "order": "desc"
}
```

**查询参数：**
```json
{
  "filter": {
    "status": "active",
    "created_at": {
      "gte": "2025-01-01",
      "lte": "2025-01-31"
    }
  },
  "search": "关键词",
  "fields": ["id", "name", "status"]
}
```

### 2.2 响应格式

**成功响应：**
```json
{
  "success": true,
  "code": 200,
  "message": "操作成功",
  "data": {
    // 具体数据
  },
  "timestamp": "2025-01-19T10:00:00Z",
  "request_id": "req_123456789"
}
```

**分页响应：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "items": [
      // 数据列表
    ],
    "pagination": {
      "page": 1,
      "limit": 20,
      "total": 100,
      "pages": 5,
      "has_next": true,
      "has_prev": false
    }
  },
  "timestamp": "2025-01-19T10:00:00Z",
  "request_id": "req_123456789"
}
```

**错误响应：**
```json
{
  "success": false,
  "code": 400,
  "message": "请求参数错误",
  "error": {
    "type": "ValidationError",
    "details": [
      {
        "field": "email",
        "message": "邮箱格式不正确"
      }
    ]
  },
  "timestamp": "2025-01-19T10:00:00Z",
  "request_id": "req_123456789"
}
```

### 2.3 状态码规范

**成功状态码：**
- `200 OK` - 请求成功
- `201 Created` - 资源创建成功
- `204 No Content` - 请求成功，无返回内容

**客户端错误：**
- `400 Bad Request` - 请求参数错误
- `401 Unauthorized` - 未认证
- `403 Forbidden` - 权限不足
- `404 Not Found` - 资源不存在
- `409 Conflict` - 资源冲突
- `422 Unprocessable Entity` - 数据验证失败
- `429 Too Many Requests` - 请求频率超限

**服务器错误：**
- `500 Internal Server Error` - 服务器内部错误
- `502 Bad Gateway` - 网关错误
- `503 Service Unavailable` - 服务不可用
- `504 Gateway Timeout` - 网关超时

## 3. 认证与授权 API

### 3.1 用户认证

#### 3.1.1 用户登录

**接口信息：**
- **URL**: `/api/v1/auth/login`
- **方法**: `POST`
- **描述**: 用户登录获取访问令牌

**请求参数：**
```json
{
  "username": "admin",
  "password": "password123",
  "remember_me": false,
  "captcha": "ABCD",
  "captcha_key": "captcha_123456"
}
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "登录成功",
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "token_type": "Bearer",
    "expires_in": 3600,
    "user": {
      "id": 1,
      "username": "admin",
      "real_name": "管理员",
      "email": "admin@example.com",
      "roles": ["admin"],
      "permissions": ["farm:read", "farm:write"]
    }
  }
}
```

#### 3.1.2 用户登出

**接口信息：**
- **URL**: `/api/v1/auth/logout`
- **方法**: `POST`
- **描述**: 用户登出，使令牌失效

**请求头：**
```http
Authorization: Bearer <token>
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "登出成功"
}
```

#### 3.1.3 令牌刷新

**接口信息：**
- **URL**: `/api/v1/auth/refresh`
- **方法**: `POST`
- **描述**: 使用刷新令牌获取新的访问令牌

**请求参数：**
```json
{
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "令牌刷新成功",
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "token_type": "Bearer",
    "expires_in": 3600
  }
}
```

### 3.2 用户信息

#### 3.2.1 获取当前用户信息

**接口信息：**
- **URL**: `/api/v1/auth/me`
- **方法**: `GET`
- **描述**: 获取当前登录用户的详细信息

**请求头：**
```http
Authorization: Bearer <token>
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "获取成功",
  "data": {
    "id": 1,
    "username": "admin",
    "real_name": "管理员",
    "email": "admin@example.com",
    "phone": "13800138000",
    "avatar_url": "https://example.com/avatar.jpg",
    "status": "active",
    "roles": [
      {
        "id": 1,
        "name": "admin",
        "display_name": "系统管理员"
      }
    ],
    "permissions": [
      "farm:read",
      "farm:write",
      "user:read",
      "user:write"
    ],
    "last_login_at": "2025-01-19T09:00:00Z",
    "created_at": "2025-01-01T00:00:00Z"
  }
}
```

## 4. 用户管理 API

### 4.1 用户列表

**接口信息：**
- **URL**: `/api/v1/users`
- **方法**: `GET`
- **描述**: 获取用户列表（支持分页和筛选）

**查询参数：**
```
page=1&limit=20&status=active&search=admin&sort=created_at&order=desc
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "items": [
      {
        "id": 1,
        "username": "admin",
        "real_name": "管理员",
        "email": "admin@example.com",
        "phone": "13800138000",
        "status": "active",
        "roles": ["admin"],
        "last_login_at": "2025-01-19T09:00:00Z",
        "created_at": "2025-01-01T00:00:00Z"
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 20,
      "total": 1,
      "pages": 1,
      "has_next": false,
      "has_prev": false
    }
  }
}
```

### 4.2 创建用户

**接口信息：**
- **URL**: `/api/v1/users`
- **方法**: `POST`
- **描述**: 创建新用户

**请求参数：**
```json
{
  "username": "newuser",
  "password": "password123",
  "real_name": "新用户",
  "email": "newuser@example.com",
  "phone": "13800138001",
  "role_ids": [2, 3],
  "status": "active"
}
```

**响应示例：**
```json
{
  "success": true,
  "code": 201,
  "message": "用户创建成功",
  "data": {
    "id": 2,
    "username": "newuser",
    "real_name": "新用户",
    "email": "newuser@example.com",
    "phone": "13800138001",
    "status": "active",
    "created_at": "2025-01-19T10:00:00Z"
  }
}
```

### 4.3 更新用户

**接口信息：**
- **URL**: `/api/v1/users/{id}`
- **方法**: `PUT`
- **描述**: 更新用户信息

**请求参数：**
```json
{
  "real_name": "更新后的姓名",
  "email": "updated@example.com",
  "phone": "13800138002",
  "status": "inactive"
}
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "用户更新成功",
  "data": {
    "id": 2,
    "username": "newuser",
    "real_name": "更新后的姓名",
    "email": "updated@example.com",
    "phone": "13800138002",
    "status": "inactive",
    "updated_at": "2025-01-19T10:30:00Z"
  }
}
```

### 4.4 删除用户

**接口信息：**
- **URL**: `/api/v1/users/{id}`
- **方法**: `DELETE`
- **描述**: 删除用户（软删除）

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "用户删除成功"
}
```

## 5. 养殖场管理 API

### 5.1 养殖场列表

**接口信息：**
- **URL**: `/api/v1/farms`
- **方法**: `GET`
- **描述**: 获取养殖场列表

**查询参数：**
```
page=1&limit=20&status=active&type=pig&scale=large&search=示例养殖场
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "items": [
      {
        "id": 1,
        "name": "示例养殖场",
        "code": "FARM001",
        "type": "pig",
        "scale": "large",
        "address": "宁夏银川市兴庆区示例路123号",
        "latitude": 38.4872,
        "longitude": 106.2309,
        "contact_person": "张三",
        "contact_phone": "13800138000",
        "license_number": "NX001234567890",
        "status": "active",
        "device_count": 15,
        "animal_count": 500,
        "created_at": "2025-01-01T00:00:00Z",
        "updated_at": "2025-01-19T10:00:00Z"
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 20,
      "total": 1,
      "pages": 1,
      "has_next": false,
      "has_prev": false
    }
  }
}
```

### 5.2 获取养殖场详情

**接口信息：**
- **URL**: `/api/v1/farms/{id}`
- **方法**: `GET`
- **描述**: 获取指定养殖场的详细信息

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "id": 1,
    "name": "示例养殖场",
    "code": "FARM001",
    "type": "pig",
    "scale": "large",
    "address": "宁夏银川市兴庆区示例路123号",
    "latitude": 38.4872,
    "longitude": 106.2309,
    "contact_person": "张三",
    "contact_phone": "13800138000",
    "license_number": "NX001234567890",
    "status": "active",
    "description": "这是一个示例养殖场",
    "established_date": "2020-01-01",
    "area": 10000,
    "capacity": 1000,
    "devices": [
      {
        "id": 1,
        "device_id": "DEV001",
        "device_name": "温度传感器1",
        "device_type": "temperature",
        "status": "online"
      }
    ],
    "animals": [
      {
        "id": 1,
        "tag_id": "PIG001",
        "breed": "大白猪",
        "status": "healthy"
      }
    ],
    "created_at": "2025-01-01T00:00:00Z",
    "updated_at": "2025-01-19T10:00:00Z"
  }
}
```

### 5.3 创建养殖场

**接口信息：**
- **URL**: `/api/v1/farms`
- **方法**: `POST`
- **描述**: 创建新的养殖场

**请求参数：**
```json
{
  "name": "新养殖场",
  "code": "FARM002",
  "type": "cattle",
  "scale": "medium",
  "address": "宁夏银川市金凤区新建路456号",
  "latitude": 38.5000,
  "longitude": 106.2500,
  "contact_person": "李四",
  "contact_phone": "13800138001",
  "license_number": "NX001234567891",
  "description": "新建的牛养殖场",
  "established_date": "2025-01-01",
  "area": 8000,
  "capacity": 800
}
```

**响应示例：**
```json
{
  "success": true,
  "code": 201,
  "message": "养殖场创建成功",
  "data": {
    "id": 2,
    "name": "新养殖场",
    "code": "FARM002",
    "type": "cattle",
    "scale": "medium",
    "status": "pending",
    "created_at": "2025-01-19T10:00:00Z"
  }
}
```

### 5.4 更新养殖场

**接口信息：**
- **URL**: `/api/v1/farms/{id}`
- **方法**: `PUT`
- **描述**: 更新养殖场信息

**请求参数：**
```json
{
  "name": "更新后的养殖场名称",
  "contact_person": "王五",
  "contact_phone": "13800138002",
  "status": "active"
}
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "养殖场更新成功",
  "data": {
    "id": 1,
    "name": "更新后的养殖场名称",
    "contact_person": "王五",
    "contact_phone": "13800138002",
    "status": "active",
    "updated_at": "2025-01-19T10:30:00Z"
  }
}
```

### 5.5 删除养殖场

**接口信息：**
- **URL**: `/api/v1/farms/{id}`
- **方法**: `DELETE`
- **描述**: 删除养殖场（软删除）

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "养殖场删除成功"
}
```

## 6. 设备管理 API

### 6.1 设备列表

**接口信息：**
- **URL**: `/api/v1/devices`
- **方法**: `GET`
- **描述**: 获取设备列表

**查询参数：**
```
page=1&limit=20&farm_id=1&status=online&device_type=temperature
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "items": [
      {
        "id": 1,
        "farm_id": 1,
        "device_id": "DEV001",
        "device_name": "温度传感器1",
        "device_type": "temperature",
        "model": "TH-100",
        "manufacturer": "传感器公司",
        "location": "猪舍A区",
        "install_date": "2025-01-01",
        "status": "online",
        "last_online_at": "2025-01-19T10:00:00Z",
        "farm": {
          "id": 1,
          "name": "示例养殖场",
          "code": "FARM001"
        },
        "latest_data": {
          "temperature": 25.5,
          "humidity": 60.2,
          "timestamp": "2025-01-19T10:00:00Z"
        },
        "created_at": "2025-01-01T00:00:00Z"
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 20,
      "total": 1,
      "pages": 1,
      "has_next": false,
      "has_prev": false
    }
  }
}
```

### 6.2 获取设备详情

**接口信息：**
- **URL**: `/api/v1/devices/{id}`
- **方法**: `GET`
- **描述**: 获取指定设备的详细信息

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "id": 1,
    "farm_id": 1,
    "device_id": "DEV001",
    "device_name": "温度传感器1",
    "device_type": "temperature",
    "model": "TH-100",
    "manufacturer": "传感器公司",
    "location": "猪舍A区",
    "install_date": "2025-01-01",
    "status": "online",
    "last_online_at": "2025-01-19T10:00:00Z",
    "config": {
      "sampling_interval": 60,
      "alert_threshold": {
        "temperature_max": 30,
        "temperature_min": 10,
        "humidity_max": 80,
        "humidity_min": 40
      }
    },
    "farm": {
      "id": 1,
      "name": "示例养殖场",
      "code": "FARM001"
    },
    "recent_data": [
      {
        "temperature": 25.5,
        "humidity": 60.2,
        "timestamp": "2025-01-19T10:00:00Z"
      }
    ],
    "created_at": "2025-01-01T00:00:00Z",
    "updated_at": "2025-01-19T10:00:00Z"
  }
}
```

### 6.3 创建设备

**接口信息：**
- **URL**: `/api/v1/devices`
- **方法**: `POST`
- **描述**: 添加新设备

**请求参数：**
```json
{
  "farm_id": 1,
  "device_id": "DEV002",
  "device_name": "湿度传感器1",
  "device_type": "humidity",
  "model": "HU-200",
  "manufacturer": "传感器公司",
  "location": "猪舍B区",
  "install_date": "2025-01-19",
  "config": {
    "sampling_interval": 30,
    "alert_threshold": {
      "humidity_max": 85,
      "humidity_min": 35
    }
  }
}
```

**响应示例：**
```json
{
  "success": true,
  "code": 201,
  "message": "设备创建成功",
  "data": {
    "id": 2,
    "device_id": "DEV002",
    "device_name": "湿度传感器1",
    "device_type": "humidity",
    "status": "offline",
    "created_at": "2025-01-19T10:00:00Z"
  }
}
```

### 6.4 获取设备数据

**接口信息：**
- **URL**: `/api/v1/devices/{id}/data`
- **方法**: `GET`
- **描述**: 获取设备历史数据

**查询参数：**
```
start_time=2025-01-19T00:00:00Z&end_time=2025-01-19T23:59:59Z&data_type=temperature&limit=100
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "device_id": "DEV001",
    "device_name": "温度传感器1",
    "data_points": [
      {
        "timestamp": "2025-01-19T10:00:00Z",
        "temperature": 25.5,
        "humidity": 60.2,
        "ammonia": 15.8,
        "co2": 800
      },
      {
        "timestamp": "2025-01-19T10:01:00Z",
        "temperature": 25.6,
        "humidity": 60.1,
        "ammonia": 15.9,
        "co2": 805
      }
    ],
    "statistics": {
      "count": 2,
      "avg_temperature": 25.55,
      "max_temperature": 25.6,
      "min_temperature": 25.5
    }
  }
}
```

## 7. 动物管理 API

### 7.1 动物列表

**接口信息：**
- **URL**: `/api/v1/animals`
- **方法**: `GET`
- **描述**: 获取动物列表

**查询参数：**
```
page=1&limit=20&farm_id=1&breed=大白猪&status=healthy&gender=male
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "items": [
      {
        "id": 1,
        "farm_id": 1,
        "tag_id": "PIG001",
        "breed": "大白猪",
        "gender": "male",
        "birth_date": "2024-06-01",
        "weight": 85.5,
        "status": "healthy",
        "location": "猪舍A区-栏位001",
        "farm": {
          "id": 1,
          "name": "示例养殖场",
          "code": "FARM001"
        },
        "health_records": [
          {
            "id": 1,
            "check_date": "2025-01-15",
            "health_status": "healthy",
            "notes": "健康状况良好"
          }
        ],
        "created_at": "2024-06-01T00:00:00Z",
        "updated_at": "2025-01-19T10:00:00Z"
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 20,
      "total": 1,
      "pages": 1,
      "has_next": false,
      "has_prev": false
    }
  }
}
```

### 7.2 获取动物详情

**接口信息：**
- **URL**: `/api/v1/animals/{id}`
- **方法**: `GET`
- **描述**: 获取指定动物的详细信息

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "id": 1,
    "farm_id": 1,
    "tag_id": "PIG001",
    "breed": "大白猪",
    "gender": "male",
    "birth_date": "2024-06-01",
    "weight": 85.5,
    "status": "healthy",
    "location": "猪舍A区-栏位001",
    "parent_info": {
      "father_tag": "PIG_FATHER_001",
      "mother_tag": "PIG_MOTHER_001"
    },
    "farm": {
      "id": 1,
      "name": "示例养殖场",
      "code": "FARM001"
    },
    "health_records": [
      {
        "id": 1,
        "check_date": "2025-01-15",
        "health_status": "healthy",
        "temperature": 38.5,
        "weight": 85.5,
        "notes": "健康状况良好",
        "veterinarian": "兽医张三",
        "created_at": "2025-01-15T10:00:00Z"
      }
    ],
    "vaccination_records": [
      {
        "id": 1,
        "vaccine_name": "猪瘟疫苗",
        "vaccination_date": "2024-07-01",
        "next_due_date": "2025-07-01",
        "veterinarian": "兽医李四",
        "created_at": "2024-07-01T10:00:00Z"
      }
    ],
    "created_at": "2024-06-01T00:00:00Z",
    "updated_at": "2025-01-19T10:00:00Z"
  }
}
```

### 7.3 创建动物档案

**接口信息：**
- **URL**: `/api/v1/animals`
- **方法**: `POST`
- **描述**: 创建新的动物档案

**请求参数：**
```json
{
  "farm_id": 1,
  "tag_id": "PIG002",
  "breed": "长白猪",
  "gender": "female",
  "birth_date": "2024-08-01",
  "weight": 75.0,
  "location": "猪舍A区-栏位002",
  "parent_info": {
    "father_tag": "PIG_FATHER_002",
    "mother_tag": "PIG_MOTHER_002"
  },
  "notes": "新引进的种猪"
}
```

**响应示例：**
```json
{
  "success": true,
  "code": 201,
  "message": "动物档案创建成功",
  "data": {
    "id": 2,
    "tag_id": "PIG002",
    "breed": "长白猪",
    "gender": "female",
    "status": "healthy",
    "created_at": "2025-01-19T10:00:00Z"
  }
}
```

## 8. 告警管理 API

### 8.1 告警列表

**接口信息：**
- **URL**: `/api/v1/alerts`
- **方法**: `GET`
- **描述**: 获取告警列表

**查询参数：**
```
page=1&limit=20&farm_id=1&level=warning&status=pending&alert_type=temperature
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "items": [
      {
        "id": 1,
        "farm_id": 1,
        "device_id": 1,
        "alert_type": "temperature",
        "level": "warning",
        "title": "温度过高告警",
        "message": "猪舍A区温度达到32°C，超过预设阈值30°C",
        "status": "pending",
        "trigger_value": 32.0,
        "threshold_value": 30.0,
        "trigger_time": "2025-01-19T10:00:00Z",
        "farm": {
          "id": 1,
          "name": "示例养殖场",
          "code": "FARM001"
        },
        "device": {
          "id": 1,
          "device_id": "DEV001",
          "device_name": "温度传感器1",
          "location": "猪舍A区"
        },
        "created_at": "2025-01-19T10:00:00Z",
        "updated_at": "2025-01-19T10:00:00Z"
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 20,
      "total": 1,
      "pages": 1,
      "has_next": false,
      "has_prev": false
    }
  }
}
```

### 8.2 处理告警

**接口信息：**
- **URL**: `/api/v1/alerts/{id}/handle`
- **方法**: `POST`
- **描述**: 处理告警

**请求参数：**
```json
{
  "action": "resolved",
  "handler_notes": "已调整通风系统，温度恢复正常",
  "solution": "增加通风量，调整温控设备参数"
}
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "告警处理成功",
  "data": {
    "id": 1,
    "status": "resolved",
    "handled_at": "2025-01-19T10:30:00Z",
    "handler_id": 1,
    "handler_name": "管理员",
    "handler_notes": "已调整通风系统，温度恢复正常"
  }
}
```

## 9. 数据统计 API

### 9.1 概览统计

**接口信息：**
- **URL**: `/api/v1/stats/overview`
- **方法**: `GET`
- **描述**: 获取系统概览统计数据

**查询参数：**
```
date_range=7d&farm_id=1
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "farms": {
      "total": 10,
      "active": 8,
      "inactive": 2
    },
    "devices": {
      "total": 150,
      "online": 145,
      "offline": 5,
      "maintenance": 0
    },
    "animals": {
      "total": 5000,
      "healthy": 4950,
      "sick": 30,
      "quarantine": 20
    },
    "alerts": {
      "total": 25,
      "pending": 5,
      "resolved": 20,
      "critical": 2,
      "warning": 15,
      "info": 8
    },
    "trends": {
      "farms_growth": 5.2,
      "devices_growth": 8.1,
      "animals_growth": 12.5,
      "alerts_reduction": -15.3
    }
  }
}
```

### 9.2 设备数据统计

**接口信息：**
- **URL**: `/api/v1/stats/devices`
- **方法**: `GET`
- **描述**: 获取设备数据统计

**查询参数：**
```
farm_id=1&device_type=temperature&start_time=2025-01-19T00:00:00Z&end_time=2025-01-19T23:59:59Z&interval=hour
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "device_type": "temperature",
    "time_range": {
      "start": "2025-01-19T00:00:00Z",
      "end": "2025-01-19T23:59:59Z"
    },
    "statistics": {
      "avg_value": 25.5,
      "max_value": 32.0,
      "min_value": 18.5,
      "data_points": 1440
    },
    "time_series": [
      {
        "timestamp": "2025-01-19T00:00:00Z",
        "avg_value": 20.5,
        "max_value": 22.0,
        "min_value": 19.0,
        "count": 60
      },
      {
        "timestamp": "2025-01-19T01:00:00Z",
        "avg_value": 21.2,
        "max_value": 23.5,
        "min_value": 19.8,
        "count": 60
      }
    ]
  }
}
```

### 9.3 告警统计

**接口信息：**
- **URL**: `/api/v1/stats/alerts`
- **方法**: `GET`
- **描述**: 获取告警统计数据

**查询参数：**
```
farm_id=1&date_range=30d&group_by=level
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "total_alerts": 150,
    "resolved_alerts": 135,
    "pending_alerts": 15,
    "resolution_rate": 90.0,
    "avg_resolution_time": 45,
    "by_level": [
      {
        "level": "critical",
        "count": 10,
        "percentage": 6.7
      },
      {
        "level": "warning",
        "count": 80,
        "percentage": 53.3
      },
      {
        "level": "info",
        "count": 60,
        "percentage": 40.0
      }
    ],
    "by_type": [
      {
        "type": "temperature",
        "count": 60,
        "percentage": 40.0
      },
      {
        "type": "humidity",
        "count": 45,
        "percentage": 30.0
      },
      {
        "type": "ammonia",
        "count": 30,
        "percentage": 20.0
      },
      {
        "type": "system",
        "count": 15,
        "percentage": 10.0
      }
    ],
    "trend": [
      {
        "date": "2025-01-13",
        "count": 8
      },
      {
        "date": "2025-01-14",
        "count": 12
      }
    ]
  }
}
```

## 10. 文件管理 API

### 10.1 文件上传

**接口信息：**
- **URL**: `/api/v1/files/upload`
- **方法**: `POST`
- **描述**: 上传文件

**请求格式：**
```http
Content-Type: multipart/form-data

file: <binary_file>
type: image|document|video
category: avatar|farm_image|device_manual|report
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "文件上传成功",
  "data": {
    "id": 1,
    "filename": "farm_image_001.jpg",
    "original_name": "养殖场照片.jpg",
    "file_path": "/uploads/images/2025/01/19/farm_image_001.jpg",
    "file_url": "https://cdn.nxxmdata.com/uploads/images/2025/01/19/farm_image_001.jpg",
    "file_size": 1024000,
    "mime_type": "image/jpeg",
    "type": "image",
    "category": "farm_image",
    "created_at": "2025-01-19T10:00:00Z"
  }
}
```

### 10.2 文件下载

**接口信息：**
- **URL**: `/api/v1/files/{id}/download`
- **方法**: `GET`
- **描述**: 下载文件

**响应：**
```http
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="farm_image_001.jpg"

<binary_file_content>
```

### 10.3 文件删除

**接口信息：**
- **URL**: `/api/v1/files/{id}`
- **方法**: `DELETE`
- **描述**: 删除文件

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "文件删除成功"
}
```

## 11. 地图服务 API

### 11.1 获取地图数据

**接口信息：**
- **URL**: `/api/v1/map/farms`
- **方法**: `GET`
- **描述**: 获取养殖场地图标注数据

**查询参数：**
```
bounds=38.4000,106.2000,38.5000,106.3000&zoom=10&status=active
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "farms": [
      {
        "id": 1,
        "name": "示例养殖场",
        "code": "FARM001",
        "latitude": 38.4872,
        "longitude": 106.2309,
        "status": "active",
        "type": "pig",
        "scale": "large",
        "device_count": 15,
        "animal_count": 500,
        "alert_count": 2,
        "marker_icon": "farm_pig_large",
        "popup_info": {
          "title": "示例养殖场",
          "description": "大型生猪养殖场",
          "contact": "张三 - 13800138000",
          "status_text": "正常运营"
        }
      }
    ],
    "bounds": {
      "north": 38.5000,
      "south": 38.4000,
      "east": 106.3000,
      "west": 106.2000
    },
    "center": {
      "latitude": 38.4500,
      "longitude": 106.2500
    }
  }
}
```

### 11.2 地理编码

**接口信息：**
- **URL**: `/api/v1/map/geocode`
- **方法**: `GET`
- **描述**: 地址转换为经纬度坐标

**查询参数：**
```
address=宁夏银川市兴庆区示例路123号
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "地理编码成功",
  "data": {
    "address": "宁夏银川市兴庆区示例路123号",
    "location": {
      "latitude": 38.4872,
      "longitude": 106.2309
    },
    "formatted_address": "宁夏回族自治区银川市兴庆区示例路123号",
    "address_components": {
      "province": "宁夏回族自治区",
      "city": "银川市",
      "district": "兴庆区",
      "street": "示例路",
      "street_number": "123号"
    },
    "confidence": 95
  }
}
```

## 12. 系统配置 API

### 12.1 获取系统配置

**接口信息：**
- **URL**: `/api/v1/config`
- **方法**: `GET`
- **描述**: 获取系统配置信息

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "查询成功",
  "data": {
    "system": {
      "name": "宁夏智慧养殖监管平台",
      "version": "2.0.0",
      "build": "20250119",
      "environment": "production"
    },
    "features": {
      "multi_tenant": true,
      "real_time_monitoring": true,
      "mobile_app": true,
      "data_export": true
    },
    "limits": {
      "max_farms_per_user": 10,
      "max_devices_per_farm": 100,
      "max_file_size": 10485760,
      "api_rate_limit": 1000
    },
    "integrations": {
      "baidu_map": {
        "enabled": true,
        "api_key": "ak_***"
      },
      "sms_service": {
        "enabled": true,
        "provider": "aliyun"
      },
      "email_service": {
        "enabled": true,
        "smtp_host": "smtp.example.com"
      }
    }
  }
}
```

### 12.2 更新系统配置

**接口信息：**
- **URL**: `/api/v1/config`
- **方法**: `PUT`
- **描述**: 更新系统配置（需要管理员权限）

**请求参数：**
```json
{
  "limits": {
    "max_farms_per_user": 15,
    "api_rate_limit": 1500
  },
  "integrations": {
    "sms_service": {
      "enabled": false
    }
  }
}
```

**响应示例：**
```json
{
  "success": true,
  "code": 200,
  "message": "配置更新成功",
  "data": {
    "updated_fields": [
      "limits.max_farms_per_user",
      "limits.api_rate_limit",
      "integrations.sms_service.enabled"
    ],
    "updated_at": "2025-01-19T10:30:00Z"
  }
}
```

## 13. 错误处理

### 13.1 错误码定义

**通用错误码：**
- `10000` - 系统内部错误
- `10001` - 参数验证失败
- `10002` - 资源不存在
- `10003` - 权限不足
- `10004` - 请求频率超限
- `10005` - 服务暂不可用

**认证相关错误码：**
- `20001` - 用户名或密码错误
- `20002` - Token无效或已过期
- `20003` - 账户被禁用
- `20004` - 登录失败次数过多

**业务相关错误码：**
- `30001` - 养殖场代码已存在
- `30002` - 设备ID已存在
- `30003` - 动物标签ID已存在
- `30004` - 文件格式不支持
- `30005` - 文件大小超限

### 13.2 错误响应示例

**参数验证错误：**
```json
{
  "success": false,
  "code": 10001,
  "message": "参数验证失败",
  "error": {
    "type": "ValidationError",
    "details": [
      {
        "field": "email",
        "message": "邮箱格式不正确",
        "value": "invalid-email"
      },
      {
        "field": "phone",
        "message": "手机号码格式不正确",
        "value": "123"
      }
    ]
  },
  "timestamp": "2025-01-19T10:00:00Z",
  "request_id": "req_123456789"
}
```

**权限不足错误：**
```json
{
  "success": false,
  "code": 10003,
  "message": "权限不足",
  "error": {
    "type": "PermissionError",
    "required_permission": "farm:write",
    "user_permissions": ["farm:read"]
  },
  "timestamp": "2025-01-19T10:00:00Z",
  "request_id": "req_123456789"
}
```

## 14. API 测试

### 14.1 测试环境

**测试服务器：**
- 地址：`https://test-api.nxxmdata.com`
- 测试账号：`test_user`
- 测试密码：`test_password_123`

**Postman集合：**
- 下载地址：`https://api.nxxmdata.com/docs/postman-collection.json`
- 包含所有API接口的测试用例
- 自动化测试脚本

### 14.2 测试用例

**用户登录测试：**
```bash
curl -X POST https://test-api.nxxmdata.com/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "test_user",
    "password": "test_password_123"
  }'
```

**获取养殖场列表测试：**
```bash
curl -X GET https://test-api.nxxmdata.com/api/v1/farms \
  -H "Authorization: Bearer <token>" \
  -H "Accept: application/json"
```

## 15. SDK 和工具

### 15.1 JavaScript SDK

**安装：**
```bash
npm install @nxxmdata/api-sdk
```

**使用示例：**
```javascript
import { NxxmDataAPI } from '@nxxmdata/api-sdk';

const api = new NxxmDataAPI({
  baseURL: 'https://api.nxxmdata.com',
  apiKey: 'your-api-key'
});

// 登录
const loginResult = await api.auth.login({
  username: 'admin',
  password: 'password123'
});

// 获取养殖场列表
const farms = await api.farms.list({
  page: 1,
  limit: 20,
  status: 'active'
});
```

### 15.2 Python SDK

**安装：**
```bash
pip install nxxmdata-api-sdk
```

**使用示例：**
```python
from nxxmdata_api import NxxmDataAPI

api = NxxmDataAPI(
    base_url='https://api.nxxmdata.com',
    api_key='your-api-key'
)

# 登录
login_result = api.auth.login(
    username='admin',
    password='password123'
)

# 获取养殖场列表
farms = api.farms.list(
    page=1,
    limit=20,
    status='active'
)
```

## 16. 版本更新

### 16.1 版本兼容性

**向后兼容性：**
- 主版本号变更可能包含破坏性更改
- 次版本号变更保持向后兼容
- 修订版本号仅包含bug修复

**废弃策略：**
- 废弃功能将在下一个主版本中移除
- 提前6个月通知废弃计划
- 提供迁移指南和工具

### 16.2 更新日志

**v2.0.0 (2025-01-19)：**
- 全面重构API架构
- 增加多端支持
- 优化响应格式
- 增强安全性
- 添加更多统计接口

**v1.0.0 (2025-01-18)：**
- 初始版本发布
- 基础CRUD功能
- JWT认证
- 基本统计功能

---

**文档维护说明：**
- 本文档将随API版本更新而更新
- 所有接口变更都会在此文档中体现
- 如有疑问请联系开发团队

**联系方式：**
- 技术支持：tech-support@nxxmdata.com
- API问题：api-support@nxxmdata.com
- 文档反馈：docs@nxxmdata.com

*最后更新时间：2025-01-19*
*文档版本：v2.0*
*维护人员：开发团队*