# 数据库详细设计

## 概述

本项目使用MySQL作为主要的关系型数据库，存储用户信息、牛只档案、交易记录、监管数据等核心业务数据。

## 数据库设计规范

### 1. 基础规范
| 条目                | 规范说明                                                                 |
|---------------------|--------------------------------------------------------------------------|
| 存储引擎            | InnoDB（支持事务和行级锁）                                               |
| 字符集              | utf8mb4（支持完整Unicode，包括emoji）                                    |
| 主键设计            | 自增BIGINT UNSIGNED（禁止使用业务字段）                                  |
| 时间字段            | 必须包含`created_at`(DEFAULT CURRENT_TIMESTAMP)和`updated_at`(ON UPDATE)|
| 命名规则            | 表名复数形式（users），字段名下划线分隔（user_name）                     |

### 2. API映射规范
| API字段类型         | 数据库实现                                                               |
|---------------------|--------------------------------------------------------------------------|
| 字符串              | VARCHAR(长度根据API校验规则定义)                                        |
| 枚举值              | ENUM类型或TINYINT+注释说明                                               |
| 嵌套对象            | JSON类型或关联表                                                        |
| 文件资源            | 存储OSS路径（VARCHAR(255)）                                             |

### 3. 安全规范
| 数据类型            | 处理方式                                                                 |
|---------------------|--------------------------------------------------------------------------|
| 密码                | BCrypt哈希存储                                                           |
| 身份证号            | AES-256加密                                                              |
| 手机号              | 脱敏存储（保留前3后4）                                                   |
| 审计字段            | 必须包含操作人ID和IP地址                                                 |

### 4. 性能规范
| 场景                | 优化策略                                                                 | 适用API端点示例         |
|---------------------|--------------------------------------------------------------------------|-------------------------|
| 高频查询            | 组合索引覆盖查询路径                                                     | GET /api/v1/orders      |
| 大文本              | 单独分表+OSS存储（如`product_descriptions`）                             | POST /api/v1/products   |
| 状态字段            | 使用TINYINT+状态字典表（便于索引和扩展）                                 | PUT /api/v1/orders/{id} |
| 批量操作            | 提供`batch_`前缀的专用表+异步处理机制                                   | POST /api/v1/batch      |
| 分页查询            | 基于游标的分页（避免OFFSET性能问题）                                    | GET /api/v1/history     |

### 5. API字段映射规范
| API字段            | 数据库字段       | 类型       | 校验规则                          | 备注                          |
|--------------------|------------------|------------|-----------------------------------|-------------------------------|
| user.name          | user_name        | VARCHAR(50)| 必填，中文2-20字符                | 显示名                        |
| user.phone         | phone            | VARCHAR(20)| 必填，正则校验^1[3-9]\d{9}$      | AES加密存储                   |
| order.status       | status           | TINYINT    | 1-5枚举值                        | 关联status_dict表             |
| product.detail     | detail_text      | TEXT       | 可选，≤2000字符                  | 存OSS链接时此字段为空         |

### 6. 状态机设计
| 业务模块       | 状态流转规则                                                                 | 触发API               |
|----------------|------------------------------------------------------------------------------|-----------------------|
| 订单系统       | 待支付→已支付→配送中→已完成（不可逆）                                       | PUT /api/v1/orders    |
| 审批流程       | 草稿→审批中→已通过/已驳回（可重新提交）                                     | POST /api/v1/approvals|
| 养殖档案       | 未认证→认证中→已认证（管理员可重置）                                        | PATCH /api/v1/farms   |

## 分库分表策略

### 1. 垂直分库
| 业务模块       | 数据库实例   | 分库依据               |
|----------------|------------|-----------------------|
| 用户中心       | db_user    | 所有用户相关表         |
| 交易系统       | db_trade   | 订单/支付/物流相关表   |
| 政府监管       | db_gov     | 防疫/补贴/检疫相关表   |

### 2. 水平分表
- **触发条件**：单表数据量 ≥ 500万行
- **分表规则**：
  - 用户表：按用户ID取模（16张）
  - 订单表：按创建月份分表（按月归档）
- **路由策略**：ShardingSphere中间件

### 3. 扩容预案
- **垂直扩容**：升级服务器配置（CPU/内存）
- **水平扩容**：增加分片数量（需停服迁移）

## 读写分离设计

### 1. 节点角色
| 节点类型 | 数量 | 作用域               | 同步方式          |
|---------|-----|---------------------|------------------|
| 主库    | 1   | 全业务写操作          | 半同步复制        |
| 从库1   | 2   | 交易业务读查询        | 异步复制          |
| 从库2   | 1   | 数据分析类查询        | 延迟复制（1小时） |

### 2. 故障转移
- **主库宕机**：VIP漂移+从库升主（30秒内完成）
- **从库延迟**：自动路由到低延迟节点

## 数据生命周期管理

### 1. 冷热分离
- **热数据**：当前业务周期数据（保留6个月）
- **冷数据**：历史数据（OSS归档存储）

### 2. 归档规则
- **触发条件**：数据创建时间 ≥ 1年
- **归档方式**：
  - 结构化数据：Parquet格式压缩
  - 图片/文件：OSS低频访问存储

## 性能优化

### 1. 缓存策略
- **查询缓存**：Redis集群（LRU淘汰策略）
- **更新机制**：
  - 写穿透（Write-Through）
  - 缓存失效（Cache Aside）

### 2. 连接池配置
- **最大连接数**：CPU核心数 × 2 + 有效磁盘数
- **验证查询**：`SELECT 1`（每5分钟）

## 灾备方案

### 1. 跨机房同步
- **拓扑结构**：主-备-灾备（三机房部署）
- **同步延迟**：≤ 5分钟（专线保障）

### 2. 恢复SLA
| 故障级别 | RTO       | RPO       |
|---------|-----------|-----------|
| P0      | ≤ 15分钟  | ≤ 1分钟   |
| P1      | ≤ 1小时   | ≤ 5分钟   |

## 监控指标

### 1. 性能看板
- **QPS/TPS**：Prometheus + Grafana
- **慢查询**：每10分钟采样分析

### 2. 容量预测
- **增长模型**：线性回归（基于历史数据）
- **预警阈值**：存储使用率 ≥ 75%

## 索引优化建议
- 高频查询字段必须加索引
- 联合索引遵循最左匹配原则
- 定期使用`EXPLAIN`分析慢查询

## 核心数据表设计

