-- ======================================
-- 锡林郭勒盟智慧养殖数字化管理平台数据库表结构
-- ======================================

-- 用户表
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username VARCHAR(50) NOT NULL UNIQUE,
    phone VARCHAR(20) NOT NULL UNIQUE,
    email VARCHAR(100) UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    salt VARCHAR(32) NOT NULL,
    avatar VARCHAR(255),
    real_name VARCHAR(50),
    id_card VARCHAR(18),
    gender INTEGER, -- 1-男，2-女
    birthday DATE,
    address VARCHAR(255),
    status INTEGER NOT NULL DEFAULT 1, -- 0-禁用，1-正常
    user_type VARCHAR(20) DEFAULT 'farmer', -- farmer, trader, consumer, finance, government
    last_login_at DATETIME,
    last_login_ip VARCHAR(45),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    deleted_at DATETIME
);

-- 牛只表
CREATE TABLE IF NOT EXISTS cattle (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    ear_tag VARCHAR(50) NOT NULL UNIQUE,
    name VARCHAR(100),
    breed VARCHAR(50) NOT NULL,
    gender VARCHAR(10) NOT NULL, -- male, female
    birth_date DATE,
    color VARCHAR(50),
    weight DECIMAL(8,2),
    height DECIMAL(6,2),
    health_status VARCHAR(20) DEFAULT 'healthy', -- healthy, sick, quarantine, dead
    status VARCHAR(20) DEFAULT 'active', -- active, sold, dead, transferred
    owner_id INTEGER NOT NULL,
    farm_location VARCHAR(255),
    parent_male_id INTEGER,
    parent_female_id INTEGER,
    vaccination_records TEXT, -- JSON格式
    health_records TEXT, -- JSON格式
    feeding_records TEXT, -- JSON格式
    images TEXT, -- JSON格式的图片URLs
    notes TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (owner_id) REFERENCES users(id),
    FOREIGN KEY (parent_male_id) REFERENCES cattle(id),
    FOREIGN KEY (parent_female_id) REFERENCES cattle(id)
);

-- 交易表
CREATE TABLE IF NOT EXISTS transactions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    transaction_no VARCHAR(50) NOT NULL UNIQUE,
    buyer_id INTEGER NOT NULL,
    seller_id INTEGER NOT NULL,
    product_type VARCHAR(20) NOT NULL, -- cattle, product
    product_id INTEGER NOT NULL,
    quantity INTEGER NOT NULL DEFAULT 1,
    unit_price DECIMAL(12,2) NOT NULL,
    total_amount DECIMAL(12,2) NOT NULL,
    currency VARCHAR(10) DEFAULT 'CNY',
    status VARCHAR(20) DEFAULT 'pending', -- pending, confirmed, completed, cancelled
    payment_status VARCHAR(20) DEFAULT 'pending', -- pending, paid, partial, refunded
    payment_method VARCHAR(20), -- wechat_pay, alipay, bank_transfer, cash
    delivery_status VARCHAR(20) DEFAULT 'pending', -- pending, shipped, delivered, received
    delivery_method VARCHAR(20), -- self_pickup, express, logistics
    delivery_address TEXT,
    delivery_phone VARCHAR(20),
    delivery_contact VARCHAR(50),
    contract_url VARCHAR(255),
    notes TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (buyer_id) REFERENCES users(id),
    FOREIGN KEY (seller_id) REFERENCES users(id)
);

