﻿-- =============================================
-- Business Database Initialization Script
-- 学业邑规划 - MiAssessment
-- 
-- This script creates all tables for the Business database
-- and inserts default configuration data
--
-- Database: SQL Server 2022
-- =============================================

USE [MiAssessment_Business];
GO

-- =============================================
-- 1. Create Users Table (用户表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[users]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[users] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [Uid] NVARCHAR(6) NOT NULL,                    -- 用户UID，6位数字
        [OpenId] NVARCHAR(64) NOT NULL,                -- 微信OpenId
        [UnionId] NVARCHAR(64) NULL,                   -- 微信UnionId
        [GzhOpenId] NVARCHAR(64) NULL,                 -- 公众号OpenId
        [Phone] NVARCHAR(20) NULL,                     -- 手机号
        [Nickname] NVARCHAR(50) NULL,                  -- 昵称
        [Avatar] NVARCHAR(500) NULL,                   -- 头像URL
        [UserLevel] INT NOT NULL DEFAULT 1,            -- 用户等级：1普通用户 2合伙人 3渠道合伙人
        [ParentUserId] BIGINT NULL,                    -- 上级用户ID
        [InviteCode] NVARCHAR(10) NULL,                -- 用户专属邀请码
        [Balance] DECIMAL(10,2) NOT NULL DEFAULT 0,    -- 可提现余额
        [TotalIncome] DECIMAL(10,2) NOT NULL DEFAULT 0,-- 累计收益
        [WithdrawnAmount] DECIMAL(10,2) NOT NULL DEFAULT 0, -- 已提现金额
        [Status] INT NOT NULL DEFAULT 1,               -- 状态：0禁用 1正常
        [IsTest] INT NOT NULL DEFAULT 0,               -- 是否测试用户
        [LastLoginTime] DATETIME2 NULL,                -- 最后登录时间
        [LastLoginIp] NVARCHAR(50) NULL,               -- 最后登录IP
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [UK_users_uid] ON [dbo].[users] ([Uid] ASC);
    CREATE UNIQUE NONCLUSTERED INDEX [UK_users_open_id] ON [dbo].[users] ([OpenId] ASC);
    CREATE NONCLUSTERED INDEX [IX_users_phone] ON [dbo].[users] ([Phone] ASC) WHERE [Phone] IS NOT NULL;
    CREATE NONCLUSTERED INDEX [IX_users_parent_user_id] ON [dbo].[users] ([ParentUserId] ASC);
    CREATE NONCLUSTERED INDEX [IX_users_user_level] ON [dbo].[users] ([UserLevel] ASC);
    
    PRINT N'Table users created successfully';
END
GO

-- =============================================
-- 2. Create User Refresh Tokens Table (刷新令牌表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[user_refresh_tokens]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[user_refresh_tokens] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [UserId] BIGINT NOT NULL,
        [TokenHash] NVARCHAR(256) NOT NULL,
        [ExpiresAt] DATETIME2 NOT NULL,
        [CreatedAt] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [CreatedByIp] NVARCHAR(50) NULL,
        [RevokedAt] DATETIME2 NULL,
        [RevokedByIp] NVARCHAR(50) NULL,
        [ReplacedByToken] NVARCHAR(256) NULL,
        CONSTRAINT [PK_user_refresh_tokens] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_user_refresh_tokens_user_id] ON [dbo].[user_refresh_tokens] ([UserId] ASC);
    CREATE NONCLUSTERED INDEX [IX_user_refresh_tokens_token_hash] ON [dbo].[user_refresh_tokens] ([TokenHash] ASC);
    
    PRINT N'Table user_refresh_tokens created successfully';
END
GO

-- =============================================
-- 3. Create User Login Logs Table (登录日志表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[user_login_logs]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[user_login_logs] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [UserId] BIGINT NOT NULL,
        [LoginType] NVARCHAR(20) NOT NULL,
        [LoginIp] NVARCHAR(50) NULL,
        [UserAgent] NVARCHAR(500) NULL,
        [Platform] NVARCHAR(20) NULL,
        [Status] INT NOT NULL DEFAULT 1,
        [FailReason] NVARCHAR(200) NULL,
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        CONSTRAINT [PK_user_login_logs] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_user_login_logs_user_id] ON [dbo].[user_login_logs] ([UserId] ASC);
    CREATE NONCLUSTERED INDEX [IX_user_login_logs_create_time] ON [dbo].[user_login_logs] ([CreateTime] DESC);
    
    PRINT N'Table user_login_logs created successfully';
END
GO

-- =============================================
-- 4. Create Banners Table (轮播图表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[banners]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[banners] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [Title] NVARCHAR(100) NULL,                    -- 标题
        [ImageUrl] NVARCHAR(500) NOT NULL,             -- 图片URL
        [LinkType] INT NOT NULL DEFAULT 0,             -- 跳转类型：0无 1内部页面 2外部链接 3小程序
        [LinkUrl] NVARCHAR(500) NULL,                  -- 跳转地址
        [AppId] NVARCHAR(50) NULL,                     -- 小程序AppId
        [Sort] INT NOT NULL DEFAULT 0,                 -- 排序
        [Status] INT NOT NULL DEFAULT 1,               -- 状态：0禁用 1启用
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_banners] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    PRINT N'Table banners created successfully';
END
GO

-- =============================================
-- 5. Create Promotions Table (宣传图表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[promotions]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[promotions] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [Title] NVARCHAR(100) NULL,                    -- 标题
        [ImageUrl] NVARCHAR(500) NOT NULL,             -- 图片URL
        [Position] INT NOT NULL DEFAULT 1,             -- 位置：1首页底部 2团队页
        [Sort] INT NOT NULL DEFAULT 0,                 -- 排序
        [Status] INT NOT NULL DEFAULT 1,               -- 状态：0禁用 1启用
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_promotions] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    PRINT N'Table promotions created successfully';
END
GO

-- =============================================
-- 6. Create Assessment Types Table (测评类型表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[assessment_types]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[assessment_types] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [Name] NVARCHAR(50) NOT NULL,                  -- 测评名称
        [Code] NVARCHAR(50) NOT NULL,                  -- 测评编码
        [ImageUrl] NVARCHAR(500) NULL,                 -- 入口图片
        [IntroContent] NVARCHAR(MAX) NULL,             -- 介绍内容
        [Price] DECIMAL(10,2) NOT NULL DEFAULT 0,      -- 价格
        [QuestionCount] INT NOT NULL DEFAULT 80,       -- 题目数量
        [Sort] INT NOT NULL DEFAULT 0,                 -- 排序
        [Status] INT NOT NULL DEFAULT 1,               -- 状态：0已下线 1已上线 2即将上线
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_assessment_types] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [UK_assessment_types_code] ON [dbo].[assessment_types] ([Code] ASC);
    
    PRINT N'Table assessment_types created successfully';
END
GO

-- =============================================
-- 7. Create Questions Table (题目表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[questions]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[questions] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [AssessmentTypeId] BIGINT NOT NULL,            -- 测评类型ID
        [QuestionNo] INT NOT NULL,                     -- 题号
        [Content] NVARCHAR(1000) NOT NULL,             -- 题目内容
        [Sort] INT NOT NULL DEFAULT 0,                 -- 排序
        [Status] INT NOT NULL DEFAULT 1,               -- 状态：0禁用 1启用
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_questions] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_questions_assessment_type_id] ON [dbo].[questions] ([AssessmentTypeId] ASC);
    CREATE UNIQUE NONCLUSTERED INDEX [UK_questions_type_no] ON [dbo].[questions] ([AssessmentTypeId], [QuestionNo]);
    
    PRINT N'Table questions created successfully';