### 1. 用户表 (users)
存储系统用户信息，包括牧民、银行职员、保险员、政府监管人员等。

```sql
CREATE TABLE users (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '用户ID',
    username VARCHAR(50) NOT NULL UNIQUE COMMENT '用户名（用于登录）',
    email VARCHAR(100) UNIQUE COMMENT '邮箱（用于通知和找回密码）',
    phone VARCHAR(20) UNIQUE COMMENT '手机号（实名认证用）',
    password_hash VARCHAR(255) NOT NULL COMMENT '密码哈希值（BCrypt加密）',
    real_name VARCHAR(50) COMMENT '真实姓名（需与身份证一致）',
    avatar_url VARCHAR(255) COMMENT '头像URL（OSS存储路径）',
    user_type ENUM('farmer', 'banker', 'insurer', 'government', 'trader', 'admin') NOT NULL COMMENT '用户类型：牧民/银行职员/保险员/政府人员/交易员/管理员',
    status TINYINT DEFAULT 1 COMMENT '状态: 1-正常, 0-禁用（禁用用户无法登录）',
    last_login TIMESTAMP NULL COMMENT '最后登录时间（用于活跃度分析）',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间（不可修改）',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间（自动维护）',
    INDEX idx_user_type (user_type) COMMENT '按用户类型加速查询'
```

### 2. 金融业务表

#### 2.1 贷款申请表 (loan_applications)
```sql
CREATE TABLE loan_applications (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    farmer_id BIGINT UNSIGNED NOT NULL COMMENT '牧户ID',
    loan_amount DECIMAL(15,2) NOT NULL COMMENT '申请金额',
    risk_score TINYINT COMMENT '风控评分(1-100)',
    collateral_type ENUM('cattle', 'land', 'equipment') COMMENT '抵押物类型',
    status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
    FOREIGN KEY (farmer_id) REFERENCES users(id),
    INDEX idx_status (status)
);
```

#### 2.2 保险保单表 (insurance_policies)
```sql
CREATE TABLE insurance_policies (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    cattle_id BIGINT UNSIGNED NOT NULL COMMENT '牛只ID',
    disaster_type ENUM('drought', 'blizzard', 'epidemic') NOT NULL,
    coverage_amount DECIMAL(15,2) NOT NULL,
    start_date DATE NOT NULL,
    end_date DATE NOT NULL,
    INDEX idx_coverage (coverage_amount)
);
```

### 3. 政府监管表

#### 3.1 防疫任务表 (quarantine_tasks)
```sql
CREATE TABLE quarantine_tasks (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    location POINT NOT NULL COMMENT 'GPS坐标',
    inspector_id BIGINT UNSIGNED NOT NULL COMMENT '检疫员ID',
    completion_status BOOLEAN DEFAULT FALSE,
    SPATIAL INDEX (location),
    FOREIGN KEY (inspector_id) REFERENCES users(id)
);
```

#### 3.2 补贴发放表 (subsidies)
```sql
CREATE TABLE subsidies (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    farmer_id BIGINT UNSIGNED NOT NULL,
    balance_score TINYINT NOT NULL COMMENT '草畜平衡评分(1-100)',
    amount DECIMAL(15,2) NOT NULL,
    payment_date DATE NOT NULL,
    FOREIGN KEY (farmer_id) REFERENCES users(id)
);
```

### 4. 数据中台表

#### 4.1 数据血缘表 (data_lineage)
```sql
CREATE TABLE data_lineage (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    source_table VARCHAR(100) NOT NULL,
    source_field VARCHAR(100) NOT NULL,
    target_table VARCHAR(100) NOT NULL,
    target_field VARCHAR(100) NOT NULL,
    transformation_rule TEXT COMMENT '转换规则SQL片段',
    UNIQUE KEY (source_table, source_field, target_table, target_field)
);
```

#### 4.2 接口审计表 (api_audit_logs)
```sql
CREATE TABLE api_audit_logs (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED,
    endpoint VARCHAR(255) NOT NULL,
    request_params JSON,
    sensitive_data BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

### 5. AI模型表

#### 5.1 体况评分表 (body_condition_scores)
```sql
CREATE TABLE body_condition_scores (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    cattle_id BIGINT UNSIGNED NOT NULL,
    score TINYINT NOT NULL COMMENT '体况评分(1-5)',
    muscle_score TINYINT COMMENT '肌肉发育评分',
    fat_score TINYINT COMMENT '脂肪覆盖评分',
    photo_url VARCHAR(255) COMMENT '评分照片URL',
    FOREIGN KEY (cattle_id) REFERENCES cattle(id)
);
```

#### 5.2 饲料配方表 (feed_formulas)
```sql
CREATE TABLE feed_formulas (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    version VARCHAR(50) NOT NULL COMMENT '配方版本',
    stage ENUM('calf', 'growing', 'fattening') NOT NULL,
    ingredients JSON NOT NULL COMMENT '原料配比',
    cost_per_kg DECIMAL(10,2) NOT NULL,
    is_active BOOLEAN DEFAULT TRUE COMMENT '是否当前使用版本',
    UNIQUE KEY (version, stage)
);
);

-- 常用查询示例：
-- 1. 按用户类型统计数量
-- SELECT user_type, COUNT(*) FROM users GROUP BY user_type;
-- 2. 查询最近登录的活跃用户
-- SELECT * FROM users WHERE last_login > DATE_SUB(NOW(), INTERVAL 7 DAY);

### 2. 贷款申请表 (loan_applications)
存储贷款申请信息，包括申请人、贷款金额、用途等。

