package jnpf.cultivate.v2.controller.web.old;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.base.ActionResult;
import jnpf.cultivate.V2CultivateOldDealApi;
import jnpf.cultivate.mapper.*;
import jnpf.cultivate.service.CultivateIdentifyItemsService;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.cultivate.v2.service.FtbCultivateIdentifyItemsPoolService;
import jnpf.cultivate.v2.service.V2CourseGainedCommentService;
import jnpf.cultivate.v2.service.V2CultivateExamService;
import jnpf.cultivate.v2.util.CultivateIdentityUtil;
import jnpf.entity.cultivate.CultivateIdentifyApply;
import jnpf.entity.cultivate.CultivateIdentifyItems;
import jnpf.enums.AppraisalScoreTypeEnum;
import jnpf.model.cultivate.po.FtbCultivateIdentifyItemsPool;
import jnpf.model.cultivate.po.exam.FtbCultivateExamUser;
import jnpf.model.cultivate.po.learn.*;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionMemberNew;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionSetting;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionUser;
import jnpf.model.cultivate.po.task.FtbCultivateTaskLog;
import jnpf.model.enums.SelfrowingEnum;
import jnpf.permission.entity.UserEntity;
import jnpf.util.CustomTenantUtil;
import jnpf.util.NoDataSourceBind;
import jnpf.util.SelfGrowthUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 培训旧数据处理模块
 */
@RestController
@Slf4j
@RequestMapping("/v2/cultivate/old")
public class V2CultivateOldDealController implements V2CultivateOldDealApi {

    @Autowired
    private V2CourseGainedCommentService ftbCourseGainedCommentService;

    @Autowired
    private UserApiV2Util userApiV2Util;

    @Resource
    private V2CultivateExamService v2CultivateExamService;
    @Resource
    private CustomTenantUtil customTenantUtil;

    @Autowired
    private FtbCultivateIdentifyItemsPoolService itemsPoolService;

    @Autowired
    private CultivateIdentifyItemsService itemsService;

    @Resource
    private FtbCultivateLearnTaskMapper ftbCultivateLearnTaskMapper;

    @Resource
    private FtbCultivateLearnTaskAssignmentMapper ftbCultivateLearnTaskAssignmentMapper;

    @Resource
    private FtbCultivateLearnTaskCourseMapper ftbCultivateLearnTaskCourseMapper;

    @Resource
    private FtbCultivateLearnTaskExamMapper ftbCultivateLearnTaskExamMapper;

    @Resource
    private FtbCultivateLearnTaskIdentificationMapper ftbCultivateLearnTaskIdentificationMapper;

    @Resource
    private FtbCultivateLearnTaskCertificateMapper ftbCultivateLearnTaskCertificateMapper;

    @Resource
    private FtbCultivateTaskLogMapper ftbCultivateTaskLogMapper;

    @Resource
    private FtbCultivateCourseLearningLogMapper ftbCultivateCourseLearningLogMapper;

    @Resource
    private FtbCultivatePositionCourceLearningMapper ftbCultivatePositionCourceLearningMapper;

    @Resource
    private FtbCultivateExamUserMapper ftbCultivateExamUserMapper;

    @Resource
    private CultivateIdentifyApplyMapper cultivateIdentifyApplyMapper;

    @Resource
    private FtbCultivatePromotionMemberNewMapper ftbCultivatePromotionMemberNewMapper;

    @Resource
    private FtbCultivatePromotionUserMapper ftbCultivatePromotionUserMapper;

    @Resource
    private FtbCultivatePromotionSettingMapper ftbCultivatePromotionSettingMapper;


    /**
     * 课程心得评论旧数据处理 V2.0版本 上线处理
     *
     * @param tenantId 租户ID
     * @return 响应
     */
    @NoDataSourceBind
    @GetMapping("/gained/comment")
    @Override
    public ActionResult<Boolean> dealOldData(@RequestParam("tenantId") String tenantId) {
        userApiV2Util.checkOutTenant(tenantId);
        Boolean result = ftbCourseGainedCommentService.dealOldData(tenantId);
        return ActionResult.success(result);
    }

