-- ============================================
-- 核心支付流程 - 数据库脚本（修复版）
-- 创建日期: 2026-01-23
-- 数据库: peixue
-- 说明: 兼容MySQL 5.7+，不使用 IF NOT EXISTS
-- ============================================

USE peixue;

-- ============================================
-- 1. 扩展订单表 (order)
-- ============================================

-- 检查并添加支付方式相关字段
SET @dbname = 'peixue';
SET @tablename = 'order';

-- payment_method
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'payment_method';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `payment_method` VARCHAR(50) COMMENT ''支付方式：wallet,timecard,package,wechat,mixed'' AFTER `payment_status`', 
    'SELECT ''Column payment_method already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- wallet_amount
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'wallet_amount';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `wallet_amount` DECIMAL(10,2) DEFAULT 0.00 COMMENT ''钱包支付金额''', 
    'SELECT ''Column wallet_amount already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- timecard_id
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'timecard_id';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `timecard_id` BIGINT COMMENT ''使用的次卡ID''', 
    'SELECT ''Column timecard_id already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- package_id
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'package_id';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `package_id` BIGINT COMMENT ''使用的套餐ID''', 
    'SELECT ''Column package_id already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- coupon_id
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'coupon_id';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `coupon_id` BIGINT COMMENT ''使用的优惠券ID''', 
    'SELECT ''Column coupon_id already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- coupon_discount
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'coupon_discount';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `coupon_discount` DECIMAL(10,2) DEFAULT 0.00 COMMENT ''优惠券折扣金额''', 
    'SELECT ''Column coupon_discount already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- service_address_id
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'service_address_id';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `service_address_id` BIGINT COMMENT ''服务地址ID''', 
    'SELECT ''Column service_address_id already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- original_amount
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'original_amount';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `original_amount` DECIMAL(10,2) COMMENT ''原价''', 
    'SELECT ''Column original_amount already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- discount_amount
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'discount_amount';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `discount_amount` DECIMAL(10,2) DEFAULT 0.00 COMMENT ''总折扣金额''', 
    'SELECT ''Column discount_amount already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- teacher_income
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'teacher_income';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `teacher_income` DECIMAL(10,2) DEFAULT 0.00 COMMENT ''陪伴员收益''', 
    'SELECT ''Column teacher_income already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- manager_commission
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'manager_commission';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `manager_commission` DECIMAL(10,2) DEFAULT 0.00 COMMENT ''管理师提成''', 
    'SELECT ''Column manager_commission already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- platform_income
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'platform_income';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `platform_income` DECIMAL(10,2) DEFAULT 0.00 COMMENT ''平台收益''', 
    'SELECT ''Column platform_income already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- settlement_status
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'settlement_status';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `settlement_status` TINYINT DEFAULT 0 COMMENT ''结算状态：0-未结算，1-已结算''', 
    'SELECT ''Column settlement_status already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- settlement_time
SET @col_exists = 0;
SELECT COUNT(*) INTO @col_exists FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = @tablename AND COLUMN_NAME = 'settlement_time';
SET @sql = IF(@col_exists = 0, 
    'ALTER TABLE `order` ADD COLUMN `settlement_time` DATETIME COMMENT ''结算时间''', 
    'SELECT ''Column settlement_time already exists'' AS message');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 添加索引（忽略已存在的索引错误）
ALTER TABLE `order` ADD INDEX `idx_timecard_id` (`timecard_id`);
ALTER TABLE `order` ADD INDEX `idx_package_id` (`package_id`);
ALTER TABLE `order` ADD INDEX `idx_coupon_id` (`coupon_id`);
ALTER TABLE `order` ADD INDEX `idx_service_address_id` (`service_address_id`);
ALTER TABLE `order` ADD INDEX `idx_settlement_status` (`settlement_status`);

-- ============================================
-- 2. 创建钱包表 (wallet)
-- ============================================