```sql
CREATE TABLE loan_applications (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '申请ID',
    user_id BIGINT UNSIGNED NOT NULL COMMENT '申请人ID（关联users表）',
    amount DECIMAL(15,2) NOT NULL COMMENT '贷款金额（单位：元，精确到分）',
    purpose VARCHAR(255) NOT NULL COMMENT '贷款用途（如：购买饲料、扩建牛舍）',
    status ENUM('pending', 'approved', 'rejected', 'disbursed') DEFAULT 'pending' COMMENT '状态：待审批/已通过/已拒绝/已放款',
    application_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '申请日期（自动记录）',
    approval_date TIMESTAMP NULL COMMENT '审批日期（审批通过时更新）',
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE COMMENT '级联删除用户时同步清理',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX idx_status (status) COMMENT '加速状态筛选',
    INDEX idx_user_id (user_id) COMMENT '加速申请人查询'
);

-- 常用查询示例：
-- 1. 按状态统计贷款申请
-- SELECT status, COUNT(*) FROM loan_applications GROUP BY status;
-- 2. 查询某用户的贷款历史
-- SELECT * FROM loan_applications WHERE user_id = 123 ORDER BY application_date DESC;

### 3. 质押物监控表 (collateral_monitoring)
存储质押物（牛只）的状态监控信息。

```sql
CREATE TABLE collateral_monitoring (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '监控ID',
    loan_id BIGINT UNSIGNED NOT NULL COMMENT '关联贷款ID',
    cattle_id BIGINT UNSIGNED NOT NULL COMMENT '质押牛只ID',
    health_status VARCHAR(100) NOT NULL COMMENT '健康状况',
    location VARCHAR(255) NOT NULL COMMENT '当前位置',
    last_check_date TIMESTAMP NULL COMMENT '最后检查日期',
    FOREIGN KEY (loan_id) REFERENCES loan_applications(id),
    FOREIGN KEY (cattle_id) REFERENCES cattle(id),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
);
```

### 4. 还款计划表 (repayment_schedules)
存储贷款的还款计划信息。

```sql
CREATE TABLE repayment_schedules (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '计划ID',
    loan_id BIGINT UNSIGNED NOT NULL COMMENT '关联贷款ID',
    due_date TIMESTAMP NOT NULL COMMENT '还款日期',
    amount DECIMAL(15,2) NOT NULL COMMENT '还款金额',
    status ENUM('pending', 'paid', 'overdue') DEFAULT 'pending' COMMENT '状态',
    payment_date TIMESTAMP NULL COMMENT '实际还款日期',
    FOREIGN KEY (loan_id) REFERENCES loan_applications(id),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
);
```

### 5. 保险申请表 (insurance_applications)
存储保险申请信息。

```sql
CREATE TABLE insurance_applications (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '申请ID',
    user_id BIGINT UNSIGNED NOT NULL COMMENT '申请人ID',
    cattle_id BIGINT UNSIGNED NOT NULL COMMENT '投保牛只ID',
    coverage_amount DECIMAL(15,2) NOT NULL COMMENT '保额',
    premium DECIMAL(15,2) NOT NULL COMMENT '保费',
    start_date TIMESTAMP NOT NULL COMMENT '保险开始日期',
    end_date TIMESTAMP NOT NULL COMMENT '保险结束日期',
    status ENUM('pending', 'approved', 'rejected', 'active', 'expired') DEFAULT 'pending' COMMENT '状态',
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (cattle_id) REFERENCES cattle(id),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
);
```

### 6. 理赔记录表 (claim_records)
存储保险理赔记录。

```sql
CREATE TABLE claim_records (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '理赔ID',
    insurance_id BIGINT UNSIGNED NOT NULL COMMENT '关联保险ID',
    claim_amount DECIMAL(15,2) NOT NULL COMMENT '理赔金额',
    claim_reason VARCHAR(255) NOT NULL COMMENT '理赔原因',
    status ENUM('pending', 'approved', 'rejected', 'paid') DEFAULT 'pending' COMMENT '状态',
    approval_date TIMESTAMP NULL COMMENT '审批日期',
    payment_date TIMESTAMP NULL COMMENT '支付日期',
    FOREIGN KEY (insurance_id) REFERENCES insurance_applications(id),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
);
```

### 7. 风险评估表 (risk_assessments)
存储保险风险评估信息。

```sql
CREATE TABLE risk_assessments (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '评估ID',
    insurance_id BIGINT UNSIGNED NOT NULL COMMENT '关联保险ID',
    risk_level ENUM('low', 'medium', 'high') NOT NULL COMMENT '风险等级',
    assessment_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '评估日期',
    notes TEXT COMMENT '评估备注',
    FOREIGN KEY (insurance_id) REFERENCES insurance_applications(id),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
);
```

### 8. 监管记录表 (supervision_records)
存储政府监管记录。

```sql
CREATE TABLE supervision_records (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '记录ID',
    user_id BIGINT UNSIGNED NOT NULL COMMENT '监管人员ID',
    cattle_id BIGINT UNSIGNED NOT NULL COMMENT '监管牛只ID',
    inspection_date TIMESTAMP NOT NULL COMMENT '检查日期',
    findings TEXT NOT NULL COMMENT '检查结果',
    actions_taken TEXT COMMENT '采取的措施',
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (cattle_id) REFERENCES cattle(id),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
);
```
    INDEX idx_username (username),
    INDEX idx_email (email),
    INDEX idx_phone (phone),
    INDEX idx_user_type (user_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';
```

### 2. 角色表 (roles)
存储系统角色信息，如管理员、牧民、银行职员等。

```sql
CREATE TABLE roles (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '角色ID',
    name VARCHAR(50) NOT NULL UNIQUE COMMENT '角色名称',
    description TEXT COMMENT '角色描述',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色表';
```

### 3. 用户角色关联表 (user_roles)
存储用户和角色的多对多关系。

```sql
CREATE TABLE user_roles (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
    user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
    role_id INT UNSIGNED NOT NULL COMMENT '角色ID',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,
    UNIQUE KEY uk_user_role (user_id, role_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户角色关联表';
```

### 4. 权限表 (permissions)
存储系统权限信息。

```sql
CREATE TABLE permissions (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '权限ID',
    name VARCHAR(100) NOT NULL UNIQUE COMMENT '权限名称',
    description TEXT COMMENT '权限描述',
    module VARCHAR(50) COMMENT '所属模块',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='权限表';
```

### 5. 角色权限关联表 (role_permissions)
存储角色和权限的多对多关系。

```sql
CREATE TABLE role_permissions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
    role_id INT UNSIGNED NOT NULL COMMENT '角色ID',
    permission_id INT UNSIGNED NOT NULL COMMENT '权限ID',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    
    FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,
    FOREIGN KEY (permission_id) REFERENCES permissions(id) ON DELETE CASCADE,
    UNIQUE KEY uk_role_permission (role_id, permission_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色权限关联表';
```

### 6. 牛只档案表 (cattle)
存储牛只基本信息，包括品种、年龄、健康状况等。

