package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.ContentReviewDto;
import com.dora.entity.Video;
// import com.dora.entity.VideoCollectionItem;
import com.dora.entity.Workflow;
import com.dora.entity.Course;
// import com.dora.mapper.VideoCollectionItemMapper;
import com.dora.mapper.VideoMapper;
import com.dora.mapper.WorkflowMapper;
import com.dora.mapper.CourseMapper;
import com.dora.util.SecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

// import java.util.List;

@RestController
@RequestMapping("/user/review")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "内容审核", description = "视频/工作流/课程提交审核接口")
public class ContentReviewController {

    private final VideoMapper videoMapper;
    private final WorkflowMapper workflowMapper;
    // private final VideoCollectionItemMapper videoCollectionItemMapper;
    private final com.dora.mapper.CourseChapterMapper courseChapterMapper;
    private final com.dora.mapper.CourseVideoMapper courseVideoMapper;
    private final CourseMapper courseMapper;

    @PostMapping("/submit")
    @Operation(summary = "提交内容审核", description = "支持视频、工作流、课程提交审核；自动写入标题/描述与合集归属")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "提交成功",
            content = @Content(schema = @Schema(implementation = ContentReviewDto.SubmitResponse.class))),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "内容不存在"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public ResponseEntity<Result<ContentReviewDto.SubmitResponse>> submit(@Valid @RequestBody ContentReviewDto.SubmitRequest req) {
        Long userId = SecurityUtil.getCurrentUserId();
        ContentReviewDto.SubmitResponse resp = new ContentReviewDto.SubmitResponse();
        resp.setContentType(req.getContentType());
        resp.setContentId(req.getContentId());
        try {
            if ("video".equalsIgnoreCase(req.getContentType())) {
                Video v = videoMapper.selectByVodVideoId(req.getContentId());
                if (v == null || v.getIsDeleted() != null && v.getIsDeleted() == 1) {
                                    // 如果视频记录不存在，自动创建一个新的视频记录
                v = new Video();
                v.setVodVideoId(req.getContentId());
                v.setOwnerId(userId);
                v.setTitle(req.getVideoTitle() != null ? req.getVideoTitle() : "未命名视频");
                v.setDescription(req.getVideoDescription() != null ? req.getVideoDescription() : "");
                v.setCoverUrl(req.getVideoCoverUrl()); // 设置封面URL
                v.setCategory(req.getVideoCategory()); // 设置分类
                v.setDuration(req.getVideoDuration()); // 设置时长
                v.setAuditStatus(0); // 待审核
                v.setIsPublic(0); // 默认不公开
                v.setViewCount(0);
                v.setLikeCount(0);
                v.setIsDeleted(0);
                    
                    // 插入新记录
                    videoMapper.insert(v);
                    log.info("自动创建视频记录，vodVideoId: {}, 数据库ID: {}", req.getContentId(), v.getId());
                }
                if (!v.getOwnerId().equals(userId)) {
                    return ResponseEntity.status(401).body(Result.error(401, "无权操作该视频"));
                }
                // 提交审核更新
                int affected = videoMapper.submitForAudit(v.getId(), userId,
                        req.getVideoTitle(), req.getVideoDescription());
                if (affected <= 0) {
                    return ResponseEntity.internalServerError().body(Result.error(500, "提交审核失败"));
                }

                // 自动课程聚合（合集即课程集合）：
                // - 若提供 collectionId，则视为归入既有课程；
                // - 若未提供，则自动创建课程，并在响应中返回 courseId，前端可持有用于后续多视频归类。
                Long courseIdForAgg = null;
                if (req.getCollectionId() != null) {
                    // 用 collectionId 作为课程ID归类
                    courseIdForAgg = req.getCollectionId();
                } else {
                    // 未提供：自动创建课程
                    Course autoCourse = new Course();
                    autoCourse.setTitle(req.getVideoTitle() != null ? req.getVideoTitle() : "我的课程");
                    autoCourse.setDescription(req.getVideoDescription());
                    autoCourse.setCoverUrl(req.getVideoCoverUrl()); // 设置课程封面
                    autoCourse.setCategory(req.getVideoCategory()); // 设置课程分类
                    autoCourse.setUserId(userId);
                    autoCourse.setIsFree(1); // 默认免费
                    autoCourse.setLevel(0); // 默认所有用户可访问
                    autoCourse.setAuditStatus(0); // 待审核
                    autoCourse.setIsDeleted(0);
                    int inserted = courseMapper.insert(autoCourse);
                    if (inserted > 0) {
                        courseIdForAgg = autoCourse.getId();
                    }
                }

                // 将视频归入课程的一个新章节（自动章节），章节序号自增
                if (courseIdForAgg != null) {
                    Integer nextOrder = courseChapterMapper.selectNextOrderNum(courseIdForAgg);
                    if (nextOrder == null || nextOrder <= 0) nextOrder = 1;
                    com.dora.entity.CourseChapter chapter = new com.dora.entity.CourseChapter();
                    chapter.setCourseId(courseIdForAgg);
                    chapter.setTitle(req.getVideoTitle() != null ? req.getVideoTitle() : ("第" + nextOrder + "章"));
                    chapter.setDescription(req.getVideoDescription());
                    chapter.setOrderNum(nextOrder);
                    int chIns = courseChapterMapper.insert(chapter);
                    if (chIns > 0) {
                        com.dora.entity.CourseVideo courseVideo = new com.dora.entity.CourseVideo();
                        courseVideo.setChapterId(chapter.getId());
                        courseVideo.setTitle(req.getVideoTitle());
                        courseVideo.setVideoId(v.getId());
                        courseVideo.setDurationSec(v.getDuration());
                        courseVideo.setOrderNum(1);
                        courseVideoMapper.insert(courseVideo);
                    }
                }
                resp.setAuditStatus(0);
                resp.setMessage("视频提交审核成功");
                resp.setCourseId(courseIdForAgg);
                return ResponseEntity.ok(Result.success(resp));
            } else if ("workflow".equalsIgnoreCase(req.getContentType())) {
                // 工作流暂时不支持通过外部ID查询，需要前端传递数据库ID
                try {
                    Long workflowId = Long.valueOf(req.getContentId());
                    Workflow w = workflowMapper.selectById(workflowId);
                    if (w == null || w.getIsDeleted() != null && w.getIsDeleted() == 1) {
                        return ResponseEntity.status(404).body(Result.error(404, "工作流不存在"));
                    }
                    if (!w.getOwnerId().equals(userId)) {
                        return ResponseEntity.status(401).body(Result.error(401, "无权操作该工作流"));
                    }
                    // 工作流信息更新通过 submitForAudit 方法处理
                    int affected = workflowMapper.submitForAudit(w.getId(), userId,
                            req.getWorkflowName(), req.getWorkflowDescription());
                    if (affected <= 0) {
                        return ResponseEntity.internalServerError().body(Result.error(500, "提交审核失败"));
                    }
                    resp.setAuditStatus(0);
                    resp.setMessage("工作流提交审核成功");
                    return ResponseEntity.ok(Result.success(resp));
                } catch (NumberFormatException e) {
                    return ResponseEntity.badRequest().body(Result.error(400, "工作流ID格式错误，请传递数字ID"));
                }
            } else if ("course".equalsIgnoreCase(req.getContentType())) {
                // 课程审核提交
                try {
                    Long courseId = Long.valueOf(req.getContentId());
                    Course course = courseMapper.selectById(courseId);
                    if (course == null || course.getIsDeleted() != null && course.getIsDeleted() == 1) {
                        return ResponseEntity.status(404).body(Result.error(404, "课程不存在"));
                    }
                    if (!course.getUserId().equals(userId)) {
                        return ResponseEntity.status(401).body(Result.error(401, "无权操作该课程"));
                    }
                    // 课程信息更新通过 submitForAudit 方法处理，收费与权限选择在课程创建/编辑接口中设置
                    int affected = courseMapper.submitForAudit(course.getId(), userId,
                            req.getCourseTitle(), req.getCourseDescription(), req.getCourseIsFree(), req.getCourseLevel());
                    
                    // 更新课程分类和封面（如果需要）
                    if (req.getCourseCategory() != null || req.getCourseCoverUrl() != null) {
                        course.setCategory(req.getCourseCategory());
                        course.setCoverUrl(req.getCourseCoverUrl());
                        courseMapper.updateById(course);
                    }
                    if (affected <= 0) {
                        return ResponseEntity.internalServerError().body(Result.error(500, "提交审核失败"));
                    }
                    resp.setAuditStatus(0);
                    resp.setMessage("课程提交审核成功");
                    return ResponseEntity.ok(Result.success(resp));
                } catch (NumberFormatException e) {
                    return ResponseEntity.badRequest().body(Result.error(400, "课程ID格式错误，请传递数字ID"));
                }
            } else {
                return ResponseEntity.badRequest().body(Result.error(400, "contentType 仅支持 video/workflow/course"));
            }
        } catch (RuntimeException e) {
            log.error("提交审核失败", e);
            return ResponseEntity.internalServerError().body(Result.error(500, e.getMessage()));
        } catch (Exception e) {
            log.error("提交审核失败", e);
            return ResponseEntity.internalServerError().body(Result.error(500, "服务器内部错误"));
        }
    }

    @PostMapping("/submit-course-collection")
    @Operation(summary = "批量提交课程集合审核", description = "一次性提交包含多个视频的课程集合，自动创建课程和章节")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "提交成功",
            content = @Content(schema = @Schema(implementation = ContentReviewDto.CourseCollectionSubmitResponse.class))),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "视频不存在"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public ResponseEntity<Result<ContentReviewDto.CourseCollectionSubmitResponse>> submitCourseCollection(
            @Valid @RequestBody ContentReviewDto.CourseCollectionSubmitRequest req) {
        Long userId = SecurityUtil.getCurrentUserId();
        ContentReviewDto.CourseCollectionSubmitResponse resp = new ContentReviewDto.CourseCollectionSubmitResponse();
        resp.setCourseCollectionId(req.getCourseCollectionId()); // 保留用于兼容性
        
        try {
            // 1. 创建新课程
            Course course = new Course();
            course.setTitle(req.getCourseTitle());
            course.setDescription(req.getCourseDescription());
            course.setCoverUrl(req.getCourseCoverUrl()); // 优先使用课程封面
            course.setCategory(req.getCourseCategory()); // 优先使用课程分类
            course.setDetailGallery(req.getDetailGallery()); // 设置详情图集
            course.setUserId(userId);
            course.setIsFree(req.getCourseIsFree());
            course.setLevel(req.getCourseLevel());
            course.setAuditStatus(0); // 待审核
            course.setIsDeleted(0);
            
            // 如果没有设置课程封面和分类，从第一个章节获取
            if (!req.getChapters().isEmpty()) {
                ContentReviewDto.CourseItem firstChapter = req.getChapters().get(0);
                if (course.getCoverUrl() == null || course.getCoverUrl().isEmpty()) {
                    course.setCoverUrl(firstChapter.getVideoCoverUrl());
                }
                if (course.getCategory() == null || course.getCategory().isEmpty()) {
                    course.setCategory(firstChapter.getVideoCategory());
                }
            }
            
            int inserted = courseMapper.insert(course);
            if (inserted <= 0) {
                return ResponseEntity.internalServerError().body(Result.error(500, "创建课程失败"));
            }
            
            resp.setCourseId(course.getId());
            
            // 2. 处理每个章节和视频
            int successChapterCount = 0;
            for (int i = 0; i < req.getChapters().size(); i++) {
                ContentReviewDto.CourseItem chapterItem = req.getChapters().get(i);
                
                // 验证视频是否存在
                Video video = videoMapper.selectByVodVideoId(chapterItem.getVideoId());
                if (video == null || video.getIsDeleted() != null && video.getIsDeleted() == 1) {
                    // 如果视频记录不存在，自动创建一个新的视频记录
                    video = new Video();
                    video.setVodVideoId(chapterItem.getVideoId());
                    video.setOwnerId(userId);
                    video.setTitle(chapterItem.getVideoTitle() != null ? chapterItem.getVideoTitle() : "未命名视频");
                    video.setDescription(chapterItem.getVideoDescription() != null ? chapterItem.getVideoDescription() : "");
                    video.setCoverUrl(chapterItem.getVideoCoverUrl()); // 设置封面URL
                    video.setCategory(chapterItem.getVideoCategory()); // 设置分类
                    video.setDuration(chapterItem.getVideoDuration()); // 设置时长
                    video.setAuditStatus(0); // 待审核
                    video.setIsPublic(0); // 默认不公开
                    video.setViewCount(0);
                    video.setLikeCount(0);
                    video.setIsDeleted(0);
                    
                    videoMapper.insert(video);
                    log.info("自动创建视频记录，vodVideoId: {}, 数据库ID: {}", chapterItem.getVideoId(), video.getId());
                }
                
                // 检查视频权限
                if (!video.getOwnerId().equals(userId)) {
                    return ResponseEntity.status(401).body(Result.error(401, "无权操作视频: " + chapterItem.getVideoId()));
                }
                
                // 创建章节
                Integer orderNum = chapterItem.getOrderNum();
                if (orderNum == null || orderNum <= 0) {
                    orderNum = i + 1; // 自动递增
                }
                
                com.dora.entity.CourseChapter chapter = new com.dora.entity.CourseChapter();
                chapter.setCourseId(course.getId());
                chapter.setTitle(chapterItem.getChapterTitle());
                chapter.setDescription(chapterItem.getChapterDescription());
                chapter.setOrderNum(orderNum);
                
                int chIns = courseChapterMapper.insert(chapter);
                if (chIns > 0) {
                    // 关联视频到章节
                    com.dora.entity.CourseVideo courseVideo = new com.dora.entity.CourseVideo();
                    courseVideo.setChapterId(chapter.getId());
                    courseVideo.setTitle(chapterItem.getVideoTitle());
                    courseVideo.setVideoId(video.getId());
                    courseVideo.setDurationSec(video.getDuration());
                    courseVideo.setOrderNum(1);
                    courseVideoMapper.insert(courseVideo);
                    
                    successChapterCount++;
                }
            }
            
            resp.setAuditStatus(0);
            resp.setMessage("课程集合提交审核成功");
            resp.setChapterCount(successChapterCount);
            
            return ResponseEntity.ok(Result.success(resp));
            
        } catch (Exception e) {
            log.error("提交课程集合审核失败", e);
            return ResponseEntity.internalServerError().body(Result.error(500, "服务器内部错误: " + e.getMessage()));
        }
    }

    @PostMapping("/submit-course-collection/v2")
    @org.springframework.transaction.annotation.Transactional
    @Operation(summary = "批量提交课程集合审核（v2，支持每章多视频）", description = "一次性提交包含多个章节与视频的课程集合，自动创建课程和章节与章节内视频排序")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "提交成功",
            content = @Content(schema = @Schema(implementation = ContentReviewDto.CourseCollectionSubmitResponse.class))),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "404", description = "视频不存在"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public org.springframework.http.ResponseEntity<com.dora.common.Result<com.dora.dto.ContentReviewDto.CourseCollectionSubmitResponse>> submitCourseCollectionV2(
            @jakarta.validation.Valid @org.springframework.web.bind.annotation.RequestBody com.dora.dto.ContentReviewDto.CourseCollectionV2SubmitRequest req) {
        Long userId = com.dora.util.SecurityUtil.getCurrentUserId();
        com.dora.dto.ContentReviewDto.CourseCollectionSubmitResponse resp = new com.dora.dto.ContentReviewDto.CourseCollectionSubmitResponse();
        resp.setCourseCollectionId(req.getCourseCollectionId());

        try {
            // 创建课程
            com.dora.entity.Course course = new com.dora.entity.Course();
            course.setTitle(req.getCourseTitle());
            course.setDescription(req.getCourseDescription());
            course.setCoverUrl(req.getCourseCoverUrl());
            course.setCategory(req.getCourseCategory());
            course.setDetailGallery(req.getDetailGallery()); // 设置详情图集
            course.setUserId(userId);
            course.setIsFree(req.getCourseIsFree());
            course.setLevel(req.getCourseLevel());
            course.setAuditStatus(0);
            course.setIsDeleted(0);

            // 如封面/分类为空，从第一章第一个视频兜底
            if (!req.getChapters().isEmpty() && (course.getCoverUrl() == null || course.getCoverUrl().isEmpty() || course.getCategory() == null || course.getCategory().isEmpty())) {
                com.dora.dto.ContentReviewDto.ChapterV2 firstChapter = req.getChapters().get(0);
                if (!firstChapter.getVideos().isEmpty()) {
                    com.dora.dto.ContentReviewDto.CourseVideoItem firstVideo = firstChapter.getVideos().get(0);
                    if (course.getCoverUrl() == null || course.getCoverUrl().isEmpty()) {
                        course.setCoverUrl(firstVideo.getVideoCoverUrl());
                    }
                    if (course.getCategory() == null || course.getCategory().isEmpty()) {
                        course.setCategory(firstVideo.getVideoCategory());
                    }
                }
            }

            int inserted = courseMapper.insert(course);
            if (inserted <= 0) {
                return org.springframework.http.ResponseEntity.internalServerError().body(com.dora.common.Result.error(500, "创建课程失败"));
            }

            resp.setCourseId(course.getId());

            int successChapterCount = 0;
            for (int i = 0; i < req.getChapters().size(); i++) {
                com.dora.dto.ContentReviewDto.ChapterV2 chapterReq = req.getChapters().get(i);

                Integer chapterOrder = chapterReq.getOrderNum();
                if (chapterOrder == null || chapterOrder <= 0) {
                    Integer nextOrder = courseChapterMapper.selectNextOrderNum(course.getId());
                    chapterOrder = (nextOrder == null || nextOrder <= 0) ? (i + 1) : nextOrder;
                }

                com.dora.entity.CourseChapter chapter = new com.dora.entity.CourseChapter();
                chapter.setCourseId(course.getId());
                chapter.setTitle(chapterReq.getChapterTitle());
                chapter.setDescription(chapterReq.getChapterDescription());
                chapter.setOrderNum(chapterOrder);

                int chIns = courseChapterMapper.insert(chapter);
                if (chIns <= 0) {
                    continue;
                }

                // 遍历章节内视频
                int localVideoOrderBase = 0;
                for (int j = 0; j < chapterReq.getVideos().size(); j++) {
                    com.dora.dto.ContentReviewDto.CourseVideoItem vItem = chapterReq.getVideos().get(j);

                    com.dora.entity.Video video = videoMapper.selectByVodVideoId(vItem.getVideoId());
                    if (video == null || video.getIsDeleted() != null && video.getIsDeleted() == 1) {
                        video = new com.dora.entity.Video();
                        video.setVodVideoId(vItem.getVideoId());
                        video.setOwnerId(userId);
                        video.setTitle(vItem.getVideoTitle() != null ? vItem.getVideoTitle() : "未命名视频");
                        video.setDescription(vItem.getVideoDescription() != null ? vItem.getVideoDescription() : "");
                        video.setCoverUrl(vItem.getVideoCoverUrl());
                        video.setCategory(vItem.getVideoCategory());
                        video.setDuration(vItem.getVideoDuration());
                        video.setAuditStatus(0);
                        video.setIsPublic(0);
                        video.setViewCount(0);
                        video.setLikeCount(0);
                        video.setIsDeleted(0);
                        videoMapper.insert(video);
                    }

                    if (!video.getOwnerId().equals(userId)) {
                        return org.springframework.http.ResponseEntity.status(401).body(com.dora.common.Result.error(401, "无权操作视频: " + vItem.getVideoId()));
                    }

                    Integer videoOrder = vItem.getOrderNum();
                    if (videoOrder == null || videoOrder <= 0) {
                        // 查询该章节下下一个视频序号
                        Integer nextOrder = courseVideoMapper.selectNextOrderNum(chapter.getId());
                        // 兜底：若无则按本地递增
                        if (nextOrder == null || nextOrder <= 0) {
                            localVideoOrderBase++;
                            videoOrder = localVideoOrderBase;
                        } else {
                            videoOrder = nextOrder;
                        }
                    }

                    com.dora.entity.CourseVideo courseVideo = new com.dora.entity.CourseVideo();
                    courseVideo.setChapterId(chapter.getId());
                    courseVideo.setTitle(vItem.getVideoTitle());
                    courseVideo.setVideoId(video.getId());
                    courseVideo.setDurationSec(video.getDuration());
                    courseVideo.setOrderNum(videoOrder);
                    courseVideoMapper.insert(courseVideo);
                }

                successChapterCount++;
            }

            resp.setAuditStatus(0);
            resp.setMessage("课程集合提交审核成功");
            resp.setChapterCount(successChapterCount);

            return org.springframework.http.ResponseEntity.ok(com.dora.common.Result.success(resp));

        } catch (Exception e) {
            log.error("提交课程集合审核失败", e);
            return org.springframework.http.ResponseEntity.internalServerError().body(com.dora.common.Result.error(500, "服务器内部错误: " + e.getMessage()));
        }
    }
}