END
GO

-- =============================================
-- 8. Create Report Categories Table (报告分类表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[report_categories]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[report_categories] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [AssessmentTypeId] BIGINT NOT NULL,            -- 测评类型ID
        [ParentId] BIGINT NOT NULL DEFAULT 0,          -- 父分类ID
        [Name] NVARCHAR(50) NOT NULL,                  -- 分类名称
        [Code] NVARCHAR(50) NOT NULL,                  -- 分类编码
        [CategoryType] INT NOT NULL,                   -- 分类类型：1八大智能 2个人特质 3细分能力 4先天学习 5学习能力 6大脑类型 7性格类型 8未来能力
        [ScoreRule] INT NOT NULL DEFAULT 1,            -- 计分规则：1累加(1-10分) 2二值(0/1分)
        [Sort] INT NOT NULL DEFAULT 0,                 -- 排序
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_report_categories] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_report_categories_assessment_type_id] ON [dbo].[report_categories] ([AssessmentTypeId] ASC);
    CREATE NONCLUSTERED INDEX [IX_report_categories_parent_id] ON [dbo].[report_categories] ([ParentId] ASC);
    CREATE NONCLUSTERED INDEX [IX_report_categories_category_type] ON [dbo].[report_categories] ([CategoryType] ASC);
    
    PRINT N'Table report_categories created successfully';
END
GO