```sql
CREATE TABLE cattle (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '牛只ID',
    ear_tag VARCHAR(50) NOT NULL UNIQUE COMMENT '耳标号',
    name VARCHAR(50) COMMENT '名称',
    breed VARCHAR(50) COMMENT '品种',
    gender ENUM('male', 'female') COMMENT '性别',
    birth_date DATE COMMENT '出生日期',
    color VARCHAR(30) COMMENT '毛色',
    weight DECIMAL(5,2) COMMENT '体重(kg)',
    health_status ENUM('healthy', 'sick', 'quarantine', 'dead') DEFAULT 'healthy' COMMENT '健康状况',
    owner_id BIGINT UNSIGNED COMMENT '所有者ID（牧民）',
    farm_location VARCHAR(255) COMMENT '牧场位置',
    status ENUM('active', 'sold', 'dead', 'quarantine') DEFAULT 'active' COMMENT '状态',
    image_url VARCHAR(255) COMMENT '图片URL',
    qr_code_url VARCHAR(255) COMMENT '二维码URL',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (owner_id) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_ear_tag (ear_tag),
    INDEX idx_owner (owner_id),
    INDEX idx_breed (breed),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='牛只档案表';
```

### 7. 饲养记录表 (feeding_records)
存储牛只饲养记录，包括饲料、疫苗、治疗等信息。

```sql
CREATE TABLE feeding_records (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '记录ID',
    cattle_id BIGINT UNSIGNED NOT NULL COMMENT '牛只ID',
    record_type ENUM('feed', 'vaccine', 'treatment', 'checkup') NOT NULL COMMENT '记录类型: 饲料, 疫苗, 治疗, 检查',
    feed_type VARCHAR(100) COMMENT '饲料类型',
    feed_amount DECIMAL(6,2) COMMENT '饲料量(kg)',
    vaccine_name VARCHAR(100) COMMENT '疫苗名称',
    treatment_desc TEXT COMMENT '治疗描述',
    medicine_name VARCHAR(100) COMMENT '药品名称',
    dosage VARCHAR(100) COMMENT '用量',
    veterinarian VARCHAR(50) COMMENT '兽医',
    cost DECIMAL(10,2) COMMENT '费用',
    record_date DATE NOT NULL COMMENT '记录日期',
    notes TEXT COMMENT '备注',
    operator_id BIGINT UNSIGNED COMMENT '操作员ID',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (cattle_id) REFERENCES cattle(id) ON DELETE CASCADE,
    FOREIGN KEY (operator_id) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_cattle_date (cattle_id, record_date),
    INDEX idx_record_type (record_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='饲养记录表';
```

### 8. 繁殖记录表 (breeding_records)
存储牛只繁殖相关信息。

```sql
CREATE TABLE breeding_records (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '记录ID',
    cattle_id BIGINT UNSIGNED NOT NULL COMMENT '母牛ID',
    breeding_method ENUM('natural', 'artificial') NOT NULL COMMENT '配种方式',
    breeding_date DATE NOT NULL COMMENT '配种日期',
    breeding_male_id BIGINT UNSIGNED COMMENT '公牛ID',
    semen_code VARCHAR(50) COMMENT '冻精编号',
    expected_delivery_date DATE COMMENT '预产期',
    actual_delivery_date DATE COMMENT '实际产犊日期',
    calf_count TINYINT DEFAULT 1 COMMENT '产犊数',
    calf_ids JSON COMMENT '犊牛IDs',
    breeding_result ENUM('success', 'failed', 'pending') DEFAULT 'pending' COMMENT '配种结果',
    notes TEXT COMMENT '备注',
    operator_id BIGINT UNSIGNED COMMENT '操作员ID',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (cattle_id) REFERENCES cattle(id) ON DELETE CASCADE,
    FOREIGN KEY (breeding_male_id) REFERENCES cattle(id) ON DELETE SET NULL,
    FOREIGN KEY (operator_id) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_cattle_date (cattle_id, breeding_date),
    INDEX idx_result (breeding_result)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='繁殖记录表';
```

### 9. 环境监测表 (environment_monitoring)
存储牧场环境监测数据。

```sql
CREATE TABLE environment_monitoring (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '记录ID',
    location VARCHAR(255) NOT NULL COMMENT '监测位置',
    temperature DECIMAL(5,2) COMMENT '温度(℃)',
    humidity DECIMAL(5,2) COMMENT '湿度(%)',
    air_quality VARCHAR(50) COMMENT '空气质量',
    ammonia_concentration DECIMAL(6,3) COMMENT '氨气浓度(ppm)',
    carbon_dioxide DECIMAL(6,2) COMMENT '二氧化碳浓度(ppm)',
    noise_level DECIMAL(5,2) COMMENT '噪音(dB)',
    light_intensity DECIMAL(7,2) COMMENT '光照强度(lux)',
    monitoring_date DATETIME NOT NULL COMMENT '监测时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    INDEX idx_location_date (location, monitoring_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='环境监测表';
```

### 10. 交易记录表 (transactions)
存储活牛交易记录。

```sql
CREATE TABLE transactions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '交易ID',
    cattle_id BIGINT UNSIGNED NOT NULL COMMENT '牛只ID',
    seller_id BIGINT UNSIGNED NOT NULL COMMENT '卖方ID',
    buyer_id BIGINT UNSIGNED NOT NULL COMMENT '买方ID',
    transaction_type ENUM('direct', 'auction', 'platform') NOT NULL COMMENT '交易类型',
    price DECIMAL(12,2) NOT NULL COMMENT '交易价格',
    currency VARCHAR(10) DEFAULT 'CNY' COMMENT '货币',
    transaction_date DATETIME NOT NULL COMMENT '交易时间',
    contract_id BIGINT UNSIGNED COMMENT '合同ID',
    status ENUM('pending', 'completed', 'cancelled') DEFAULT 'pending' COMMENT '状态',
    payment_status ENUM('unpaid', 'partial', 'paid') DEFAULT 'unpaid' COMMENT '付款状态',
    delivery_status ENUM('pending', 'in_transit', 'delivered') DEFAULT 'pending' COMMENT '交付状态',
    notes TEXT COMMENT '备注',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (cattle_id) REFERENCES cattle(id) ON DELETE CASCADE,
    FOREIGN KEY (seller_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (buyer_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (contract_id) REFERENCES contracts(id) ON DELETE SET NULL,
    INDEX idx_cattle_date (cattle_id, transaction_date),
    INDEX idx_seller (seller_id),
    INDEX idx_buyer (buyer_id),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='交易记录表';
```

### 11. 合同表 (contracts)
存储交易合同信息。

