package com.fs.app.controller;


import cn.hutool.json.JSONUtil;
import com.fs.app.annotation.Login;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.R;
import com.fs.common.utils.StringUtils;
import com.fs.course.config.CourseConfig;
import com.fs.course.domain.FsCourseQuestionBank;
import com.fs.course.domain.FsCourseWatchLog;
import com.fs.course.param.FsCourseQuestionAnswerUParam;
import com.fs.course.param.FsCourseSendRewardUParam;
import com.fs.course.param.FsUserCourseVideoFinishUParam;
import com.fs.course.service.*;
import com.fs.course.vo.FsUserCourseVideoH5DVO;
import com.fs.course.vo.FsUserCourseVideoH5VO;
import com.fs.course.vo.FsUserCourseVideoQuestionVO;
import com.fs.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

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

    @Autowired
    private IFsUserCourseVideoService courseVideoService;

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

    @Autowired
    private IFsCourseWatchLogService courseWatchLogService;

    @Autowired
    private IFsCourseQuestionBankService questionBankService;


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

    @ApiOperation("h5课程详情")
    @GetMapping("/getH5CourseVideoDetails")
    public R getCourseVideoDetails(FsUserCourseVideoFinishUParam param)
    {
        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;
        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).put("maxBufferLength",config.getMaxBufferLength());
        }
        // 从Redis中获取观看时长
        String redisKey = "h5user:watch:duration:" + param.getQwUserId()+ ":" + param.getQwExternalId() + ":" + param.getVideoId();
        String durationStr = redisCache.getCacheObject(redisKey);
        FsCourseWatchLog log = courseWatchLogService.getWatchCourseVideoH5(param.getVideoId(),param.getQwUserId(),param.getQwExternalId());
        //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("maxBufferLength",config.getMaxBufferLength()).put("isFinish",isFinish);    }



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


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


    @ApiOperation("获取缓冲流量")
    @PostMapping("/getInternetTraffic")
    public R getInternetTraffic(@RequestBody FsUserCourseVideoFinishUParam param) {
        return courseVideoService.getInternetTraffic(param);
    }

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

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

    @PostMapping("/getErrMsg")
    public void getErrMsg(@RequestParam("msg") String msg) {
        logger.error("zyp \n【h5看课中途报错】：{}",msg);
    }

}
