package com.dora.service.impl;

import com.dora.dto.PageResultDto;
import com.dora.dto.UserContentManageDto;
import com.dora.entity.Course;
import com.dora.entity.Video;
import com.dora.entity.Workflow;
import com.dora.mapper.CourseMapper;
import com.dora.mapper.VideoMapper;
import com.dora.mapper.WorkflowMapper;
import com.dora.service.UserContentManageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserContentManageServiceImpl implements UserContentManageService {

	private final VideoMapper videoMapper;
	private final WorkflowMapper workflowMapper;
	private final CourseMapper courseMapper;

	@Override
	public PageResultDto<Video> listMyVideos(Long userId, UserContentManageDto.PageQuery query) {
		int page = query.getPage() != null && query.getPage() > 0 ? query.getPage() : 1;
		int size = query.getSize() != null && query.getSize() > 0 ? query.getSize() : 10;
		int offset = (page - 1) * size;
		Long total = videoMapper.countByOwner(userId, query.getAuditStatus(), query.getKeyword());
		List<Video> list = total != null && total > 0
			? videoMapper.listByOwnerPaged(userId, query.getAuditStatus(), query.getKeyword(), offset, size)
			: List.of();
		return new PageResultDto<>(total == null ? 0L : total, (long) page, (long) size, list);
	}

	@Override
	public PageResultDto<Workflow> listMyWorkflows(Long userId, UserContentManageDto.PageQuery query) {
		int page = query.getPage() != null && query.getPage() > 0 ? query.getPage() : 1;
		int size = query.getSize() != null && query.getSize() > 0 ? query.getSize() : 10;
		int offset = (page - 1) * size;
		Long total = workflowMapper.countByOwner(userId, query.getAuditStatus(), query.getKeyword());
		List<Workflow> list = total != null && total > 0
			? workflowMapper.listByOwnerPaged(userId, query.getAuditStatus(), query.getKeyword(), offset, size)
			: List.of();
		return new PageResultDto<>(total == null ? 0L : total, (long) page, (long) size, list);
	}

	@Override
	public PageResultDto<Course> listMyCourses(Long userId, UserContentManageDto.PageQuery query) {
		int page = query.getPage() != null && query.getPage() > 0 ? query.getPage() : 1;
		int size = query.getSize() != null && query.getSize() > 0 ? query.getSize() : 10;
		int offset = (page - 1) * size;
		Long total = courseMapper.countByOwner(userId, query.getAuditStatus(), query.getKeyword());
		List<Course> list = total != null && total > 0
			? courseMapper.listByOwnerPaged(userId, query.getAuditStatus(), query.getKeyword(), offset, size)
			: List.of();
		return new PageResultDto<>(total == null ? 0L : total, (long) page, (long) size, list);
	}

	@Override
	@Transactional
	public boolean updateMyVideo(Long userId, Long videoId, UserContentManageDto.VideoUpdateRequest req) {
		Video update = new Video();
		update.setId(videoId);
		update.setOwnerId(userId);
		update.setTitle(req.getTitle());
		update.setDescription(req.getDescription());
		update.setCoverUrl(req.getCoverUrl());
		update.setCategory(req.getCategory());
		update.setIsPublic(req.getIsPublic());
		int affected = videoMapper.updateById(update);
		return affected > 0;
	}

	@Override
	@Transactional
	public boolean deleteMyVideo(Long userId, Long videoId) {
		int affected = videoMapper.softDelete(videoId, userId);
		return affected > 0;
	}

	@Override
	@Transactional
	public boolean updateMyWorkflow(Long userId, Long workflowId, UserContentManageDto.WorkflowUpdateRequest req) {
		Workflow update = new Workflow();
		update.setId(workflowId);
		update.setOwnerId(userId);
		update.setName(req.getName());
		update.setDescription(req.getDescription());
		update.setCoverUrl(req.getCoverUrl());
		update.setCategory(req.getCategory());
		update.setIsPublic(req.getIsPublic());
		update.setFullAccessRole(req.getFullAccessRole());
		update.setCopyAccessRole(req.getCopyAccessRole());
		update.setPrice(req.getPrice());
		update.setIsFree(req.getIsFree());
		
		// 新增：支持数据包更新
		update.setData(req.getData());
		update.setDataFileUrl(req.getDataFileUrl());
		
		// 新增：支持演示视频更新
		if (req.getVodVideoId() != null) {
			update.setVodVideoId(req.getVodVideoId());
		} else if (req.getVideoId() != null) {
			// 兼容前端传videoId的情况，统一存储到vodVideoId字段
			update.setVodVideoId(req.getVideoId());
		}
		
		// 新增：支持详情图集更新
		update.setDetailGallery(req.getDetailGallery());
		
		// 重要：更新后重置为待审核状态（与课程更新逻辑保持一致）
		update.setAuditStatus(0);
		
		int affected = workflowMapper.updateById(update);
		return affected > 0;
	}

	@Override
	@Transactional
	public boolean deleteMyWorkflow(Long userId, Long workflowId) {
		int affected = workflowMapper.softDelete(workflowId, userId);
		return affected > 0;
	}

	@Override
	@Transactional
	public boolean updateMyCourse(Long userId, UserContentManageDto.CourseUpdateRequest req) {
		Course update = new Course();
		update.setId(req.getId());
		update.setUserId(userId);
		update.setTitle(req.getTitle());
		update.setDescription(req.getDescription());
		update.setCoverUrl(req.getCoverUrl());
		update.setDetailGallery(req.getDetailGallery());
		update.setCategory(req.getCategory());
		update.setIsFree(req.getIsFree());
		update.setLevel(req.getLevel());
		int affected = courseMapper.updateById(update);
		return affected > 0;
	}

	@Override
	@Transactional
	public boolean deleteMyCourse(Long userId, Long courseId) {
		int affected = courseMapper.softDelete(courseId, userId);
		return affected > 0;
	}

	@Override
	public UserContentManageDto.MyStatsResponse getMyStats(Long userId) {
		UserContentManageDto.MyStatsResponse stats = new UserContentManageDto.MyStatsResponse();
		// 统计视频
		stats.setVideoTotal(videoMapper.countByOwner(userId, null, null));
		stats.setVideoPending(videoMapper.countByOwner(userId, 0, null));
		stats.setVideoApproved(videoMapper.countByOwner(userId, 1, null));
		stats.setVideoRejected(videoMapper.countByOwner(userId, 2, null));
		// 统计工作流
		stats.setWorkflowTotal(workflowMapper.countByOwner(userId, null, null));
		stats.setWorkflowPending(workflowMapper.countByOwner(userId, 0, null));
		stats.setWorkflowApproved(workflowMapper.countByOwner(userId, 1, null));
		stats.setWorkflowRejected(workflowMapper.countByOwner(userId, 2, null));
		// 统计课程
		stats.setCourseTotal(courseMapper.countByOwner(userId, null, null));
		stats.setCoursePending(courseMapper.countByOwner(userId, 0, null));
		stats.setCourseApproved(courseMapper.countByOwner(userId, 1, null));
		stats.setCourseRejected(courseMapper.countByOwner(userId, 2, null));
		return stats;
	}
}