```sql
CREATE TABLE contracts (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '合同ID',
    contract_number VARCHAR(50) NOT NULL UNIQUE COMMENT '合同编号',
    seller_id BIGINT UNSIGNED NOT NULL COMMENT '卖方ID',
    buyer_id BIGINT UNSIGNED NOT NULL COMMENT '买方ID',
    cattle_details JSON COMMENT '牛只详情',
    total_price DECIMAL(15,2) NOT NULL COMMENT '总价',
    currency VARCHAR(10) DEFAULT 'CNY' COMMENT '货币',
    contract_date DATE NOT NULL COMMENT '合同日期',
    effective_date DATE COMMENT '生效日期',
    expiry_date DATE COMMENT '到期日期',
    payment_terms TEXT COMMENT '付款条款',
    delivery_terms TEXT COMMENT '交付条款',
    contract_status ENUM('draft', 'signed', 'active', 'completed', 'cancelled') DEFAULT 'draft' COMMENT '合同状态',
    contract_file_url VARCHAR(255) COMMENT '合同文件URL',
    notes TEXT COMMENT '备注',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (seller_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (buyer_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_contract_number (contract_number),
    INDEX idx_seller (seller_id),
    INDEX idx_buyer (buyer_id),
    INDEX idx_status (contract_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='合同表';
```

### 12. 商品表 (products)
存储牛肉商城商品信息。

```sql
CREATE TABLE products (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '商品ID',
    name VARCHAR(100) NOT NULL COMMENT '商品名称',
    description TEXT COMMENT '商品描述',
    category_id INT UNSIGNED COMMENT '分类ID',
    sku VARCHAR(50) UNIQUE COMMENT 'SKU',
    price DECIMAL(10,2) NOT NULL COMMENT '价格',
    original_price DECIMAL(10,2) COMMENT '原价',
    currency VARCHAR(10) DEFAULT 'CNY' COMMENT '货币',
    stock_quantity INT DEFAULT 0 COMMENT '库存数量',
    min_stock INT DEFAULT 0 COMMENT '最低库存',
    unit VARCHAR(20) COMMENT '单位',
    weight DECIMAL(8,3) COMMENT '重量(kg)',
    origin VARCHAR(100) COMMENT '产地',
    production_date DATE COMMENT '生产日期',
    expiration_date DATE COMMENT '保质期',
    cattle_id BIGINT UNSIGNED COMMENT '关联牛只ID',
    status ENUM('active', 'inactive', 'discontinued') DEFAULT 'active' COMMENT '状态',
    image_urls JSON COMMENT '图片URL列表',
    tags JSON COMMENT '标签',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (cattle_id) REFERENCES cattle(id) ON DELETE SET NULL,
    INDEX idx_name (name),
    INDEX idx_category (category_id),
    INDEX idx_sku (sku),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='商品表';
```

### 13. 商品分类表 (product_categories)
存储商品分类信息。

```sql
CREATE TABLE product_categories (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '分类ID',
    name VARCHAR(50) NOT NULL COMMENT '分类名称',
    parent_id INT UNSIGNED DEFAULT 0 COMMENT '父分类ID',
    level TINYINT DEFAULT 1 COMMENT '层级',
    sort_order INT DEFAULT 0 COMMENT '排序',
    image_url VARCHAR(255) COMMENT '图片URL',
    status TINYINT DEFAULT 1 COMMENT '状态: 1-正常, 0-禁用',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    INDEX idx_parent (parent_id),
    INDEX idx_level (level)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='商品分类表';
```

### 14. 订单表 (orders)
存储用户订单信息。

```sql
CREATE TABLE orders (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '订单ID',
    order_number VARCHAR(50) NOT NULL UNIQUE COMMENT '订单编号',
    user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
    total_amount DECIMAL(12,2) NOT NULL COMMENT '订单总额',
    currency VARCHAR(10) DEFAULT 'CNY' COMMENT '货币',
    order_status ENUM('pending', 'confirmed', 'processing', 'shipped', 'delivered', 'cancelled', 'refunded') DEFAULT 'pending' COMMENT '订单状态',
    payment_status ENUM('unpaid', 'partial', 'paid') DEFAULT 'unpaid' COMMENT '付款状态',
    shipping_status ENUM('unshipped', 'shipped', 'delivered') DEFAULT 'unshipped' COMMENT '发货状态',
    receiver_name VARCHAR(50) COMMENT '收货人姓名',
    receiver_phone VARCHAR(20) COMMENT '收货人电话',
    receiver_address TEXT COMMENT '收货地址',
    shipping_method VARCHAR(50) COMMENT '配送方式',
    shipping_fee DECIMAL(10,2) DEFAULT 0.00 COMMENT '运费',
    notes TEXT COMMENT '备注',
    payment_method VARCHAR(50) COMMENT '付款方式',
    paid_at TIMESTAMP NULL COMMENT '付款时间',
    shipped_at TIMESTAMP NULL COMMENT '发货时间',
    delivered_at TIMESTAMP NULL COMMENT '送达时间',
    cancelled_at TIMESTAMP NULL COMMENT '取消时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_order_number (order_number),
    INDEX idx_user (user_id),
    INDEX idx_status (order_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单表';
```

### 15. 订单项表 (order_items)
存储订单详情信息。

```sql
CREATE TABLE order_items (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '订单项ID',
    order_id BIGINT UNSIGNED NOT NULL COMMENT '订单ID',
    product_id BIGINT UNSIGNED NOT NULL COMMENT '商品ID',
    quantity INT NOT NULL COMMENT '数量',
    unit_price DECIMAL(10,2) NOT NULL COMMENT '单价',
    total_price DECIMAL(12,2) NOT NULL COMMENT '总价',
    cattle_id BIGINT UNSIGNED COMMENT '关联牛只ID',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE,
    FOREIGN KEY (cattle_id) REFERENCES cattle(id) ON DELETE SET NULL,
    INDEX idx_order (order_id),
    INDEX idx_product (product_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单项表';
```

### 16. 物流跟踪表 (logistics_tracking)
存储物流跟踪信息。

```sql
CREATE TABLE logistics_tracking (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '物流ID',
    order_id BIGINT UNSIGNED NOT NULL COMMENT '订单ID',
    tracking_number VARCHAR(100) UNIQUE COMMENT '物流单号',
    carrier VARCHAR(50) COMMENT '承运商',
    status ENUM('pending', 'in_transit', 'delivered', 'exception') DEFAULT 'pending' COMMENT '物流状态',
    origin VARCHAR(255) COMMENT '起始地',
    destination VARCHAR(255) COMMENT '目的地',
    estimated_delivery_date DATE COMMENT '预计送达日期',
    actual_delivery_date DATE COMMENT '实际送达日期',
    current_location VARCHAR(255) COMMENT '当前位置',
    tracking_info JSON COMMENT '物流跟踪信息',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
    INDEX idx_tracking_number (tracking_number),
    INDEX idx_order (order_id),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='物流跟踪表';
```

