-- =====================================================
-- 客资管理系统数据库变更脚本
-- 适用于: mp-java 数据库
-- 创建时间: 2026-04-14
-- =====================================================

-- 1. 扩展客资表 - 添加派单、推荐人相关字段
ALTER TABLE cms_contact_lead
ADD COLUMN assigned_user_id INT DEFAULT NULL COMMENT '被分配的业务员用户ID',
ADD COLUMN referrer_user_id INT DEFAULT NULL COMMENT '推荐人用户ID（全民推荐）',
ADD COLUMN referral_fee DECIMAL(10,2) DEFAULT 0.00 COMMENT '推荐费金额',
ADD COLUMN referral_fee_paid TINYINT DEFAULT 0 COMMENT '推荐费是否已支付 0否 1是',
ADD COLUMN referrer_share DECIMAL(5,2) DEFAULT 0.00 COMMENT '推荐人分成比例%',
ADD COLUMN dispatch_time DATETIME DEFAULT NULL COMMENT '派单时间',
ADD COLUMN dispatch_admin_id INT DEFAULT NULL COMMENT '派单管理员ID',
ADD COLUMN follow_count INT DEFAULT 0 COMMENT '跟进次数',
ADD COLUMN last_follow_time DATETIME DEFAULT NULL COMMENT '最后跟进时间',
ADD COLUMN appointment_time DATETIME DEFAULT NULL COMMENT '预约时间',
ADD COLUMN deal_amount DECIMAL(12,2) DEFAULT NULL COMMENT '成交金额',
ADD COLUMN deal_time DATETIME DEFAULT NULL COMMENT '成交时间',
ADD COLUMN source_type VARCHAR(20) DEFAULT 'form' COMMENT '来源类型: form表单 website网站 miniapp小程序 referral推荐人 admin录入';

-- 创建索引
CREATE INDEX idx_lead_assigned ON cms_contact_lead(assigned_user_id);
CREATE INDEX idx_lead_referrer ON cms_contact_lead(referrer_user_id);
CREATE INDEX idx_lead_status ON cms_contact_lead(status);
CREATE INDEX idx_lead_source ON cms_contact_lead(source_type);