-- 商品表（牛肉商城）
CREATE TABLE IF NOT EXISTS products (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name VARCHAR(200) NOT NULL,
    sku VARCHAR(50) UNIQUE,
    category VARCHAR(50) NOT NULL, -- beef, dairy, snacks, processed, equipment, feed
    subcategory VARCHAR(50),
    description TEXT,
    price DECIMAL(10,2) NOT NULL,
    original_price DECIMAL(10,2),
    cost_price DECIMAL(10,2),
    currency VARCHAR(10) DEFAULT 'CNY',
    stock INTEGER DEFAULT 0,
    sales_count INTEGER DEFAULT 0,
    weight DECIMAL(8,3),
    dimensions VARCHAR(100),
    shelf_life INTEGER, -- 保质期(天)
    storage_conditions VARCHAR(200),
    origin VARCHAR(100),
    brand VARCHAR(100),
    specifications TEXT, -- JSON格式的规格参数
    images TEXT, -- JSON格式的图片URLs
    video_url VARCHAR(255),
    seller_id INTEGER NOT NULL,
    status VARCHAR(20) DEFAULT 'pending_review', -- active, inactive, out_of_stock, pending_review, rejected
    featured INTEGER DEFAULT 0,
    rating DECIMAL(3,2) DEFAULT 0,
    review_count INTEGER DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (seller_id) REFERENCES users(id)
);