### 17. 贷款申请表 (loan_applications)
存储银行贷款申请信息。

```sql
CREATE TABLE loan_applications (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '贷款申请ID',
    applicant_id BIGINT UNSIGNED NOT NULL COMMENT '申请人ID',
    loan_type ENUM('cattle', 'farm', 'equipment', 'operating') NOT NULL COMMENT '贷款类型',
    cattle_ids JSON COMMENT '质押牛只IDs',
    loan_amount DECIMAL(15,2) NOT NULL COMMENT '贷款金额',
    currency VARCHAR(10) DEFAULT 'CNY' COMMENT '货币',
    interest_rate DECIMAL(5,4) COMMENT '利率',
    term_months INT COMMENT '期限(月)',
    purpose TEXT COMMENT '用途',
    repayment_method ENUM('equal_principal', 'equal_payment', 'bullet') COMMENT '还款方式',
    guarantee_type ENUM('cattle_pledge', 'guarantor', 'insurance', 'credit') COMMENT '担保方式',
    status ENUM('submitted', 'under_review', 'approved', 'rejected', 'disbursed', 'completed', 'overdue') DEFAULT 'submitted' COMMENT '状态',
    reviewer_id BIGINT UNSIGNED COMMENT '审核人ID',
    review_notes TEXT COMMENT '审核备注',
    approved_amount DECIMAL(15,2) COMMENT '批准金额',
    approved_date TIMESTAMP NULL COMMENT '批准日期',
    disbursement_date TIMESTAMP NULL COMMENT '放款日期',
    repayment_schedule JSON COMMENT '还款计划',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (applicant_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (reviewer_id) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_applicant (applicant_id),
    INDEX idx_status (status),
    INDEX idx_type (loan_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='贷款申请表';
```

### 18. 保险申请表 (insurance_applications)
存储保险申请信息。

```sql
CREATE TABLE insurance_applications (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '保险申请ID',
    applicant_id BIGINT UNSIGNED NOT NULL COMMENT '申请人ID',
    insurance_type ENUM('cattle_death', 'cattle_health', 'cattle_theft', 'property') NOT NULL COMMENT '保险类型',
    cattle_ids JSON COMMENT '保险牛只IDs',
    policy_number VARCHAR(50) UNIQUE COMMENT '保单号',
    insured_amount DECIMAL(15,2) COMMENT '保险金额',
    premium DECIMAL(12,2) COMMENT '保费',
    currency VARCHAR(10) DEFAULT 'CNY' COMMENT '货币',
    start_date DATE COMMENT '起保日期',
    end_date DATE COMMENT '终保日期',
    status ENUM('applied', 'underwriting', 'issued', 'active', 'expired', 'cancelled', 'claiming', 'settled') DEFAULT 'applied' COMMENT '状态',
    underwriter_id BIGINT UNSIGNED COMMENT '核保人ID',
    underwriting_notes TEXT COMMENT '核保备注',
    policy_file_url VARCHAR(255) COMMENT '保单文件URL',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (applicant_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (underwriter_id) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_applicant (applicant_id),
    INDEX idx_policy_number (policy_number),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='保险申请表';
```

### 19. 理赔申请表 (claims)
存储保险理赔信息。

```sql
CREATE TABLE claims (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '理赔申请ID',
    insurance_id BIGINT UNSIGNED NOT NULL COMMENT '保险ID',
    applicant_id BIGINT UNSIGNED NOT NULL COMMENT '申请人ID',
    claim_amount DECIMAL(12,2) NOT NULL COMMENT '理赔金额',
    currency VARCHAR(10) DEFAULT 'CNY' COMMENT '货币',
    incident_date DATE NOT NULL COMMENT '事故日期',
    incident_type ENUM('death', 'illness', 'accident', 'theft') NOT NULL COMMENT '事故类型',
    description TEXT COMMENT '事故描述',
    evidence_files JSON COMMENT '证据文件URL列表',
    status ENUM('submitted', 'under_review', 'approved', 'rejected', 'paid') DEFAULT 'submitted' COMMENT '状态',
    reviewer_id BIGINT UNSIGNED COMMENT '审核人ID',
    review_notes TEXT COMMENT '审核备注',
    approved_amount DECIMAL(12,2) COMMENT '批准金额',
    paid_amount DECIMAL(12,2) COMMENT '赔付金额',
    submitted_at TIMESTAMP NULL COMMENT '提交时间',
    reviewed_at TIMESTAMP NULL COMMENT '审核时间',
    approved_at TIMESTAMP NULL COMMENT '批准时间',
    paid_at TIMESTAMP NULL COMMENT '赔付时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (insurance_id) REFERENCES insurance_applications(id) ON DELETE CASCADE,
    FOREIGN KEY (applicant_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (reviewer_id) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_insurance (insurance_id),
    INDEX idx_applicant (applicant_id),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='理赔申请表';
```

### 20. 政府监管报告表 (government_reports)
存储政府监管报告信息。

```sql
CREATE TABLE government_reports (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '报告ID',
    report_type ENUM('production', 'sales', 'disease', 'environment', 'finance') NOT NULL COMMENT '报告类型',
    reporter_id BIGINT UNSIGNED NOT NULL COMMENT '报告人ID',
    reporting_period_start DATE NOT NULL COMMENT '报告期开始日期',
    reporting_period_end DATE NOT NULL COMMENT '报告期结束日期',
    data_content JSON COMMENT '报告数据内容',
    summary TEXT COMMENT '摘要',
    status ENUM('draft', 'submitted', 'approved', 'rejected') DEFAULT 'draft' COMMENT '状态',
    approver_id BIGINT UNSIGNED COMMENT '审批人ID',
    approval_notes TEXT COMMENT '审批备注',
    submitted_at TIMESTAMP NULL COMMENT '提交时间',
    approved_at TIMESTAMP NULL COMMENT '审批时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (reporter_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_reporter (reporter_id),
    INDEX idx_type (report_type),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='政府监管报告表';
```

## 官网相关表设计

### 1. 官网首页配置表 (website_homepage)
存储官网首页的配置信息。