CREATE TABLE IF NOT EXISTS `wallet` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `user_id` BIGINT NOT NULL COMMENT '用户ID',
  `balance` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '余额',
  `frozen_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '冻结金额',
  `total_recharge` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '累计充值',
  `total_consume` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '累计消费',
  `total_withdraw` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '累计提现',
  `version` INT NOT NULL DEFAULT 0 COMMENT '乐观锁版本号',
  `tenant_id` BIGINT COMMENT '租户ID',
  `created_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT DEFAULT 0 COMMENT '删除标记',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_user_id` (`user_id`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='钱包表';

-- ============================================
-- 3. 创建钱包交易记录表 (wallet_transaction)
-- ============================================

CREATE TABLE IF NOT EXISTS `wallet_transaction` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `user_id` BIGINT NOT NULL COMMENT '用户ID',
  `wallet_id` BIGINT NOT NULL COMMENT '钱包ID',
  `order_id` BIGINT COMMENT '关联订单ID',
  `transaction_type` VARCHAR(50) NOT NULL COMMENT '交易类型：recharge-充值，consume-消费，refund-退款，withdraw-提现，income-收益',
  `amount` DECIMAL(10,2) NOT NULL COMMENT '交易金额',
  `balance_before` DECIMAL(10,2) NOT NULL COMMENT '交易前余额',
  `balance_after` DECIMAL(10,2) NOT NULL COMMENT '交易后余额',
  `transaction_no` VARCHAR(100) COMMENT '交易流水号',
  `payment_channel` VARCHAR(50) COMMENT '支付渠道：wechat,alipay',
  `status` TINYINT DEFAULT 1 COMMENT '状态：0-失败，1-成功，2-处理中',
  `remark` VARCHAR(500) COMMENT '备注',
  `tenant_id` BIGINT COMMENT '租户ID',
  `created_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT DEFAULT 0 COMMENT '删除标记',
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_wallet_id` (`wallet_id`),
  KEY `idx_order_id` (`order_id`),
  KEY `idx_transaction_no` (`transaction_no`),
  KEY `idx_created_time` (`created_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='钱包交易记录表';

-- ============================================
-- 4. 创建次卡表 (time_card)
-- ============================================