    /**
     * 鉴定项旧数据处理
     *
     * @param tenantId 租户ID
     * @return 响应
     */
    @NoDataSourceBind
    @GetMapping("/identify/deal-old")
    @Override
    @Transactional
    public ActionResult<Boolean> identifyDealOldData(String tenantId) {

        userApiV2Util.checkOutTenant(tenantId);
        // 1. 查询所有未删除的鉴定项
        List<CultivateIdentifyItems> allItems = itemsService.list(
                Wrappers.<CultivateIdentifyItems>lambdaQuery()
                        .eq(CultivateIdentifyItems::getPoolId, "")
                        .eq(CultivateIdentifyItems::getDeleteMark, 0)
        );

        if (allItems == null || allItems.isEmpty()) {
            return ActionResult.success(true);
        }
        List<FtbCultivateIdentifyItemsPool> ftbCultivateIdentifyItemsPools = itemsPoolService.listAll();
        Map<String, String> oldItemsMap = new HashMap<>();
        Map<String, String> oldBisinessIdMap = new HashMap<>();
        Map<String, FtbCultivateIdentifyItemsPool> oldPoolMap = new HashMap<>();
        if (CollUtil.isNotEmpty(ftbCultivateIdentifyItemsPools)) {
            for (FtbCultivateIdentifyItemsPool pool : ftbCultivateIdentifyItemsPools) {
                oldItemsMap.put(CultivateIdentityUtil.buildRepeatKey(pool), pool.getId());
                oldPoolMap.put(CultivateIdentityUtil.buildRepeatKey(pool), pool);
            }
        }
        List<CultivateIdentifyItems> needAdd = new ArrayList<>();
        for (CultivateIdentifyItems item : allItems) {
            String itemString = CultivateIdentityUtil.buildRepeatKey(item);
            String poolId = oldItemsMap.get(itemString);

            if (StringUtils.isEmpty(poolId)) {
                poolId = UserApiV2Util.generateId();
                oldItemsMap.put(itemString, poolId);
                item.setBusinessId(SelfGrowthUtil.provideACustomIDBasedOnTheModule(SelfrowingEnum.ITEM_POOL));
                oldBisinessIdMap.put(itemString, item.getBusinessId());
                needAdd.add(item);
            } else {
                item.setBusinessId(oldBisinessIdMap.get(itemString));
            }
            item.setPoolId(poolId);
        }

        itemsService.updateBatchById(allItems);
        // 3. 为每组创建鉴定项池记录，并更新鉴定项的poolId
        List<FtbCultivateIdentifyItemsPool> poolList = new ArrayList<>();
        if (CollUtil.isNotEmpty(needAdd)) {
            for (CultivateIdentifyItems identifyItems : needAdd) {
                // 创建鉴定项池记录
                FtbCultivateIdentifyItemsPool pool = new FtbCultivateIdentifyItemsPool();
                pool.setId(identifyItems.getPoolId());
                pool.setName(identifyItems.getName());
                pool.setType(identifyItems.getType());
                pool.setCateId("2");
                if (identifyItems.getType().equals(AppraisalScoreTypeEnum.FIXED.getCode())) {
                    pool.setTotalScore(identifyItems.getScore().intValue());
                } else {
                    pool.setMinScore(identifyItems.getMinScore());
                    pool.setMaxScore(identifyItems.getMaxScore());
                }
                pool.setBusinessId(identifyItems.getBusinessId());
                pool.setEnabledMark(0);
                pool.setCreatorUserId("349057407209541");
                pool.setCreatorTime(new Date());
                pool.setLastModifyUserId("349057407209541");
                pool.setLastModifyTime(new Date());
                poolList.add(pool);
            }
        }

        if (CollUtil.isNotEmpty(poolList)) {
            itemsPoolService.saveBatch(poolList);
        }
        return ActionResult.success(true);
    }

    @NoDataSourceBind
    @GetMapping(value = "/deal-data")
    public ActionResult<Boolean> dealExamOldData(@RequestParam String tenantId) {

        customTenantUtil.checkOutTenant(tenantId);
        Boolean b = v2CultivateExamService.dealExamOldData();
        return ActionResult.success(b);
    }