```sql
CREATE TABLE website_homepage (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '配置ID',
    section_name VARCHAR(50) NOT NULL COMMENT '板块名称',
    content_type ENUM('banner', 'video', 'text', 'link') NOT NULL COMMENT '内容类型',
    title VARCHAR(100) NOT NULL COMMENT '标题',
    subtitle VARCHAR(200) COMMENT '副标题',
    content TEXT COMMENT '内容',
    media_url VARCHAR(255) COMMENT '媒体文件URL（图片或视频）',
    link_url VARCHAR(255) COMMENT '链接地址',
    sort_order INT DEFAULT 0 COMMENT '排序顺序',
    is_active BOOLEAN DEFAULT TRUE COMMENT '是否启用',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    INDEX idx_section (section_name),
    INDEX idx_active (is_active),
    INDEX idx_sort (sort_order)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='官网首页配置表';
```

### 2. 新闻资讯表 (news_articles)
存储新闻资讯信息。

```sql
CREATE TABLE news_articles (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '新闻ID',
    title VARCHAR(150) NOT NULL COMMENT '标题',
    subtitle VARCHAR(200) COMMENT '副标题',
    content TEXT NOT NULL COMMENT '内容',
    author VARCHAR(50) COMMENT '作者',
    source VARCHAR(100) COMMENT '来源',
    cover_image VARCHAR(255) COMMENT '封面图片URL',
    is_featured BOOLEAN DEFAULT FALSE COMMENT '是否推荐',
    status ENUM('draft', 'published', 'archived') DEFAULT 'draft' COMMENT '状态',
    publish_date TIMESTAMP NULL COMMENT '发布时间',
    category VARCHAR(50) COMMENT '分类',
    views INT UNSIGNED DEFAULT 0 COMMENT '浏览量',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (author_id) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_status (status),
    INDEX idx_category (category),
    INDEX idx_publish_date (publish_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='新闻资讯表';
```

### 3. 政策公告表 (policy_announcements)
存储政策公告信息。

```sql
CREATE TABLE policy_announcements (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '公告ID',
    title VARCHAR(150) NOT NULL COMMENT '标题',
    content TEXT NOT NULL COMMENT '内容',
    issuer VARCHAR(100) NOT NULL COMMENT '发布机构',
    issue_date DATE NOT NULL COMMENT '发布日期',
    effective_date DATE COMMENT '生效日期',
    document_number VARCHAR(50) COMMENT '文号',
    attachment_url VARCHAR(255) COMMENT '附件URL',
    is_important BOOLEAN DEFAULT FALSE COMMENT '是否重要公告',
    status ENUM('draft', 'published', 'expired') DEFAULT 'draft' COMMENT '状态',
    views INT UNSIGNED DEFAULT 0 COMMENT '浏览量',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    INDEX idx_issue_date (issue_date),
    INDEX idx_status (status),
    INDEX idx_issuer (issuer)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='政策公告表';
```

## 数据库关系图

