package com.cirle.scientific.controller.course;


import com.cirle.scientific.constants.LoginConsts;
import com.cirle.scientific.controller.index.RootIndexController;
import com.cirle.scientific.dto.QkjRecommendDTO;
import com.cirle.scientific.dto.QkjTqcourseCourseDto;
import com.cirle.scientific.po.QkjCatalogs;
import com.cirle.scientific.po.QkjTqcourse;
import com.cirle.scientific.pojo.BizCodeEnum;
import com.cirle.scientific.pojo.Result;
import com.cirle.scientific.service.CommonService;
import com.cirle.scientific.service.CourseService;
import com.cirle.scientific.service.RecommendService;
import com.cirle.scientific.utils.DeviceUtil;
import com.cirle.scientific.utils.IpUtil;
import com.cirle.scientific.utils.LoginUtil;
import com.cirle.scientific.utils.UserLoginUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

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

@Controller
@RequestMapping("/course")
@Api("精品课相关接口")
public class CourseController {


    @Autowired
    CourseService courseService;
    @Autowired
    CommonService commonService;
    @Autowired
    RecommendService recommendService;

    @Autowired
    LoginUtil loginUtil;


    @GetMapping("/index")
    @ApiOperation(value = "去往精品课首页")
    public String courseIndex(@ApiParam(name = "from", value = "请求类型 web：网站 H5：手机端") @RequestParam(name = "from", required = true) String from) {
        if (StringUtils.isNotBlank(from) && from.equals("H5")) {
            return "html5/course/course-index";
        } else {
            return "web/course/course-index";
        }
    }

    @GetMapping("/courseDetails")
    @ApiOperation(value = "去往精品课详情页")
    public String courseDetails(
            HttpServletRequest request,
            @ApiParam(name = "from", value = "请求类型 web：网站 H5：手机端") @RequestParam(name = "from", required = true) String from,
            @ApiParam(name = "id", value = "专区id") @RequestParam(name = "id", required = true) Integer id, Model model
    ) {
        String refererUrl = request.getHeader("Referer");
        if(refererUrl!=null && refererUrl.contains("login")){
            model.addAttribute("fromlogin","1");
        }else{
            model.addAttribute("fromlogin","0");
        }
        request.setAttribute("id", id);
        if (StringUtils.isNotBlank(from) && from.equals("H5")) {
            QkjTqcourse qkjTqcourse = courseService.findById(id);
            if (qkjTqcourse.getZq() == 2) {
                //专区
                return "html5/course/course-prefecture-list";
            } else {
                //普通课程
                return "html5/course/course-details";
            }

        } else {
            return "web/course/course-details";
        }
    }


    @GetMapping("/coursePrefectureList")
    @ApiOperation(value = "去往精品课专区列表页")
    public String coursePrefectureList(
            HttpServletRequest request,
            @ApiParam(name = "from", value = "请求类型 web：网站 H5：手机端") @RequestParam(name = "from", required = true) String from,
            @ApiParam(name = "id", value = "专区id") @RequestParam(name = "id", required = true) Integer id
    ) {
        request.setAttribute("id", id);
        if (StringUtils.isNotBlank(from) && from.equals("H5")) {
            return "html5/course/course-prefecture-list";
        } else {
            return "web/course/course-prefecture-list";
        }
    }

    @PostMapping("/getIndexData")
    @ResponseBody
    @ApiOperation(value = "课程数据接口")
    public Result getIndexData(HttpServletRequest request,
            Integer start, Integer size, Integer cataId, Integer fId, String sortBy,String from,
            @ApiParam(name = "memCard", value = "用户唯一标识") @RequestAttribute(name = "memCard", required = false) String memCard
    ) {
        if (request.getSession().getAttribute("UserCard") != null) {
            memCard = (String) request.getSession().getAttribute("UserCard");
        }
        boolean isPC=DeviceUtil.isMobileDevice(request);
        return courseService.getIndexData(cataId, fId, start, size, memCard, sortBy, from,isPC);
    }


    @PostMapping("/getCataList")
    @ResponseBody
    @ApiOperation(value = "课程首页获取分类")
    public Result<List<QkjCatalogs>> getCataList(Integer fId, Integer type) {
        return Result.success(commonService.getCatalogsByFuId(fId, type));
    }

    @PostMapping("/getCataListForThreeLevel")
    @ResponseBody
    @ApiOperation(value = "课程首页获取分类")
    public Result<List<QkjCatalogs>> getCataListForTreeLevel(Integer fId, Integer type) {
        return Result.success(commonService.getCatalogsByFuIdForThreeLevel(fId, type));
    }

    @PostMapping("/getCataListForCourseware")
    @ResponseBody
    @ApiOperation(value = "课程首页获取分类")
    public Result<List<QkjCatalogs>> getCataListForCourseware(Integer fId, Integer type) {
        return Result.success(commonService.getCatalogsByFuIdForCourseware(fId, type));
    }