-- =============================================
-- 9. Create Question Category Mappings Table (题目分类映射表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[question_category_mappings]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[question_category_mappings] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [QuestionId] BIGINT NOT NULL,                  -- 题目ID
        [CategoryId] BIGINT NOT NULL,                  -- 分类ID
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        CONSTRAINT [PK_question_category_mappings] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_question_category_mappings_question_id] ON [dbo].[question_category_mappings] ([QuestionId] ASC);
    CREATE NONCLUSTERED INDEX [IX_question_category_mappings_category_id] ON [dbo].[question_category_mappings] ([CategoryId] ASC);
    CREATE UNIQUE NONCLUSTERED INDEX [UK_question_category_mappings] ON [dbo].[question_category_mappings] ([QuestionId], [CategoryId]);
    
    PRINT N'Table question_category_mappings created successfully';
END
GO

-- =============================================
-- 10. Create Report Conclusions Table (报告结论表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[report_conclusions]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[report_conclusions] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [CategoryId] BIGINT NOT NULL,                  -- 分类ID
        [ConclusionType] INT NOT NULL,                 -- 结论类型：1最强 2较强 3较弱 4最弱
        [Title] NVARCHAR(100) NULL,                    -- 结论标题
        [Content] NVARCHAR(MAX) NOT NULL,              -- 结论内容
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_report_conclusions] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_report_conclusions_category_id] ON [dbo].[report_conclusions] ([CategoryId] ASC);
    
    PRINT N'Table report_conclusions created successfully';
END
GO

-- =============================================
-- 11. Create Orders Table (订单表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[orders]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[orders] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [OrderNo] NVARCHAR(32) NOT NULL,               -- 订单编号
        [UserId] BIGINT NOT NULL,                      -- 用户ID
        [OrderType] INT NOT NULL,                      -- 订单类型：1测评订单 2学业规划订单
        [ProductId] BIGINT NOT NULL,                   -- 商品ID
        [ProductName] NVARCHAR(100) NOT NULL,          -- 商品名称
        [Amount] DECIMAL(10,2) NOT NULL,               -- 订单金额
        [PayAmount] DECIMAL(10,2) NOT NULL,            -- 实付金额
        [PayType] INT NULL,                            -- 支付方式：1微信支付 2邀请码
        [InviteCodeId] BIGINT NULL,                    -- 使用的邀请码ID
        [Status] INT NOT NULL DEFAULT 1,               -- 状态：1待支付 2已支付 3已完成 4退款中 5已退款 6已取消
        [PayTime] DATETIME2 NULL,                      -- 支付时间
        [TransactionId] NVARCHAR(64) NULL,             -- 微信支付交易号
        [RefundTime] DATETIME2 NULL,                   -- 退款时间
        [RefundAmount] DECIMAL(10,2) NULL,             -- 退款金额
        [RefundReason] NVARCHAR(500) NULL,             -- 退款原因
        [Remark] NVARCHAR(500) NULL,                   -- 备注
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_orders] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [UK_orders_order_no] ON [dbo].[orders] ([OrderNo] ASC);
    CREATE NONCLUSTERED INDEX [IX_orders_user_id] ON [dbo].[orders] ([UserId] ASC);
    CREATE NONCLUSTERED INDEX [IX_orders_status] ON [dbo].[orders] ([Status] ASC);
    CREATE NONCLUSTERED INDEX [IX_orders_create_time] ON [dbo].[orders] ([CreateTime] DESC);
    CREATE NONCLUSTERED INDEX [IX_orders_order_type] ON [dbo].[orders] ([OrderType] ASC);
    
    PRINT N'Table orders created successfully';
END
GO

-- =============================================
-- 12. Create Order Notifies Table (订单通知表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[order_notifies]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[order_notifies] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [OrderNo] NVARCHAR(64) NOT NULL,
        [TransactionId] NVARCHAR(64) NULL,
        [NotifyUrl] NVARCHAR(500) NULL,
        [NonceStr] NVARCHAR(64) NULL,
        [PayTime] DATETIME2 NULL,
        [PayAmount] DECIMAL(10,2) NOT NULL DEFAULT 0,
        [Status] INT NOT NULL DEFAULT 0,
        [RetryCount] INT NOT NULL DEFAULT 0,
        [Attach] NVARCHAR(100) NULL,
        [OpenId] NVARCHAR(100) NULL,
        [RawData] NVARCHAR(MAX) NULL,
        [ErrorMessage] NVARCHAR(500) NULL,
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        CONSTRAINT [PK_order_notifies] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_order_notifies_order_no] ON [dbo].[order_notifies] ([OrderNo] ASC);
    CREATE NONCLUSTERED INDEX [IX_order_notifies_status] ON [dbo].[order_notifies] ([Status] ASC);
    
    PRINT N'Table order_notifies created successfully';
