-- ======================================
-- 商城管理系统数据库表结构
-- ======================================

-- 商品分类表
CREATE TABLE IF NOT EXISTS product_categories (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name VARCHAR(50) NOT NULL,
    parent_id INTEGER DEFAULT 0,
    level INTEGER DEFAULT 1,
    sort_order INTEGER DEFAULT 0,
    image_url VARCHAR(255),
    status INTEGER DEFAULT 1, -- 1-正常, 0-禁用
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- 商品表
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', 'other'
    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,
    seo_title VARCHAR(200),
    seo_description TEXT,
    seo_keywords VARCHAR(500),
    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 product_reviews (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    product_id INTEGER NOT NULL,
    order_id INTEGER NOT NULL,
    user_id INTEGER NOT NULL,
    rating INTEGER NOT NULL, -- 评分(1-5)
    content TEXT,
    images TEXT, -- JSON格式的评价图片URLs
    helpful_count INTEGER DEFAULT 0,
    reply_content TEXT, -- 商家回复
    status VARCHAR(20) DEFAULT 'active', -- 'active', 'hidden', 'deleted'
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE,
    FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

-- 购物车表
CREATE TABLE IF NOT EXISTS shopping_cart (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    product_id INTEGER NOT NULL,
    quantity INTEGER NOT NULL DEFAULT 1,
    specifications TEXT, -- JSON格式的选择规格
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE,
    UNIQUE(user_id, product_id)
);

-- 优惠券表
CREATE TABLE IF NOT EXISTS coupons (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    code VARCHAR(50) UNIQUE NOT NULL,
    name VARCHAR(100) NOT NULL,
    type VARCHAR(20) NOT NULL, -- 'fixed', 'percentage'
    value DECIMAL(10,2) NOT NULL,
    min_amount DECIMAL(10,2) DEFAULT 0, -- 最低消费金额
    max_discount DECIMAL(10,2), -- 最大优惠金额(百分比优惠券)
    usage_limit INTEGER DEFAULT 1, -- 使用次数限制
    used_count INTEGER DEFAULT 0, -- 已使用次数
    user_limit INTEGER DEFAULT 1, -- 每用户使用次数限制
    start_date DATETIME,
    end_date DATETIME,
    status VARCHAR(20) DEFAULT 'active', -- 'active', 'inactive', 'expired'
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- 用户优惠券使用记录表
CREATE TABLE IF NOT EXISTS user_coupon_usage (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    coupon_id INTEGER NOT NULL,
    order_id INTEGER,
    used_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (coupon_id) REFERENCES coupons(id) ON DELETE CASCADE,
    FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE SET NULL
);

-- 创建索引
CREATE INDEX IF NOT EXISTS idx_products_category ON products(category);
CREATE INDEX IF NOT EXISTS idx_products_seller ON products(seller_id);
CREATE INDEX IF NOT EXISTS idx_products_status ON products(status);
CREATE INDEX IF NOT EXISTS idx_products_featured ON products(featured);

CREATE INDEX IF NOT EXISTS idx_orders_user ON orders(user_id);
CREATE INDEX IF NOT EXISTS idx_orders_status ON orders(status);
CREATE INDEX IF NOT EXISTS idx_orders_payment_status ON orders(payment_status);
CREATE INDEX IF NOT EXISTS idx_orders_order_date ON orders(order_date);

CREATE INDEX IF NOT EXISTS idx_order_items_order ON order_items(order_id);
CREATE INDEX IF NOT EXISTS idx_order_items_product ON order_items(product_id);

CREATE INDEX IF NOT EXISTS idx_reviews_product ON product_reviews(product_id);
CREATE INDEX IF NOT EXISTS idx_reviews_user ON product_reviews(user_id);
CREATE INDEX IF NOT EXISTS idx_reviews_rating ON product_reviews(rating);

CREATE INDEX IF NOT EXISTS idx_cart_user ON shopping_cart(user_id);
CREATE INDEX IF NOT EXISTS idx_cart_product ON shopping_cart(product_id);

-- 插入初始商品分类数据
INSERT OR IGNORE INTO product_categories (id, name, parent_id, level, sort_order) VALUES
(1, '牛肉制品', 0, 1, 1),
(2, '乳制品', 0, 1, 2),
(3, '休闲食品', 0, 1, 3),
(4, '设备用品', 0, 1, 4),
(5, '饲料用品', 0, 1, 5),
(11, '新鲜牛肉', 1, 2, 1),
(12, '牛肉干', 1, 2, 2),
(13, '牛肉罐头', 1, 2, 3),
(21, '鲜奶', 2, 2, 1),
(22, '酸奶', 2, 2, 2),
(23, '奶粉', 2, 2, 3);

-- 插入示例商品数据
INSERT OR IGNORE INTO products (id, name, sku, category, description, price, original_price, stock, seller_id, status, featured, images, origin) VALUES
(1, '优质牛肉礼盒装', 'BEEF001', 'beef', '来自锡林浩特优质牧场的新鲜牛肉，肉质鲜美，营养丰富', 268.00, 298.00, 45, 1, 'active', 1, '["https://example.com/beef1.jpg"]', '内蒙古锡林浩特'),
(2, '有机牛奶', 'MILK001', 'dairy', '纯天然有机牛奶，无添加剂，营养价值高', 25.80, 28.00, 120, 1, 'active', 1, '["https://example.com/milk1.jpg"]', '内蒙古呼伦贝尔'),
(3, '手工牛肉干', 'JERKY001', 'beef', '传统工艺制作，口感醇厚，便于携带', 58.00, 68.00, 80, 1, 'active', 0, '["https://example.com/jerky1.jpg"]', '内蒙古阿拉善'),
(4, '牧场酸奶', 'YOGURT001', 'dairy', '新鲜牧场奶源，益生菌发酵，口感顺滑', 12.50, 15.00, 200, 1, 'active', 1, '["https://example.com/yogurt1.jpg"]', '内蒙古锡林郭勒'),
(5, '精选牛排', 'STEAK001', 'beef', '优质牛排，适合煎烤，肉质鲜嫩', 128.00, 148.00, 30, 1, 'active', 1, '["https://example.com/steak1.jpg"]', '内蒙古通辽');

-- 插入示例优惠券数据
INSERT OR IGNORE INTO coupons (id, code, name, type, value, min_amount, usage_limit, start_date, end_date, status) VALUES
(1, 'WELCOME10', '新用户优惠券', 'fixed', 10.00, 50.00, 1000, '2024-01-01 00:00:00', '2024-12-31 23:59:59', 'active'),
(2, 'SAVE20', '满200减20', 'fixed', 20.00, 200.00, 500, '2024-01-01 00:00:00', '2024-12-31 23:59:59', 'active'),
(3, 'PERCENT5', '95折优惠', 'percentage', 5.00, 100.00, 300, '2024-01-01 00:00:00', '2024-12-31 23:59:59', 'active');

SELECT '商城数据库表创建完成！' AS message;