    /**
     * 迁移旧培训任务数据到新的任务日志表
     * 将旧培训任务中每个人的学习情况同步到新建立的中间表中 ftb_cultivate_task_log
     * 默认第一阶段的阶段id就是用任务的主键id
     *
     * @param tenantId 租户ID
     * @return 响应
     */
    @NoDataSourceBind
    @GetMapping("/task/old-data")
    @Transactional
    @Override
    public ActionResult<String> migrateOldTaskData(@RequestParam("tenantId") String tenantId) {
        userApiV2Util.checkOutTenant(tenantId);

        try {
            log.info("开始迁移旧培训任务数据...");

            // 1. 查询所有有效的旧培训任务
            List<FtbCultivateLearnTask> allTasks = ftbCultivateLearnTaskMapper.selectList(
                    Wrappers.<FtbCultivateLearnTask>lambdaQuery()
                            .eq(FtbCultivateLearnTask::getEnableMark, 0)
            );

            if (allTasks == null || allTasks.isEmpty()) {
                log.info("没有找到有效的培训任务");
                return ActionResult.success("没有找到需要迁移的数据");
            }

            log.info("共找到 {} 个有效培训任务", allTasks.size());

            // 预加载所有任务的课程、考试、鉴定、证书配置，避免N+1查询
            Map<String, List<FtbCultivateLearnTaskCourse>> taskCoursesMap = new HashMap<>();
            Map<String, List<FtbCultivateLearnTaskExam>> taskExamsMap = new HashMap<>();
            Map<String, List<FtbCultivateLearnTaskIdentification>> taskIdentificationsMap = new HashMap<>();
            Map<String, List<FtbCultivateLearnTaskCertificate>> taskCertificatesMap = new HashMap<>();

            // 提取所有任务ID
            List<String> taskIds = allTasks.stream()
                    .map(FtbCultivateLearnTask::getId)
                    .collect(Collectors.toList());


            // 批量查询所有任务关联的课程
            List<FtbCultivateLearnTaskCourse> allCourses = ftbCultivateLearnTaskCourseMapper.selectList(
                    Wrappers.<FtbCultivateLearnTaskCourse>lambdaQuery()
                            .in(FtbCultivateLearnTaskCourse::getTaskId, taskIds)
                            .eq(FtbCultivateLearnTaskCourse::getEnableMark, 0)
            );
            // 按任务ID分组
            taskCoursesMap = allCourses.stream()
                    .collect(Collectors.groupingBy(FtbCultivateLearnTaskCourse::getTaskId));

            // 批量查询所有任务关联的考试
            List<FtbCultivateLearnTaskExam> allExams = ftbCultivateLearnTaskExamMapper.selectList(
                    Wrappers.<FtbCultivateLearnTaskExam>lambdaQuery()
                            .in(FtbCultivateLearnTaskExam::getTaskId, taskIds)
                            .eq(FtbCultivateLearnTaskExam::getEnableMark, 0)
            );
            // 按任务ID分组
            taskExamsMap = allExams.stream()
                    .collect(Collectors.groupingBy(FtbCultivateLearnTaskExam::getTaskId));

            // 批量查询所有任务关联的鉴定
            List<FtbCultivateLearnTaskIdentification> allIdentifications = ftbCultivateLearnTaskIdentificationMapper.selectList(
                    Wrappers.<FtbCultivateLearnTaskIdentification>lambdaQuery()
                            .in(FtbCultivateLearnTaskIdentification::getTaskId, taskIds)
                            .eq(FtbCultivateLearnTaskIdentification::getEnableMark, 0)
            );
            // 按任务ID分组
            taskIdentificationsMap = allIdentifications.stream()
                    .collect(Collectors.groupingBy(FtbCultivateLearnTaskIdentification::getTaskId));

            // 批量查询所有任务关联的证书
            List<FtbCultivateLearnTaskCertificate> allCertificates = ftbCultivateLearnTaskCertificateMapper.selectList(
                    Wrappers.<FtbCultivateLearnTaskCertificate>lambdaQuery()
                            .in(FtbCultivateLearnTaskCertificate::getTaskId, taskIds)
                            .eq(FtbCultivateLearnTaskCertificate::getEnableMark, 0)
            );
            // 按任务ID分组
            taskCertificatesMap = allCertificates.stream()
                    .collect(Collectors.groupingBy(FtbCultivateLearnTaskCertificate::getTaskId));


            log.info("完成预加载任务配置信息");

            int totalMigrated = 0;
            int processedTaskCount = 0;
            Date now = new Date();

            // 2. 遍历每个任务，处理其关联的用户学习情况
            for (FtbCultivateLearnTask task : allTasks) {
                String taskId = task.getId();
                processedTaskCount++;

                if (processedTaskCount % 10 == 0) {
                    log.info("正在处理第 {}/{} 个任务: {}", processedTaskCount, allTasks.size(), task.getTaskName());
                }

                // 3. 查询该任务下所有分配的用户
                List<FtbCultivateLearnTaskAssignment> assignments = ftbCultivateLearnTaskAssignmentMapper.selectList(
                        Wrappers.<FtbCultivateLearnTaskAssignment>lambdaQuery()
                                .eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId)
                                .eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0)
                );

                if (assignments == null || assignments.isEmpty()) {
                    continue;
                }

                // 获取该任务的配置信息
                List<FtbCultivateLearnTaskCourse> courses = taskCoursesMap.getOrDefault(taskId, new ArrayList<>());
                List<FtbCultivateLearnTaskExam> exams = taskExamsMap.getOrDefault(taskId, new ArrayList<>());
                List<FtbCultivateLearnTaskIdentification> identifications = taskIdentificationsMap.getOrDefault(taskId, new ArrayList<>());
                List<FtbCultivateLearnTaskCertificate> certificates = taskCertificatesMap.getOrDefault(taskId, new ArrayList<>());

                // 准备批量插入/更新的列表
                List<FtbCultivateTaskLog> toInsert = new ArrayList<>();
                List<FtbCultivateTaskLog> toUpdate = new ArrayList<>();

                // 4. 为每个用户创建或更新任务日志记录
                for (FtbCultivateLearnTaskAssignment assignment : assignments) {
                    String userId = assignment.getUserId();

                    // 使用任务ID作为第一阶段ID
                    String phaseId = taskId;

                    // 检查是否已存在该任务-用户-阶段的日志记录
                    FtbCultivateTaskLog existingLog = ftbCultivateTaskLogMapper.selectOne(
                            Wrappers.<FtbCultivateTaskLog>lambdaQuery()
                                    .eq(FtbCultivateTaskLog::getTaskId, taskId)
                                    .eq(FtbCultivateTaskLog::getUserId, userId)
                                    .eq(FtbCultivateTaskLog::getPhaseId, phaseId)
                                    .eq(FtbCultivateTaskLog::getEnabledMark, 0)
                    );

                    FtbCultivateTaskLog taskLog;
                    if (existingLog != null) {
                        // 如果已存在，则更新
                        taskLog = existingLog;
                    } else {
                        // 如果不存在，则创建新记录
                        taskLog = new FtbCultivateTaskLog();
                        taskLog.setTaskId(taskId);
                        taskLog.setUserId(userId);
                        taskLog.setPhaseId(phaseId);
                        taskLog.setEnabledMark(0);
                        taskLog.setCreatorUserId(userId);
                        taskLog.setCreatorTime(now);
                    }

                    // 设置基本状态信息
                    // 根据用户的学习状态设置任务日志状态
                    // 学习状态 0未开始，1进行中，2已完成，3已逾期
                    Integer studyStats = assignment.getStudyStats();
                    if (studyStats == 2) {
                        taskLog.setState(2); // 2-已完成
                    } else {
                        taskLog.setState(1); // 默认未完成
                    }

                    if (CollUtil.isNotEmpty(certificates)) {
                        // 设置证书颁发状态
                        taskLog.setIssuedCertificate(assignment.getIssuedCertificate());
                    } else {
                        taskLog.setIssuedCertificate(-1); // 默认未配置证书
                    }

                    // 查询并设置课程状态：检查用户对任务中所有课程的完成情况
                    if (!courses.isEmpty()) {
                        // 提取所有课程ID
                        List<String> courseIds = new ArrayList<>();
                        for (FtbCultivateLearnTaskCourse course : courses) {
                            courseIds.add(course.getCourseId());
                        }

                        // 查询用户对这些课程的完成情况（使用ftb_cultivate_position_cource_learning表）
                        Long completedCount = ftbCultivatePositionCourceLearningMapper.countCompletedCoursesByUserAndCourseIds(
                                courseIds, userId
                        );

                        // 判断是否所有课程都已完成
                        boolean allCoursesCompleted = false;
                        if (completedCount != null && completedCount > 0) {
                            // 如果完成的课程数量等于任务配置的课程数量，则全部完成
                            allCoursesCompleted = completedCount >= courseIds.size();
                        }

                        // 设置课程状态：1-已完成，0-未完成
                        taskLog.setCourseState(allCoursesCompleted ? 1 : 0);
                    } else {
                        taskLog.setCourseState(-1); // 未配置课程
                    }

                    // 设置考试状态：查询用户对任务中所有考试的完成情况
                    if (!exams.isEmpty()) {
                        // 提取所有考试ID
                        List<String> examIds = new ArrayList<>();
                        for (FtbCultivateLearnTaskExam exam : exams) {
                            examIds.add(exam.getExamId());
                        }

                        // 查询用户对这些考试的记录（使用ftb_cultivate_exam_user表）
                        List<FtbCultivateExamUser> examUsers = ftbCultivateExamUserMapper.selectList(
                                Wrappers.<FtbCultivateExamUser>lambdaQuery()
                                        .in(FtbCultivateExamUser::getExamId, examIds)
                                        .eq(FtbCultivateExamUser::getUserId, userId)
                                        .eq(FtbCultivateExamUser::getExamSource, 4)
                                        .eq(FtbCultivateExamUser::getRelationTaskId, taskId)
                                        .orderByDesc(FtbCultivateExamUser::getCreatorTime)
                                        .eq(FtbCultivateExamUser::getEnabledMark, 1)
                        );

                        // 判断是否有合格或优秀的考试记录
                        boolean examCompleted = false;
                        if (CollUtil.isNotEmpty(examUsers)) {
                            // 检查是否有合格(3)或优秀(5)的记录
                            if (examUsers.get(0).getStatus() == 3 || examUsers.get(0).getStatus() == 4 || examUsers.get(0).getStatus() == 5) {
                                examCompleted = true;
                            }
                            taskLog.setExamResult(examUsers.get(0).getStatus());
                            taskLog.setUserExamId(examUsers.get(0).getId());
                            taskLog.setExamState(examCompleted ? 1 : 0);
                        } else {
                            taskLog.setExamState(-1); // 未配置考试
                            taskLog.setExamResult(-1); // 未配置考试
                        }

                    }

                    // 设置鉴定状态：如果有鉴定配置则为0(未完成)，否则为-1(未配置)，再查询一下这个鉴定关联的数据
                    if (!identifications.isEmpty()) {
                        // 提取所有鉴定ID
                        List<String> identifyIds = new ArrayList<>();
                        for (FtbCultivateLearnTaskIdentification identification : identifications) {
                            identifyIds.add(identification.getIdentificationId());
                        }

                        // 查询用户对这些鉴定的记录（使用ftb_cultivate_identify_apply表，关联ftb_cultivate_identify_apply_table_backups）
                        List<CultivateIdentifyApply> identifyApplies = cultivateIdentifyApplyMapper.queryIdentifyApply(
                                userId,
                                identifyIds,
                                4, // 4-任务鉴定
                                taskId
                        );

                        // 判断是否有合格或优秀的鉴定记录

                        if (CollUtil.isNotEmpty(identifyApplies)) {
                            CultivateIdentifyApply latestApply = identifyApplies.get(0);
                            taskLog.setUserIdentifyId(latestApply.getId());
                            if (latestApply.getStatus().equals(1)) {
                                // 检查是否有合格(0)或优秀(1)的记录
                                taskLog.setIdentifyResult(latestApply.getResult());
                            } else {
                                taskLog.setIdentifyState(0);
                            }

                        } else {
                            taskLog.setIdentifyState(0);
                        }

                    } else {
                        taskLog.setIdentifyState(-1); // 未配置鉴定
                        taskLog.setIdentifyResult(-1); // 未配置鉴定
                    }

                    // 练习状态默认为-1(未配置)，因为旧数据中没有练习相关表
                    taskLog.setPracticeState(-1);


                    // 添加到对应的列表
                    if (existingLog != null) {
                        taskLog.setLastModifyUserId(userId);
                        taskLog.setLastModifyTime(now);
                        toUpdate.add(taskLog);
                    } else {
                        taskLog.setLastModifyUserId(userId);
                        taskLog.setLastModifyTime(now);
                        toInsert.add(taskLog);
                    }
                    totalMigrated++;
                }

                // 批量插入和更新
                if (!toInsert.isEmpty()) {
                    for (FtbCultivateTaskLog log : toInsert) {
                        ftbCultivateTaskLogMapper.insert(log);
                    }
                }
                if (!toUpdate.isEmpty()) {
                    for (FtbCultivateTaskLog log : toUpdate) {
                        ftbCultivateTaskLogMapper.updateById(log);
                    }
                }
            }

