-- ============================================================
-- 酒店民宿短租预订平台 - 数据库初始化脚本
-- ============================================================

CREATE DATABASE IF NOT EXISTS `rent_platform` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE `rent_platform`;

-- ============================================================
-- 1. 用户表
-- ============================================================
CREATE TABLE `users` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `phone` VARCHAR(20) NULL COMMENT '手机号',
  `password` VARCHAR(255) DEFAULT NULL COMMENT '密码(AES加密存储)',
  `wechat_openid` VARCHAR(100) NULL COMMENT '微信openid',
  `wechat_unionid` VARCHAR(100) NULL COMMENT '微信unionid',
  `nickname` VARCHAR(50) DEFAULT '' COMMENT '昵称',
  `avatar` VARCHAR(500) DEFAULT '' COMMENT '头像URL',
  `gender` TINYINT UNSIGNED DEFAULT 0 COMMENT '性别 0-未知 1-男 2-女',
  `real_name` VARCHAR(50) DEFAULT NULL COMMENT '真实姓名',
  `id_card` VARCHAR(255) DEFAULT NULL COMMENT '身份证号(加密存储)',
  `status` ENUM('active','frozen','deleted') NOT NULL DEFAULT 'active' COMMENT '状态',
  `last_login_at` DATETIME DEFAULT NULL COMMENT '最后登录时间',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_phone` (`phone`),
  KEY `idx_wechat_openid` (`wechat_openid`),
  KEY `idx_wechat_unionid` (`wechat_unionid`),
  KEY `idx_status` (`status`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表';

-- ============================================================
-- 2. 平台管理员表
-- ============================================================
CREATE TABLE `admins` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(50) NOT NULL COMMENT '用户名',
  `password` VARCHAR(255) NOT NULL COMMENT '密码(bcrypt哈希)',
  `name` VARCHAR(50) NOT NULL COMMENT '姓名',
  `phone` VARCHAR(20) DEFAULT NULL COMMENT '手机号',
  `email` VARCHAR(100) DEFAULT NULL COMMENT '邮箱',
  `role` ENUM('super_admin','admin','operator') NOT NULL DEFAULT 'admin' COMMENT '角色:超级管理员/管理员/运营',
  `status` ENUM('active','frozen') NOT NULL DEFAULT 'active' COMMENT '状态',
  `last_login_at` DATETIME DEFAULT NULL COMMENT '最后登录时间',
  `last_login_ip` VARCHAR(50) DEFAULT NULL COMMENT '最后登录IP',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_username` (`username`),
  KEY `idx_role` (`role`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='平台管理员表';

-- ============================================================
-- 3. 商家账户表
-- ============================================================
CREATE TABLE `sellers` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `phone` VARCHAR(20) NOT NULL COMMENT '手机号',
  `password` VARCHAR(255) DEFAULT NULL COMMENT '密码(bcrypt哈希)',
  `contact_name` VARCHAR(50) NOT NULL COMMENT '联系人姓名',
  `email` VARCHAR(100) DEFAULT NULL COMMENT '邮箱',
  `status` ENUM('active','frozen','deleted') NOT NULL DEFAULT 'active' COMMENT '状态',
  `last_login_at` DATETIME DEFAULT NULL COMMENT '最后登录时间',
  `last_login_ip` VARCHAR(50) DEFAULT NULL COMMENT '最后登录IP',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_phone` (`phone`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商家账户表';

-- ============================================================
-- 4. 第三方账号绑定表
-- ============================================================
CREATE TABLE `user_oauth` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  `provider` ENUM('wechat','alipay') NOT NULL COMMENT '第三方平台',
  `openid` VARCHAR(128) NOT NULL COMMENT '第三方OpenID',
  `union_id` VARCHAR(128) DEFAULT NULL COMMENT 'UnionID',
  `nickname` VARCHAR(100) DEFAULT NULL COMMENT '第三方昵称',
  `avatar` VARCHAR(500) DEFAULT NULL COMMENT '第三方头像',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_provider_openid` (`provider`,`openid`),
  KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='第三方账号绑定表';

-- ============================================================
-- 5. 商家表
-- ============================================================
CREATE TABLE `merchants` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `seller_id` BIGINT UNSIGNED NOT NULL COMMENT '关联商家账户ID',
  `shop_name` VARCHAR(100) NOT NULL COMMENT '店铺名称',
  `logo` VARCHAR(500) DEFAULT '' COMMENT '店铺Logo',
  `cover_image` VARCHAR(500) DEFAULT '' COMMENT '店铺封面图片',
  `hotel_images` TEXT DEFAULT NULL COMMENT '酒店照片，多张URL用逗号分隔',
  `description` TEXT COMMENT '店铺描述',
  `store_license` VARCHAR(255) DEFAULT NULL COMMENT '门店营业执照',
  `phone` VARCHAR(20) NOT NULL COMMENT '联系电话',
  `province` VARCHAR(50) DEFAULT '' COMMENT '省',
  `city` VARCHAR(50) DEFAULT '' COMMENT '市',
  `district` VARCHAR(50) DEFAULT '' COMMENT '区',
  `address` VARCHAR(255) DEFAULT '' COMMENT '详细地址',
  `longitude` DECIMAL(10,7) DEFAULT NULL COMMENT '经度',
  `latitude` DECIMAL(10,7) DEFAULT NULL COMMENT '纬度',
  `business_license` VARCHAR(500) DEFAULT '' COMMENT '营业执照图片',
  `contract_type` VARCHAR(20) DEFAULT 'personal' COMMENT '签约类型：personal-个人签约，company-公司签约',
  `id_card_front` VARCHAR(255) DEFAULT NULL COMMENT '身份证正面（个人签约）',
  `id_card_back` VARCHAR(255) DEFAULT NULL COMMENT '身份证反面（个人签约）',
  `legal_id_card_front` VARCHAR(255) DEFAULT NULL COMMENT '法人身份证正面（公司签约）',
  `legal_id_card_back` VARCHAR(255) DEFAULT NULL COMMENT '法人身份证反面（公司签约）',
  `license_no` VARCHAR(50) DEFAULT '' COMMENT '营业执照编号',
  `legal_person` VARCHAR(50) DEFAULT '' COMMENT '法人姓名',
  `status` ENUM('pending','approved','rejected','frozen') NOT NULL DEFAULT 'pending' COMMENT '状态',
  `reject_reason` VARCHAR(500) DEFAULT NULL COMMENT '拒绝原因',
  `deposit` DECIMAL(10,2) DEFAULT 0.00 COMMENT '保证金',
  `wallet_balance` DECIMAL(10,2) DEFAULT 0.00 COMMENT '待提现余额',
  `bank_name` VARCHAR(100) DEFAULT '' COMMENT '开户银行',
  `bank_account` VARCHAR(50) DEFAULT '' COMMENT '银行账号',
  `account_name` VARCHAR(50) DEFAULT '' COMMENT '账户名',
  `account_type` VARCHAR(20) DEFAULT 'company' COMMENT '账户类型：company-对公账户，personal-对私账户',
  `bank_branch` VARCHAR(100) DEFAULT NULL COMMENT '支行信息（对私账户）',
  `bank_license` VARCHAR(255) DEFAULT NULL COMMENT '开户营业执照（对公账户）',
  `account_id_card_front` VARCHAR(255) DEFAULT NULL COMMENT '开户身份证正面（对私账户）',
  `account_id_card_back` VARCHAR(255) DEFAULT NULL COMMENT '开户身份证反面（对私账户）',
  `rating` DECIMAL(2,1) DEFAULT 5.0 COMMENT '评分',
  `review_count` INT UNSIGNED DEFAULT 0 COMMENT '评价数',
  `sales_count` INT UNSIGNED DEFAULT 0 COMMENT '销量统计',
  `auto_confirm` TINYINT(1) DEFAULT 0 COMMENT '是否自动接单',
  `auto_confirm_rules` JSON DEFAULT NULL COMMENT '自动接单规则配置',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_seller_id` (`seller_id`),
  KEY `idx_status` (`status`),
  KEY `idx_city` (`city`),
  KEY `idx_rating` (`rating`),
  KEY `idx_sales_count` (`sales_count`),
  KEY `idx_contract_type` (`contract_type`),
  KEY `idx_account_type` (`account_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商家表';

-- ============================================================
-- 6. 房型/房源表
-- ============================================================
CREATE TABLE `rooms` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `merchant_id` BIGINT UNSIGNED NOT NULL COMMENT '商家ID',
  `name` VARCHAR(100) NOT NULL COMMENT '房型名称',
  `type` ENUM('hotel','homestay','apartment','hostel') NOT NULL DEFAULT 'hotel' COMMENT '类型:酒店/民宿/公寓/青旅',
  `area` DECIMAL(6,2) DEFAULT 0.00 COMMENT '面积(平方米)',
  `bed_type` VARCHAR(50) DEFAULT '' COMMENT '床型(如:大床/双床/榻榻米)',
  `max_guests` TINYINT UNSIGNED DEFAULT 1 COMMENT '最多入住人数',
  `floor` VARCHAR(20) DEFAULT '' COMMENT '楼层',
  `facilities` JSON DEFAULT NULL COMMENT '设施列表(WiFi,停车,早餐等)',
  `images` JSON DEFAULT NULL COMMENT '图片URL列表',
  `cover_image` VARCHAR(500) DEFAULT '' COMMENT '封面图',
  `price` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '基础价格/晚',
  `status` ENUM('on_sale','off_sale') NOT NULL DEFAULT 'on_sale' COMMENT '状态',
  `audit_status` ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending' COMMENT '审核状态',
  `audit_reject_reason` VARCHAR(500) DEFAULT NULL COMMENT '审核拒绝原因',
  `rating` DECIMAL(2,1) DEFAULT 5.0 COMMENT '评分',
  `review_count` INT UNSIGNED DEFAULT 0 COMMENT '评价数',
  `description` TEXT COMMENT '房源描述',
  `cancel_policy` ENUM('free','flexible','strict') DEFAULT 'flexible' COMMENT '取消政策',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_merchant_id` (`merchant_id`),
  KEY `idx_type` (`type`),
  KEY `idx_status_price` (`status`,`price`),
  KEY `idx_rating` (`rating`),
  KEY `idx_audit_status` (`audit_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='房型/房源表';

-- ============================================================
-- 7. 房量房价日历表
-- ============================================================
CREATE TABLE `room_calendar` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `room_id` BIGINT UNSIGNED NOT NULL COMMENT '房型ID',
  `date` DATE NOT NULL COMMENT '日期',
  `price` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '当日房价',
  `stock` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '可售数量',
  `sold` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '已售数量',
  `status` ENUM('available','unavailable') NOT NULL DEFAULT 'available' COMMENT '房态',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_room_date` (`room_id`,`date`),
  KEY `idx_date` (`date`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='房量房价日历表';

-- ============================================================
-- 8. 房态变更日志表
-- ============================================================
CREATE TABLE `room_calendar_logs` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `room_id` BIGINT UNSIGNED NOT NULL COMMENT '房型ID',
  `operator_id` BIGINT UNSIGNED NOT NULL COMMENT '操作人ID',
  `date_range` VARCHAR(100) NOT NULL COMMENT '变更日期范围',
  `change_type` ENUM('price','stock','status') NOT NULL COMMENT '变更类型',
  `old_value` VARCHAR(100) DEFAULT NULL COMMENT '变更前值',
  `new_value` VARCHAR(100) DEFAULT NULL COMMENT '变更后值',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_room_id` (`room_id`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='房态变更日志表';

-- ============================================================
-- 9. 订单表
-- ============================================================
CREATE TABLE `orders` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `order_no` VARCHAR(32) NOT NULL COMMENT '订单号',
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  `merchant_id` BIGINT UNSIGNED NOT NULL COMMENT '商家ID',
  `room_id` BIGINT UNSIGNED NOT NULL COMMENT '房型ID',
  `check_in_date` DATE NOT NULL COMMENT '入住日期',
  `check_out_date` DATE NOT NULL COMMENT '离店日期',
  `nights` TINYINT UNSIGNED NOT NULL COMMENT '入住晚数',
  `room_count` TINYINT UNSIGNED DEFAULT 1 COMMENT '房间数',
  `room_price` DECIMAL(10,2) NOT NULL COMMENT '房费单价',
  `room_amount` DECIMAL(10,2) NOT NULL COMMENT '房费总额',
  `service_fee` DECIMAL(10,2) DEFAULT 0.00 COMMENT '软件服务费',
  `merchant_income` DECIMAL(10,2) DEFAULT 0.00 COMMENT '商家预计收入',
  `coupon_discount` DECIMAL(10,2) DEFAULT 0.00 COMMENT '优惠券抵扣',
  `user_coupon_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '使用的用户优惠券ID',
  `total_amount` DECIMAL(10,2) NOT NULL COMMENT '订单总金额',
  `pay_amount` DECIMAL(10,2) NOT NULL COMMENT '实付金额',
  `payment_method` ENUM('wechat','alipay','balance') DEFAULT NULL COMMENT '支付方式',
  `payment_no` VARCHAR(64) DEFAULT NULL COMMENT '支付流水号',
  `paid_at` DATETIME DEFAULT NULL COMMENT '支付时间',
  `status` ENUM('pending_pay','pending_confirm','pending_checkin','checked_in','completed','cancelled','refunding','refunded') NOT NULL DEFAULT 'pending_pay' COMMENT '订单状态',
  `cancel_reason` VARCHAR(500) DEFAULT NULL COMMENT '取消原因',
  `contact_name` VARCHAR(50) NOT NULL COMMENT '联系人姓名',
  `contact_phone` VARCHAR(20) NOT NULL COMMENT '联系人手机',
  `contact_id_card` VARCHAR(18) DEFAULT NULL COMMENT '联系人身份证号',
  `guest_count` TINYINT UNSIGNED DEFAULT 1 COMMENT '入住人数',
  `remark` VARCHAR(500) DEFAULT '' COMMENT '备注',
  `source` ENUM('miniapp','web','third_party') DEFAULT 'miniapp' COMMENT '订单来源',
  `confirmed_at` DATETIME DEFAULT NULL COMMENT '商家确认时间',
  `checkin_at` DATETIME DEFAULT NULL COMMENT '实际入住时间',
  `checkout_at` DATETIME DEFAULT NULL COMMENT '实际离店时间',
  `cancelled_at` DATETIME DEFAULT NULL COMMENT '取消时间',
  `refund_amount` DECIMAL(10,2) DEFAULT NULL COMMENT '退款金额',
  `refund_at` DATETIME DEFAULT NULL COMMENT '退款时间',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_order_no` (`order_no`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_merchant_id` (`merchant_id`),
  KEY `idx_room_id` (`room_id`),
  KEY `idx_status` (`status`),
  KEY `idx_check_in` (`check_in_date`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单表';

-- ============================================================
-- 10. 评价表
-- ============================================================
CREATE TABLE `reviews` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `order_id` BIGINT UNSIGNED NOT NULL COMMENT '订单ID',
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  `merchant_id` BIGINT UNSIGNED NOT NULL COMMENT '商家ID',
  `room_id` BIGINT UNSIGNED NOT NULL COMMENT '房型ID',
  `rating` TINYINT UNSIGNED NOT NULL COMMENT '评分(1-5)',
  `content` TEXT COMMENT '评价内容',
  `images` JSON DEFAULT NULL COMMENT '评价图片列表',
  `merchant_reply` TEXT COMMENT '商家回复',
  `replied_at` DATETIME DEFAULT NULL COMMENT '回复时间',
  `is_anonymous` TINYINT(1) DEFAULT 0 COMMENT '是否匿名',
  `status` ENUM('pending','visible','hidden','rejected') DEFAULT 'pending' COMMENT '状态:pending待审核,visible已通过,hidden已隐藏,rejected已拒绝',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_order_id` (`order_id`),
  KEY `idx_merchant_id` (`merchant_id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_rating` (`rating`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='评价表';

-- ============================================================
-- 11. 收藏表
-- ============================================================
CREATE TABLE `favorites` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  `room_id` BIGINT UNSIGNED NOT NULL COMMENT '房型ID',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_user_room` (`user_id`,`room_id`),
  KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='收藏表';

-- ============================================================
-- 12. 优惠券模板表
-- ============================================================
CREATE TABLE `coupons` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL COMMENT '优惠券名称',
  `type` ENUM('fixed','percent') NOT NULL COMMENT '类型:固定金额/百分比折扣',
  `value` DECIMAL(10,2) NOT NULL COMMENT '优惠金额/折扣比例',
  `min_amount` DECIMAL(10,2) DEFAULT 0.00 COMMENT '最低使用金额',
  `total_count` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '发放总量',
  `used_count` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '已使用数量',
  `remain_count` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '剩余数量',
  `start_date` DATE NOT NULL COMMENT '生效日期',
  `end_date` DATE NOT NULL COMMENT '失效日期',
  `scope` ENUM('platform','merchant','room') DEFAULT 'platform' COMMENT '适用范围',
  `scope_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '范围关联ID(商家ID/房型ID)',
  `status` ENUM('active','paused','ended') DEFAULT 'active' COMMENT '状态',
  `created_by` BIGINT UNSIGNED DEFAULT NULL COMMENT '创建人ID',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_status_dates` (`status`,`start_date`,`end_date`),
  KEY `idx_scope` (`scope`,`scope_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='优惠券模板表';

-- ============================================================
-- 13. 用户优惠券表
-- ============================================================
CREATE TABLE `user_coupons` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  `coupon_id` BIGINT UNSIGNED NOT NULL COMMENT '优惠券ID',
  `status` ENUM('unused','used','expired') NOT NULL DEFAULT 'unused' COMMENT '状态',
  `order_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '关联订单ID',
  `used_at` DATETIME DEFAULT NULL COMMENT '使用时间',
  `expire_at` DATETIME NOT NULL COMMENT '过期时间',
  `received_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '领取时间',
  PRIMARY KEY (`id`),
  KEY `idx_user_status` (`user_id`,`status`),
  KEY `idx_coupon_id` (`coupon_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户优惠券表';

-- ============================================================
-- 14. 促销活动表
-- ============================================================
CREATE TABLE `promotions` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `merchant_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '商家ID(NULL为平台活动)',
  `name` VARCHAR(100) NOT NULL COMMENT '活动名称',
  `type` ENUM('full_reduction','discount','package') NOT NULL COMMENT '类型:满减/折扣/套餐',
  `rules` JSON NOT NULL COMMENT '活动规则',
  `room_ids` JSON DEFAULT NULL COMMENT '参与房型ID列表',
  `start_date` DATETIME NOT NULL COMMENT '开始时间',
  `end_date` DATETIME NOT NULL COMMENT '结束时间',
  `status` ENUM('pending','active','paused','ended') NOT NULL DEFAULT 'pending' COMMENT '状态',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_merchant_id` (`merchant_id`),
  KEY `idx_status_dates` (`status`,`start_date`,`end_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='促销活动表';

-- ============================================================
-- 15. 会员等级表
-- ============================================================
CREATE TABLE `member_levels` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) NOT NULL COMMENT '等级名称',
  `level` TINYINT UNSIGNED NOT NULL COMMENT '等级序号',
  `min_points` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '最低成长值',
  `discount` DECIMAL(3,2) DEFAULT 1.00 COMMENT '折扣(0.95=95折)',
  `benefits` JSON DEFAULT NULL COMMENT '权益描述',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_level` (`level`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='会员等级表';

-- ============================================================
-- 16. 用户会员信息表
-- ============================================================
CREATE TABLE `user_members` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  `level_id` BIGINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '等级ID',
  `points` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '积分',
  `growth_value` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '成长值',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_user_id` (`user_id`),
  KEY `idx_level_id` (`level_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户会员信息表';

-- ============================================================
-- 17-18. 旧版财务表已删除，使用新版财务系统（见第四部分）
-- ============================================================

-- ============================================================
-- 19. 消息通知表
-- ============================================================
CREATE TABLE `notifications` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  `title` VARCHAR(200) NOT NULL COMMENT '标题',
  `content` TEXT NOT NULL COMMENT '内容',
  `type` ENUM('order','system','promotion','review') NOT NULL COMMENT '类型',
  `is_read` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已读',
  `extra` JSON DEFAULT NULL COMMENT '附加数据',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_user_read` (`user_id`,`is_read`),
  KEY `idx_type` (`type`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='消息通知表';

-- ============================================================
-- 20. 广告位表
-- ============================================================
CREATE TABLE `advertisements` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `position` VARCHAR(50) NOT NULL COMMENT '广告位标识',
  `title` VARCHAR(200) DEFAULT '' COMMENT '广告标题',
  `image` VARCHAR(500) NOT NULL COMMENT '广告图片',
  `link_type` ENUM('room','merchant','page','url') DEFAULT 'url' COMMENT '链接类型',
  `link_value` VARCHAR(500) DEFAULT '' COMMENT '链接值',
  `sort` INT DEFAULT 0 COMMENT '排序',
  `status` ENUM('active','inactive') DEFAULT 'active' COMMENT '状态',
  `start_time` DATETIME DEFAULT NULL COMMENT '投放开始时间',
  `end_time` DATETIME DEFAULT NULL COMMENT '投放结束时间',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_position` (`position`),
  KEY `idx_status_sort` (`status`,`sort`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='广告位表';

-- ============================================================
-- 21. 平台配置表
-- ============================================================
CREATE TABLE `platform_configs` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `config_key` VARCHAR(100) NOT NULL COMMENT '配置键',
  `config_value` TEXT NOT NULL COMMENT '配置值',
  `description` VARCHAR(200) DEFAULT '' COMMENT '说明',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_config_key` (`config_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='平台配置表';

-- ============================================================
-- 22. 操作日志表
-- ============================================================
CREATE TABLE `operation_logs` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '操作人ID',
  `module` VARCHAR(50) NOT NULL COMMENT '模块',
  `action` VARCHAR(50) NOT NULL COMMENT '操作',
  `target_type` VARCHAR(50) DEFAULT NULL COMMENT '目标类型',
  `target_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '目标ID',
  `detail` JSON DEFAULT NULL COMMENT '操作详情',
  `ip` VARCHAR(45) DEFAULT NULL COMMENT 'IP地址',
  `user_agent` VARCHAR(500) DEFAULT NULL COMMENT 'UA',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_module_action` (`module`,`action`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='操作日志表';

-- ============================================================

-- ============================================================
-- 24. 营销活动总表
-- ============================================================
CREATE TABLE `mkt_activities` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL COMMENT '活动名称',
  `type` ENUM('invite_cashback') NOT NULL DEFAULT 'invite_cashback' COMMENT '活动类型',
  `enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
  `config` JSON NOT NULL COMMENT '活动配置',
  `start_time` DATETIME DEFAULT NULL COMMENT '活动开始时间',
  `end_time` DATETIME DEFAULT NULL COMMENT '活动结束时间',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_type` (`type`),
  KEY `idx_enabled` (`enabled`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='营销活动总表';

-- ============================================================
-- 25. 邀请关系表
-- ============================================================
CREATE TABLE `mkt_invitations` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `activity_id` BIGINT UNSIGNED NOT NULL COMMENT '活动ID',
  `inviter_id` BIGINT UNSIGNED NOT NULL COMMENT '邀请人用户ID',
  `invitee_id` BIGINT UNSIGNED NOT NULL COMMENT '被邀请人用户ID',
  `invite_code` VARCHAR(32) NOT NULL COMMENT '邀请码',
  `scene` VARCHAR(100) DEFAULT NULL COMMENT '小程序scene参数',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_invitee_id` (`invitee_id`),
  KEY `idx_activity_id` (`activity_id`),
  KEY `idx_inviter_id` (`inviter_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='邀请关系表';

-- ============================================================
-- 26. 返现记录表
-- ============================================================
CREATE TABLE `mkt_cashbacks` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `activity_id` BIGINT UNSIGNED NOT NULL COMMENT '活动ID',
  `inviter_id` BIGINT UNSIGNED NOT NULL COMMENT '邀请人用户ID',
  `invitee_id` BIGINT UNSIGNED NOT NULL COMMENT '被邀请人用户ID',
  `order_id` BIGINT UNSIGNED NOT NULL COMMENT '关联订单ID',
  `order_no` VARCHAR(32) NOT NULL COMMENT '订单号',
  `order_amount` DECIMAL(10,2) NOT NULL COMMENT '订单金额',
  `order_index` TINYINT UNSIGNED NOT NULL COMMENT '被邀请人第几单(1/2)',
  `rate` DECIMAL(5,4) NOT NULL COMMENT '返现比例',
  `amount` DECIMAL(10,2) NOT NULL COMMENT '返现金额',
  `status` ENUM('pending','settled','cancelled') NOT NULL DEFAULT 'pending' COMMENT '状态',
  `settled_at` DATETIME DEFAULT NULL COMMENT '到账时间',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_order_inviter` (`order_id`, `inviter_id`),
  KEY `idx_activity_id` (`activity_id`),
  KEY `idx_inviter_id` (`inviter_id`),
  KEY `idx_invitee_id` (`invitee_id`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='返现记录表';

-- ============================================================
-- 27. 用户邀请统计表
-- ============================================================
CREATE TABLE `mkt_user_invite_stats` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `activity_id` BIGINT UNSIGNED NOT NULL COMMENT '活动ID',
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  `invite_code` VARCHAR(32) NOT NULL COMMENT '专属邀请码',
  `total_invites` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '累计邀请人数',
  `total_orders` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '累计下单人数',
  `total_cashback` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '累计返现金额',
  `available_balance` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '可提现余额',
  `withdrawn_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '已提现金额',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_activity_user` (`activity_id`, `user_id`),
  UNIQUE KEY `uk_invite_code` (`invite_code`),
  KEY `idx_activity_id` (`activity_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户邀请统计表';

-- ============================================================
-- 28. 邀请提现申请表
-- ============================================================
CREATE TABLE `mkt_invite_withdrawals` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `activity_id` BIGINT UNSIGNED NOT NULL COMMENT '活动ID',
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  `amount` DECIMAL(10,2) NOT NULL COMMENT '提现金额',
  `status` ENUM('pending','approved','rejected','paid') NOT NULL DEFAULT 'pending' COMMENT '状态',
  `reject_reason` VARCHAR(500) DEFAULT NULL COMMENT '拒绝原因',
  `reviewer_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '审核人ID',
  `reviewed_at` DATETIME DEFAULT NULL COMMENT '审核时间',
  `paid_at` DATETIME DEFAULT NULL COMMENT '打款时间',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_activity_id` (`activity_id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='邀请提现申请表';


-- ============================================================
-- 补充字段（原 002-004 迁移脚本）
-- ============================================================

-- 注意：cover_image 和 sales_count 已经在 merchants 表定义中包含，无需再次添加

-- 修复 mkt_user_invite_stats 表的 user_id 字段
-- 确保字段定义正确

ALTER TABLE `mkt_user_invite_stats`
MODIFY COLUMN `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID';


-- ============================================================
-- 财务系统 - 按角色拆分账户、交易流水、提现表
-- 版本: v3.0
-- 说明: 用户、商家、平台的账户和交易流水独立管理
-- ============================================================


-- ============================================================
-- 第一部分：账户表（按角色拆分）
-- ============================================================

-- 1. 用户账户表
CREATE TABLE IF NOT EXISTS `user_accounts` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账户ID',
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  `balance` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '可用余额',
  `frozen_balance` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '冻结余额（提现中）',
  `total_income` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计收入（邀请返现）',
  `total_expense` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计支出（提现）',
  `total_cashback` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计返现收入',
  `total_withdraw` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计提现金额',
  `version` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '乐观锁版本号',
  `status` ENUM('active','frozen','closed') NOT NULL DEFAULT 'active' COMMENT '账户状态',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_user_id` (`user_id`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户账户表';

-- 2. 商家账户表
CREATE TABLE IF NOT EXISTS `merchant_accounts` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账户ID',
  `merchant_id` BIGINT UNSIGNED NOT NULL COMMENT '商家ID',
  `balance` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '可用余额',
  `frozen_balance` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '冻结余额（提现中）',
  `debt_amount` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '欠款金额（退款扣回）',
  `total_income` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计收入（订单结算）',
  `total_expense` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计支出（提现+退款扣回）',
  `total_settlement` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计结算金额',
  `total_withdraw` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计提现金额',
  `last_settlement_at` DATETIME DEFAULT NULL COMMENT '最后结算时间',
  `pending_settlement` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '待结算金额',
  `version` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '乐观锁版本号',
  `status` ENUM('active','frozen','closed') NOT NULL DEFAULT 'active' COMMENT '账户状态',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_merchant_id` (`merchant_id`),
  KEY `idx_status` (`status`),
  KEY `idx_last_settlement_at` (`last_settlement_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商家账户表';

-- 3. 平台账户表
CREATE TABLE IF NOT EXISTS `platform_accounts` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账户ID',
  `account_name` VARCHAR(50) NOT NULL COMMENT '账户名称（如：主账户、备用账户）',
  `balance` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '可用余额',
  `frozen_balance` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '冻结余额（提现中）',
  `total_income` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计收入（订单收入）',
  `total_expense` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计支出（结算+返现+提现）',
  `total_order_income` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计订单收入',
  `total_service_fee` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计服务费收入',
  `total_settlement` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计商家结算支出',
  `total_cashback` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计返现支出',
  `total_withdraw` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '累计提现金额',
  `version` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '乐观锁版本号',
  `status` ENUM('active','frozen','closed') NOT NULL DEFAULT 'active' COMMENT '账户状态',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_account_name` (`account_name`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='平台账户表';

-- ============================================================
-- 第二部分：交易流水表（按角色拆分）
-- ============================================================

-- 4. 用户交易流水表
CREATE TABLE IF NOT EXISTS `user_transactions` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '流水ID',
  `transaction_no` VARCHAR(32) NOT NULL COMMENT '交易流水号（全局唯一）',
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  `account_id` BIGINT UNSIGNED NOT NULL COMMENT '用户账户ID',
  `direction` ENUM('income','expense') NOT NULL COMMENT '方向：income-收入/expense-支出',
  `amount` DECIMAL(12,2) NOT NULL COMMENT '金额（正数）',
  `balance_before` DECIMAL(12,2) NOT NULL COMMENT '交易前余额',
  `balance_after` DECIMAL(12,2) NOT NULL COMMENT '交易后余额',
  `transaction_type` VARCHAR(50) NOT NULL COMMENT '交易类型',
  `business_type` VARCHAR(50) NOT NULL COMMENT '业务类型：cashback/withdraw/refund',
  `business_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '业务ID（订单ID/提现ID等）',
  `business_no` VARCHAR(32) DEFAULT NULL COMMENT '业务单号',
  `related_account_type` ENUM('platform','merchant') DEFAULT NULL COMMENT '对方账户类型',
  `related_account_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '对方账户ID',
  `remark` VARCHAR(500) DEFAULT NULL COMMENT '备注',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_transaction_no` (`transaction_no`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_account_id` (`account_id`),
  KEY `idx_transaction_type` (`transaction_type`),
  KEY `idx_business` (`business_type`, `business_id`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户交易流水表';

-- 5. 商家交易流水表
CREATE TABLE IF NOT EXISTS `merchant_transactions` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '流水ID',
  `transaction_no` VARCHAR(32) NOT NULL COMMENT '交易流水号（全局唯一）',
  `merchant_id` BIGINT UNSIGNED NOT NULL COMMENT '商家ID',
  `account_id` BIGINT UNSIGNED NOT NULL COMMENT '商家账户ID',
  `direction` ENUM('income','expense') NOT NULL COMMENT '方向：income-收入/expense-支出',
  `amount` DECIMAL(12,2) NOT NULL COMMENT '金额（正数）',
  `balance_before` DECIMAL(12,2) NOT NULL COMMENT '交易前余额',
  `balance_after` DECIMAL(12,2) NOT NULL COMMENT '交易后余额',
  `transaction_type` VARCHAR(50) NOT NULL COMMENT '交易类型',
  `business_type` VARCHAR(50) NOT NULL COMMENT '业务类型：settlement/withdraw/refund',
  `business_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '业务ID（结算单ID/提现ID等）',
  `business_no` VARCHAR(32) DEFAULT NULL COMMENT '业务单号',
  `related_account_type` ENUM('platform') DEFAULT NULL COMMENT '对方账户类型',
  `related_account_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '对方账户ID',
  `remark` VARCHAR(500) DEFAULT NULL COMMENT '备注',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_transaction_no` (`transaction_no`),
  KEY `idx_merchant_id` (`merchant_id`),
  KEY `idx_account_id` (`account_id`),
  KEY `idx_transaction_type` (`transaction_type`),
  KEY `idx_business` (`business_type`, `business_id`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商家交易流水表';

-- 6. 平台交易流水表
CREATE TABLE IF NOT EXISTS `platform_transactions` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '流水ID',
  `transaction_no` VARCHAR(32) NOT NULL COMMENT '交易流水号（全局唯一）',
  `account_id` BIGINT UNSIGNED NOT NULL COMMENT '平台账户ID',
  `direction` ENUM('income','expense') NOT NULL COMMENT '方向：income-收入/expense-支出',
  `amount` DECIMAL(12,2) NOT NULL COMMENT '金额（正数）',
  `balance_before` DECIMAL(12,2) NOT NULL COMMENT '交易前余额',
  `balance_after` DECIMAL(12,2) NOT NULL COMMENT '交易后余额',
  `transaction_type` VARCHAR(50) NOT NULL COMMENT '交易类型',
  `business_type` VARCHAR(50) NOT NULL COMMENT '业务类型：order/settlement/cashback/withdraw/refund',
  `business_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '业务ID',
  `business_no` VARCHAR(32) DEFAULT NULL COMMENT '业务单号',
  `related_account_type` ENUM('user','merchant') DEFAULT NULL COMMENT '对方账户类型',
  `related_account_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '对方账户ID',
  `remark` VARCHAR(500) DEFAULT NULL COMMENT '备注',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_transaction_no` (`transaction_no`),
  KEY `idx_account_id` (`account_id`),
  KEY `idx_transaction_type` (`transaction_type`),
  KEY `idx_business` (`business_type`, `business_id`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='平台交易流水表';

-- ============================================================
-- 第三部分：提现表（按角色拆分）
-- ============================================================

-- 7. 用户提现表
CREATE TABLE IF NOT EXISTS `user_withdrawals` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '提现ID',
  `withdraw_no` VARCHAR(32) NOT NULL COMMENT '提现单号（全局唯一）',
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  `account_id` BIGINT UNSIGNED NOT NULL COMMENT '用户账户ID',
  `amount` DECIMAL(12,2) NOT NULL COMMENT '提现金额',
  `fee` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '手续费',
  `actual_amount` DECIMAL(12,2) NOT NULL COMMENT '实际到账金额',
  `payment_channel` ENUM('wechat','alipay') NOT NULL COMMENT '提现渠道',
  `payment_account` VARCHAR(100) DEFAULT NULL COMMENT '收款账号',
  `payment_name` VARCHAR(50) DEFAULT NULL COMMENT '收款人姓名',
  `status` ENUM('pending','approved','rejected','paid','failed') NOT NULL DEFAULT 'pending' COMMENT '状态',
  `reject_reason` VARCHAR(500) DEFAULT NULL COMMENT '拒绝原因',
  `reviewer_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '审核人ID',
  `reviewed_at` DATETIME DEFAULT NULL COMMENT '审核时间',
  `paid_at` DATETIME DEFAULT NULL COMMENT '打款时间',
  `payment_no` VARCHAR(100) DEFAULT NULL COMMENT '第三方支付单号',
  `remark` VARCHAR(500) DEFAULT NULL COMMENT '备注',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '申请时间',
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_withdraw_no` (`withdraw_no`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_account_id` (`account_id`),
  KEY `idx_status` (`status`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户提现表';

-- 8. 商家提现表
CREATE TABLE IF NOT EXISTS `merchant_withdrawals` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '提现ID',
  `withdraw_no` VARCHAR(32) NOT NULL COMMENT '提现单号（全局唯一）',
  `merchant_id` BIGINT UNSIGNED NOT NULL COMMENT '商家ID',
  `account_id` BIGINT UNSIGNED NOT NULL COMMENT '商家账户ID',
  `amount` DECIMAL(12,2) NOT NULL COMMENT '提现金额',
  `fee` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '手续费',
  `actual_amount` DECIMAL(12,2) NOT NULL COMMENT '实际到账金额',
  `payment_channel` ENUM('bank','wechat','alipay') NOT NULL DEFAULT 'bank' COMMENT '提现渠道',
  `bank_name` VARCHAR(100) DEFAULT NULL COMMENT '开户银行',
  `bank_account` VARCHAR(50) DEFAULT NULL COMMENT '银行账号',
  `account_name` VARCHAR(50) DEFAULT NULL COMMENT '账户名',
  `status` ENUM('pending','approved','rejected','paid','failed') NOT NULL DEFAULT 'pending' COMMENT '状态',
  `reject_reason` VARCHAR(500) DEFAULT NULL COMMENT '拒绝原因',
  `reviewer_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '审核人ID',
  `reviewed_at` DATETIME DEFAULT NULL COMMENT '审核时间',
  `paid_at` DATETIME DEFAULT NULL COMMENT '打款时间',
  `payment_no` VARCHAR(100) DEFAULT NULL COMMENT '第三方支付单号',
  `remark` VARCHAR(500) DEFAULT NULL COMMENT '备注',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '申请时间',
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_withdraw_no` (`withdraw_no`),
  KEY `idx_merchant_id` (`merchant_id`),
  KEY `idx_account_id` (`account_id`),
  KEY `idx_status` (`status`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商家提现表';

-- 9. 平台提现表
CREATE TABLE IF NOT EXISTS `platform_withdrawals` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '提现ID',
  `withdraw_no` VARCHAR(32) NOT NULL COMMENT '提现单号（全局唯一）',
  `account_id` BIGINT UNSIGNED NOT NULL COMMENT '平台账户ID',
  `amount` DECIMAL(12,2) NOT NULL COMMENT '提现金额',
  `fee` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '手续费',
  `actual_amount` DECIMAL(12,2) NOT NULL COMMENT '实际到账金额',
  `payment_channel` ENUM('bank') NOT NULL DEFAULT 'bank' COMMENT '提现渠道',
  `bank_name` VARCHAR(100) NOT NULL COMMENT '开户银行',
  `bank_account` VARCHAR(50) NOT NULL COMMENT '银行账号',
  `account_name` VARCHAR(50) NOT NULL COMMENT '账户名',
  `status` ENUM('pending','approved','rejected','paid','failed') NOT NULL DEFAULT 'pending' COMMENT '状态',
  `reject_reason` VARCHAR(500) DEFAULT NULL COMMENT '拒绝原因',
  `reviewer_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '审核人ID（超级管理员）',
  `reviewed_at` DATETIME DEFAULT NULL COMMENT '审核时间',
  `paid_at` DATETIME DEFAULT NULL COMMENT '打款时间',
  `payment_no` VARCHAR(100) DEFAULT NULL COMMENT '第三方支付单号',
  `remark` VARCHAR(500) DEFAULT NULL COMMENT '备注',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '申请时间',
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_withdraw_no` (`withdraw_no`),
  KEY `idx_account_id` (`account_id`),
  KEY `idx_status` (`status`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='平台提现表';

-- ============================================================
-- 第四部分：结算和对账表
-- ============================================================

-- 10. 结算单表 - 商家按周期结算订单收入
CREATE TABLE IF NOT EXISTS `settlements` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '结算单ID',
  `settlement_no` VARCHAR(32) NOT NULL COMMENT '结算单号',
  `merchant_id` BIGINT UNSIGNED NOT NULL COMMENT '商家ID',
  `period_start` DATE NOT NULL COMMENT '结算周期开始日期',
  `period_end` DATE NOT NULL COMMENT '结算周期结束日期',
  `order_count` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '订单数量',
  `order_amount` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '订单总额',
  `service_fee` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '服务费总额',
  `settlement_amount` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '结算金额（订单总额-服务费）',
  `debt_amount` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '扣除欠款金额',
  `actual_amount` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '实际结算金额（扣除欠款后）',
  `status` ENUM('pending','settled','failed') NOT NULL DEFAULT 'pending' COMMENT '状态',
  `settled_at` DATETIME DEFAULT NULL COMMENT '结算时间',
  `remark` VARCHAR(500) DEFAULT NULL COMMENT '备注',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_settlement_no` (`settlement_no`),
  KEY `idx_merchant_id` (`merchant_id`),
  KEY `idx_period` (`period_start`, `period_end`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='结算单表';

-- 11. 结算明细表 - 记录结算单包含的订单明细
CREATE TABLE IF NOT EXISTS `settlement_items` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '明细ID',
  `settlement_id` BIGINT UNSIGNED NOT NULL COMMENT '结算单ID',
  `order_id` BIGINT UNSIGNED NOT NULL COMMENT '订单ID',
  `order_no` VARCHAR(32) NOT NULL COMMENT '订单号',
  `order_amount` DECIMAL(12,2) NOT NULL COMMENT '订单金额',
  `service_fee` DECIMAL(12,2) NOT NULL COMMENT '服务费',
  `settlement_amount` DECIMAL(12,2) NOT NULL COMMENT '结算金额',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  KEY `idx_settlement_id` (`settlement_id`),
  KEY `idx_order_id` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='结算明细表';

-- 12. 日对账表 - 每日自动对账，确保资金平衡
CREATE TABLE IF NOT EXISTS `daily_reconciliations` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '对账ID',
  `reconciliation_date` DATE NOT NULL COMMENT '对账日期',
  `platform_balance` DECIMAL(12,2) NOT NULL COMMENT '平台账户余额',
  `merchant_balance_sum` DECIMAL(12,2) NOT NULL COMMENT '所有商家账户余额总和',
  `user_balance_sum` DECIMAL(12,2) NOT NULL COMMENT '所有用户账户余额总和',
  `total_balance` DECIMAL(12,2) NOT NULL COMMENT '总余额（平台+商家+用户）',
  `order_income` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '当日订单收入',
  `service_fee` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '当日服务费',
  `merchant_settlement` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '当日商家结算',
  `cashback_expense` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '当日返现支出',
  `withdraw_expense` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '当日提现支出',
  `refund_expense` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '当日退款支出',
  `status` ENUM('balanced','unbalanced') NOT NULL DEFAULT 'balanced' COMMENT '状态',
  `error_message` TEXT DEFAULT NULL COMMENT '异常信息',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_date` (`reconciliation_date`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='日对账表';

-- ============================================================
-- 常住人信息表
-- ============================================================

CREATE TABLE `guests` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  `name` VARCHAR(50) NOT NULL COMMENT '姓名',
  `phone` VARCHAR(20) NOT NULL COMMENT '手机号',
  `id_card` VARCHAR(18) DEFAULT NULL COMMENT '身份证号',
  `gender` ENUM('male','female') DEFAULT NULL COMMENT '性别',
  `is_default` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否默认',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_is_default` (`is_default`),
  CONSTRAINT `fk_guests_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='常住人信息表';

-- ============================================================
-- 第五部分：表结构补充和字段添加
-- ============================================================

-- 1. 订单表添加第三方支付交易号字段（用于微信支付退款）
ALTER TABLE `orders`
ADD COLUMN `transaction_id` VARCHAR(64) NULL COMMENT '第三方支付交易号' AFTER `payment_no`,
ADD INDEX `idx_transaction_id` (`transaction_id`);

-- 2. 用户表添加实名认证字段
ALTER TABLE `users`
ADD COLUMN `is_verified` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否实名认证' AFTER `id_card`,
ADD COLUMN `verified_at` DATETIME DEFAULT NULL COMMENT '实名认证时间' AFTER `is_verified`;

-- ============================================================
-- 第六部分：初始化数据
-- ============================================================

-- 注意：平台账户等初始数据请在 database/seeds/001_init_data.sql 中初始化

-- ============================================================
-- 第七部分：创建触发器
-- ============================================================

-- 注意：触发器使用 DELIMITER 命令，某些数据库工具不支持
-- 如果执行失败，请使用 mysql 命令行工具执行，或在应用层处理账户创建逻辑

-- 1. 用户注册时自动创建账户
-- DROP TRIGGER IF EXISTS `trg_user_create_account`;
-- DELIMITER $$
-- CREATE TRIGGER `trg_user_create_account` AFTER INSERT ON `users`
-- FOR EACH ROW
-- BEGIN
--   IF NEW.status = 'active' THEN
--     INSERT INTO `user_accounts` (`user_id`, `balance`, `frozen_balance`, `total_income`, `total_expense`, `status`)
--     VALUES (NEW.id, 0.00, 0.00, 0.00, 0.00, 'active');
--   END IF;
-- END$$
-- DELIMITER ;

-- 2. 商家审核通过时自动创建账户
-- DROP TRIGGER IF EXISTS `trg_merchant_create_account`;
-- DELIMITER $$
-- CREATE TRIGGER `trg_merchant_create_account` AFTER UPDATE ON `merchants`
-- FOR EACH ROW
-- BEGIN
--   IF NEW.status = 'approved' AND OLD.status != 'approved' THEN
--     INSERT INTO `merchant_accounts` (`merchant_id`, `balance`, `frozen_balance`, `total_income`, `total_expense`, `status`)
--     VALUES (NEW.id, 0.00, 0.00, 0.00, 0.00, 'active');
--   END IF;
-- END$$
-- DELIMITER ;

-- ============================================================
-- 完成
-- ============================================================

SELECT '数据库初始化完成！' as message;
SELECT '已创建平台账户' as info;
