package com.dora.service.impl;

import com.dora.dto.WorkflowLikeDto;
import com.dora.entity.WorkflowLike;
import com.dora.mapper.WorkflowLikeMapper;
import com.dora.mapper.WorkflowMapper;
import com.dora.service.WorkflowLikeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 工作流点赞服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WorkflowLikeServiceImpl implements WorkflowLikeService {

    private final WorkflowLikeMapper workflowLikeMapper;
    private final WorkflowMapper workflowMapper;

    @Override
    @Transactional
    public WorkflowLikeDto.LikeResponse toggleLike(Long userId, Long workflowId) {
        WorkflowLikeDto.LikeResponse response = new WorkflowLikeDto.LikeResponse();
        
        try {
            // 检查是否存在重复的点赞记录
            int duplicateCount = workflowLikeMapper.countDuplicateLikes(userId, workflowId);
            if (duplicateCount > 1) {
                // 删除重复记录，保留最早的一条
                workflowLikeMapper.deleteDuplicateLikes(userId, workflowId);
                log.warn("发现重复的点赞记录，已清理 - userId: {}, workflowId: {}, 重复数量: {}", 
                        userId, workflowId, duplicateCount);
            }
            
            // 查询当前点赞状态（只查有效记录）
            WorkflowLike activeLike = workflowLikeMapper.selectByUserAndWorkflow(userId, workflowId);
            boolean isLiked = activeLike != null;
            
            if (isLiked) {
                // 取消点赞
                workflowLikeMapper.deleteByUserAndWorkflow(userId, workflowId);
                response.setMessage("取消收藏成功");
                response.setIsLiked(false);
            } else {
                // 检查是否存在已删除的记录
                WorkflowLike existingLike = workflowLikeMapper.selectByUserAndWorkflowIncludeDeleted(userId, workflowId);
                
                if (existingLike != null) {
                    // 恢复已删除的记录
                    workflowLikeMapper.restoreByUserAndWorkflow(userId, workflowId);
                    response.setMessage("收藏成功");
                } else {
                    // 插入新记录
                    WorkflowLike workflowLike = new WorkflowLike();
                    workflowLike.setUserId(userId);
                    workflowLike.setWorkflowId(workflowId);
                    int insertCount = workflowLikeMapper.insert(workflowLike);
                    
                    if (insertCount > 0) {
                        response.setMessage("收藏成功");
                    } else {
                        // 记录已存在，可能是并发操作
                        log.warn("工作流点赞记录已存在（并发操作） - userId: {}, workflowId: {}", userId, workflowId);
                        response.setMessage("已收藏");
                    }
                }
                response.setIsLiked(true);
            }
            
            int likeCount = workflowLikeMapper.countByWorkflowId(workflowId);
            response.setSuccess(true);
            response.setLikeCount(likeCount);
            
            // 同步更新workflow表的like_count字段
            int updateResult = workflowMapper.updateLikeCount(workflowId, likeCount);
            if (updateResult > 0) {
                log.info("同步更新工作流点赞数成功 - workflowId: {}, likeCount: {}", workflowId, likeCount);
            } else {
                log.warn("同步更新工作流点赞数失败 - workflowId: {}, likeCount: {}", workflowId, likeCount);
            }
            
            log.info("工作流点赞操作 - userId: {}, workflowId: {}, isLiked: {}, likeCount: {}", 
                    userId, workflowId, response.getIsLiked(), likeCount);
                    
        } catch (Exception e) {
            log.error("工作流点赞操作失败 - userId: {}, workflowId: {}", 
                    userId, workflowId, e);
            response.setSuccess(false);
            response.setMessage("操作失败：" + e.getMessage());
        }
        
        return response;
    }

    @Override
    public Boolean isLiked(Long userId, Long workflowId) {
        try {
            return workflowLikeMapper.selectByUserAndWorkflow(userId, workflowId) != null;
        } catch (Exception e) {
            log.error("检查工作流点赞状态失败 - userId: {}, workflowId: {}", 
                    userId, workflowId, e);
            return false;
        }
    }

    @Override
    public Integer getLikeCount(Long workflowId) {
        try {
            return workflowLikeMapper.countByWorkflowId(workflowId);
        } catch (Exception e) {
            log.error("获取工作流点赞数量失败 - workflowId: {}", workflowId, e);
            return 0;
        }
    }

    @Override
    public WorkflowLikeDto.LikeListResponse getUserLikes(Long userId, Integer page, Integer size) {
        WorkflowLikeDto.LikeListResponse response = new WorkflowLikeDto.LikeListResponse();
        
        try {
            int offset = (page - 1) * size;
            List<WorkflowLikeDto.LikeRecord> records = new ArrayList<>();
            
            // 获取用户点赞的工作流列表（包含工作流信息）
            List<WorkflowLikeMapper.WorkflowLikeWithInfo> workflowLikesWithInfo = 
                workflowLikeMapper.selectByUserIdWithWorkflowInfo(userId, offset, size);
            
            for (WorkflowLikeMapper.WorkflowLikeWithInfo likeWithInfo : workflowLikesWithInfo) {
                WorkflowLikeDto.LikeRecord record = new WorkflowLikeDto.LikeRecord();
                record.setId(likeWithInfo.getId());
                record.setWorkflowId(likeWithInfo.getWorkflowId());
                record.setWorkflowName(likeWithInfo.getWorkflowName());
                record.setWorkflowDescription(likeWithInfo.getWorkflowDescription());
                record.setWorkflowCover(likeWithInfo.getWorkflowCover());
                record.setCreateTime(likeWithInfo.getCreateTime());
                records.add(record);
            }
            
            int total = workflowLikeMapper.countByUserId(userId);
            
            response.setSuccess(true);
            response.setMessage("获取成功");
            response.setRecords(records);
            response.setTotal(total);
            response.setPage(page);
            response.setSize(size);
            
            log.info("获取用户工作流点赞列表成功 - userId: {}, 记录数: {}, 总数: {}", 
                    userId, records.size(), total);
            
        } catch (Exception e) {
            log.error("获取用户工作流点赞列表失败 - userId: {}", userId, e);
            response.setSuccess(false);
            response.setMessage("获取失败：" + e.getMessage());
        }
        
        return response;
    }

    @Override
    public WorkflowLikeDto.LikeStatsResponse getUserLikeStats(Long userId) {
        WorkflowLikeDto.LikeStatsResponse response = new WorkflowLikeDto.LikeStatsResponse();
        
        try {
            int workflowLikeCount = workflowLikeMapper.countByUserId(userId);
            
            response.setSuccess(true);
            response.setMessage("获取成功");
            response.setWorkflowLikeCount(workflowLikeCount);
            
        } catch (Exception e) {
            log.error("获取用户工作流点赞统计失败 - userId: {}", userId, e);
            response.setSuccess(false);
            response.setMessage("获取失败：" + e.getMessage());
        }
        
        return response;
    }
} 