package com.fs.app.controller;


import com.fs.app.annotation.Login;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.course.domain.*;
import com.fs.course.param.*;
import com.fs.course.service.*;
import com.fs.course.vo.*;
import com.fs.his.vo.OptionsVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Api("课堂接口")
@Slf4j
@RestController
@RequestMapping(value="/app/course")
public class CourseController extends  AppBaseController{
    @Autowired
    private IFsUserCourseService courseService;
    @Autowired
    private IFsUserCourseCategoryService courseCategoryService;
    @Autowired
    private IFsUserCourseVideoService courseVideoService;
    @Autowired
    private IFsUserCourseLikeService courseLikeService;
    @Autowired
    private IFsUserCourseFavoriteService courseFavoriteService;
    @Autowired
    private IFsUserCourseStudyService courseStudyService;
    @Autowired
    private IFsUserCourseStudyLogService courseStudyLogService;
    @Autowired
    private IFsCourseSopAppLinkService courseSopAppLinkService;
    @Autowired
    ITencentCloudCosService tencentCloudCosService;

//    @Cacheable(value="getCourseCate" )
    @ApiOperation("获取分类")
    @GetMapping("/getCourseCate")
    public R getCourseCate(@RequestParam(value = "isShow",required = false) Integer isShow){
        try {
            List<OptionsVO> list = courseCategoryService.selectFsUserCourseCategoryPidList(isShow);
            return R.ok().put("data",list);
        } catch (Exception e){
            return R.error("操作异常");
        }
    }

