package com.fs.app.controller.store;


import cn.hutool.json.JSONUtil;
import com.fs.app.annotation.Login;
import com.fs.app.controller.AppBaseController;
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.config.CourseConfig;
import com.fs.course.domain.*;
import com.fs.course.param.*;
import com.fs.course.service.*;
import com.fs.course.service.impl.TencentCloudCosService;
import com.fs.course.vo.*;
import com.fs.his.vo.OptionsVO;
import com.fs.hisStore.service.IFsStorePaymentScrmService;
import com.fs.system.service.ISysConfigService;
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 io.swagger.annotations.ApiParam;
import lombok.Synchronized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
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 springfox.documentation.spring.web.readers.operation.CachingOperationNameGenerator;

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

@Api("课堂接口")
@RestController
@RequestMapping(value="/store/app/course")
public class CourseScrmController extends AppBaseController {
    Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private IFsUserCourseService courseService;
    @Autowired
    private IFsStorePaymentScrmService storePaymentService;
    @Autowired
    private IFsUserCourseCategoryService courseCategoryService;

    @Autowired
    private IFsUserCourseVideoService courseVideoService;

    @Autowired
    private IFsUserCourseFollowService courseFollowService;
    @Autowired
    private IFsUserCourseLikeService courseLikeService;

    @Autowired
    private IFsUserCourseFavoriteService courseFavoriteService;
    @Autowired
    private IFsUserCourseStudyService courseStudyService;
    @Autowired
    private IFsUserCourseStudyLogService courseStudyLogService;
    @Autowired
    private IFsUserCourseNoteService courseNoteService;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IFsCourseLinkService courseLinkService;

    @Autowired
    private IFsCourseQuestionBankService questionBankService;

    @Autowired
    private IFsCourseWatchLogService courseWatchLogService;
    @Autowired
    private CachingOperationNameGenerator cachingOperationNameGenerator;
    @Autowired
    private IFsUserCoursePeriodService coursePeriodService;
    @Autowired
    private IFsCourseWatchCommentService courseWatchCommentService;


    @Cacheable(value="getCourseCate" )
    @ApiOperation("获取分类")
    @GetMapping("/getCourseCate")
    public R getCourseCate(){
        try {
            Integer isShow = null;
            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);
    }