CREATE TABLE IF NOT EXISTS `time_card` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `user_id` BIGINT NOT NULL COMMENT '用户ID',
  `name` VARCHAR(100) NOT NULL COMMENT '次卡名称',
  `total_times` INT NOT NULL DEFAULT 0 COMMENT '总次数',
  `used_times` INT NOT NULL DEFAULT 0 COMMENT '已使用次数',
  `remaining_times` INT NOT NULL DEFAULT 0 COMMENT '剩余次数',
  `price` DECIMAL(10,2) NOT NULL COMMENT '价格',
  `expire_date` DATE COMMENT '过期日期',
  `status` TINYINT DEFAULT 1 COMMENT '状态：0-已过期，1-使用中，2-已用完',
  `version` INT NOT NULL DEFAULT 0 COMMENT '乐观锁版本号',
  `tenant_id` BIGINT COMMENT '租户ID',
  `created_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT DEFAULT 0 COMMENT '删除标记',
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_status` (`status`),
  KEY `idx_expire_date` (`expire_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='次卡表';

-- ============================================
-- 5. 创建次卡使用记录表 (time_card_usage)
-- ============================================

CREATE TABLE IF NOT EXISTS `time_card_usage` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `user_id` BIGINT NOT NULL COMMENT '用户ID',
  `timecard_id` BIGINT NOT NULL COMMENT '次卡ID',
  `order_id` BIGINT NOT NULL COMMENT '订单ID',
  `used_times` INT NOT NULL DEFAULT 1 COMMENT '使用次数',
  `remaining_times` INT NOT NULL COMMENT '剩余次数',
  `remark` VARCHAR(500) COMMENT '备注',
  `tenant_id` BIGINT COMMENT '租户ID',
  `created_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT DEFAULT 0 COMMENT '删除标记',
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_timecard_id` (`timecard_id`),
  KEY `idx_order_id` (`order_id`),
  KEY `idx_created_time` (`created_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='次卡使用记录表';

-- ============================================
-- 6. 创建优惠券表 (coupon)
-- ============================================

CREATE TABLE IF NOT EXISTS `coupon` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `name` VARCHAR(100) NOT NULL COMMENT '优惠券名称',
  `type` TINYINT NOT NULL COMMENT '类型：1-满减券，2-折扣券，3-代金券',
  `discount_type` TINYINT NOT NULL COMMENT '折扣类型：1-金额，2-折扣',
  `discount_value` DECIMAL(10,2) NOT NULL COMMENT '折扣值（金额或折扣率）',
  `min_amount` DECIMAL(10,2) DEFAULT 0.00 COMMENT '最低消费金额',
  `max_discount` DECIMAL(10,2) COMMENT '最大折扣金额',
  `total_quantity` INT NOT NULL COMMENT '发行总量',
  `received_quantity` INT DEFAULT 0 COMMENT '已领取数量',
  `used_quantity` INT DEFAULT 0 COMMENT '已使用数量',
  `start_time` DATETIME NOT NULL COMMENT '开始时间',
  `end_time` DATETIME NOT NULL COMMENT '结束时间',
  `status` TINYINT DEFAULT 1 COMMENT '状态：0-停用，1-启用',
  `tenant_id` BIGINT COMMENT '租户ID',
  `created_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT DEFAULT 0 COMMENT '删除标记',
  PRIMARY KEY (`id`),
  KEY `idx_status` (`status`),
  KEY `idx_start_end_time` (`start_time`, `end_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='优惠券表';

-- ============================================
-- 7. 创建用户优惠券表 (user_coupon)
-- ============================================

CREATE TABLE IF NOT EXISTS `user_coupon` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `user_id` BIGINT NOT NULL COMMENT '用户ID',
  `coupon_id` BIGINT NOT NULL COMMENT '优惠券ID',
  `order_id` BIGINT COMMENT '使用的订单ID',
  `status` TINYINT DEFAULT 0 COMMENT '状态：0-未使用，1-已使用，2-已过期',
  `receive_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '领取时间',
  `use_time` DATETIME COMMENT '使用时间',
  `expire_time` DATETIME NOT NULL COMMENT '过期时间',
  `tenant_id` BIGINT COMMENT '租户ID',
  `created_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT DEFAULT 0 COMMENT '删除标记',
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_coupon_id` (`coupon_id`),
  KEY `idx_order_id` (`order_id`),
  KEY `idx_status` (`status`),
  KEY `idx_expire_time` (`expire_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户优惠券表';

-- ============================================
-- 8. 创建用户地址表 (user_address)
-- ============================================

CREATE TABLE IF NOT EXISTS `user_address` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `user_id` BIGINT NOT NULL COMMENT '用户ID',
  `contact_name` VARCHAR(50) NOT NULL COMMENT '联系人姓名',
  `contact_phone` VARCHAR(20) NOT NULL COMMENT '联系电话',
  `province` VARCHAR(50) COMMENT '省份',
  `city` VARCHAR(50) COMMENT '城市',
  `district` VARCHAR(50) COMMENT '区县',
  `address` VARCHAR(200) NOT NULL COMMENT '详细地址',
  `address_tag` VARCHAR(20) COMMENT '地址标签：家，公司，学校',
  `longitude` DECIMAL(10,6) COMMENT '经度',
  `latitude` DECIMAL(10,6) COMMENT '纬度',
  `is_default` TINYINT DEFAULT 0 COMMENT '是否默认地址：0-否，1-是',
  `tenant_id` BIGINT COMMENT '租户ID',
  `created_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT DEFAULT 0 COMMENT '删除标记',
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_is_default` (`is_default`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户地址表';

-- ============================================
-- 9. 创建管理师提成表 (manager_commission)
-- ============================================

CREATE TABLE IF NOT EXISTS `manager_commission` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `manager_id` BIGINT NOT NULL COMMENT '管理师ID',
  `order_id` BIGINT NOT NULL COMMENT '订单ID',
  `order_amount` DECIMAL(10,2) NOT NULL COMMENT '订单金额',
  `commission_ratio` DECIMAL(5,2) NOT NULL DEFAULT 10.00 COMMENT '提成比例（%）',
  `commission_amount` DECIMAL(10,2) NOT NULL COMMENT '提成金额',
  `status` TINYINT DEFAULT 0 COMMENT '状态：0-未结算，1-已结算',
  `settlement_time` DATETIME COMMENT '结算时间',
  `remark` VARCHAR(500) COMMENT '备注',
  `tenant_id` BIGINT COMMENT '租户ID',
  `created_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT DEFAULT 0 COMMENT '删除标记',
  PRIMARY KEY (`id`),
  KEY `idx_manager_id` (`manager_id`),
  KEY `idx_order_id` (`order_id`),
  KEY `idx_status` (`status`),
  KEY `idx_created_time` (`created_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='管理师提成表';

-- ============================================
-- 完成提示
-- ============================================

SELECT '✅ 核心支付流程数据库脚本执行完成！' AS message;