END
GO

-- =============================================
-- 13. Create Assessment Records Table (测评记录表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[assessment_records]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[assessment_records] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [UserId] BIGINT NOT NULL,                      -- 用户ID
        [OrderId] BIGINT NOT NULL,                     -- 订单ID
        [AssessmentTypeId] BIGINT NOT NULL,            -- 测评类型ID
        [Name] NVARCHAR(50) NOT NULL,                  -- 测评人姓名
        [Phone] NVARCHAR(20) NOT NULL,                 -- 手机号
        [Gender] INT NOT NULL,                         -- 性别：1男 2女
        [Age] INT NOT NULL,                            -- 年龄
        [EducationStage] INT NOT NULL,                 -- 学业阶段
        [Province] NVARCHAR(50) NOT NULL,              -- 省份
        [City] NVARCHAR(50) NOT NULL,                  -- 城市
        [District] NVARCHAR(50) NOT NULL,              -- 区县
        [Status] INT NOT NULL DEFAULT 1,               -- 状态：1待测评 2测评中 3生成中 4已完成
        [StartTime] DATETIME2 NULL,                    -- 开始答题时间
        [SubmitTime] DATETIME2 NULL,                   -- 提交答题时间
        [CompleteTime] DATETIME2 NULL,                 -- 报告生成完成时间
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_assessment_records] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_assessment_records_user_id] ON [dbo].[assessment_records] ([UserId] ASC);
    CREATE NONCLUSTERED INDEX [IX_assessment_records_order_id] ON [dbo].[assessment_records] ([OrderId] ASC);
    CREATE NONCLUSTERED INDEX [IX_assessment_records_status] ON [dbo].[assessment_records] ([Status] ASC);
    
    PRINT N'Table assessment_records created successfully';
END
GO

-- =============================================
-- 14. Create Assessment Answers Table (测评答案表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[assessment_answers]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[assessment_answers] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [RecordId] BIGINT NOT NULL,                    -- 测评记录ID
        [QuestionId] BIGINT NOT NULL,                  -- 题目ID
        [QuestionNo] INT NOT NULL,                     -- 题号
        [AnswerValue] INT NOT NULL,                    -- 答案值（1-10）
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        CONSTRAINT [PK_assessment_answers] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_assessment_answers_record_id] ON [dbo].[assessment_answers] ([RecordId] ASC);
    CREATE UNIQUE NONCLUSTERED INDEX [UK_assessment_answers] ON [dbo].[assessment_answers] ([RecordId], [QuestionId]);
    
    PRINT N'Table assessment_answers created successfully';
END
GO

-- =============================================
-- 15. Create Assessment Results Table (测评结果表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[assessment_results]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[assessment_results] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [RecordId] BIGINT NOT NULL,                    -- 测评记录ID
        [CategoryId] BIGINT NOT NULL,                  -- 分类ID
        [Score] DECIMAL(10,2) NOT NULL,                -- 得分
        [MaxScore] DECIMAL(10,2) NOT NULL,             -- 满分
        [Percentage] DECIMAL(5,2) NOT NULL,            -- 百分比
        [Rank] INT NOT NULL,                           -- 排名
        [StarLevel] INT NOT NULL,                      -- 星级（1-5）
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        CONSTRAINT [PK_assessment_results] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_assessment_results_record_id] ON [dbo].[assessment_results] ([RecordId] ASC);
    CREATE NONCLUSTERED INDEX [IX_assessment_results_category_id] ON [dbo].[assessment_results] ([CategoryId] ASC);
    
    PRINT N'Table assessment_results created successfully';
END
GO

-- =============================================
-- 16. Create Planners Table (规划师表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[planners]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[planners] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [Name] NVARCHAR(50) NOT NULL,                  -- 姓名
        [Avatar] NVARCHAR(500) NOT NULL,               -- 头像
        [Introduction] NVARCHAR(1000) NULL,            -- 简介
        [Price] DECIMAL(10,2) NOT NULL,                -- 咨询价格
        [Sort] INT NOT NULL DEFAULT 0,                 -- 排序
        [Status] INT NOT NULL DEFAULT 1,               -- 状态：0禁用 1启用
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_planners] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    PRINT N'Table planners created successfully';
END
GO

