package jnpf.cultivate.controller.app.course;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.cultivate.service.CultivateCourseMsgService;
import jnpf.cultivate.service.CultivateCourseMsgUserService;
import jnpf.cultivate.service.FtbCultivateCourseAppService;
import jnpf.cultivate.service.FtbCultivateCourseChapterService;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.dto.course.app.FtbChapterStudyDTO;
import jnpf.model.cultivate.dto.course.app.FtbCultivateCourseMsgForAppDTO;
import jnpf.model.cultivate.dto.course.app.FtbGlobalCurriculumAppWrapDTO;
import jnpf.model.cultivate.dto.course.app.FtbUserLevelMessageReadDTO;
import jnpf.model.cultivate.vo.course.app.*;
import jnpf.util.UserProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * app端课程模块
 *
 * @author fantaibao
 * @date 2023/12/19
 */
@RestController
@RequestMapping("/app/ftb-cultivate-course")
public class FtbCultivateCourseAppController {
    @Resource
    private FtbCultivateCourseAppService ftbCultivateCourseAppService;
    @Resource
    private CultivateCourseMsgService cultivateCourseMsgService;
    @Resource
    private CultivateCourseMsgUserService msgUserService;
    @Resource
    private FtbCultivateCourseChapterService ftbCultivateCourseChapterService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * App查询用户未读信息列表
     * @return
     */
    @GetMapping("/queryUserUnreadMsg")
    public ActionResult<List<FtbCultivateCourseMsgForAppVO>> queryUserUnreadMsg() {
        List<FtbCultivateCourseMsgForAppVO> list =  cultivateCourseMsgService.queryUserUnreadMsg();
        return ActionResult.success(list);
    }

    /**
     * App查询用户课程未勾选“课程内容更新需要重新学习”信息列表
     *
     * @param courseId 课程id（必传）
     * @return
     */
    @GetMapping("/query-user-unread-update")
    public ActionResult<List<FtbCultivateCourseMsgForAppVO>> queryUserUnreadMsgUpdate(String courseId) {
        List<FtbCultivateCourseMsgForAppVO> list = cultivateCourseMsgService.queryUserUnreadMsgUpdate(courseId);
        return ActionResult.success(list);
    }

    /**
     * App更新用户已读信息
     * @param dto
     * @return
     */
    @PutMapping("/updateInfoByMsgId")
    public ActionResult<String> updateInfoByMsgId(@RequestBody FtbCultivateCourseMsgForAppDTO dto) {
        msgUserService.updateInfoByMsgId(dto);
        return ActionResult.success();
    }

    /**
     * APP课程学习模块-课程详情
     *
     * @param courseId 课程主键id,必填
     * @return {@link ActionResult}<{@link FtbCourseDetailsAppVO}>
     */
    @GetMapping("/course-details")
    public ActionResult<FtbCourseDetailsAppVO> courseDetails(@RequestParam("courseId") String courseId,
                                                             @RequestParam("userId") String userId) {
        FtbCourseDetailsAppVO ftbCourseDetailsAppVO = ftbCultivateCourseAppService.courseDetails(courseId,userId);
        return ActionResult.success(ftbCourseDetailsAppVO);
    }

    /**
     * APP课程学习模块-课程大纲
     *
     * @param courseId 课程主键id,必填
     * @return {@link ActionResult}<{@link FtbCourseDetailsAppVO}>
     */
    @GetMapping("/course-outline")
    public ActionResult<FtbCourseOutlineAppVO> courseOutline(@RequestParam("courseId") String courseId,
                                                             @RequestParam("userId") String userId) {
        String lockKey = "course-outline:" + courseId + ":" + userId;
        if (redisTemplate.opsForValue().setIfAbsent(lockKey, UUID.fastUUID(), 3, TimeUnit.SECONDS)) {
            try {

                FtbCourseOutlineAppVO ftbCourseOutlineAppVOS = ftbCultivateCourseAppService.courseOutline(courseId, userId);
                return ActionResult.success(ftbCourseOutlineAppVOS);
            } catch (Exception e) {
                throw e;
            } finally {
                redisTemplate.delete(lockKey);
            }
        } else {
            throw new RuntimeException("访问太快了");
        }

    }