-- 2. 派单记录表
CREATE TABLE IF NOT EXISTS lead_dispatch (
    dispatch_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '派单ID',
    lead_id INT NOT NULL COMMENT '客资ID',
    from_user_id INT DEFAULT NULL COMMENT '原分配用户ID(如果重新分配)',
    to_user_id INT NOT NULL COMMENT '新分配用户ID(业务员)',
    admin_id INT NOT NULL COMMENT '执行派单的管理员ID',
    dispatch_remarks VARCHAR(500) DEFAULT NULL COMMENT '派单备注',
    dispatch_type TINYINT DEFAULT 1 COMMENT '派单类型: 1新分配 2重新分配 3抢单',
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '派单时间',
    INDEX idx_dispatch_lead (lead_id),
    INDEX idx_dispatch_to_user (to_user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='客资派单记录表';

-- 3. 跟进记录表
CREATE TABLE IF NOT EXISTS lead_follow_log (
    follow_id INT PRIMARY KEY AUTO_INCREMENT,
    lead_id INT NOT NULL COMMENT '客资ID',
    user_id INT NOT NULL COMMENT '跟进人ID',
    follow_type TINYINT NOT NULL COMMENT '跟进方式: 1电话 2微信 3上门 4短信 5其他',
    follow_content VARCHAR(1000) NOT NULL COMMENT '跟进内容',
    next_follow_time DATETIME DEFAULT NULL COMMENT '下次跟进时间',
    next_follow_plan VARCHAR(500) DEFAULT NULL COMMENT '下次跟进计划',
    attachment_urls VARCHAR(1000) DEFAULT NULL COMMENT '附件URLs(JSON数组)',
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_follow_lead (lead_id),
    INDEX idx_follow_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='客资跟进记录表';

-- 4. 推荐人关系表（全民推荐）
CREATE TABLE IF NOT EXISTS lead_referral (
    referral_id INT PRIMARY KEY AUTO_INCREMENT,
    referrer_user_id INT NOT NULL COMMENT '推荐人用户ID',
    referred_lead_id INT NOT NULL COMMENT '被推荐的客资ID',
    referral_code VARCHAR(32) DEFAULT NULL COMMENT '推荐码(用于匿名推荐)',
    referral_fee DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '推荐费',
    referral_status TINYINT DEFAULT 0 COMMENT '推荐状态: 0待确认 1有效 2无效 3已结算',
    customer_name VARCHAR(100) DEFAULT NULL COMMENT '客户姓名(匿名推荐时存储)',
    customer_phone VARCHAR(20) DEFAULT NULL COMMENT '客户电话(匿名推荐时存储)',
    settlement_time DATETIME DEFAULT NULL COMMENT '结算时间',
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_referral_referrer (referrer_user_id),
    INDEX idx_referral_lead (referred_lead_id),
    INDEX idx_referral_code (referral_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='客资推荐关系表';

-- 5. 用户角色扩展表（多管理员支持）
CREATE TABLE IF NOT EXISTS gxwebsoft_core.sys_user_role_extend (
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT NOT NULL COMMENT '用户ID',
    role_type VARCHAR(20) NOT NULL COMMENT '角色类型: admin管理员 salesman业务员 referrer推荐人',
    is_primary TINYINT DEFAULT 1 COMMENT '是否主角色 0否 1是',
    permissions JSON DEFAULT NULL COMMENT '权限配置(JSON)',
    max_leads INT DEFAULT NULL COMMENT '最大客资分配数(业务员)',
    commission_rate DECIMAL(5,2) DEFAULT NULL COMMENT '佣金比例%(业务员)',
    referral_bonus DECIMAL(10,2) DEFAULT NULL COMMENT '推荐奖金%(推荐人)',
    status TINYINT DEFAULT 1 COMMENT '状态: 0禁用 1启用',
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uk_user_role (user_id, role_type),
    INDEX idx_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户角色扩展表';

-- 6. 数据统计汇总表（定期生成报表用）
CREATE TABLE IF NOT EXISTS lead_statistics (
    stat_id INT PRIMARY KEY AUTO_INCREMENT,
    stat_date DATE NOT NULL COMMENT '统计日期',
    user_id INT DEFAULT NULL COMMENT '用户ID(Null表示全站)',
    role_type VARCHAR(20) DEFAULT NULL COMMENT '角色类型',
    total_leads INT DEFAULT 0 COMMENT '总客资数',
    new_leads INT DEFAULT 0 COMMENT '新增客资数',
    assigned_leads INT DEFAULT 0 COMMENT '已分配客资数',
    followed_leads INT DEFAULT 0 COMMENT '已跟进客资数',
    dealed_leads INT DEFAULT 0 COMMENT '已成交客资数',
    deal_amount DECIMAL(15,2) DEFAULT 0.00 COMMENT '成交总金额',
    referral_count INT DEFAULT 0 COMMENT '推荐成功数',
    referral_fee DECIMAL(12,2) DEFAULT 0.00 COMMENT '推荐费总额',
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uk_stat_date_user (stat_date, user_id, role_type),
    INDEX idx_stat_date (stat_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='客资数据统计表';

-- 7. 推荐费结算记录表
CREATE TABLE IF NOT EXISTS lead_referral_settlement (
    settlement_id INT PRIMARY KEY AUTO_INCREMENT,
    referral_id INT NOT NULL COMMENT '推荐关系ID',
    referrer_user_id INT NOT NULL COMMENT '推荐人ID',
    lead_id INT NOT NULL COMMENT '关联客资ID',
    settlement_amount DECIMAL(10,2) NOT NULL COMMENT '结算金额',
    settlement_type TINYINT DEFAULT 1 COMMENT '结算方式: 1自动 2手动',
    settlement_admin_id INT DEFAULT NULL COMMENT '操作管理员ID',
    settlement_remarks VARCHAR(500) DEFAULT NULL COMMENT '结算备注',
    status TINYINT DEFAULT 0 COMMENT '状态: 0待确认 1已转账 2已到账',
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    confirm_time DATETIME DEFAULT NULL COMMENT '确认时间',
    INDEX idx_settlement_referrer (referrer_user_id),
    INDEX idx_settlement_lead (lead_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='推荐费结算记录表';

-- =====================================================
-- 初始化数据
-- =====================================================

-- 插入默认管理员角色扩展
INSERT INTO gxwebsoft_core.sys_user_role_extend (user_id, role_type, is_primary, permissions, status)
SELECT user_id, 'admin', 1, '{"canDispatch": true, "canManageUsers": true, "canViewStats": true, "canSetCommission": true}', 1
FROM gxwebsoft_core.sys_user WHERE status = 0 AND deleted = 0 LIMIT 1;

-- =====================================================
-- 视图: 客资完整信息视图
-- =====================================================
CREATE OR REPLACE VIEW v_lead_full_info AS
SELECT
    l.lead_id,
    l.name AS customer_name,
    l.phone AS customer_phone,
    l.company,
    l.need AS requirement,
    l.status,
    l.source_type,
    l.create_time,
    l.dispatch_time,
    l.deal_amount,
    l.deal_time,
    l.referral_fee,
    l.referral_fee_paid,
    au.user_id AS assigned_user_id,
    au.nickname AS assigned_user_name,
    au.real_name AS assigned_real_name,
    au.phone AS assigned_user_phone,
    ru.user_id AS referrer_user_id,
    ru.nickname AS referrer_name,
    ru.phone AS referrer_phone,
    admin.user_id AS dispatch_admin_id,
    admin.nickname AS dispatch_admin_name,
    l.follow_count,
    l.last_follow_time,
    l.appointment_time,
    CASE l.status
        WHEN 0 THEN '待跟进'
        WHEN 1 THEN '跟进中'
        WHEN 2 THEN '已成交'
        WHEN 3 THEN '无效'
        ELSE '未知'
    END AS status_text
FROM cms_contact_lead l
LEFT JOIN gxwebsoft_core.sys_user au ON l.assigned_user_id = au.user_id
LEFT JOIN gxwebsoft_core.sys_user ru ON l.referrer_user_id = ru.user_id
LEFT JOIN gxwebsoft_core.sys_user admin ON l.dispatch_admin_id = admin.user_id
WHERE l.deleted = 0;