-- =============================================
-- 17. Create Planner Bookings Table (规划预约表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[planner_bookings]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[planner_bookings] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [UserId] BIGINT NOT NULL,                      -- 用户ID
        [OrderId] BIGINT NOT NULL,                     -- 订单ID
        [PlannerId] BIGINT NOT NULL,                   -- 规划师ID
        [BookingDate] DATE NOT NULL,                   -- 预约日期
        [BookingTime] NVARCHAR(20) NOT NULL,           -- 预约时间
        [Name] NVARCHAR(50) NOT NULL,                  -- 姓名
        [Phone] NVARCHAR(20) NOT NULL,                 -- 手机号
        [Gender] INT NOT NULL,                         -- 性别
        [Grade] INT NOT NULL,                          -- 年级
        [MajorName] NVARCHAR(100) NULL,                -- 专业名称
        [ScoreChinese] INT NULL,                       -- 语文成绩
        [ScoreMath] INT NULL,                          -- 数学成绩
        [ScoreEnglish] INT NULL,                       -- 英语成绩
        [ScorePhysics] INT NULL,                       -- 物理成绩
        [ScoreChemistry] INT NULL,                     -- 化学成绩
        [ScoreBiology] INT NULL,                       -- 生物成绩
        [ScoreGeography] INT NULL,                     -- 地理成绩
        [ScorePolitics] INT NULL,                      -- 政治成绩
        [FamilyAtmosphere] NVARCHAR(500) NULL,         -- 家庭氛围
        [Expectation] NVARCHAR(500) NULL,              -- 期望
        [Province] NVARCHAR(50) NULL,                  -- 省份
        [City] NVARCHAR(50) NULL,                      -- 城市
        [District] NVARCHAR(50) NULL,                  -- 区县
        [School] NVARCHAR(100) NULL,                   -- 学校
        [StudyInfo] NVARCHAR(1000) NULL,               -- 学情
        [Status] INT NOT NULL DEFAULT 1,               -- 状态：1待联系 2已联系 3已完成 4已取消
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_planner_bookings] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_planner_bookings_user_id] ON [dbo].[planner_bookings] ([UserId] ASC);
    CREATE NONCLUSTERED INDEX [IX_planner_bookings_planner_id] ON [dbo].[planner_bookings] ([PlannerId] ASC);
    CREATE NONCLUSTERED INDEX [IX_planner_bookings_booking_date] ON [dbo].[planner_bookings] ([BookingDate] ASC);
    
    PRINT N'Table planner_bookings created successfully';
END
GO

-- =============================================
-- 18. Create Invite Codes Table (邀请码表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[invite_codes]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[invite_codes] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [Code] NVARCHAR(10) NOT NULL,                  -- 邀请码
        [BatchNo] NVARCHAR(32) NULL,                   -- 批次号
        [AssignUserId] BIGINT NULL,                    -- 分配给的用户ID
        [AssignTime] DATETIME2 NULL,                   -- 分配时间
        [UseUserId] BIGINT NULL,                       -- 使用者用户ID
        [UseOrderId] BIGINT NULL,                      -- 使用的订单ID
        [UseTime] DATETIME2 NULL,                      -- 使用时间
        [Status] INT NOT NULL DEFAULT 1,               -- 状态：1未分配 2已分配 3已使用
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_invite_codes] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [UK_invite_codes_code] ON [dbo].[invite_codes] ([Code] ASC);
    CREATE NONCLUSTERED INDEX [IX_invite_codes_assign_user_id] ON [dbo].[invite_codes] ([AssignUserId] ASC);
    CREATE NONCLUSTERED INDEX [IX_invite_codes_status] ON [dbo].[invite_codes] ([Status] ASC);
    
    PRINT N'Table invite_codes created successfully';
END
GO

-- =============================================
-- 19. Create Commissions Table (佣金记录表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[commissions]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[commissions] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [UserId] BIGINT NOT NULL,                      -- 获得佣金的用户ID
        [FromUserId] BIGINT NOT NULL,                  -- 来源用户ID
        [OrderId] BIGINT NOT NULL,                     -- 关联订单ID
        [OrderAmount] DECIMAL(10,2) NOT NULL,          -- 订单金额
        [CommissionRate] DECIMAL(5,2) NOT NULL,        -- 佣金比例
        [CommissionAmount] DECIMAL(10,2) NOT NULL,     -- 佣金金额
        [Level] INT NOT NULL,                          -- 层级：1直接下级 2间接下级
        [Status] INT NOT NULL DEFAULT 1,               -- 状态：1待结算 2已结算
        [SettleTime] DATETIME2 NULL,                   -- 结算时间
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_commissions] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_commissions_user_id] ON [dbo].[commissions] ([UserId] ASC);
    CREATE NONCLUSTERED INDEX [IX_commissions_from_user_id] ON [dbo].[commissions] ([FromUserId] ASC);
    CREATE NONCLUSTERED INDEX [IX_commissions_order_id] ON [dbo].[commissions] ([OrderId] ASC);
    
    PRINT N'Table commissions created successfully';