-- 订单表
CREATE TABLE IF NOT EXISTS orders (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    order_number VARCHAR(50) UNIQUE NOT NULL,
    user_id INTEGER NOT NULL,
    order_type VARCHAR(20) DEFAULT 'normal', -- normal, group_buy, presale, custom
    total_amount DECIMAL(12,2) NOT NULL,
    discount_amount DECIMAL(12,2) DEFAULT 0,
    shipping_fee DECIMAL(10,2) DEFAULT 0,
    tax_amount DECIMAL(10,2) DEFAULT 0,
    final_amount DECIMAL(12,2) NOT NULL,
    currency VARCHAR(10) DEFAULT 'CNY',
    payment_method VARCHAR(20), -- wechat_pay, alipay, bank_transfer, cash_on_delivery
    payment_status VARCHAR(20) DEFAULT 'pending', -- pending, paid, partial, refunded, failed
    shipping_method VARCHAR(20), -- express, self_pickup, same_city
    shipping_address TEXT,
    shipping_phone VARCHAR(20),
    shipping_name VARCHAR(50),
    tracking_number VARCHAR(100),
    status VARCHAR(20) DEFAULT 'pending_payment', -- pending_payment, paid, processing, shipping, delivered, completed, cancelled, refunded
    coupon_code VARCHAR(50),
    notes TEXT,
    order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
    payment_date DATETIME,
    shipping_date DATETIME,
    delivery_date DATETIME,
    completion_date DATETIME,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

-- 订单商品表
CREATE TABLE IF NOT EXISTS order_items (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    order_id INTEGER NOT NULL,
    product_id INTEGER NOT NULL,
    product_name VARCHAR(200) NOT NULL, -- 商品名称快照
    product_sku VARCHAR(50),
    product_image VARCHAR(255),
    unit_price DECIMAL(10,2) NOT NULL,
    quantity INTEGER NOT NULL,
    total_price DECIMAL(12,2) NOT NULL,
    currency VARCHAR(10) DEFAULT 'CNY',
    specifications TEXT, -- JSON格式的规格参数快照
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products(id)
);

-- 金融服务表
CREATE TABLE IF NOT EXISTS financial_services (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    service_type VARCHAR(20) NOT NULL, -- loan, insurance, investment
    service_name VARCHAR(100) NOT NULL,
    provider VARCHAR(100) NOT NULL,
    description TEXT,
    interest_rate DECIMAL(5,4), -- 利率
    min_amount DECIMAL(12,2),
    max_amount DECIMAL(12,2),
    term_months INTEGER, -- 期限(月)
    requirements TEXT, -- JSON格式的申请要求
    documents_required TEXT, -- JSON格式的所需文档
    status VARCHAR(20) DEFAULT 'active', -- active, inactive, suspended
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- 金融申请表
CREATE TABLE IF NOT EXISTS financial_applications (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    application_no VARCHAR(50) NOT NULL UNIQUE,
    user_id INTEGER NOT NULL,
    service_id INTEGER NOT NULL,
    application_type VARCHAR(20) NOT NULL, -- loan, insurance, investment
    amount DECIMAL(12,2) NOT NULL,
    term_months INTEGER,
    purpose TEXT,
    collateral_info TEXT, -- JSON格式的抵押物信息
    documents TEXT, -- JSON格式的文档URLs
    status VARCHAR(20) DEFAULT 'pending', -- pending, reviewing, approved, rejected, completed
    reviewer_id INTEGER,
    review_notes TEXT,
    approval_date DATETIME,
    disbursement_date DATETIME,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (service_id) REFERENCES financial_services(id),
    FOREIGN KEY (reviewer_id) REFERENCES users(id)
);

-- 政府监管记录表
CREATE TABLE IF NOT EXISTS government_inspections (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    inspection_no VARCHAR(50) NOT NULL UNIQUE,
    inspector_id INTEGER NOT NULL,
    farm_id INTEGER NOT NULL,
    inspection_type VARCHAR(20) NOT NULL, -- health, safety, environment, quality
    inspection_date DATE NOT NULL,
    status VARCHAR(20) DEFAULT 'scheduled', -- scheduled, in_progress, completed, cancelled
    findings TEXT, -- JSON格式的检查结果
    violations TEXT, -- JSON格式的违规记录
    recommendations TEXT,
    follow_up_required INTEGER DEFAULT 0, -- 0-否，1-是
    follow_up_date DATE,
    documents TEXT, -- JSON格式的文档URLs
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (inspector_id) REFERENCES users(id),
    FOREIGN KEY (farm_id) REFERENCES users(id)
);

-- 系统日志表
CREATE TABLE IF NOT EXISTS system_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER,
    action VARCHAR(50) NOT NULL,
    resource VARCHAR(50),
    resource_id INTEGER,
    ip_address VARCHAR(45),
    user_agent TEXT,
    request_data TEXT, -- JSON格式
    response_data TEXT, -- JSON格式
    status_code INTEGER,
    execution_time INTEGER, -- 毫秒
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

-- 创建索引
CREATE INDEX IF NOT EXISTS idx_users_phone ON users(phone);
CREATE INDEX IF NOT EXISTS idx_users_status ON users(status);
CREATE INDEX IF NOT EXISTS idx_users_user_type ON users(user_type);

CREATE INDEX IF NOT EXISTS idx_cattle_ear_tag ON cattle(ear_tag);
CREATE INDEX IF NOT EXISTS idx_cattle_owner_id ON cattle(owner_id);
CREATE INDEX IF NOT EXISTS idx_cattle_status ON cattle(status);
CREATE INDEX IF NOT EXISTS idx_cattle_breed ON cattle(breed);

CREATE INDEX IF NOT EXISTS idx_transactions_buyer_id ON transactions(buyer_id);
CREATE INDEX IF NOT EXISTS idx_transactions_seller_id ON transactions(seller_id);
CREATE INDEX IF NOT EXISTS idx_transactions_status ON transactions(status);
CREATE INDEX IF NOT EXISTS idx_transactions_created_at ON transactions(created_at);

CREATE INDEX IF NOT EXISTS idx_products_category ON products(category);
CREATE INDEX IF NOT EXISTS idx_products_seller_id ON products(seller_id);
CREATE INDEX IF NOT EXISTS idx_products_status ON products(status);

CREATE INDEX IF NOT EXISTS idx_orders_user_id ON orders(user_id);
CREATE INDEX IF NOT EXISTS idx_orders_status ON orders(status);
CREATE INDEX IF NOT EXISTS idx_orders_order_date ON orders(order_date);

CREATE INDEX IF NOT EXISTS idx_financial_applications_user_id ON financial_applications(user_id);
CREATE INDEX IF NOT EXISTS idx_financial_applications_status ON financial_applications(status);

CREATE INDEX IF NOT EXISTS idx_government_inspections_inspector_id ON government_inspections(inspector_id);
CREATE INDEX IF NOT EXISTS idx_government_inspections_farm_id ON government_inspections(farm_id);
CREATE INDEX IF NOT EXISTS idx_government_inspections_inspection_date ON government_inspections(inspection_date);

CREATE INDEX IF NOT EXISTS idx_system_logs_user_id ON system_logs(user_id);
CREATE INDEX IF NOT EXISTS idx_system_logs_action ON system_logs(action);
CREATE INDEX IF NOT EXISTS idx_system_logs_created_at ON system_logs(created_at);