    @PostMapping("/addVideoPlayRecorde")
    @ResponseBody
    @ApiOperation(value = "保存学习记录")
    public Result addVideoPlayRecorde(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(name = "memCard", value = "memCard") @RequestAttribute(value = "memCard", required = false) String memCard,
            @ApiParam(name = "objType", value = "课程类型 1-精品课子课时  2-专栏子课时  3-直播  4.知识点  5.精品课背书 6.专栏背书") @RequestParam(name = "objType") int objType,
            @ApiParam(name = "objId", value = "课程id") @RequestParam(name = "objId") int objId,
            @ApiParam(name = "playTime", value = "视频播放截止时间（毫秒）") @RequestParam(name = "playTime") int playTime,
            @ApiParam(name = "totalLearnTime", value = "学习时长（毫秒）") @RequestParam(name = "totalLearnTime") int totalLearnTime
    ) {

        boolean replace = loginUtil.isReplace(request, response, memCard);
        if(replace){
            return Result.failed(BizCodeEnum.NO_LOGIN_REPLACE);
        }
        String ipAddr = IpUtil.getIpAddr(request);
        return Result.success(courseService.addVideoPlayRecorde(memCard, objType, objId, playTime, totalLearnTime, ipAddr));
    }

    @PostMapping("/saveplaylog")
    @ResponseBody
    @ApiOperation(value = "保存视频播放记录")
    public Result saveplaylog(HttpServletRequest request,
                                      @ApiParam(name = "memCard", value = "memCard") @RequestAttribute(value = "memCard", required = false) String memCard,
                                      @ApiParam(name = "liveId", value = "直播id") @RequestParam(name = "liveId") int liveId,
                                      @ApiParam(name = "learnTime", value = "学习时长（秒）") @RequestParam(name = "learnTime") int learnTime
    ) {
        if (request.getSession().getAttribute("UserCard") != null) {
            memCard = (String) request.getSession().getAttribute("UserCard");
        }
        return Result.success(courseService.saveplaylog(memCard, liveId, learnTime));
    }

    @PostMapping("/getAdInfo")
    @ResponseBody
    @ApiOperation(value = "课程首页获取广告位")
    public Result<List<QkjRecommendDTO>> getAdInfo(HttpServletRequest request) {
        // 默认展示pc端内容
        Integer status = 3;
        if(DeviceUtil.isMobileDevice(request)) {
            status = 2;
        }
        List<QkjRecommendDTO> recmdTop = recommendService.findByPosIdLimit(3L, status, 1, 10);
        return Result.success(recmdTop);
    }

    @PostMapping("/getAdInfoNew")
    @ResponseBody
    @ApiOperation(value = "课程首页获取广告位")
    public Result<List<QkjRecommendDTO>> getAdInfoNew(
            @RequestParam(name = "id", required = true) Long id
    ) {
        QkjTqcourse byId = courseService.findById(id.intValue());
        List<QkjRecommendDTO> recmdTop = recommendService.findByPostTypeAndObjId(1, byId.getId().intValue(), 1, 100);
        return Result.success(recmdTop);
    }

    @PostMapping("/findTqCourseCourseInfo")
    @ResponseBody
    @ApiOperation(value = "获取子课时详情")
    public Result<QkjTqcourseCourseDto> findTqCourseCourseInfo(@RequestParam(name = "id", required = true) Long id) {
        return courseService.findTqCourseCourseInfo(id);
    }


    @PostMapping("/saveCommon")
    @ResponseBody
    @ApiOperation(value = "保存用户留言")
    public Result saveCommon(HttpServletRequest request,
            @ApiParam(name = "memCard", value = "memCard") @RequestAttribute(value = "memCard", required = false) String memCard,
            @ApiParam(name = "content", value = "content") @RequestParam(value = "content", required = false) String content,
            @RequestParam(name = "id", required = true) Long id
    ) {
        if (request.getSession().getAttribute("UserCard") != null) {
            memCard = (String) request.getSession().getAttribute("UserCard");
        }
        return courseService.saveCommon(id, memCard, content);
    }
    @GetMapping("/checkCode")
    @ResponseBody
    @ApiOperation(value = "校验提取码")
    public Result checkCode(HttpServletRequest request,
                             @ApiParam(name = "memCard", value = "memCard") @RequestAttribute(value = "memCard", required = false) String memCard,
                             @ApiParam(name = "code", value = "code") @RequestParam(value = "code", required = true) String code,
                             @RequestParam(name = "id", required = true) Long id
    ) {
        if (request.getSession().getAttribute("UserCard") != null) {
            memCard = (String) request.getSession().getAttribute("UserCard");
        }
        String ip = IpUtil.getIpAddr(request);
        return courseService.checkCode(ip, memCard, code,id);
    }
}
