package com.fs.app.controller.course;



import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.fs.app.annotation.UserOperationLog;
import com.fs.app.controller.AppBaseController;
import com.fs.common.annotation.Log;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.ResponseResult;
import com.fs.app.annotation.Login;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.CloudHostUtils;
import com.fs.common.core.redis.RedisCache;
import com.fs.course.config.CourseConfig;
import com.fs.course.domain.FsCourseWatchLog;
import com.fs.course.domain.FsUserCourseVideo;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.course.mapper.FsUserCourseVideoMapper;
import com.fs.course.param.*;
import com.fs.course.param.newfs.FsUserCourseAddCompanyUserParam;
import com.fs.course.param.newfs.FsUserCourseVideoLinkParam;
import com.fs.course.param.newfs.FsUserCourseVideoRemainTimeParam;
import com.fs.course.param.newfs.FsUserCourseVideoUParam;
import com.fs.course.service.*;
import com.fs.course.vo.FsUserCourseVideoH5VO;
import com.fs.course.vo.newfs.FsUserCourseVideoLinkDetailsVO;
import com.fs.feishu.model.FeishuLinkParam;
import com.fs.feishu.service.FeiShuService;
import com.fs.his.domain.FsUser;
import com.fs.his.enums.FsUserOperationEnum;
import com.fs.im.dto.OpenImResponseDTO;
import com.fs.im.service.OpenIMService;
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.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

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

    @Autowired
    private IFsUserCourseVideoService courseVideoService;


    @Autowired
    private IFsCourseLinkService courseLinkService;


    @Autowired
    private IFsCourseQuestionBankService questionBankService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private FsCourseWatchLogMapper fsCourseWatchLogMapper;
    @Autowired
    private FsUserCourseVideoMapper fsUserCourseVideoMapper;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private FeiShuService feiShuService;

    @Login
    @ApiOperation("判断是否添加客服（是否关联销售）")
    @PostMapping("/isAddKf")
    public ResponseResult<FsUser> isAddCompanyUser(@Valid @RequestBody FsUserCourseAddCompanyUserParam param) {
        if (ObjectUtil.isEmpty(param.getUserId())){
            Long userId = Long.parseLong(getUserId());
            param.setUserId(userId);
        }
        return courseVideoService.isAddCompanyUser(param);
    }

    /**
     * 绑定关系
     *
     * @param param
     * @return
     */
    @PostMapping("/isSaveKf")
    public R isSaveKf(@RequestBody FsUserCourseVideoAddKfUParam param){
        Long userId = Long.parseLong(getUserId());
        param.setUserId(userId);
        return courseVideoService.isSaveKf(param);
    }


    @ApiOperation("h5课程简介")
    @GetMapping("/getH5CourseByVideoId")
    public R getCourseByVideoId(@RequestParam("videoId") Long videoId)
    {
        FsUserCourseVideoH5VO course = courseService.selectFsUserCourseVideoH5VOByVideoId(videoId);
        if (CloudHostUtils.hasCloudHostName("金牛明医","康年堂")){
            course.setCourseName("");
        }
        return R.ok().put("data",course);
    }

    @ApiOperation("h5课程完课倒计时")
    @PostMapping("/getRemainTime")
    public R getRemainTime(@RequestBody FsUserCourseVideoRemainTimeParam param)
    {
        String json = sysConfigService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        Integer remainTime = 0;
        if (config.getCompletionCountdown() != null && config.getCompletionCountdown()) {
            FsCourseWatchLog fsCourseWatchLog = fsCourseWatchLogMapper.selectFsCourseWatchLogWithUCCV(param);
            if (fsCourseWatchLog == null) {
                return R.error("");
            }

            // 如果已经完课，剩余时间为0
            if (fsCourseWatchLog != null && fsCourseWatchLog.getLogType() != null && fsCourseWatchLog.getLogType() == 2) {
                remainTime = 0;
            } else {
                // 获取已观看时长（优先从Redis获取，因为可能还未同步到数据库）
                Long watchedDuration = 0L;
                String redisKey = "h5wxuser:watch:duration:" + param.getFsUserId() + ":" + param.getVideoId() + ":" + param.getCompanyUserId();
                String durationStr = redisCache.getCacheObject(redisKey);
                if (durationStr != null) {
                    watchedDuration = Long.valueOf(durationStr);
                } else if (fsCourseWatchLog != null && fsCourseWatchLog.getDuration() != null) {
                    watchedDuration = fsCourseWatchLog.getDuration();
                }

                // 获取视频总时长（参照scheduleUpdateDurationToDatabase中的getFsUserVideoDuration方法）
                Long videoDuration = getFsUserVideoDuration(param.getVideoId().longValue());

                if (videoDuration != null && videoDuration > 0 && config.getAnswerRate() != null) {
                    // 参照scheduleUpdateDurationToDatabase中的完课逻辑：percentage >= config.getAnswerRate()
                    // 计算需要观看的时长（秒）
                    long requiredDuration = videoDuration * config.getAnswerRate() / 100;

                    // 计算剩余时间（秒）
                    long remainTimeSeconds = requiredDuration - watchedDuration;
                    remainTime = (int) Math.max(0, remainTimeSeconds);
                }
            }
        }

        return R.ok().put("remainTime",remainTime);
    }

    private Long getFsUserVideoDuration(Long videoId) {
        //将视频时长也存到redis
        String videoRedisKey = "h5wxuser:video:duration:" + videoId;
        Long videoDuration = 0L;
        try {
            videoDuration = redisCache.getCacheObject(videoRedisKey);
        } catch (Exception e) {
            String string = redisCache.getCacheObject(videoRedisKey);
            if (string != null) {
                videoDuration = Long.parseLong(string);
            }
            logger.error("key中id为S:{}", videoDuration);
        }

        if (videoDuration == null || videoDuration == 0) {
            FsUserCourseVideo video = fsUserCourseVideoMapper.selectFsUserCourseVideoByVideoId(videoId);
            if (video != null && video.getDuration() != null) {
                videoDuration = video.getDuration();
                redisCache.setCacheObject(videoRedisKey, video.getDuration());
            }
        }
        return videoDuration;
    }

    @Login
    @ApiOperation("H5课程详情")
    @GetMapping("/videoDetails")
    @UserOperationLog(operationType = FsUserOperationEnum.STUDY)
    public ResponseResult<FsUserCourseVideoLinkDetailsVO> getCourseVideoDetails(FsUserCourseVideoLinkParam param) {
        param.setFsUserId(Long.parseLong(getUserId()));
        return courseVideoService.getLinkCourseVideoDetails(param);
    }

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

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


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


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

    @ApiOperation("发放奖励")
    @PostMapping("/sendReward")
    @UserOperationLog(operationType = FsUserOperationEnum.SENDREWARD)
    @RepeatSubmit
    public R sendReward(@RequestBody FsCourseSendRewardUParam param)
    {
        if (ObjectUtil.isEmpty(param.getUserId())){
            Long userId = Long.parseLong(getUserId());
            param.setUserId(userId);
        }
        logger.info("zyp \n【发放奖励】2：{}",param);
        return courseVideoService.sendRewardByFsUser(param);
    }


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

    @ApiOperation("获取我的sop课程-短信链接")
    @PostMapping("/getSopCourseH5StudyListByMsg")
    public R getSopCourseH5StudyListByMsg(@RequestBody FsCourseH5ListParam param ){
        return  courseLinkService.getSopCourseH5StudyListByMsg(param);
    }

    @ApiOperation("获取我的sop课程详情")
    @PostMapping("/getSopCourseH5StudyInfo")
    public R getSopCourseH5StudyInfo(@RequestBody FsCourseH5ListParam  param ){
        // 查询看课记录
        return courseLinkService.getLinkInfo(param.getLogId());
    }

    @ApiOperation("获取飞书课程链接")
    @PostMapping("/getFeiShuCourseNewLink")
    public R getFeiShuCourseNewLink(@RequestBody FeishuLinkParam param) {
        if (StringUtils.isBlank(param.getLink())){
            return R.error("飞书课程短链不能为空");
        }
        String feishuCourseNewLink = feiShuService.getFeishuCourseNewLink(param);
        return R.ok().put("data", feishuCourseNewLink);
    }


}