    @Cacheable(value = "getProductCateByPid", key = "#pid")
    @ApiOperation("获取子分类")
    @GetMapping("/getProductCateByPid")
    public R getProductCateByPid(@RequestParam(value="pid") Long pid){
        try {
            List<OptionsVO> list = courseCategoryService.selectCateListByPid(pid);
            return R.ok().put("data",list);
        } catch (Exception e){
            return R.error("操作异常");
        }
    }
//    @Cacheable(value = "getCourseList",key = "#param" )
    @ApiOperation("课程列表")
    @GetMapping("/getCourseList")
    public R getCourseList(FsUserCourseListUParam param)
    {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsUserCourseListUVO> list= courseService.selectFsUserCourseListUVO(param);
        PageInfo<FsUserCourseListUVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @ApiOperation("课程简介")
    @GetMapping("/getCourseDescription")
    public R getCourseDescription(@RequestParam("courseId") Long courseId,HttpServletRequest request)
    {
        FsUserCourse course = courseService.selectFsUserCourseByCourseId(courseId);
        return R.ok().put("data",course);
    }

    @Login
    @ApiOperation("获取收藏课程")
    @GetMapping("/getMyFavoriteCourseList")
    public R getMyFavoriteCourseList(FsUserCourseListUParam param)
    {
        param.setUserId(Long.parseLong(getUserId()));
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsUserCourseFavoriteListUVO> list= courseFavoriteService.selectFsUserCourseFavoriteListUVO(param);
        PageInfo<FsUserCourseFavoriteListUVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("获取我的评论课程")
    @GetMapping("/getMyCommentCourseList")
    public R getMyCommentCourseList(FsUserCourseListUParam param)
    {
        param.setUserId(Long.parseLong(getUserId()));
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsUserCourseListUVO> list= courseService.selectFsUserCourseCommentListUVO(param);
        PageInfo<FsUserCourseListUVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("获取在学课程")
    @GetMapping("/getCourseStudyList")
    public R getMyCourseList(FsUserCourseListUParam param)
    {
        param.setUserId(Long.parseLong(getUserId()));
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsUserCourseStudyListUVO> list= courseStudyService.selectFsUserCourseStudyListUVO(param);
        // 创建 Map 用于按时间分组
        Map<String, List<FsUserCourseStudyListUVO>> groupedByTime = new LinkedHashMap<>(); // 保留插入顺序
        for (FsUserCourseStudyListUVO vo:list){
            String date = DateUtils.parseDateToStr("yyyy-MM-dd",vo.getStudyTime());
            if (!groupedByTime.containsKey(date)) {
                groupedByTime.put(date, new ArrayList<>());
            }
            groupedByTime.get(date).add(vo);
        }
        // 将 Map 转为列表，包含时间信息
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<String, List<FsUserCourseStudyListUVO>> entry : groupedByTime.entrySet()) {
            Map<String, Object> item = new HashMap<>();
            item.put("date", entry.getKey());
            item.put("courses", entry.getValue());
            result.add(item);
        }
        PageInfo<Map<String, Object>> listPageInfo = new PageInfo<>(result);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("获取我的sop课程")
    @GetMapping("/getSopCourseStudyList")
    public R getSopCourseStudyList(FsCourseSopLinkParam param){

        PageHelper.startPage(param.getPageNum(), param.getPageSize());

        long userId = Long.parseLong(getUserId());

        List<FsSopMyCourseLinkVO> list = courseSopAppLinkService.getSopCourseStudyList(userId);

        //获取 客户有多少未读消息
        Integer isNotRead = courseSopAppLinkService.selectSopCountIsNotRead(userId);

        PageInfo<FsSopMyCourseLinkVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo).put("isNotRead",isNotRead);
    }

    @Login
    @ApiOperation("修改我的sop课程已读未读状态")
    @GetMapping("/updateSopAppLink/{id}")
    public R updateSopAppLink(@PathVariable("id") String id){

        try {
            courseSopAppLinkService.updateFsCourseSopAppLinkByLink(id);

            return R.ok();
        }catch (Exception e){
            return R.error();
        }

    }

    @ApiOperation("获取课程详情")
    @GetMapping("/getCourseById")
    public R getCourseById(@RequestParam("courseId")Long courseId)
    {
        FsUserCourseUVO courseUVO=courseService.selectFsUserCourseUVOByCourseId(courseId);
        if (courseUVO.getIsDel()==1 || courseUVO.getIsShow()==0){
            courseUVO.setIsShow(0);
        }
        if (StringUtils.isNotEmpty(getUserId())) {
            FsUserCourseStudyLog studyLog = courseStudyLogService.selectFsUserCourseStudyByCourseId(courseId,Long.parseLong(getUserId()));
            if (studyLog!=null){
                courseUVO.setStudyLog(studyLog);
            }
        }

        //更新观看数
        courseService.updateViews(courseId);
        return R.ok().put("data",courseUVO);
    }

    @ApiOperation("获取课程目录")
    @GetMapping("/getCourseVideoList")
    public R getCourseVideoList(FsUserCourseVideoListUParam param)
    {
        if (StringUtils.isNotEmpty(getUserId())) {
            param.setUserId(Long.parseLong(getUserId()));
        }
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsUserCourseVideoListUVO> list= courseVideoService.selectFsUserCourseVideoListUVOByCourseId(param);
        PageInfo<FsUserCourseVideoListUVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("分享课程")
    @GetMapping("/shareCourse")
    public R shareCourse(@RequestParam("courseId")Long courseId)
    {
        //更新分享数
        courseService.updateShares(courseId);
        return R.ok();
    }

    @Login
    @ApiOperation("新增课堂学习记录")
    @PostMapping("/addStudyCourse")
    public R addStudyCourse(@RequestBody FsUserCourseAddStudyCourseParam param)
    {
        //更新时长
        param.setUserId(Long.parseLong(getUserId()));
        return courseService.addStudyCourse(param);
    }


    @Login
    @ApiOperation("获取是否点赞")
    @GetMapping("/checkLike")
    public R checkLike(@RequestParam("courseId")Long courseId, HttpServletRequest request){
        String headValue =  ServletUtils.getRequest().getHeader("APPToken");
        Claims claims=jwtUtils.getClaimByToken(headValue);
        if(claims!=null){
            String userId = claims.getSubject().toString();
            R r=courseLikeService.checkLike(courseId,Long.parseLong(userId));
            if (r.get("code").equals(200)){
                return R.ok().put("isLike",1);
            }else {
                return R.ok().put("isLike",0);
            }
//            return courseLikeService.checkLike(courseId,Long.parseLong(userId));
        }
        else{
            return R.error("未登录");
        }

    }

    @Login
    @ApiOperation("点赞")
    @PostMapping("/doLike")
    @Transactional
    @Synchronized
    public R doLike(@RequestBody FsUserCourseFollowUParam param, HttpServletRequest request){
        R r=courseLikeService.checkLike(param.getCourseId(),Long.parseLong(getUserId()));
        if(r.get("code").equals(200)){
            //取消点赞
            courseLikeService.deleteLike(param.getCourseId(),Long.parseLong(getUserId()));
            courseService.updateLikes(param.getCourseId(),-1);
            return R.ok("已取消喜欢");
        }
        else{
            //关注
            FsUserCourseLike map=new FsUserCourseLike();
            map.setCourseId(param.getCourseId());
            map.setUserId(Long.parseLong(getUserId()));
            map.setCreateTime(new Date());
            courseLikeService.insertFsUserCourseLike(map);
            courseService.updateLikes(param.getCourseId(),1);
            return R.ok("已喜欢");
        }
    }


    @Login
    @ApiOperation("获取是否收藏")
    @GetMapping("/checkFavorite")
    public R checkFavorite(@RequestParam("courseId")Long courseId, HttpServletRequest request){
        String headValue =  ServletUtils.getRequest().getHeader("APPToken");
        Claims claims=jwtUtils.getClaimByToken(headValue);
        if(claims!=null){
            String userId = claims.getSubject().toString();
            R r=courseFavoriteService.checkFavorite(courseId,Long.parseLong(userId));
            if (r.get("code").equals(200)){
                return R.ok().put("isFavorite",1);
            }else {
                return R.ok().put("isFavorite",0);
            }
//            return courseFavoriteService.checkFavorite(courseId,Long.parseLong(userId));
        }
        else{
            return R.error("未登录");
        }

    }

    @Login
    @ApiOperation("收藏")
    @PostMapping("/doFavorite")
    @Transactional
    @Synchronized
    public R doFavorite(@RequestBody FsUserCourseFollowUParam param, HttpServletRequest request){
        R r=courseFavoriteService.checkFavorite(param.getCourseId(),Long.parseLong(getUserId()));
        if(r.get("code").equals(200)){
            //取消点赞
            courseFavoriteService.deleteFavorite(param.getCourseId(),Long.parseLong(getUserId()));
            courseService.updateFavorite(param.getCourseId(),-1);
            return R.ok("已取消收藏");
        }
        else{
            //关注
            FsUserCourseFavorite map=new FsUserCourseFavorite();
            map.setCourseId(param.getCourseId());
            map.setUserId(Long.parseLong(getUserId()));
            map.setCreateTime(new Date());
            courseFavoriteService.insertFsUserCourseFavorite(map);
            //更新课程点赞数
            courseService.updateFavorite(param.getCourseId(),1);
            return R.ok("已收藏");
        }
    }

    @Login
    @ApiOperation("获取积分")
    @PostMapping("/getIntegral")
    public R getIntegral(@RequestBody FsUserCourseGetIntegralParam param, HttpServletRequest request){
        param.setUserId(Long.parseLong(getUserId()));
        return courseService.getIntegralByCourseVideo(param);
    }
    @GetMapping("/videoTranscode")
    public void videoTranscode(){
        tencentCloudCosService.videoTranscode();
    }
    @GetMapping("/updateUrl")
    public void updateUrl(){
        tencentCloudCosService.updateUrl();
    }

    @Login
    @ApiOperation("发放奖励App")
    @PostMapping("/sendAppReward")
    @RepeatSubmit
    public R sendAppReward(@RequestBody FsCourseSendRewardUParam param)
    {
        param.setUserId(Long.parseLong(getUserId()));
        log.info("zyp \n【发放APP奖励】：{}",param);
        return courseVideoService.sendAppReward(param);
    }
}
