package com.dora.service.impl;

import com.dora.dto.WorkflowCategoryDto;
import com.dora.dto.WorkflowListItemDto;
import com.dora.dto.WorkflowDetailDto;
import com.dora.dto.WorkflowVideoPlayDto;
import com.dora.dto.WorkflowDataDto;
import com.dora.dto.CategoryDto;
import com.dora.dto.VodDto;
import com.dora.entity.Category;
import com.dora.dto.PageResultDto;
import com.dora.entity.Workflow;
import com.dora.entity.User;
import com.dora.entity.Video;
import com.dora.exception.BusinessException;
import com.dora.mapper.WorkflowMapper;
import com.dora.mapper.WorkflowCopyStatMapper;
import com.dora.mapper.UserMapper;
import com.dora.mapper.VideoMapper;
import com.dora.service.CategoryService;
import com.dora.service.ContentRevenueStageService;
import com.dora.service.WorkflowService;
import com.dora.service.VodService;
import com.dora.util.MembershipUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 工作流服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WorkflowServiceImpl implements WorkflowService {

    private final WorkflowMapper workflowMapper;
    private final UserMapper userMapper;
    private final VideoMapper videoMapper;
    private final WorkflowCopyStatMapper workflowCopyStatMapper;
    private final VodService vodService;
    private final CategoryService categoryService;
    private final ContentRevenueStageService contentRevenueStageService;
    private final MembershipUtil membershipUtil;

    @Override
    public List<WorkflowCategoryDto> getCategories() {
        try {
            // 构建分类DTO列表
            List<WorkflowCategoryDto> categories = new ArrayList<>();
            
            // 添加热门推荐（默认分类）
            WorkflowCategoryDto hotCategory = new WorkflowCategoryDto();
            hotCategory.setId("hot");
            hotCategory.setName("热门推荐");
            // 热门推荐的数量是所有已审核工作流的总数
            Long totalCount = workflowMapper.countAllWorkflows();
            hotCategory.setCount(totalCount != null ? totalCount.intValue() : 0);
            hotCategory.setIsDefault(true);
            categories.add(hotCategory);
            
            // 从新的category表获取工作流分类
            List<CategoryDto> workflowCategoryDtos = categoryService.getEnabledCategoriesByType(Category.TYPE_WORKFLOW);
            
            // 转换为WorkflowCategoryDto并计算每个分类下的工作流数量
            for (CategoryDto categoryDto : workflowCategoryDtos) {
                WorkflowCategoryDto workflowCategoryDto = new WorkflowCategoryDto();
                workflowCategoryDto.setId(categoryDto.getId().toString()); // 使用分类ID作为字符串
                workflowCategoryDto.setName(categoryDto.getName());
                workflowCategoryDto.setIsDefault(false);
                
                // 查询该分类下的工作流数量
                Long count = workflowMapper.countWorkflowsByCategoryId(categoryDto.getId());
                workflowCategoryDto.setCount(count != null ? count.intValue() : 0);
                
                // 只有有工作流的分类才显示
                if (workflowCategoryDto.getCount() > 0) {
                    categories.add(workflowCategoryDto);
                }
            }
            
            // 按数量降序排序（热门推荐除外）
            categories.sort((c1, c2) -> {
                if ("hot".equals(c1.getId())) return -1;
                if ("hot".equals(c2.getId())) return 1;
                return Integer.compare(c2.getCount(), c1.getCount());
            });
            
            // 限制最多返回10个分类
            if (categories.size() > 10) {
                categories = categories.subList(0, 10);
                log.info("工作流分类数量超过10个，已限制为前10个分类");
            }
            
            return categories;
        } catch (Exception e) {
            log.error("获取工作流分类列表失败", e);
            throw new BusinessException("获取工作流分类列表失败");
        }
    }

    @Override
    public PageResultDto<WorkflowListItemDto> getHotWorkflows(int page, int size) {
        try {
            int offset = (page - 1) * size;
            
            // 获取热门工作流列表
            List<Workflow> workflows = workflowMapper.selectHotWorkflows(offset, size);
            Long total = workflowMapper.countAllWorkflows();
            
            // 转换为DTO
            List<WorkflowListItemDto> workflowDtos = convertToWorkflowListDto(workflows);
            
            return new PageResultDto<>(total, (long) page, (long) size, workflowDtos);
        } catch (Exception e) {
            log.error("获取热门工作流列表失败", e);
            throw new BusinessException("获取热门工作流列表失败");
        }
    }

    @Override
    public PageResultDto<WorkflowListItemDto> getWorkflowsByCategory(String category, int page, int size) {
        try {
            int offset = (page - 1) * size;
            
            // 获取指定分类的工作流列表
            List<Workflow> workflows = workflowMapper.selectWorkflowsByCategory(category, offset, size);
            Long total = workflowMapper.countWorkflowsByCategory(category);
            
            // 转换为DTO
            List<WorkflowListItemDto> workflowDtos = convertToWorkflowListDto(workflows);
            
            return new PageResultDto<>(total, (long) page, (long) size, workflowDtos, category);
        } catch (Exception e) {
            log.error("获取分类工作流列表失败 - category: {}", category, e);
            throw new BusinessException("获取分类工作流列表失败");
        }
    }

    @Override
    public Workflow getWorkflowById(Long id) {
        try {
            Workflow workflow = workflowMapper.selectById(id);
            if (workflow == null) {
                throw new BusinessException("工作流不存在");
            }
            return workflow;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("获取工作流详情失败 - id: {}", id, e);
            throw new BusinessException("获取工作流详情失败");
        }
    }

    @Override
    public Long createOrUpdateWorkflow(Long ownerId, Workflow workflow) {
        // 校验上传模式：至少二选一
        boolean hasJson = workflow.getData() != null && !workflow.getData().trim().isEmpty();
        boolean hasFile = workflow.getDataFileUrl() != null && !workflow.getDataFileUrl().trim().isEmpty();
        if (!hasJson && !hasFile) {
            throw new BusinessException("请提供工作流JSON或依赖文件地址");
        }

        // 设置所有者ID
        workflow.setOwnerId(ownerId);

        // 名称、访问级别等基本字段合理化
        if (workflow.getName() == null) workflow.setName("未命名工作流");
        if (workflow.getFullAccessRole() == null) workflow.setFullAccessRole(1);
        if (workflow.getCopyAccessRole() == null) workflow.setCopyAccessRole(1);
        if (workflow.getIsFree() == null) workflow.setIsFree(0);
        if (workflow.getIsPublic() == null) workflow.setIsPublic(0);
        if (workflow.getAuditStatus() == null) workflow.setAuditStatus(0); // 默认待审核

        // vodVideoId字段已经统一，无需额外同步

        Long workflowId = null;
        try {
            if (workflow.getId() != null) {
                // 更新现有工作流
                log.info("更新现有工作流，ID: {}", workflow.getId());
                
                // 检查工作流是否存在且属于当前用户
                Workflow existingWorkflow = workflowMapper.selectById(workflow.getId());
                if (existingWorkflow == null) {
                    throw new BusinessException("工作流不存在");
                }
                if (!existingWorkflow.getOwnerId().equals(ownerId)) {
                    throw new BusinessException("无权限操作此工作流");
                }

                // 更新工作流
                int updated = workflowMapper.updateById(workflow);
                if (updated <= 0) {
                    throw new BusinessException("更新工作流失败");
                }

                workflowId = workflow.getId();
                log.info("工作流更新成功，ID: {}", workflowId);
            } else {
                // 创建新工作流
                log.info("创建新工作流，名称: {}, 模式: {}, 视频ID: {}", workflow.getName(), 
                    workflow.getDataFileUrl() != null && !workflow.getDataFileUrl().trim().isEmpty() ? "资源包模式" : "JSON模式",
                    workflow.getVodVideoId());
                
                // 检查是否已存在同名工作流
                Workflow existingWorkflow = workflowMapper.selectByNameAndOwner(workflow.getName(), ownerId);
                if (existingWorkflow != null) {
                    throw new BusinessException("已存在同名工作流，请使用不同的名称");
                }

                // 插入新工作流
                int inserted = workflowMapper.insert(workflow);
                if (inserted <= 0) {
                    throw new BusinessException("创建工作流失败");
                }

                workflowId = workflow.getId();
                log.info("工作流创建成功，ID: {}, 模式: {}, 视频ID: {}", workflowId, 
                    workflow.getDataFileUrl() != null && !workflow.getDataFileUrl().trim().isEmpty() ? "资源包模式" : "JSON模式",
                    workflow.getVodVideoId());
            }

            // 如果工作流包含视频ID，自动更新视频表
            if (workflow.getVodVideoId() != null && !workflow.getVodVideoId().trim().isEmpty()) {
                try {
                    updateVideoFromWorkflow(workflow);
                } catch (Exception e) {
                    log.warn("自动更新视频表失败，但不影响工作流操作: {}", e.getMessage());
                }
            } else {
                // 工作流必须包含视频ID，否则无法创建
                throw new BusinessException("工作流必须包含视频ID，请先上传视频");
            }

            return workflowId;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("创建或更新工作流失败", e);
            throw new BusinessException("操作失败: " + e.getMessage());
        }
    }

    /**
     * 根据工作流信息自动更新视频表
     */
    private void updateVideoFromWorkflow(Workflow workflow) {
        try {
            // 根据vodVideoId查找视频
            Video video = videoMapper.selectByVodVideoId(workflow.getVodVideoId());
            if (video != null) {
                // 更新现有视频信息
                Video updateVideo = new Video();
                updateVideo.setId(video.getId());
                
                // 如果工作流有封面，更新视频封面
                if (workflow.getCoverUrl() != null && !workflow.getCoverUrl().trim().isEmpty()) {
                    updateVideo.setCoverUrl(workflow.getCoverUrl());
                }
                
                // 如果工作流有分类，更新视频分类
                if (workflow.getCategory() != null && !workflow.getCategory().trim().isEmpty()) {
                    updateVideo.setCategory(workflow.getCategory());
                }
                
                // 如果工作流有描述，更新视频描述
                if (workflow.getDescription() != null && !workflow.getDescription().trim().isEmpty()) {
                    updateVideo.setDescription(workflow.getDescription());
                }
                
                // 更新视频
                int updated = videoMapper.updateById(updateVideo);
                if (updated > 0) {
                    log.info("自动更新视频表成功，视频ID: {}, 工作流ID: {}", video.getId(), workflow.getId());
                }
            } else {
                // 如果找不到对应视频，自动创建新视频记录
                log.info("未找到对应的视频记录，自动创建新视频，vodVideoId: {}", workflow.getVodVideoId());
                createVideoFromWorkflow(workflow);
            }
        } catch (Exception e) {
            log.error("自动更新视频表失败，vodVideoId: {}, 错误: {}", workflow.getVodVideoId(), e.getMessage());
        }
    }

    /**
     * 根据工作流信息自动创建新视频记录
     */
    private void createVideoFromWorkflow(Workflow workflow) {
        try {
            Video newVideo = new Video();
            
            // 使用工作流中的完整信息创建视频记录
            newVideo.setTitle(workflow.getName() != null ? workflow.getName() : "未命名视频");
            newVideo.setDescription(workflow.getDescription() != null ? workflow.getDescription() : "");
            newVideo.setOwnerId(workflow.getOwnerId());
            newVideo.setCoverUrl(workflow.getCoverUrl()); // 使用工作流的封面
            newVideo.setVodVideoId(workflow.getVodVideoId());
            newVideo.setCategory(workflow.getCategory() != null ? workflow.getCategory() : "未分类");
            
            // 设置视频的基本属性
            newVideo.setIsPublic(workflow.getIsPublic() != null ? workflow.getIsPublic() : 0); // 继承工作流的公开设置
            newVideo.setAuditStatus(0); // 默认待审核，与工作流保持一致
            newVideo.setViewCount(0);
            newVideo.setLikeCount(0);
            newVideo.setIsDeleted(0); // 设置逻辑删除标识为0（未删除）
            
            // 尝试从阿里云VOD获取视频信息
            try {
                VodVideoInfo vodInfo = getVodVideoInfo(workflow.getVodVideoId());
                if (vodInfo != null) {
                    newVideo.setDuration(vodInfo.getDuration());
                    log.info("成功获取VOD视频信息，时长: {}秒", vodInfo.getDuration());
                } else {
                    // 如果获取失败，使用默认值
                    newVideo.setDuration(0);
                    log.warn("无法获取VOD视频信息，使用默认值，vodVideoId: {}", workflow.getVodVideoId());
                }
            } catch (Exception e) {
                // VOD API调用失败，使用默认值
                newVideo.setDuration(0);
                log.warn("获取VOD视频信息失败，使用默认值，vodVideoId: {}, 错误: {}", workflow.getVodVideoId(), e.getMessage());
            }
            
            // 插入新视频记录
            int inserted = videoMapper.insert(newVideo);
            if (inserted > 0) {
                log.info("自动创建视频记录成功，视频ID: {}, 工作流ID: {}, vodVideoId: {}, 标题: {}, 分类: {}", 
                    newVideo.getId(), workflow.getId(), workflow.getVodVideoId(), 
                    newVideo.getTitle(), newVideo.getCategory());
            } else {
                log.error("自动创建视频记录失败，工作流ID: {}", workflow.getId());
            }
        } catch (Exception e) {
            log.error("自动创建视频记录失败，工作流ID: {}, 错误: {}", workflow.getId(), e.getMessage());
        }
    }

    /**
     * 从阿里云VOD获取视频信息
     */
    private VodVideoInfo getVodVideoInfo(String vodVideoId) {
        try {
            // 这里可以调用阿里云VOD API获取视频信息
            // 暂时返回null，后续可以集成VOD API
            // TODO: 集成阿里云VOD API获取视频URL和时长
            return null;
        } catch (Exception e) {
            log.error("获取VOD视频信息失败，vodVideoId: {}, 错误: {}", vodVideoId, e.getMessage());
            return null;
        }
    }

    /**
     * VOD视频信息内部类
     */
    private static class VodVideoInfo {
        private Integer duration;

        public Integer getDuration() { return duration; }
        public void setDuration(Integer duration) { this.duration = duration; }
    }

    /**
     * 将Workflow实体转换为WorkflowListItemDto
     */
    private List<WorkflowListItemDto> convertToWorkflowListDto(List<Workflow> workflows) {
        if (workflows == null || workflows.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取所有创建者ID
        List<Long> creatorIds = workflows.stream()
                .map(Workflow::getOwnerId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        
        // 批量获取创建者信息
        final Map<Long, User> userMap;
        if (!creatorIds.isEmpty()) {
            List<User> users = userMapper.selectByIds(creatorIds);
            userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user, (existing, replacement) -> existing));
        } else {
            userMap = new HashMap<>();
        }
        
        return workflows.stream().map(workflow -> {
            WorkflowListItemDto dto = new WorkflowListItemDto();
            
            // 基本信息
            dto.setId(workflow.getId());
            dto.setName(workflow.getName() != null ? workflow.getName() : "");
            dto.setDescription(workflow.getDescription() != null ? workflow.getDescription() : "");
            dto.setCoverUrl(workflow.getCoverUrl());
            dto.setPrice(workflow.getPrice());
            dto.setCategory(workflow.getCategory());
            dto.setLikeCount(workflow.getLikeCount() != null ? workflow.getLikeCount() : 0);
            dto.setRating(workflow.getRating() != null ? workflow.getRating() : 0);
            dto.setCreateTime(workflow.getCreateTime());
            dto.setUpdateTime(workflow.getUpdateTime());
            dto.setIsFree(workflow.getIsFree() != null && workflow.getIsFree() == 1);
            
            // 设置权限信息
            dto.setFullAccessRole(workflow.getFullAccessRole());
            dto.setCopyAccessRole(workflow.getCopyAccessRole());
            dto.setFullAccessRoleName(getRoleNameByLevel(workflow.getFullAccessRole()));
            dto.setCopyAccessRoleName(getRoleNameByLevel(workflow.getCopyAccessRole()));
            
            // 设置创建者信息
            if (workflow.getOwnerId() != null) {
                User creator = userMap.get(workflow.getOwnerId());
                if (creator != null) {
                    WorkflowListItemDto.CreatorDto creatorDto = new WorkflowListItemDto.CreatorDto();
                    creatorDto.setId(String.valueOf(creator.getId()));
                    creatorDto.setUsername(creator.getUsername() != null ? creator.getUsername() : "");
                    creatorDto.setAvatarUrl(creator.getAvatarUrl());
                    dto.setCreator(creatorDto);
                }
            }
            
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public WorkflowDetailDto getWorkflowDetail(Long workflowId, Long userId) {
        try {
            // 获取工作流信息
            Workflow workflow = workflowMapper.selectById(workflowId);
            if (workflow == null) {
                throw new BusinessException("工作流不存在");
            }

            // 检查工作流审核状态 - 只有通过审核或者是创作者本人可以查看
            if (workflow.getAuditStatus() != 1 && (userId == null || !userId.equals(workflow.getOwnerId()))) {
                throw new BusinessException("工作流未通过审核");
            }

            WorkflowDetailDto result = new WorkflowDetailDto();

            // 设置工作流基本信息
            result.setWorkflow(buildWorkflowInfo(workflow));

            // 设置用户权限信息
            result.setUserPermission(buildUserPermission(userId, workflow));

            return result;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("获取工作流详情失败 - workflowId: {}, userId: {}", workflowId, userId, e);
            throw new BusinessException("获取工作流详情失败");
        }
    }

    @Override
    public WorkflowVideoPlayDto.PlayAuthResponse getWorkflowVideoPlayAuth(WorkflowVideoPlayDto.GetPlayAuthRequest request, Long userId) {
        try {
            // 获取工作流信息
            Workflow workflow = workflowMapper.selectById(request.getWorkflowId());
            if (workflow == null) {
                throw new BusinessException("工作流不存在");
            }

            // 检查是否有预览视频
            if (workflow.getVodVideoId() == null || workflow.getVodVideoId().trim().isEmpty()) {
                throw new BusinessException("该工作流没有预览视频");
            }

            // 验证用户权限（预览视频通常需要较低的权限）
            if (!hasVideoAccessPermission(userId, workflow)) {
                User user = userMapper.selectById(userId);
                String userRoleName = getRoleNameByLevel(user != null ? user.getRole() : 0);
                String requiredRoleName = getRoleNameByLevel(workflow.getFullAccessRole());
                
                throw new BusinessException(String.format("权限不足：您当前是%s用户，该工作流需要%s及以上权限", userRoleName, requiredRoleName));
            }

            // 调用VOD服务获取播放凭证
            VodDto.GetVideoPlayAuthRequest vodRequest = new VodDto.GetVideoPlayAuthRequest();
            vodRequest.setVideoId(workflow.getVodVideoId());
            vodRequest.setAuthInfoTimeout(request.getAuthInfoTimeout());

            VodDto.VideoPlayAuthResponse vodResponse = vodService.getVideoPlayAuth(vodRequest, userId);

            // 构建响应
            WorkflowVideoPlayDto.PlayAuthResponse response = new WorkflowVideoPlayDto.PlayAuthResponse();
            response.setPlayAuth(vodResponse.getPlayAuth());
            response.setRequestId(vodResponse.getRequestId());

            // 设置视频元信息
            WorkflowVideoPlayDto.VideoMeta videoMeta = new WorkflowVideoPlayDto.VideoMeta();
            if (vodResponse.getVideoMeta() != null) {
                videoMeta.setVodVideoId(vodResponse.getVideoMeta().getVideoId());
                videoMeta.setTitle(workflow.getName());
                videoMeta.setDuration(vodResponse.getVideoMeta().getDuration());
                videoMeta.setCoverURL(vodResponse.getVideoMeta().getCoverURL());
                videoMeta.setStatus(vodResponse.getVideoMeta().getStatus());
                videoMeta.setSize(vodResponse.getVideoMeta().getSize());
            }
            response.setVideoMeta(videoMeta);

            // 设置用户权限信息
            User user = userMapper.selectById(userId);
            WorkflowVideoPlayDto.UserPermissionInfo permissionInfo = new WorkflowVideoPlayDto.UserPermissionInfo();
            permissionInfo.setUserRole(user != null ? user.getRole() : 0);
            permissionInfo.setUserRoleName(getRoleNameByLevel(user != null ? user.getRole() : 0));
            permissionInfo.setRequiredLevel(workflow.getFullAccessRole());
            permissionInfo.setHasPermission(true);
            permissionInfo.setCheckTime(java.time.LocalDateTime.now());
            response.setUserPermission(permissionInfo);

            return response;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("获取工作流视频播放凭证失败 - request: {}, userId: {}", request, userId, e);
            throw new BusinessException("获取播放凭证失败: " + e.getMessage());
        }
    }

    /**
     * 构建工作流基本信息
     */
    private WorkflowDetailDto.WorkflowInfo buildWorkflowInfo(Workflow workflow) {
        WorkflowDetailDto.WorkflowInfo workflowInfo = new WorkflowDetailDto.WorkflowInfo();
        workflowInfo.setId(workflow.getId());
        workflowInfo.setName(valueOrEmpty(workflow.getName()));
        workflowInfo.setDescription(valueOrEmpty(workflow.getDescription()));
        workflowInfo.setCoverUrl(workflow.getCoverUrl());
        workflowInfo.setDetailGallery(workflow.getDetailGallery());
        workflowInfo.setVodVideoId(workflow.getVodVideoId());
        workflowInfo.setPrice(workflow.getPrice());
        workflowInfo.setLikeCount(workflow.getLikeCount() != null ? workflow.getLikeCount() : 0);
        workflowInfo.setFullAccessRole(workflow.getFullAccessRole());
        workflowInfo.setCopyAccessRole(workflow.getCopyAccessRole());
        workflowInfo.setCategory(workflow.getCategory());
        workflowInfo.setRating(workflow.getRating());
        workflowInfo.setIsFree(workflow.getIsFree() != null && workflow.getIsFree() == 1);
        workflowInfo.setIsPublic(workflow.getIsPublic() != null && workflow.getIsPublic() == 1);
        workflowInfo.setFullAccessRoleName(getRoleNameByLevel(workflow.getFullAccessRole()));
        workflowInfo.setCopyAccessRoleName(getRoleNameByLevel(workflow.getCopyAccessRole()));
        workflowInfo.setCreateTime(workflow.getCreateTime());
        workflowInfo.setUpdateTime(workflow.getUpdateTime());

        // 计算并设置复制次数
        Integer copyCount = workflowCopyStatMapper.countCopiesByWorkflowId(workflow.getId());
        workflowInfo.setCopyCount(copyCount != null ? copyCount : 0);

        // 设置数据类型相关信息
        setWorkflowDataTypeInfo(workflowInfo, workflow);

        // 设置创建者信息
        if (workflow.getOwnerId() != null) {
            User creator = userMapper.selectById(workflow.getOwnerId());
            if (creator != null) {
                WorkflowDetailDto.CreatorInfo creatorInfo = new WorkflowDetailDto.CreatorInfo();
                creatorInfo.setId(String.valueOf(creator.getId()));
                creatorInfo.setUsername(creator.getUsername());
                creatorInfo.setAvatarUrl(creator.getAvatarUrl());
                workflowInfo.setCreator(creatorInfo);
            }
        }

        return workflowInfo;
    }

    /**
     * 构建用户权限信息
     */
    private WorkflowDetailDto.UserPermission buildUserPermission(Long userId, Workflow workflow) {
        WorkflowDetailDto.UserPermission permission = new WorkflowDetailDto.UserPermission();
        permission.setRequiredFullAccessLevel(workflow.getFullAccessRole());
        permission.setRequiredFullAccessLevelName(getRoleNameByLevel(workflow.getFullAccessRole()));
        permission.setRequiredCopyLevel(workflow.getCopyAccessRole());
        permission.setRequiredCopyLevelName(getRoleNameByLevel(workflow.getCopyAccessRole()));

        if (userId != null) {
            User user = userMapper.selectById(userId);
            if (user != null) {
                permission.setUserRole(user.getRole());
                permission.setUserRoleName(getRoleNameByLevel(user.getRole()));
                permission.setHasFullAccess(user.getRole() >= workflow.getFullAccessRole());
                permission.setHasCopyAccess(user.getRole() >= workflow.getCopyAccessRole());
                permission.setMembershipExpiresAt(user.getMembershipExpiresAt());

                if (!permission.getHasFullAccess()) {
                    permission.setAccessDeniedReason("您当前是" + permission.getUserRoleName() + "用户，查看完整数据需要" + permission.getRequiredFullAccessLevelName() + "及以上权限");
                }
            } else {
                permission.setUserRole(0);
                permission.setUserRoleName("游客");
                permission.setHasFullAccess(workflow.getFullAccessRole() <= 0);
                permission.setHasCopyAccess(workflow.getCopyAccessRole() <= 0);
                permission.setAccessDeniedReason("用户不存在");
            }
        } else {
            permission.setUserRole(0);
            permission.setUserRoleName("游客");
            permission.setHasFullAccess(workflow.getFullAccessRole() <= 0);
            permission.setHasCopyAccess(workflow.getCopyAccessRole() <= 0);
            if (workflow.getFullAccessRole() > 0) {
                permission.setAccessDeniedReason("请先登录，该工作流需要" + permission.getRequiredFullAccessLevelName() + "及以上权限");
            }
        }

        return permission;
    }

    /**
     * 检查用户是否有视频访问权限
     */
    private boolean hasVideoAccessPermission(Long userId, Workflow workflow) {
        if (userId == null) {
            // 游客只能访问已审核通过且不需要权限的工作流视频
            return workflow.getAuditStatus() == 1 && workflow.getFullAccessRole() <= 0;
        }
        
        // 如果是创作者本人，可以访问自己的工作流视频（无论审核状态）
        if (userId.equals(workflow.getOwnerId())) {
            return true;
        }
        
        // 其他用户需要工作流已审核通过且有足够权限
        User user = userMapper.selectById(userId);
        return user != null && workflow.getAuditStatus() == 1 && user.getRole() >= workflow.getFullAccessRole();
    }

    /**
     * 根据级别获取角色名称
     */
    private String getRoleNameByLevel(Integer level) {
        if (level == null || level <= 0) {
            return "游客";
        } else if (level == 1) {
            return "普通用户";
        } else if (level == 2) {
            return "VIP用户";
        } else {
            return "SVIP用户";
        }
    }

    @Override
    public WorkflowDataDto.DataFileResponse getWorkflowDataFile(Long workflowId, Long userId) {
        try {
            log.info("获取工作流数据包下载地址 - workflowId: {}, userId: {}", workflowId, userId);

            // 获取工作流信息
            Workflow workflow = workflowMapper.selectById(workflowId);
            if (workflow == null) {
                throw new BusinessException("工作流不存在");
            }

            // 检查工作流审核状态 - 只有通过审核或者是创作者本人可以下载数据
            if (workflow.getAuditStatus() != 1 && (userId == null || !userId.equals(workflow.getOwnerId()))) {
                throw new BusinessException("工作流未通过审核");
            }

            // 检查是否为文件模式
            if (workflow.getDataFileUrl() == null || workflow.getDataFileUrl().trim().isEmpty()) {
                throw new BusinessException("该工作流不是文件模式，无法获取数据包下载地址");
            }

            // 验证用户权限（需要复制权限）
            if (!hasCopyPermission(userId, workflow)) {
                User user = userMapper.selectById(userId);
                String userRoleName = getRoleNameByLevel(user != null ? user.getRole() : 0);
                String requiredRoleName = getRoleNameByLevel(workflow.getCopyAccessRole());
                
                throw new BusinessException(String.format("权限不足：您当前是%s用户，获取数据包需要%s及以上权限", userRoleName, requiredRoleName));
            }

            // 记录复制统计
            recordCopyAccess(workflow, userId);

            // 构建响应
            WorkflowDataDto.DataFileResponse response = new WorkflowDataDto.DataFileResponse();
            response.setWorkflowId(workflow.getId());
            response.setWorkflowName(workflow.getName());
            response.setDataFileUrl(workflow.getDataFileUrl());
            
            // 设置文件信息（可以根据URL推断或从其他地方获取）
            response.setFileSize(0L); // 如果有文件大小信息可以设置
            response.setFileFormat(getFileFormat(workflow.getDataFileUrl()));
            response.setValidityPeriod(3600L); // 1小时有效期

            // 设置访问统计信息
            Integer totalCopyCount = workflowCopyStatMapper.countCopiesByWorkflowId(workflowId);
            WorkflowDataDto.AccessStatInfo accessStat = new WorkflowDataDto.AccessStatInfo();
            accessStat.setTotalCopyCount(totalCopyCount != null ? totalCopyCount : 0);
            accessStat.setAccessTime(java.time.LocalDateTime.now());
            accessStat.setAccessType("data_file");
            response.setAccessStat(accessStat);

            // 设置用户权限信息
            response.setUserPermission(buildDataUserPermission(userId, workflow));

            log.info("获取工作流数据包下载地址成功 - workflowId: {}, userId: {}, totalCopyCount: {}", 
                    workflowId, userId, accessStat.getTotalCopyCount());

            return response;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("获取工作流数据包下载地址失败 - workflowId: {}, userId: {}", workflowId, userId, e);
            throw new BusinessException("获取数据包下载地址失败: " + e.getMessage());
        }
    }

    @Override
    public WorkflowDataDto.JsonDataResponse getWorkflowJsonData(Long workflowId, Long userId) {
        try {
            log.info("获取工作流JSON数据 - workflowId: {}, userId: {}", workflowId, userId);

            // 获取工作流信息
            Workflow workflow = workflowMapper.selectById(workflowId);
            if (workflow == null) {
                throw new BusinessException("工作流不存在");
            }

            // 检查工作流审核状态 - 只有通过审核或者是创作者本人可以获取数据
            if (workflow.getAuditStatus() != 1 && (userId == null || !userId.equals(workflow.getOwnerId()))) {
                throw new BusinessException("工作流未通过审核");
            }

            // 检查是否为JSON模式
            if (workflow.getData() == null || workflow.getData().trim().isEmpty()) {
                throw new BusinessException("该工作流不是JSON模式，无法获取JSON数据");
            }

            // 验证用户权限（需要复制权限）
            if (!hasCopyPermission(userId, workflow)) {
                User user = userMapper.selectById(userId);
                String userRoleName = getRoleNameByLevel(user != null ? user.getRole() : 0);
                String requiredRoleName = getRoleNameByLevel(workflow.getCopyAccessRole());
                
                throw new BusinessException(String.format("权限不足：您当前是%s用户，获取JSON数据需要%s及以上权限", userRoleName, requiredRoleName));
            }

            // 记录复制统计
            recordCopyAccess(workflow, userId);

            // 构建响应
            WorkflowDataDto.JsonDataResponse response = new WorkflowDataDto.JsonDataResponse();
            response.setWorkflowId(workflow.getId());
            response.setWorkflowName(workflow.getName());
            response.setJsonData(workflow.getData());
            response.setDataSize((long) workflow.getData().getBytes().length);
            response.setDataVersion("1.0"); // 可以根据实际情况设置版本

            // 设置访问统计信息
            Integer totalCopyCount = workflowCopyStatMapper.countCopiesByWorkflowId(workflowId);
            WorkflowDataDto.AccessStatInfo accessStat = new WorkflowDataDto.AccessStatInfo();
            accessStat.setTotalCopyCount(totalCopyCount != null ? totalCopyCount : 0);
            accessStat.setAccessTime(java.time.LocalDateTime.now());
            accessStat.setAccessType("json_data");
            response.setAccessStat(accessStat);

            // 设置用户权限信息
            response.setUserPermission(buildDataUserPermission(userId, workflow));

            log.info("获取工作流JSON数据成功 - workflowId: {}, userId: {}, dataSize: {}, totalCopyCount: {}", 
                    workflowId, userId, response.getDataSize(), accessStat.getTotalCopyCount());

            return response;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("获取工作流JSON数据失败 - workflowId: {}, userId: {}", workflowId, userId, e);
            throw new BusinessException("获取JSON数据失败: " + e.getMessage());
        }
    }

    /**
     * 检查用户是否有复制权限
     */
    private boolean hasCopyPermission(Long userId, Workflow workflow) {
        if (userId == null) {
            return workflow.getCopyAccessRole() <= 0; // 游客权限
        }
        
        // 如果是创作者本人，可以复制自己的工作流数据
        if (userId.equals(workflow.getOwnerId())) {
            return true;
        }
        
        // 其他用户需要有足够的角色权限
        User user = userMapper.selectById(userId);
        return user != null && user.getRole() >= workflow.getCopyAccessRole();
    }

    /**
     * 记录复制访问统计并检查收益阶段
     */
    private void recordCopyAccess(Workflow workflow, Long userId) {
        try {
            // 1. 检查用户是否已经使用过该工作流（用于防重复收益）
            Integer userPreviousCopyCount = workflowCopyStatMapper.countUserCopiesByWorkflowId(workflow.getId(), userId);
            boolean isFirstTimeUser = (userPreviousCopyCount == null || userPreviousCopyCount == 0);
            
            // 2. 记录复制统计（无论是否第一次使用都要记录）
            workflowCopyStatMapper.insertCopyRecord(workflow.getId(), workflow.getOwnerId(), userId);
            log.info("记录工作流复制统计成功 - workflowId: {}, ownerId: {}, copyUserId: {}, isFirstTime: {}", 
                    workflow.getId(), workflow.getOwnerId(), userId, isFirstTimeUser);
            
            // 3. 只有首次使用的用户才参与收益计算，且不能是工作流创作者本人
            if (isFirstTimeUser) {
                // 检查是否为创作者本人，创作者下载自己的工作流不产生收益
                if (userId.equals(workflow.getOwnerId())) {
                    log.info("创作者下载自己的工作流，不计入收益统计 - workflowId: {}, ownerId: {}", 
                            workflow.getId(), workflow.getOwnerId());
                    return;
                }

                // 检查用户是否为纯兑换会员，兑换会员不参与收益计算
                if (membershipUtil.isExchangeMemberWithoutRevenue(userId)) {
                    String membershipType = membershipUtil.getMembershipTypeDescription(userId);
                    log.info("{}不参与工作流收益计算 - workflowId: {}, userId: {}, membershipType: {}", 
                            membershipType, workflow.getId(), userId, membershipType);
                    return;
                }
                
                // 获取当前有效使用数（去重后的总用户数）
                Integer currentUniqueUserCount = workflowCopyStatMapper.countUniqueUsersByWorkflowId(workflow.getId());
                if (currentUniqueUserCount == null) {
                    currentUniqueUserCount = 0;
                }
                
                log.debug("工作流当前使用数 - workflowId: {}, uniqueUserCount: {}, 用户首次使用", workflow.getId(), currentUniqueUserCount);
                
                // 4. 检查并更新收益阶段（自动分成）
                try {
                    contentRevenueStageService.checkAndUpdateWorkflowRevenueStages(
                        workflow.getId(), 
                        workflow.getOwnerId(), 
                        currentUniqueUserCount
                    );
                } catch (Exception e) {
                    log.error("检查工作流收益阶段失败，但不影响主业务流程 - workflowId: {}", workflow.getId(), e);
                    // 不抛出异常，避免影响主业务流程
                }
            } else {
                log.info("用户已使用过该工作流，不计入收益统计 - workflowId: {}, userId: {}, previousCount: {}", 
                        workflow.getId(), userId, userPreviousCopyCount);
            }
            
        } catch (Exception e) {
            log.error("记录工作流复制统计失败 - workflowId: {}, userId: {}", workflow.getId(), userId, e);
            // 不抛出异常，避免影响主业务流程
        }
    }

    /**
     * 构建数据访问用户权限信息
     */
    private WorkflowDataDto.UserPermissionInfo buildDataUserPermission(Long userId, Workflow workflow) {
        WorkflowDataDto.UserPermissionInfo permission = new WorkflowDataDto.UserPermissionInfo();
        
        if (userId != null) {
            User user = userMapper.selectById(userId);
            if (user != null) {
                permission.setUserRole(user.getRole());
                permission.setUserRoleName(getRoleNameByLevel(user.getRole()));
                permission.setRequiredLevel(workflow.getCopyAccessRole());
                permission.setHasPermission(user.getRole() >= workflow.getCopyAccessRole());
            } else {
                permission.setUserRole(0);
                permission.setUserRoleName("游客");
                permission.setRequiredLevel(workflow.getCopyAccessRole());
                permission.setHasPermission(false);
            }
        } else {
            permission.setUserRole(0);
            permission.setUserRoleName("游客");
            permission.setRequiredLevel(workflow.getCopyAccessRole());
            permission.setHasPermission(workflow.getCopyAccessRole() <= 0);
        }
        
        permission.setCheckTime(java.time.LocalDateTime.now());
        return permission;
    }

    /**
     * 设置工作流数据类型信息
     */
    private void setWorkflowDataTypeInfo(WorkflowDetailDto.WorkflowInfo workflowInfo, Workflow workflow) {
        boolean hasDataFile = workflow.getDataFileUrl() != null && !workflow.getDataFileUrl().trim().isEmpty();
        boolean hasJsonData = workflow.getData() != null && !workflow.getData().trim().isEmpty();
        
        workflowInfo.setHasDataFile(hasDataFile);
        workflowInfo.setHasJsonData(hasJsonData);
        
        // 设置数据类型
        if (hasDataFile && hasJsonData) {
            workflowInfo.setDataType("both");
        } else if (hasDataFile) {
            workflowInfo.setDataType("file_only");
        } else if (hasJsonData) {
            workflowInfo.setDataType("json_only");
        } else {
            workflowInfo.setDataType("none");
        }
        
        log.debug("工作流数据类型设置 - workflowId: {}, dataType: {}, hasDataFile: {}, hasJsonData: {}", 
                workflow.getId(), workflowInfo.getDataType(), hasDataFile, hasJsonData);
    }

    /**
     * 根据文件URL推断文件格式
     */
    private String getFileFormat(String fileUrl) {
        if (fileUrl == null || fileUrl.trim().isEmpty()) {
            return "unknown";
        }
        
        String lowerUrl = fileUrl.toLowerCase();
        if (lowerUrl.endsWith(".zip")) {
            return "zip";
        } else if (lowerUrl.endsWith(".rar")) {
            return "rar";
        } else if (lowerUrl.endsWith(".7z")) {
            return "7z";
        } else if (lowerUrl.endsWith(".tar.gz") || lowerUrl.endsWith(".tgz")) {
            return "tar.gz";
        } else {
            return "archive";
        }
    }

    private String valueOrEmpty(String s) {
        return s == null ? "" : s;
    }
} 