```
erDiagram
    users ||--o{ user_roles : has
    roles ||--o{ user_roles : includes
    roles ||--o{ role_permissions : has
    permissions ||--o{ role_permissions : includes
    users ||--o{ cattle : owns
    cattle ||--o{ feeding_records : has
    cattle ||--o{ breeding_records : has
    cattle ||--o{ transactions : involved_in
    users ||--o{ transactions : involved_in
    contracts ||--o{ transactions : related_to
    cattle ||--o{ products : related_to
    product_categories ||--o{ products : belongs_to
    users ||--o{ orders : places
    orders ||--o{ order_items : contains
    products ||--o{ order_items : contains
    cattle ||--o{ order_items : related_to
    orders ||--o{ logistics_tracking : has
    users ||--o{ loan_applications : applies
    users ||--o{ loan_applications : reviews
    cattle ||--o{ loan_applications : pledged
    users ||--o{ insurance_applications : applies
    users ||--o{ insurance_applications : underwrites
    cattle ||--o{ insurance_applications : insured
    insurance_applications ||--o{ claims : has
    users ||--o{ claims : applies
    users ||--o{ claims : reviews
    users ||--o{ government_reports : submits
    users ||--o{ government_reports : approves
    users ||--o{ news : authors
    users ||--o{ messages : processes

    users {
        BIGINT id PK
        VARCHAR username
        VARCHAR email
        VARCHAR phone
        VARCHAR password_hash
        VARCHAR real_name
        VARCHAR avatar_url
        ENUM user_type
        TINYINT status
        TIMESTAMP last_login
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    roles {
        INT id PK
        VARCHAR name
        TEXT description
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    user_roles {
        BIGINT id PK
        BIGINT user_id FK
        INT role_id FK
        TIMESTAMP created_at
    }
    
    permissions {
        INT id PK
        VARCHAR name
        TEXT description
        VARCHAR module
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    role_permissions {
        BIGINT id PK
        INT role_id FK
        INT permission_id FK
        TIMESTAMP created_at
    }
    
    cattle {
        BIGINT id PK
        VARCHAR ear_tag
        VARCHAR name
        VARCHAR breed
        ENUM gender
        DATE birth_date
        VARCHAR color
        DECIMAL weight
        ENUM health_status
        BIGINT owner_id FK
        VARCHAR farm_location
        ENUM status
        VARCHAR image_url
        VARCHAR qr_code_url
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    feeding_records {
        BIGINT id PK
        BIGINT cattle_id FK
        ENUM record_type
        VARCHAR feed_type
        DECIMAL feed_amount
        VARCHAR vaccine_name
        TEXT treatment_desc
        VARCHAR medicine_name
        VARCHAR dosage
        VARCHAR veterinarian
        DECIMAL cost
        DATE record_date
        TEXT notes
        BIGINT operator_id FK
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    breeding_records {
        BIGINT id PK
        BIGINT cattle_id FK
        ENUM breeding_method
        DATE breeding_date
        BIGINT breeding_male_id FK
        VARCHAR semen_code
        DATE expected_delivery_date
        DATE actual_delivery_date
        TINYINT calf_count
        JSON calf_ids
        ENUM breeding_result
        TEXT notes
        BIGINT operator_id FK
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    environment_monitoring {
        BIGINT id PK
        VARCHAR location
        DECIMAL temperature
        DECIMAL humidity
        VARCHAR air_quality
        DECIMAL ammonia_concentration
        DECIMAL carbon_dioxide
        DECIMAL noise_level
        DECIMAL light_intensity
        DATETIME monitoring_date
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    transactions {
        BIGINT id PK
        BIGINT cattle_id FK
        BIGINT seller_id FK
        BIGINT buyer_id FK
        ENUM transaction_type
        DECIMAL price
        VARCHAR currency
        DATETIME transaction_date
        BIGINT contract_id FK
        ENUM status
        ENUM payment_status
        ENUM delivery_status
        TEXT notes
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    contracts {
        BIGINT id PK
        VARCHAR contract_number
        BIGINT seller_id FK
        BIGINT buyer_id FK
        JSON cattle_details
        DECIMAL total_price
        VARCHAR currency
        DATE contract_date
        DATE effective_date
        DATE expiry_date
        TEXT payment_terms
        TEXT delivery_terms
        ENUM contract_status
        VARCHAR contract_file_url
        TEXT notes
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    products {
        BIGINT id PK
        VARCHAR name
        TEXT description
        INT category_id FK
        VARCHAR sku
        DECIMAL price
        DECIMAL original_price
        VARCHAR currency
        INT stock_quantity
        INT min_stock
        VARCHAR unit
        DECIMAL weight
        VARCHAR origin
        DATE production_date
        DATE expiration_date
        BIGINT cattle_id FK
        ENUM status
        JSON image_urls
        JSON tags
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    product_categories {
        INT id PK
        VARCHAR name
        INT parent_id
        TINYINT level
        INT sort_order
        VARCHAR image_url
        TINYINT status
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    orders {
        BIGINT id PK
        VARCHAR order_number
        BIGINT user_id FK
        DECIMAL total_amount
        VARCHAR currency
        ENUM order_status
        ENUM payment_status
        ENUM shipping_status
        VARCHAR receiver_name
        VARCHAR receiver_phone
        TEXT receiver_address
        VARCHAR shipping_method
        DECIMAL shipping_fee
        TEXT notes
        VARCHAR payment_method
        TIMESTAMP paid_at
        TIMESTAMP shipped_at
        TIMESTAMP delivered_at
        TIMESTAMP cancelled_at
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    order_items {
        BIGINT id PK
        BIGINT order_id FK
        BIGINT product_id FK
        INT quantity
        DECIMAL unit_price
        DECIMAL total_price
        BIGINT cattle_id FK
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    logistics_tracking {
        BIGINT id PK
        BIGINT order_id FK
        VARCHAR tracking_number
        VARCHAR carrier
        ENUM status
        VARCHAR origin
        VARCHAR destination
        DATE estimated_delivery_date
        DATE actual_delivery_date
        VARCHAR current_location
        JSON tracking_info
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    loan_applications {
        BIGINT id PK
        BIGINT applicant_id FK
        ENUM loan_type
        JSON cattle_ids
        DECIMAL loan_amount
        VARCHAR currency
        DECIMAL interest_rate
        INT term_months
        TEXT purpose
        ENUM repayment_method
        ENUM guarantee_type
        ENUM status
        BIGINT reviewer_id FK
        TEXT review_notes
        DECIMAL approved_amount
        TIMESTAMP approved_date
        TIMESTAMP disbursement_date
        JSON repayment_schedule
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    insurance_applications {
        BIGINT id PK
        BIGINT applicant_id FK
        ENUM insurance_type
        JSON cattle_ids
        VARCHAR policy_number
        DECIMAL insured_amount
        DECIMAL premium
        VARCHAR currency
        DATE start_date
        DATE end_date
        ENUM status
        BIGINT underwriter_id FK
        TEXT underwriting_notes
        VARCHAR policy_file_url
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    claims {
        BIGINT id PK
        BIGINT insurance_id FK
        BIGINT applicant_id FK
        DECIMAL claim_amount
        VARCHAR currency
        DATE incident_date
        ENUM incident_type
        TEXT description
        JSON evidence_files
        ENUM status
        BIGINT reviewer_id FK
        TEXT review_notes
        DECIMAL approved_amount
        DECIMAL paid_amount
        TIMESTAMP submitted_at
        TIMESTAMP reviewed_at
        TIMESTAMP approved_at
        TIMESTAMP paid_at
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    government_reports {
        BIGINT id PK
        ENUM report_type
        BIGINT reporter_id FK
        DATE reporting_period_start
        DATE reporting_period_end
        JSON data_content
        TEXT summary
        ENUM status
        BIGINT approver_id FK
        TEXT approval_notes
        TIMESTAMP submitted_at
        TIMESTAMP approved_at
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    news {
        BIGINT id PK
        VARCHAR title
        TEXT summary
        LONGTEXT content
        ENUM category
        VARCHAR image_url
        BIGINT author_id FK
        INT views
        ENUM status
        TIMESTAMP published_at
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
    
    messages {
        BIGINT id PK
        VARCHAR name
        VARCHAR email
        VARCHAR phone
        TEXT content
        ENUM status
        BIGINT processed_by FK
        TIMESTAMP processed_at
        TIMESTAMP created_at
        TIMESTAMP updated_at
    }
```

### 21. 新闻资讯表 (news)
存储官网新闻资讯信息。

```sql
CREATE TABLE news (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '新闻ID',
    title VARCHAR(200) NOT NULL COMMENT '标题',
    summary TEXT COMMENT '摘要',
    content LONGTEXT NOT NULL COMMENT '内容',
    category ENUM('policy', 'market', 'technology', 'general') NOT NULL COMMENT '分类: 政策解读/市场动态/技术前沿/综合',
    image_url VARCHAR(255) COMMENT '封面图片URL',
    author_id BIGINT UNSIGNED COMMENT '作者ID',
    views INT DEFAULT 0 COMMENT '浏览量',
    status ENUM('draft', 'published', 'archived') DEFAULT 'draft' COMMENT '状态: 草稿/已发布/已归档',
    published_at TIMESTAMP NULL COMMENT '发布时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (author_id) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_category (category),
    INDEX idx_status (status),
    INDEX idx_published_at (published_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='新闻资讯表';
```

### 22. 用户留言表 (messages)
存储用户在官网提交的留言信息。

```sql
CREATE TABLE messages (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '留言ID',
    name VARCHAR(50) NOT NULL COMMENT '姓名',
    email VARCHAR(100) NOT NULL COMMENT '邮箱',
    phone VARCHAR(20) COMMENT '电话',
    content TEXT NOT NULL COMMENT '留言内容',
    status ENUM('pending', 'processed', 'archived') DEFAULT 'pending' COMMENT '状态: 待处理/已处理/已归档',
    processed_by BIGINT UNSIGNED COMMENT '处理人ID',
    processed_at TIMESTAMP NULL COMMENT '处理时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (processed_by) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_status (status),
    INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户留言表';
```