            log.info("旧培训任务数据迁移完成，共处理 {} 个任务，迁移 {} 条记录", processedTaskCount, totalMigrated);
            return ActionResult.success("迁移完成，共处理 " + processedTaskCount + " 个任务，" + totalMigrated + " 条用户任务记录");

        } catch (Exception e) {
            log.error("迁移旧培训任务数据时发生错误", e);
            return ActionResult.fail("迁移失败: " + e.getMessage());
        }
    }

    /**
     * 旧晋升通道成员数据迁移接口
     * 将 ftb_cultivate_promotion_member_new 表中的用户数据迁移到
     * ftb_cultivate_promotion_user 和 ftb_cultivate_promotion_setting 表中
     * 同时校验用户是否为正常状态（enabledMark = 1）
     *
     * @param tenantId    租户ID
     * @param promotionId 晋升通道ID（可选，如果传入则只迁移指定通道的数据）
     * @return 响应结果
     */
    @NoDataSourceBind
    @GetMapping("/promotion/migrate-old-data")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ActionResult<String> migratePromotionOldData(@RequestParam("tenantId") String tenantId,
                                                        @RequestParam(value = "promotionId", required = false) String promotionId) {
        userApiV2Util.checkOutTenant(tenantId);

        try {
            log.info("开始迁移旧晋升通道成员数据...");
            if (StringUtils.isNotEmpty(promotionId)) {
                log.info("指定晋升通道ID: {}", promotionId);
            }

            // 1. 查询所有有效的旧晋升通道成员数据（deleteMark=0表示未删除）
            LambdaQueryWrapper<FtbCultivatePromotionMemberNew> queryWrapper = Wrappers.<FtbCultivatePromotionMemberNew>lambdaQuery()
                    .eq(FtbCultivatePromotionMemberNew::getDeleteMark, 0);

            // 如果传入了promotionId，则只查询指定通道的数据
            if (StringUtils.isNotEmpty(promotionId)) {
                queryWrapper.eq(FtbCultivatePromotionMemberNew::getPromotionId, promotionId);
            }

            List<FtbCultivatePromotionMemberNew> memberNewList = ftbCultivatePromotionMemberNewMapper.selectList(queryWrapper);

            if (memberNewList == null || memberNewList.isEmpty()) {
                log.info("没有找到有效的旧晋升通道成员数据");
                return ActionResult.success("没有找到需要迁移的数据");
            }

            log.info("共找到 {} 条旧晋升通道成员数据", memberNewList.size());

            // 2. 提取所有用户ID
            Set<String> userIds = memberNewList.stream()
                    .map(FtbCultivatePromotionMemberNew::getUserId)
                    .filter(StringUtils::isNotEmpty)
                    .collect(Collectors.toSet());

            if (userIds.isEmpty()) {
                log.warn("旧数据中没有有效的用户ID");
                return ActionResult.success("没有有效的用户数据需要迁移");
            }

            List<UserEntity> userNameForUserIdsReturnList = userApiV2Util.getUserNameForUserIdsReturnList(new ArrayList<>(userIds), tenantId);
            log.info("共提取到 {} 个唯一用户ID", userIds.size());
            if (CollUtil.isEmpty(userNameForUserIdsReturnList)) {
                return ActionResult.success("没有有效的用户数据需要迁移");
            }

            // 3. 过滤出在用户列表中存在的成员（确保用户有效）
            Set<String> validUserIds = userNameForUserIdsReturnList.stream()
                    .map(UserEntity::getId)
                    .filter(StringUtils::isNotEmpty)
                    .collect(Collectors.toSet());

            List<FtbCultivatePromotionMemberNew> validMembers = memberNewList.stream()
                    .filter(member -> validUserIds.contains(member.getUserId()))
                    .collect(Collectors.toList());

            if (validMembers.isEmpty()) {
                log.info("没有有效的用户数据需要迁移");
                return ActionResult.success("没有有效的用户数据需要迁移");
            }

            log.info("共有 {} 条用户数据需要迁移", validMembers.size());

            // 4. 准备批量插入的数据
            Date now = new Date();
            String systemUserId = "349057407209541"; // 系统用户ID

            List<FtbCultivatePromotionUser> promotionUsersToInsert = new ArrayList<>();
            List<FtbCultivatePromotionSetting> promotionSettingsToInsert = new ArrayList<>();


            int migratedCount = 0;
            int skippedCount = 0;

            // 6. 处理每个有效的成员数据
            for (FtbCultivatePromotionMemberNew member : validMembers) {
                String memberPromotionId = member.getPromotionId();
                String userId = member.getUserId();


                FtbCultivatePromotionUser promotionUser = new FtbCultivatePromotionUser();
                promotionUser.setId(UserApiV2Util.generateId());
                promotionUser.setPromotionId(memberPromotionId);
                promotionUser.setUserId(userId);
                promotionUser.setEnabledMark(0);
                promotionUser.setUserSelect(0);
                promotionUser.setIsComplete(0);
                promotionUser.setCreatorUserId(systemUserId);
                promotionUser.setCreatorTime(now);
                promotionUser.setLastModifyUserId(systemUserId);
                promotionUser.setLastModifyTime(now);
                promotionUsersToInsert.add(promotionUser);
                migratedCount++;


                FtbCultivatePromotionSetting userSetting = new FtbCultivatePromotionSetting();
                userSetting.setId(UserApiV2Util.generateId());
                userSetting.setPromotionId(memberPromotionId);
                userSetting.setScope(3); // 3-用户
                userSetting.setPostId("");
                userSetting.setScopeId(userId);
                userSetting.setEnabledMark(0);
                userSetting.setCreatorUserId(systemUserId);
                userSetting.setCreatorTime(now);
                userSetting.setLastModifyUserId(systemUserId);
                userSetting.setLastModifyTime(now);
                promotionSettingsToInsert.add(userSetting);

            }

            // 7. 批量插入数据
            if (!promotionUsersToInsert.isEmpty()) {
                for (FtbCultivatePromotionUser user : promotionUsersToInsert) {
                    ftbCultivatePromotionUserMapper.insert(user);
                }
                log.info("成功插入 {} 条晋升用户记录", promotionUsersToInsert.size());
            }

            if (!promotionSettingsToInsert.isEmpty()) {
                for (FtbCultivatePromotionSetting setting : promotionSettingsToInsert) {
                    ftbCultivatePromotionSettingMapper.insert(setting);
                }
                log.info("成功插入 {} 条晋升配置记录", promotionSettingsToInsert.size());
            }

            String resultMsg = String.format(
                    "迁移完成！%s共处理 %d 条数据，成功迁移 %d 条，跳过 %d 条重复记录，插入 %d 条用户记录，%d 条配置记录",
                    StringUtils.isNotEmpty(promotionId) ? "[通道ID: " + promotionId + "] " : "",
                    validMembers.size(), migratedCount, skippedCount,
                    promotionUsersToInsert.size(), promotionSettingsToInsert.size()
            );
            log.info(resultMsg);
            return ActionResult.success(resultMsg);

        } catch (Exception e) {
            log.error("迁移旧晋升通道成员数据时发生错误", e);
            return ActionResult.fail("迁移失败: " + e.getMessage());
        }
    }
}