-- =============================================
-- 客户数据变更追踪系统 - 数据库建表脚本
-- =============================================

-- 1. 客户数据历史记录表
-- 用于保存客户数据的每个版本快照
DROP TABLE IF EXISTS `customer_export_data_history`;
CREATE TABLE `customer_export_data_history` (
    `history_id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '历史记录ID',
    `customer_id` BIGINT(20) NOT NULL COMMENT '客户ID（关联customer_export_data表的id）',
    `version` INT(11) NOT NULL COMMENT '版本号（从1开始递增）',
    `data_fingerprint` VARCHAR(64) NOT NULL COMMENT '数据指纹（MD5哈希值，用于快速判断数据是否变更）',
    `change_type` VARCHAR(20) NOT NULL COMMENT '变更类型：INSERT-新增, UPDATE-更新, DELETE-删除',
    `change_time` DATETIME NOT NULL COMMENT '变更时间',

    -- 以下字段为客户数据快照（与customer_export_data表结构一致）
    `customer_name` VARCHAR(255) DEFAULT NULL COMMENT '客户名称',
    `description` TEXT DEFAULT NULL COMMENT '描述',
    `gender` INT(11) DEFAULT NULL COMMENT '性别：0-未知, 1-男性, 2-女性',
    `add_user_name` VARCHAR(255) DEFAULT NULL COMMENT '添加人姓名',
    `add_user_account` VARCHAR(255) DEFAULT NULL COMMENT '添加人账号',
    `add_user_department` VARCHAR(255) DEFAULT NULL COMMENT '添加人所属部门',
    `add_time` DATETIME DEFAULT NULL COMMENT '添加时间',
    `add_date` DATE DEFAULT NULL COMMENT '添加日期',
    `source` VARCHAR(255) DEFAULT NULL COMMENT '来源',
    `mobile` VARCHAR(255) DEFAULT NULL COMMENT '手机号',
    `company` VARCHAR(255) DEFAULT NULL COMMENT '公司名称',
    `email` VARCHAR(255) DEFAULT NULL COMMENT '邮箱',
    `address` VARCHAR(500) DEFAULT NULL COMMENT '地址',
    `position` VARCHAR(255) DEFAULT NULL COMMENT '职位',
    `phone` VARCHAR(255) DEFAULT NULL COMMENT '电话',
    `tag_group_1` TEXT DEFAULT NULL COMMENT '标签组1(投放)',
    `tag_group_2` TEXT DEFAULT NULL COMMENT '标签组2(公司孵化)',
    `tag_group_3` TEXT DEFAULT NULL COMMENT '标签组3(商务)',
    `tag_group_4` TEXT DEFAULT NULL COMMENT '标签组4(成交日期)',
    `tag_group_5` TEXT DEFAULT NULL COMMENT '标签组5(年级组)',
    `tag_group_6` TEXT DEFAULT NULL COMMENT '标签组6(客户属性)',
    `tag_group_7` TEXT DEFAULT NULL COMMENT '标签组7(成交)',
    `tag_group_8` TEXT DEFAULT NULL COMMENT '标签组8(成交品牌)',
    `tag_group_9` TEXT DEFAULT NULL COMMENT '标签组9(线索通标签)',
    `tag_group_10` TEXT DEFAULT NULL COMMENT '标签组10(A1组)',
    `tag_group_11` TEXT DEFAULT NULL COMMENT '标签组11(B1组)',
    `tag_group_12` TEXT DEFAULT NULL COMMENT '标签组12(C1组)',
    `tag_group_13` TEXT DEFAULT NULL COMMENT '标签组13(D1组)',
    `tag_group_14` TEXT DEFAULT NULL COMMENT '标签组14(E1组)',
    `tag_group_15` TEXT DEFAULT NULL COMMENT '标签组15(意向度)',
    `tag_group_16` TEXT DEFAULT NULL COMMENT '标签组16(自然流)',
    `tag_group_17` TEXT DEFAULT NULL COMMENT '标签组17(F1组)',
    `tag_group_18` TEXT DEFAULT NULL COMMENT '标签组18(G1组)',

    PRIMARY KEY (`history_id`),
    KEY `idx_customer_id` (`customer_id`),
    KEY `idx_version` (`version`),
    KEY `idx_change_time` (`change_time`),
    KEY `idx_customer_version` (`customer_id`, `version`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='客户数据历史记录表';


-- 2. 客户数据变更日志表
-- 用于记录每个字段的具体变更内容
DROP TABLE IF EXISTS `customer_data_change_log`;
CREATE TABLE `customer_data_change_log` (
    `log_id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '日志ID',
    `history_id` BIGINT(20) NOT NULL COMMENT '历史记录ID（关联customer_export_data_history表）',
    `customer_id` BIGINT(20) NOT NULL COMMENT '客户ID',
    `version` INT(11) NOT NULL COMMENT '版本号',
    `field_name` VARCHAR(100) NOT NULL COMMENT '字段名称（英文）',
    `field_label` VARCHAR(100) NOT NULL COMMENT '字段标签（中文）',
    `old_value` TEXT DEFAULT NULL COMMENT '旧值',
    `new_value` TEXT DEFAULT NULL COMMENT '新值',
    `change_time` DATETIME NOT NULL COMMENT '变更时间',

    PRIMARY KEY (`log_id`),
    KEY `idx_history_id` (`history_id`),
    KEY `idx_customer_id` (`customer_id`),
    KEY `idx_version` (`version`),
    KEY `idx_field_name` (`field_name`),
    KEY `idx_change_time` (`change_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='客户数据变更日志表';


-- 3. 为customer_export_data表添加唯一索引
-- 使用"客户名称+添加人账号+添加时间"作为唯一标识
ALTER TABLE `customer_export_data` ADD UNIQUE INDEX `uk_customer_unique` (`customer_name`, `add_user_account`, `add_time`);


-- =============================================
-- Mapper XML 配置参考
-- =============================================

-- CustomerExportDataHistoryMapper.xml 需要添加以下SQL：

/*
<!-- 根据客户ID查询最大版本号 -->
<select id="selectMaxVersionByCustomerId" resultType="java.lang.Integer">
    SELECT MAX(version)
    FROM customer_export_data_history
    WHERE customer_id = #{customerId}
</select>

<!-- 根据客户ID和版本号查询历史记录 -->
<select id="selectByCustomerIdAndVersion" resultType="com.ruoyi.excel.wecom.domain.CustomerExportDataHistory">
    SELECT *
    FROM customer_export_data_history
    WHERE customer_id = #{customerId} AND version = #{version}
</select>

<!-- 根据客户ID查询所有历史记录（按版本号倒序） -->
<select id="selectHistoryByCustomerId" resultType="com.ruoyi.excel.wecom.domain.CustomerExportDataHistory">
    SELECT *
    FROM customer_export_data_history
    WHERE customer_id = #{customerId}
    ORDER BY version DESC
</select>
*/


-- CustomerDataChangeLogMapper.xml 需要添加以下SQL：

/*
<!-- 根据客户ID查询所有变更日志（按时间倒序） -->
<select id="selectChangeLogByCustomerId" resultType="com.ruoyi.excel.wecom.domain.CustomerDataChangeLog">
    SELECT *
    FROM customer_data_change_log
    WHERE customer_id = #{customerId}
    ORDER BY change_time DESC
</select>

<!-- 根据历史记录ID查询变更日志 -->
<select id="selectChangeLogByHistoryId" resultType="com.ruoyi.excel.wecom.domain.CustomerDataChangeLog">
    SELECT *
    FROM customer_data_change_log
    WHERE history_id = #{historyId}
    ORDER BY log_id
</select>

<!-- 根据客户ID和版本号查询变更日志 -->
<select id="selectChangeLogByCustomerIdAndVersion" resultType="com.ruoyi.excel.wecom.domain.CustomerDataChangeLog">
    SELECT *
    FROM customer_data_change_log
    WHERE customer_id = #{customerId} AND version = #{version}
    ORDER BY log_id
</select>

<!-- 批量插入变更日志 -->
<insert id="batchInsert" parameterType="java.util.List">
    INSERT INTO customer_data_change_log (
        history_id, customer_id, version, field_name, field_label,
        old_value, new_value, change_time
    ) VALUES
    <foreach collection="changeLogs" item="item" separator=",">
        (
            #{item.historyId}, #{item.customerId}, #{item.version},
            #{item.fieldName}, #{item.fieldLabel}, #{item.oldValue},
            #{item.newValue}, #{item.changeTime}
        )
    </foreach>
</insert>
*/


-- CustomerExportDataMapper.xml 需要添加以下SQL：

/*
<!-- 根据客户唯一标识查询客户数据（客户名称+添加人账号+添加时间） -->
<select id="selectByUniqueKey" resultType="com.ruoyi.excel.wecom.domain.CustomerExportData">
    SELECT *
    FROM customer_export_data
    WHERE customer_name = #{customerName}
      AND add_user_account = #{addUserAccount}
      AND add_time = #{addTime}
    LIMIT 1
</select>
*/


-- =============================================
-- 测试查询示例
-- =============================================

-- 查询某个客户的所有历史版本
-- SELECT * FROM customer_export_data_history WHERE customer_id = 1 ORDER BY version DESC;

-- 查询某个客户的所有变更日志
-- SELECT * FROM customer_data_change_log WHERE customer_id = 1 ORDER BY change_time DESC;

-- 查询某个版本的具体变更内容
-- SELECT * FROM customer_data_change_log WHERE customer_id = 1 AND version = 2;

-- 查询最近的变更记录（所有客户）
-- SELECT * FROM customer_data_change_log ORDER BY change_time DESC LIMIT 100;

-- 统计每个客户的版本数量
-- SELECT customer_id, COUNT(*) as version_count FROM customer_export_data_history GROUP BY customer_id;