END
GO

-- =============================================
-- 20. Create Withdrawals Table (提现记录表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[withdrawals]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[withdrawals] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [WithdrawalNo] NVARCHAR(32) NOT NULL,          -- 提现单号
        [UserId] BIGINT NOT NULL,                      -- 用户ID
        [Amount] DECIMAL(10,2) NOT NULL,               -- 提现金额
        [BeforeBalance] DECIMAL(10,2) NOT NULL,        -- 提现前余额
        [AfterBalance] DECIMAL(10,2) NOT NULL,         -- 提现后余额
        [Status] INT NOT NULL DEFAULT 1,               -- 状态：1申请中 2提现中 3已提现 4已取消
        [AuditUserId] BIGINT NULL,                     -- 审核人ID
        [AuditTime] DATETIME2 NULL,                    -- 审核时间
        [AuditRemark] NVARCHAR(500) NULL,              -- 审核备注
        [PayTime] DATETIME2 NULL,                      -- 打款时间
        [PayTransactionId] NVARCHAR(64) NULL,          -- 打款交易号
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_withdrawals] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [UK_withdrawals_withdrawal_no] ON [dbo].[withdrawals] ([WithdrawalNo] ASC);
    CREATE NONCLUSTERED INDEX [IX_withdrawals_user_id] ON [dbo].[withdrawals] ([UserId] ASC);
    CREATE NONCLUSTERED INDEX [IX_withdrawals_status] ON [dbo].[withdrawals] ([Status] ASC);
    
    PRINT N'Table withdrawals created successfully';
END
GO

