package com.fs.course.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.course.config.CourseConfig;
import com.fs.course.domain.FsUserCourse;
import com.fs.course.domain.FsUserCourseVideo;
import com.fs.course.mapper.FsUserCourseVideoMapper;
import com.fs.course.param.BatchRedUpdate;
import com.fs.course.param.BatchVideoSvae;
import com.fs.course.param.CourseVideoUpdates;
import com.fs.course.service.IFsUserCourseService;
import com.fs.course.service.IFsUserCourseVideoService;
import com.fs.course.vo.FsUserCourseVideoChooseVO;
import com.fs.framework.web.service.TokenService;
import com.fs.his.vo.OptionsVO;
import com.fs.qw.vo.SortDayVo;
import com.fs.system.service.ISysConfigService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课堂视频Controller
 *
 * @author fs
 * @date 2024-05-17
 */
@RestController
@RequestMapping("/course/userCourseVideo")
public class FsUserCourseVideoController extends BaseController
{
    @Autowired
    private IFsUserCourseVideoService fsUserCourseVideoService;

    @Autowired
    private FsUserCourseVideoMapper fsUserCourseVideoMapper;
    @Autowired
    private IFsUserCourseService fsUserCourseService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 查询课堂视频列表
     */
    @PreAuthorize("@ss.hasPermi('course:userCourseVideo:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsUserCourseVideo fsUserCourseVideo)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if (ObjectUtil.isNotEmpty(config.getIsBound())&&config.getIsBound()){
            fsUserCourseVideo.setUserId(userId);
        }
        startPage();
        List<FsUserCourseVideo> list = fsUserCourseVideoService.selectFsUserCourseVideoList(fsUserCourseVideo);
        return getDataTable(list);
    }

    /**
     * 导出课堂视频列表
     */
    @PreAuthorize("@ss.hasPermi('course:userCourseVideo:export')")
    @Log(title = "课堂视频", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsUserCourseVideo fsUserCourseVideo)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if (ObjectUtil.isNotEmpty(config.getIsBound())&&config.getIsBound()){
            fsUserCourseVideo.setUserId(userId);
        }
        List<FsUserCourseVideo> list = fsUserCourseVideoService.selectFsUserCourseVideoList(fsUserCourseVideo);
        ExcelUtil<FsUserCourseVideo> util = new ExcelUtil<FsUserCourseVideo>(FsUserCourseVideo.class);
        return util.exportExcel(list, "课堂视频数据");
    }

    /**
     * 获取课堂视频详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:userCourseVideo:query')")
    @GetMapping(value = "/{videoId}")
    public AjaxResult getInfo(@PathVariable("videoId") Long videoId)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if (ObjectUtil.isNotEmpty(config.getIsBound())&&config.getIsBound()){
            return AjaxResult.success(fsUserCourseVideoService.selectFsUserCourseVideoByVideoIdVO(videoId,userId));
        }
        return AjaxResult.success(fsUserCourseVideoService.selectFsUserCourseVideoByVideoIdVO(videoId,null));
    }

    /**
     * 新增课堂视频
     */
    @PreAuthorize("@ss.hasPermi('course:userCourseVideo:add')")
    @Log(title = "课堂视频", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsUserCourseVideo fsUserCourseVideo)
    {
        Long count = fsUserCourseVideoMapper.selectFsUserCourseVideoByCourseSort(fsUserCourseVideo.getCourseId(),fsUserCourseVideo.getCourseSort());
        if (count>0){
            return AjaxResult.error("课程排序重复");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if (ObjectUtil.isNotEmpty(config.getIsBound())&&config.getIsBound()){
            fsUserCourseVideo.setUserId(userId);
        }
        // 设置项目ID
        FsUserCourse fsUserCourse = fsUserCourseService.selectFsUserCourseByCourseId(fsUserCourseVideo.getCourseId());
        fsUserCourseVideo.setProjectId(fsUserCourse.getProject());
        return toAjax(fsUserCourseVideoService.insertFsUserCourseVideo(fsUserCourseVideo));
    }

    /**
     * 修改课堂视频
     */
    @PreAuthorize("@ss.hasPermi('course:userCourseVideo:edit')")
    @Log(title = "课堂视频", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsUserCourseVideo fsUserCourseVideo)
    {
        return toAjax(fsUserCourseVideoService.updateFsUserCourseVideo(fsUserCourseVideo));
    }

    /**
     * 删除课堂视频
     */
    @PreAuthorize("@ss.hasPermi('course:userCourseVideo:remove')")
    @Log(title = "课堂视频", businessType = BusinessType.DELETE)
	@DeleteMapping("/{videoIds}")
    public AjaxResult remove(@PathVariable String[] videoIds)
    {
        return toAjax(fsUserCourseVideoService.deleteFsUserCourseVideoByVideoIds(videoIds));
    }


    @GetMapping("/getVideoListByCourseId")
    public TableDataInfo getVideoListByCourseId(FsUserCourseVideo fsUserCourseVideo)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if (ObjectUtil.isNotEmpty(config.getIsBound())&&config.getIsBound()){
            fsUserCourseVideo.setUserId(userId);
        }
        List<FsUserCourseVideo> list = fsUserCourseVideoService.selectFsUserCourseVideoListByCourseId(fsUserCourseVideo);
        return getDataTable(list);
    }

    @GetMapping("/getVideoListByCourseIdAll")
    public TableDataInfo getVideoListByCourseIdAll(Long courseId)
    {

        FsUserCourseVideo courseVideo=new FsUserCourseVideo();
        courseVideo.setCourseId(courseId);
        courseVideo.setIsDel(0);
        List<FsUserCourseVideo> list = fsUserCourseVideoService.selectFsUserCourseVideoList(courseVideo);
        return getDataTable(list);
    }

    @PostMapping("/sortCourseVideo")
    public AjaxResult sortCourseVideo(@RequestBody List<FsUserCourseVideo> list){
        fsUserCourseVideoService.sortCourseVideo(list);
        return toAjax(1);
    }


    @GetMapping("/getSort/{courseId}")
    public R remove(@PathVariable("courseId") Long courseId)
    {
        return R.ok().put("data",fsUserCourseVideoService.selectCourseVideoSort(courseId));
    }

    @PostMapping("/updates")
    public R updates(@RequestBody CourseVideoUpdates vo){
        fsUserCourseVideoService.updates(vo);
        return R.ok();
    }
    @PostMapping("/batchSaveVideo")
    public R batchSaveVideo(@RequestBody BatchVideoSvae vo){
        // 设置项目ID
        FsUserCourse fsUserCourse = fsUserCourseService.selectFsUserCourseByCourseId(vo.getCourseId());
        vo.setProjectId(fsUserCourse.getProject());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if (ObjectUtil.isNotEmpty(config.getIsBound())&&config.getIsBound()){
            vo.setUserId(userId);
        }
        fsUserCourseVideoService.batchSaveVideo(vo);
        return R.ok();
    }
    @PostMapping("/batchUpdateRed")
    @Log(title = "按课程批量保存设置红包金额", businessType = BusinessType.UPDATE)
    public R batchUpdateRed(@RequestBody List<BatchRedUpdate> list){
        fsUserCourseVideoService.batchUpdateRed(list);
        return R.ok();
    }


    @GetMapping("/getVideoListLikeName")
    public R getVideoListLikeName(@RequestParam(required = false) String name,
                                   @RequestParam(required = false) String periodId,
                                   @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                   @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String,Object> params = new HashMap<>();
        params.put("name", name);
        params.put("periodId", periodId);

        PageHelper.startPage(pageNum, pageSize);
        List<OptionsVO> periodList = fsUserCourseVideoService.selectVideoListByMap(params);
        return R.ok().put("data", new PageInfo<>(periodList));
    }

    @GetMapping("/getChooseCourseVideoList")
    public R getChooseCourseVideoList(@RequestParam(required = false) Long courseId,
                                      @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                      @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);

        Map<String,Object> params = new HashMap<>();
        params.put("courseId", courseId);
        if (ObjectUtil.isNotEmpty(config.getIsBound())&&config.getIsBound()){
            params.put("userId", userId);
        }

        PageHelper.startPage(pageNum, pageSize);
        List<FsUserCourseVideoChooseVO> list = fsUserCourseVideoService.getChooseCourseVideoListByMap(params);
        return R.ok().put("data", new PageInfo<>(list));
    }
}