    @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);
    }

    @ApiOperation("h5课程简介")
    @GetMapping("/getH5CourseByVideoId")
    public R getCourseByVideoId(@RequestParam("videoId") Long videoId,HttpServletRequest request)
    {
        FsUserCourseVideoH5VO course = courseService.selectFsUserCourseVideoH5VOByVideoId(videoId);
        return R.ok().put("data",course);
    }

    @Login
    @ApiOperation("h5课程详情加问答")
    @GetMapping("/getH5CourseVideoDetails")
    public R getCourseVideoDetails(FsUserCourseVideoFinishUParam param)
    {
        param.setUserId(Long.parseLong(getUserId()));
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        FsUserCourseVideoH5DVO course = courseService.selectFsUserCourseVideoH5DVOByVideoId(param.getVideoId());
        List<FsUserCourseVideoQuestionVO> questionVOList = new ArrayList<>();
        if (StringUtils.isNotEmpty(course.getQuestionBankId())){
            String[] questionIds = course.getQuestionBankId().split(",");
            for (String questionId : questionIds){
                FsUserCourseVideoQuestionVO vo = new FsUserCourseVideoQuestionVO();
                FsCourseQuestionBank questionBank = questionBankService.selectFsCourseQuestionBankById(Long.parseLong(questionId));
                if (questionBank!=null&&questionBank.getStatus()!=0){
                    BeanUtils.copyProperties(questionBank,vo);
                    questionVOList.add(vo);
                }
            }
        }
        Long duration = 0L;
        long tipsTime = 0L;
        int isFinish = 0;
//        //课程logo
//        if (param.getPeriodId()!=null){
//            FsUserCoursePeriod fsUserCoursePeriod = coursePeriodService.selectFsUserCoursePeriodById(param.getPeriodId());
//            if (fsUserCoursePeriod!=null){
//                config.setCourseLogo(fsUserCoursePeriod.getCourseLogo());
//            }
//        }
        if (param.getLinkType()!=null&&param.getLinkType()==1){
            return R.ok().put("course",course).put("questions",questionVOList).put("config",config).put("playDuration",duration).put("tipsTime",tipsTime);
        }

        if (param.getIsRoom()!=null&&param.getIsRoom()==1&&param.getQwExternalId()==null){
            return R.ok().put("course",course).put("questions",questionVOList).put("config",config).put("playDuration",duration).put("tipsTime",tipsTime);
        }
        // 从Redis中获取观看时长
        String redisKey = "h5user:watch:duration:" + param.getQwUserId()+ ":" + param.getQwExternalId() + ":" + param.getVideoId();
        String durationStr = redisCache.getCacheObject(redisKey);
        FsCourseWatchLog log = courseWatchLogService.getWatchCourseVideo(param.getUserId(),param.getVideoId(),param.getQwUserId(),param.getQwExternalId());
        if (log==null){
            return R.error("记录不存在，请联系客服!");
        }
        //redis取不到查库
        if (durationStr != null) {
            duration = Long.parseLong(durationStr);
        }else {
            duration = log.getDuration();
        }

        if (course.getDuration()!=null){
            tipsTime = course.getDuration()/2;
        }
        //判断是否完课
        if (log.getLogType()==2){
            isFinish=1;
        }

        //将视频时长也存到redis
        String videoRedisKey = "h5user:video:duration:" + param.getVideoId();
        Long videoDuration = redisCache.getCacheObject(videoRedisKey);
        if (videoDuration==null){
            redisCache.setCacheObject(videoRedisKey,course.getDuration());
        }


        return R.ok().put("course",course).put("questions",questionVOList).put("config",config).put("playDuration",duration).put("tipsTime",tipsTime).put("isFinish",isFinish);
    }


    @ApiOperation("答题")
    @PostMapping("/courseAnswer")
    @Login
    public R courseAnswer(@RequestBody FsCourseQuestionAnswerUParam param)
    {
        logger.info("zyp \n【答题】：{}",param.getQuestions());
        if (param.getDuration()==null){
            logger.info("zyp \n【未识别到时长】：{}",param.getUserId());
        }
        param.setUserId(Long.parseLong(getUserId()));
        return questionBankService.courseAnswer(param, false);
    }


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

    @ApiOperation("获取真实链接")
    @GetMapping("/getRealLink")
    public R getRealLink(@RequestParam("sortLink")String link)
    {
        return courseLinkService.getRealLink(link);
    }

    @Login
    @ApiOperation("更新看课时长")
    @PostMapping("/updateWatchDuration")
    public R updateWatchDuration(@RequestBody FsUserCourseVideoFinishUParam param)
    {
        param.setUserId(Long.parseLong(getUserId()));
        return courseVideoService.updateWatchDuration(param);
    }

    @Login
    @ApiOperation("每十分钟获取积分")
    @PostMapping("/getIntegralByH5Video")
    public R getIntegralByH5Video(@RequestBody FsUserCourseVideoFinishUParam param)
    {
        param.setUserId(Long.parseLong(getUserId()));
        return courseVideoService.getIntegralByH5Video(param);
    }

    /**
     * 是否添加客服
     */
    @Login
    @ApiOperation("是否添加客服")
    @PostMapping("/isAddKf")
    public R isAddKf(@RequestBody FsUserCourseVideoAddKfUParam param) {
        Long userId = Long.parseLong(getUserId());
        param.setUserId(userId);
        return courseVideoService.isAddKf(param);
    }

    @Login
    @ApiOperation("获取缓冲流量")
    @PostMapping("/getInternetTraffic")
    public R getInternetTraffic(@RequestBody FsUserCourseVideoFinishUParam param) {
        Long userId = Long.parseLong(getUserId());
        param.setUserId(userId);
        return courseVideoService.getInternetTraffic(param);
    }


    @Login
    @PostMapping("/getErrMsg")
    public void getErrMsg(@RequestParam("msg") String msg) {
        Long userId = Long.parseLong(getUserId());
        logger.error("zyp \n【看课中途报错】：{}","userId:"+userId+msg);
    }


    @Autowired
    TencentCloudCosService tencentCloudCosService;

    @GetMapping("/test1")
    public void test1() {
        tencentCloudCosService.updateUrl();
    }


//    @GetMapping("/test2")
//    public void test2() {
//
//        courseWatchLogService.scheduleBatchUpdateToDatabase();
//    }

    @Login
    @ApiOperation("保存评论数据")
    @PostMapping("/saveMsg")
    public R saveMsg(@RequestBody FsCourseWatchCommentSaveParam param)
    {
        param.setUserId(Long.parseLong(getUserId()));
        return courseWatchCommentService.saveH5CourseWatchComment(param);
    }

    @Login
    @ApiOperation("撤销评论")
    @PutMapping("/revokeMsg")
    public R revokeMsg(@ApiParam(value = "评论id", required = true) @RequestParam Long commentId)
    {
        return courseWatchCommentService.revokeH5CourseWatchComment(commentId);
    }

    @ApiOperation("获取历史评论数据")
    @GetMapping("/getComments")
    public R getCourseWatchComments(FsCourseWatchCommentListParam param)
    {
        //获取配置信息中需要查询的数据条数
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        param.setListNum(config.getViewCommentNum() != null &&  config.getViewCommentNum() != 0 ? config.getViewCommentNum() : 200);

        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsCourseWatchCommentVO> list = courseWatchCommentService.selectH5CourseWatchComments(param);
        PageInfo<FsCourseWatchCommentVO> pageInfo = new PageInfo<>(list);
        return R.ok().put("data", pageInfo);
    }


    /**
     * 手动根据销售员工信息发放奖励
     * @param userId
     * @return
     */
    @GetMapping("/sendRewardByTest")
    public R sendRewardByTest(@RequestBody Long userId)
    {
        logger.info("zyp \n【发放奖励】6：{}",userId);
        return  storePaymentService.sendRewardByTest(userId);
    }

}
