-- 社区生鲜团购系统数据库结构
-- 说明：本脚本只负责数据库对象定义，不包含演示数据。

CREATE DATABASE IF NOT EXISTS flash_sale_db
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

USE flash_sale_db;

-- ================================
-- 1. 用户表
-- ================================
CREATE TABLE IF NOT EXISTS users (
    id         BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '用户ID',
    username   VARCHAR(50)  NOT NULL UNIQUE COMMENT '用户名',
    password   VARCHAR(255) NOT NULL COMMENT '密码（加密）',
    email      VARCHAR(100) COMMENT '邮箱',
    phone      VARCHAR(20) COMMENT '手机号',
    avatar     VARCHAR(500) COMMENT '头像',
    role       VARCHAR(20)  NOT NULL DEFAULT 'USER' COMMENT '角色：ADMIN/USER',
    status     TINYINT      NOT NULL DEFAULT 1 COMMENT '状态：1-正常，0-禁用',
    last_login TIMESTAMP NULL COMMENT '最后登录时间',
    created_at TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX idx_users_username (username),
    INDEX idx_users_email (email),
    INDEX idx_users_phone (phone),
    INDEX idx_users_status (status),
    INDEX idx_users_created_at (created_at)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT ='用户表';

-- ================================
-- 2. 商品表
-- ================================
CREATE TABLE IF NOT EXISTS products (
    id          BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '商品ID',
    name        VARCHAR(200)   NOT NULL COMMENT '商品名称',
    description TEXT COMMENT '商品描述',
    price       DECIMAL(10, 2) NOT NULL COMMENT '商品价格',
    category    VARCHAR(100) COMMENT '商品分类',
    stock       INT            NOT NULL DEFAULT 0 COMMENT '库存数量',
    image_url   VARCHAR(500) COMMENT '商品图片URL',
    status      TINYINT        NOT NULL DEFAULT 1 COMMENT '状态：1-上架，0-下架',
    created_at  TIMESTAMP      NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at  TIMESTAMP      NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX idx_products_name (name),
    INDEX idx_products_category (category),
    INDEX idx_products_price (price),
    INDEX idx_products_stock (stock),
    INDEX idx_products_status (status),
    INDEX idx_products_created_at (created_at)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT ='商品表';

-- ================================
-- 3. 秒杀活动表
-- ================================
CREATE TABLE IF NOT EXISTS flash_sales (
    id          BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '秒杀活动ID',
    product_id  BIGINT         NOT NULL COMMENT '商品ID',
    flash_price DECIMAL(10, 2) NOT NULL COMMENT '秒杀价格',
    flash_stock INT            NOT NULL COMMENT '秒杀库存',
    start_time  TIMESTAMP      NOT NULL COMMENT '开始时间',
    end_time    TIMESTAMP      NOT NULL COMMENT '结束时间',
    status      TINYINT        NOT NULL DEFAULT 1 COMMENT '状态：1-未开始，2-进行中，3-已结束',
    created_at  TIMESTAMP      NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at  TIMESTAMP      NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    CONSTRAINT fk_flash_sales_product FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE,
    INDEX idx_flash_sales_product_id (product_id),
    INDEX idx_flash_sales_start_time (start_time),
    INDEX idx_flash_sales_end_time (end_time),
    INDEX idx_flash_sales_status (status),
    INDEX idx_flash_sales_created_at (created_at)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT ='秒杀活动表';

-- ================================
-- 4. 订单主表
-- ================================
CREATE TABLE IF NOT EXISTS orders (
    id               BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '订单ID',
    order_no         VARCHAR(64)    NOT NULL UNIQUE COMMENT '订单号',
    group_no         VARCHAR(64) COMMENT '聚合订单号（兼容旧数据）',
    user_id          BIGINT         NOT NULL COMMENT '用户ID',
    product_id       BIGINT         NOT NULL COMMENT '兼容字段：主商品ID',
    flash_sale_id    BIGINT COMMENT '秒杀活动ID',
    group_buying_group_id BIGINT COMMENT '拼团团组ID',
    quantity         INT            NOT NULL DEFAULT 1 COMMENT '兼容字段：总购买数量',
    total_price      DECIMAL(10, 2) NOT NULL COMMENT '订单总价',
    status           TINYINT        NOT NULL DEFAULT 1 COMMENT '状态：1-待支付，2-已支付，3-已发货，4-已完成，5-已取消',
    order_type       TINYINT        NOT NULL DEFAULT 1 COMMENT '订单类型：1-普通订单，2-秒杀订单',
    receiver_name    VARCHAR(100) COMMENT '收货人',
    receiver_phone   VARCHAR(20) COMMENT '收货手机号',
    receiver_address VARCHAR(255) COMMENT '收货地址',
    remark           VARCHAR(255) COMMENT '订单备注',
    payment_method   VARCHAR(50) COMMENT '支付方式',
    paid_at          TIMESTAMP NULL COMMENT '支付时间',
    shipped_at       TIMESTAMP NULL COMMENT '发货时间',
    completed_at     TIMESTAMP NULL COMMENT '完成时间',
    created_at       TIMESTAMP      NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at       TIMESTAMP      NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    CONSTRAINT fk_orders_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
    CONSTRAINT fk_orders_product FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE,
    INDEX idx_orders_order_no (order_no),
    INDEX idx_orders_group_no (group_no),
    INDEX idx_orders_user_id (user_id),
    INDEX idx_orders_product_id (product_id),
    INDEX idx_orders_flash_sale_id (flash_sale_id),
    INDEX idx_orders_status (status),
    INDEX idx_orders_order_type (order_type),
    INDEX idx_orders_created_at (created_at)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT ='订单主表';

-- ================================
-- 5. 订单明细表
-- ================================
CREATE TABLE IF NOT EXISTS order_items (
    id                BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '明细ID',
    order_id          BIGINT         NOT NULL COMMENT '主订单ID',
    product_id        BIGINT         NOT NULL COMMENT '商品ID',
    product_name      VARCHAR(200)   NOT NULL COMMENT '商品名称快照',
    product_image_url VARCHAR(500) COMMENT '商品图片快照',
    price             DECIMAL(10, 2) NOT NULL COMMENT '下单单价',
    quantity          INT            NOT NULL COMMENT '购买数量',
    subtotal          DECIMAL(10, 2) NOT NULL COMMENT '小计',
    created_at        TIMESTAMP      NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    CONSTRAINT fk_order_items_order FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE,
    CONSTRAINT fk_order_items_product FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE,
    INDEX idx_order_items_order_id (order_id),
    INDEX idx_order_items_product_id (product_id)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT ='订单明细表';

-- ================================
-- 6. 用户地址表
-- ================================
CREATE TABLE IF NOT EXISTS user_addresses (
    id         BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '地址ID',
    user_id    BIGINT       NOT NULL COMMENT '用户ID',
    name       VARCHAR(100) NOT NULL COMMENT '收货人',
    phone      VARCHAR(20)  NOT NULL COMMENT '手机号',
    province   VARCHAR(50) COMMENT '省份',
    city       VARCHAR(50) COMMENT '城市',
    district   VARCHAR(50) COMMENT '区县',
    address    VARCHAR(255) NOT NULL COMMENT '详细地址',
    is_default TINYINT      NOT NULL DEFAULT 0 COMMENT '是否默认地址',
    created_at TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    CONSTRAINT fk_user_addresses_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
    INDEX idx_user_addresses_user_id (user_id),
    INDEX idx_user_addresses_default (is_default)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT ='用户地址表';

-- ================================
-- 7. 商品评价表
-- ================================
CREATE TABLE IF NOT EXISTS product_reviews (
    id          BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '评价ID',
    product_id  BIGINT  NOT NULL COMMENT '商品ID',
    user_id     BIGINT  NOT NULL COMMENT '用户ID',
    order_id    BIGINT  NOT NULL COMMENT '订单ID',
    rating      TINYINT NOT NULL DEFAULT 5 COMMENT '评分',
    content     TEXT    NOT NULL COMMENT '评价内容',
    status      TINYINT NOT NULL DEFAULT 1 COMMENT '状态：1-显示，0-隐藏',
    admin_reply TEXT COMMENT '管理员回复',
    replied_at  TIMESTAMP NULL COMMENT '回复时间',
    created_at  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    CONSTRAINT fk_product_reviews_product FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE,
    CONSTRAINT fk_product_reviews_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
    CONSTRAINT fk_product_reviews_order FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE,
    UNIQUE KEY uk_review_order_user_product (order_id, user_id, product_id),
    INDEX idx_product_reviews_product_id (product_id),
    INDEX idx_product_reviews_user_id (user_id),
    INDEX idx_product_reviews_status (status)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT ='商品评价表';

-- ================================
-- 8. 用户收藏表
-- ================================
CREATE TABLE IF NOT EXISTS user_favorites (
    id         BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '收藏ID',
    user_id    BIGINT NOT NULL COMMENT '用户ID',
    product_id BIGINT NOT NULL COMMENT '商品ID',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    CONSTRAINT fk_user_favorites_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
    CONSTRAINT fk_user_favorites_product FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE,
    UNIQUE KEY uk_favorite_user_product (user_id, product_id),
    INDEX idx_user_favorites_user_id (user_id),
    INDEX idx_user_favorites_product_id (product_id)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT ='用户收藏表';

-- ================================
-- 9. 视图
-- ================================
-- ================================
-- 9. 拼团活动表
-- ================================
CREATE TABLE IF NOT EXISTS group_buying (
    id               BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '拼团活动ID',
    product_id       BIGINT         NOT NULL COMMENT '商品ID',
    group_price      DECIMAL(10, 2) NOT NULL COMMENT '拼团价格',
    required_members INT            NOT NULL DEFAULT 2 COMMENT '成团人数',
    duration_minutes INT            NOT NULL DEFAULT 1440 COMMENT '拼团有效期（分钟）',
    total_stock      INT            NOT NULL COMMENT '总库存',
    remaining_stock  INT            NOT NULL COMMENT '剩余库存',
    max_per_user     INT            NOT NULL DEFAULT 1 COMMENT '每人限购',
    status           TINYINT        NOT NULL DEFAULT 0 COMMENT '状态：0-草稿 1-未开始 2-进行中 3-已结束',
    start_time       DATETIME       NOT NULL COMMENT '开始时间',
    end_time         DATETIME       NOT NULL COMMENT '结束时间',
    created_at       TIMESTAMP      NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at       TIMESTAMP      NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    CONSTRAINT fk_group_buying_product FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE,
    INDEX idx_group_buying_product_id (product_id),
    INDEX idx_group_buying_status (status),
    INDEX idx_group_buying_start_time (start_time),
    INDEX idx_group_buying_end_time (end_time)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT ='拼团活动表';

-- ================================
-- 10. 拼团团组表
-- ================================
CREATE TABLE IF NOT EXISTS group_buying_group (
    id               BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '团组ID',
    group_no         VARCHAR(64)  NOT NULL UNIQUE COMMENT '团号',
    group_buying_id  BIGINT       NOT NULL COMMENT '关联拼团活动',
    leader_user_id   BIGINT       NOT NULL COMMENT '团长用户ID',
    required_members INT          NOT NULL COMMENT '需要人数',
    current_members  INT          NOT NULL DEFAULT 1 COMMENT '当前人数',
    status           TINYINT      NOT NULL DEFAULT 1 COMMENT '状态：1-拼团中 2-已成团 3-已失败(超时)',
    expire_time      DATETIME     NOT NULL COMMENT '过期时间',
    created_at       TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    completed_at     TIMESTAMP NULL COMMENT '成团时间',
    CONSTRAINT fk_gbg_group_buying FOREIGN KEY (group_buying_id) REFERENCES group_buying (id) ON DELETE CASCADE,
    CONSTRAINT fk_gbg_leader FOREIGN KEY (leader_user_id) REFERENCES users (id) ON DELETE CASCADE,
    INDEX idx_gbg_group_no (group_no),
    INDEX idx_gbg_group_buying_id (group_buying_id),
    INDEX idx_gbg_status (status),
    INDEX idx_gbg_expire_time (expire_time)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT ='拼团团组表';

-- ================================
-- 11. 拼团成员表
-- ================================
CREATE TABLE IF NOT EXISTS group_buying_member (
    id        BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '成员ID',
    group_id  BIGINT    NOT NULL COMMENT '关联团组',
    user_id   BIGINT    NOT NULL COMMENT '用户ID',
    order_id  BIGINT COMMENT '关联订单',
    status    TINYINT   NOT NULL DEFAULT 1 COMMENT '状态：1-已加入 2-已成团 3-已退出',
    joined_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '加入时间',
    CONSTRAINT fk_gbm_group FOREIGN KEY (group_id) REFERENCES group_buying_group (id) ON DELETE CASCADE,
    CONSTRAINT fk_gbm_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
    UNIQUE KEY uk_group_user (group_id, user_id),
    INDEX idx_gbm_group_id (group_id),
    INDEX idx_gbm_user_id (user_id),
    INDEX idx_gbm_order_id (order_id)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT ='拼团成员表';

-- ================================
-- 12. 视图
-- ================================
CREATE OR REPLACE VIEW active_flash_sales AS
SELECT fs.id,
       fs.product_id,
       p.name AS product_name,
       p.price AS original_price,
       fs.flash_price,
       fs.flash_stock,
       fs.start_time,
       fs.end_time,
       fs.status,
       p.image_url
FROM flash_sales fs
JOIN products p ON fs.product_id = p.id
WHERE fs.status = 2
  AND fs.start_time <= NOW()
  AND fs.end_time > NOW()
  AND p.status = 1;

CREATE OR REPLACE VIEW order_statistics AS
SELECT DATE(created_at) AS order_date,
       COUNT(*) AS total_orders,
       SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS pending_orders,
       SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) AS paid_orders,
       SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) AS completed_orders,
       SUM(CASE WHEN order_type = 2 THEN 1 ELSE 0 END) AS flash_sale_orders,
       SUM(total_price) AS total_amount
FROM orders
GROUP BY DATE(created_at)
ORDER BY order_date DESC;