-- =============================================
-- 21. Create Configs Table (系统配置表)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[configs]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[configs] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [ConfigKey] NVARCHAR(100) NOT NULL,            -- 配置键
        [ConfigValue] NVARCHAR(MAX) NOT NULL,          -- 配置值
        [ConfigType] NVARCHAR(50) NOT NULL,            -- 配置类型
        [Description] NVARCHAR(500) NULL,              -- 描述
        [Sort] INT NOT NULL DEFAULT 0,                 -- 排序
        [CreateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [UpdateTime] DATETIME2 NOT NULL DEFAULT GETDATE(),
        [IsDeleted] BIT NOT NULL DEFAULT 0,
        CONSTRAINT [PK_configs] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [UK_configs_key] ON [dbo].[configs] ([ConfigKey] ASC);
    
    PRINT N'Table configs created successfully';
END
GO

-- =============================================
-- Add Foreign Key Constraints (外键约束)
-- =============================================
PRINT N'Adding foreign key constraints...';

-- users -> users (parent)
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_users_parent')
BEGIN
    ALTER TABLE [dbo].[users] ADD CONSTRAINT [FK_users_parent] 
    FOREIGN KEY ([ParentUserId]) REFERENCES [dbo].[users]([Id]);
END

-- user_refresh_tokens -> users
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_user_refresh_tokens_user')
BEGIN
    ALTER TABLE [dbo].[user_refresh_tokens] ADD CONSTRAINT [FK_user_refresh_tokens_user] 
    FOREIGN KEY ([UserId]) REFERENCES [dbo].[users]([Id]);
END

-- user_login_logs -> users
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_user_login_logs_user')
BEGIN
    ALTER TABLE [dbo].[user_login_logs] ADD CONSTRAINT [FK_user_login_logs_user] 
    FOREIGN KEY ([UserId]) REFERENCES [dbo].[users]([Id]);
END

-- questions -> assessment_types
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_questions_assessment_type')
BEGIN
    ALTER TABLE [dbo].[questions] ADD CONSTRAINT [FK_questions_assessment_type] 
    FOREIGN KEY ([AssessmentTypeId]) REFERENCES [dbo].[assessment_types]([Id]);
END

-- report_categories -> assessment_types
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_report_categories_assessment_type')
BEGIN
    ALTER TABLE [dbo].[report_categories] ADD CONSTRAINT [FK_report_categories_assessment_type] 
    FOREIGN KEY ([AssessmentTypeId]) REFERENCES [dbo].[assessment_types]([Id]);
END

-- question_category_mappings -> questions
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_question_category_mappings_question')
BEGIN
    ALTER TABLE [dbo].[question_category_mappings] ADD CONSTRAINT [FK_question_category_mappings_question] 
    FOREIGN KEY ([QuestionId]) REFERENCES [dbo].[questions]([Id]);
END

-- question_category_mappings -> report_categories
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_question_category_mappings_category')
BEGIN
    ALTER TABLE [dbo].[question_category_mappings] ADD CONSTRAINT [FK_question_category_mappings_category] 
    FOREIGN KEY ([CategoryId]) REFERENCES [dbo].[report_categories]([Id]);
END

-- report_conclusions -> report_categories
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_report_conclusions_category')
BEGIN
    ALTER TABLE [dbo].[report_conclusions] ADD CONSTRAINT [FK_report_conclusions_category] 
    FOREIGN KEY ([CategoryId]) REFERENCES [dbo].[report_categories]([Id]);
END

-- orders -> users
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_orders_user')
BEGIN
    ALTER TABLE [dbo].[orders] ADD CONSTRAINT [FK_orders_user] 
    FOREIGN KEY ([UserId]) REFERENCES [dbo].[users]([Id]);
END

-- assessment_records -> users
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_assessment_records_user')
BEGIN
    ALTER TABLE [dbo].[assessment_records] ADD CONSTRAINT [FK_assessment_records_user] 
    FOREIGN KEY ([UserId]) REFERENCES [dbo].[users]([Id]);
END

-- assessment_records -> orders
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_assessment_records_order')
BEGIN
    ALTER TABLE [dbo].[assessment_records] ADD CONSTRAINT [FK_assessment_records_order] 
    FOREIGN KEY ([OrderId]) REFERENCES [dbo].[orders]([Id]);
END

-- assessment_records -> assessment_types
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_assessment_records_assessment_type')
BEGIN
    ALTER TABLE [dbo].[assessment_records] ADD CONSTRAINT [FK_assessment_records_assessment_type] 
    FOREIGN KEY ([AssessmentTypeId]) REFERENCES [dbo].[assessment_types]([Id]);
END

-- assessment_answers -> assessment_records
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_assessment_answers_record')
BEGIN
    ALTER TABLE [dbo].[assessment_answers] ADD CONSTRAINT [FK_assessment_answers_record] 
    FOREIGN KEY ([RecordId]) REFERENCES [dbo].[assessment_records]([Id]);
END

-- assessment_answers -> questions
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_assessment_answers_question')
BEGIN
    ALTER TABLE [dbo].[assessment_answers] ADD CONSTRAINT [FK_assessment_answers_question] 
    FOREIGN KEY ([QuestionId]) REFERENCES [dbo].[questions]([Id]);
END

-- assessment_results -> assessment_records
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_assessment_results_record')
BEGIN
    ALTER TABLE [dbo].[assessment_results] ADD CONSTRAINT [FK_assessment_results_record] 
    FOREIGN KEY ([RecordId]) REFERENCES [dbo].[assessment_records]([Id]);
END

-- assessment_results -> report_categories
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_assessment_results_category')
BEGIN
    ALTER TABLE [dbo].[assessment_results] ADD CONSTRAINT [FK_assessment_results_category] 
    FOREIGN KEY ([CategoryId]) REFERENCES [dbo].[report_categories]([Id]);
END

-- planner_bookings -> users
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_planner_bookings_user')
BEGIN
    ALTER TABLE [dbo].[planner_bookings] ADD CONSTRAINT [FK_planner_bookings_user] 
    FOREIGN KEY ([UserId]) REFERENCES [dbo].[users]([Id]);
END

-- planner_bookings -> orders
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_planner_bookings_order')
BEGIN
    ALTER TABLE [dbo].[planner_bookings] ADD CONSTRAINT [FK_planner_bookings_order] 
    FOREIGN KEY ([OrderId]) REFERENCES [dbo].[orders]([Id]);
END

-- planner_bookings -> planners
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_planner_bookings_planner')
BEGIN
    ALTER TABLE [dbo].[planner_bookings] ADD CONSTRAINT [FK_planner_bookings_planner] 
    FOREIGN KEY ([PlannerId]) REFERENCES [dbo].[planners]([Id]);
END

-- commissions -> users
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_commissions_user')
BEGIN
    ALTER TABLE [dbo].[commissions] ADD CONSTRAINT [FK_commissions_user] 
    FOREIGN KEY ([UserId]) REFERENCES [dbo].[users]([Id]);
END

-- commissions -> orders
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_commissions_order')
BEGIN
    ALTER TABLE [dbo].[commissions] ADD CONSTRAINT [FK_commissions_order] 
    FOREIGN KEY ([OrderId]) REFERENCES [dbo].[orders]([Id]);
END

-- withdrawals -> users
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE name = 'FK_withdrawals_user')
BEGIN
    ALTER TABLE [dbo].[withdrawals] ADD CONSTRAINT [FK_withdrawals_user] 
    FOREIGN KEY ([UserId]) REFERENCES [dbo].[users]([Id]);