    /**
     * App课程学习模块-增加当前课程浏览量
     *
     * @param courseId 课程主键id,必填
     * @return {@link ActionResult}
     */
    @PutMapping("/course-browsing/{id}")
    public ActionResult courseBrowsing(@PathVariable("id") String courseId) {
        ftbCultivateCourseAppService.courseBrowsing(courseId);
        return ActionResult.success();
    }

    /**
     * App课程学习模块-完成章节学习
     *
     * @param ftbChapterStudyDTO
     * @return {@link ActionResult}
     */
    @PostMapping("/chapter-study")
    public ActionResult chapterStudy(@Validated @RequestBody FtbChapterStudyDTO ftbChapterStudyDTO) {
        UserInfo userInfo = UserProvider.getUser();

        String lockKey = "chapterStudy:" + userInfo.getUserId()+":"+ftbChapterStudyDTO.getType()+":"+ftbChapterStudyDTO.getCourseId()+":"+ftbChapterStudyDTO.getChapterId();
        if (redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 10, TimeUnit.SECONDS)) {
            try {
                ftbCultivateCourseAppService.chapterStudy(userInfo, ftbChapterStudyDTO);
                return ActionResult.success();
            } catch (Exception e) {
                throw e;
            } finally {
                redisTemplate.delete(lockKey);
            }
        } else {
            throw new RuntimeException("请不要重复提交");
        }
    }

    /**
     * App课程学习模块-时长记录
     *
     * @param ftbChapterStudyDTO
     * @return {@link ActionResult}
     */
    @PostMapping("/duration-record")
    public ActionResult durationRecord(@Validated @RequestBody FtbChapterStudyDTO ftbChapterStudyDTO) {
        UserInfo userInfo = UserProvider.getUser();
        ftbCultivateCourseAppService.durationRecord(userInfo, ftbChapterStudyDTO);
        return ActionResult.success();
    }

    /**
     * App课程学习模块-章节详情
     */
    @GetMapping("/chapter-details/{id}")
    public ActionResult<FtbChapterAppDetails> chapterDetails(@PathVariable("id") String id) {
        FtbChapterAppDetails ftbChapterAppDetails = ftbCultivateCourseAppService.chapterDetails(id);
        return ActionResult.success(ftbChapterAppDetails);
    }


    /**
     * 查询用户职等是否发生变化
     *
     * @param type 类型(必传)0晋升通道,1岗位学习
     * @return {@link ActionResult}
     */
    @GetMapping("/check-job-grade-changes")
    public ActionResult<List<FtbCheckJobGradeChangeVO>> checkJobGradeChanges(Integer type) {
        List<FtbCheckJobGradeChangeVO> result = cultivateCourseMsgService.checkJobGradeChanges(type);
        return ActionResult.success(result);
    }

    /**
     * 岗位职等发生变化时标记消息已读
     *
     * @return {@link ActionResult}
     */
    @PutMapping("/user-level-message-has-been-read")
    public ActionResult userLevelMessageHasBeenRead(@RequestBody FtbUserLevelMessageReadDTO ftbUserLevelMessageReadDTO) {
        cultivateCourseMsgService.userLevelMessageHasBeenRead(ftbUserLevelMessageReadDTO);
        return ActionResult.success();
    }

    /**
     * 通用课程列表
     *
     * @param cultivatePage 分页参数
     * @return {@link ActionResult}
     */
    @GetMapping("/general-course-list")
    public ActionResult<FtbGlobalCurriculumAppWrapVO> generalCourseList(CultivatePage cultivatePage
            , FtbGlobalCurriculumAppWrapDTO ftbGlobalCurriculumAppWrapDTO) {
        Page<FtbGlobalCurriculumAppVO> page = cultivatePage.coverCultivatePage();
        FtbGlobalCurriculumAppWrapVO result = ftbCultivateCourseChapterService.generalCourseList(page, ftbGlobalCurriculumAppWrapDTO);
        return ActionResult.success(result);
    }

}