END

PRINT N'Foreign key constraints added successfully';
GO

-- =============================================
-- Add Table Comments (表注释)
-- =============================================
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'用户表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'users';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'刷新令牌表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'user_refresh_tokens';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'登录日志表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'user_login_logs';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'轮播图表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'banners';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'宣传图表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'promotions';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'测评类型表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'assessment_types';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'题目表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'questions';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'报告分类表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'report_categories';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'题目分类映射表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'question_category_mappings';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'报告结论表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'report_conclusions';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'订单表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'orders';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'订单通知表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'order_notifies';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'测评记录表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'assessment_records';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'测评答案表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'assessment_answers';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'测评结果表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'assessment_results';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'规划师表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'planners';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'规划预约表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'planner_bookings';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'邀请码表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'invite_codes';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'佣金记录表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'commissions';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'提现记录表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'withdrawals';
EXEC sp_addextendedproperty @name=N'MS_Description', @value=N'系统配置表', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'configs';
GO

-- =============================================
-- Insert Default Data (默认数据)
-- =============================================
PRINT N'Inserting default data...';

-- 插入默认测评类型
IF NOT EXISTS (SELECT 1 FROM [dbo].[assessment_types] WHERE [Code] = 'MI_ASSESSMENT')
BEGIN
    INSERT INTO [dbo].[assessment_types] ([Name], [Code], [Price], [QuestionCount], [Sort], [Status])
    VALUES (N'多元智能测评', 'MI_ASSESSMENT', 99.00, 80, 1, 1);
    PRINT N'Default assessment type inserted';
END

-- 插入默认系统配置
IF NOT EXISTS (SELECT 1 FROM [dbo].[configs] WHERE [ConfigKey] = 'assessment_price')
BEGIN
    INSERT INTO [dbo].[configs] ([ConfigKey], [ConfigValue], [ConfigType], [Description])
    VALUES 
    ('assessment_price', '99.00', 'price', N'测评价格'),
    ('commission_rate_level1', '0.30', 'commission', N'一级分销佣金比例'),
    ('commission_rate_level2', '0.10', 'commission', N'二级分销佣金比例'),
    ('commission_rate_direct', '0.40', 'commission', N'无上级时直接佣金比例'),
    ('withdraw_min_amount', '10.00', 'withdraw', N'最低提现金额'),
    ('service_phone', '400-000-0000', 'contact', N'客服电话'),
    ('service_wechat', '', 'contact', N'客服微信'),
    ('user_agreement', '', 'agreement', N'用户协议内容'),
    ('privacy_policy', '', 'agreement', N'隐私政策内容'),
    ('about_us_content', '', 'content', N'关于我们内容');
    PRINT N'Default configs inserted';
END
GO

-- =============================================
-- Script Completion
-- =============================================
PRINT N'';
PRINT N'=============================================';
PRINT N'Business database initialization completed!';
PRINT N'=============================================';
PRINT N'Tables created: 21';
PRINT N'  - users (用户表)';
PRINT N'  - user_refresh_tokens (刷新令牌表)';
PRINT N'  - user_login_logs (登录日志表)';
PRINT N'  - banners (轮播图表)';
PRINT N'  - promotions (宣传图表)';
PRINT N'  - assessment_types (测评类型表)';
PRINT N'  - questions (题目表)';
PRINT N'  - report_categories (报告分类表)';
PRINT N'  - question_category_mappings (题目分类映射表)';
PRINT N'  - report_conclusions (报告结论表)';
PRINT N'  - orders (订单表)';
PRINT N'  - order_notifies (订单通知表)';
PRINT N'  - assessment_records (测评记录表)';
PRINT N'  - assessment_answers (测评答案表)';
PRINT N'  - assessment_results (测评结果表)';
PRINT N'  - planners (规划师表)';
PRINT N'  - planner_bookings (规划预约表)';
PRINT N'  - invite_codes (邀请码表)';
PRINT N'  - commissions (佣金记录表)';
PRINT N'  - withdrawals (提现记录表)';
PRINT N'  - configs (系统配置表)';
PRINT N'=============================================';
GO
