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.annotation.RepeatSubmit;
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.params.FsUserCourseConfigParam;
import com.fs.course.service.IFsUserCourseService;
import com.fs.course.service.IFsUserCourseVideoService;
import com.fs.course.vo.FsUserCourseListPVO;
import com.fs.framework.web.service.TokenService;
import com.fs.his.utils.RedisCacheUtil;
import com.fs.his.vo.OptionsVO;
import com.fs.qw.param.FsUserCourseRedPageParam;
import com.fs.sop.service.IQwSopTempService;
import com.fs.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 课程Controller
 *
 * @author fs
 * @date 2024-05-15
 */
@RestController
@RequestMapping("/course/userCourse")
public class FsUserCourseController extends BaseController {
    @Autowired
    private IFsUserCourseService fsUserCourseService;

    @Autowired
    private IFsUserCourseVideoService courseVideoService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IQwSopTempService sopTempService;

    /**
     * 查询课程列表
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsUserCourse fsUserCourse) {
        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()) {
            fsUserCourse.setUserId(userId);
        }
        List<FsUserCourseListPVO> list = fsUserCourseService.selectFsUserCourseListPVO(fsUserCourse);
        return getDataTable(list);
    }

    /**
     * 查询公域课程列表
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:publicList')")
    @GetMapping("/publicList")
    public TableDataInfo publicList(FsUserCourse fsUserCourse) {
        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()) {
            fsUserCourse.setUserId(userId);
        }
        List<FsUserCourseListPVO> list = fsUserCourseService.selectFsUserCourseListPVO(fsUserCourse);
        return getDataTable(list);
    }

    /**
     * 导出课程列表
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:export')")
    @Log(title = "课程", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsUserCourse fsUserCourse) {
        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()) {
            fsUserCourse.setUserId(userId);
        }
        List<FsUserCourse> list = fsUserCourseService.selectFsUserCourseList(fsUserCourse);
        ExcelUtil<FsUserCourse> util = new ExcelUtil<FsUserCourse>(FsUserCourse.class);
        return util.exportExcel(list, "课程数据");
    }

    /**
     * 导出公域课程列表
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:publicExport')")
    @Log(title = "课程", businessType = BusinessType.EXPORT)
    @GetMapping("/publicExport")
    public AjaxResult publicExport(FsUserCourse fsUserCourse) {
        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()) {
            fsUserCourse.setUserId(userId);
        }
        List<FsUserCourse> list = fsUserCourseService.selectFsUserCourseList(fsUserCourse);
        ExcelUtil<FsUserCourse> util = new ExcelUtil<FsUserCourse>(FsUserCourse.class);
        return util.exportExcel(list, "课程数据");
    }

    /**
     * 获取课程详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:query')")
    @GetMapping(value = "/{courseId}")
    public AjaxResult getInfo(@PathVariable("courseId") Long courseId) {
        return AjaxResult.success(fsUserCourseService.selectFsUserCourseByCourseId(courseId));
    }

    /**
     * 获取公域课程详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:publicQuery')")
    @GetMapping(value = "/public/{courseId}")
    public AjaxResult publicGetInfo(@PathVariable("courseId") Long courseId) {
        return AjaxResult.success(fsUserCourseService.selectFsUserCourseByCourseId(courseId));
    }

    /**
     * 新增课程
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:add')")
    @Log(title = "课程", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsUserCourse fsUserCourse) {
        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()) {
            fsUserCourse.setUserId(userId);
        }
        fsUserCourseService.insertFsUserCourse(fsUserCourse);
        redisCacheUtil.delRedisKey("getCourseList");

        return toAjax(1);
    }

    /**
     * 新增课程
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:publicAdd')")
    @Log(title = "课程", businessType = BusinessType.INSERT)
    @PostMapping("/public")
    public AjaxResult publicAdd(@RequestBody FsUserCourse fsUserCourse) {
        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()) {
            fsUserCourse.setUserId(userId);
        }
        fsUserCourseService.insertFsUserCourse(fsUserCourse);
        redisCacheUtil.delRedisKey("getCourseList");

        return toAjax(1);
    }

    /**
     * 修改课程
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:edit')")
    @Log(title = "课程", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsUserCourse fsUserCourse) {
        fsUserCourseService.updateFsUserCourse(fsUserCourse);
        redisCacheUtil.delRedisKey("getCourseList");
        return toAjax(1);
    }

    /**
     * 统一修改课程红包
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:editRedPage')")
    @Log(title = "修改课程红包", businessType = BusinessType.UPDATE)
    @PostMapping("/editRedPage")
    public AjaxResult editRedPage(@RequestBody FsUserCourseRedPageParam redPageParam) {
        courseVideoService.updateFsUserCourseRedPage(redPageParam);
        return toAjax(1);
    }

    /**
     * 修改课程
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:publicEdit')")
    @Log(title = "课程", businessType = BusinessType.UPDATE)
    @PutMapping("/public")
    public AjaxResult publicEdit(@RequestBody FsUserCourse fsUserCourse) {
        fsUserCourseService.updateFsUserCourse(fsUserCourse);
        redisCacheUtil.delRedisKey("getCourseList");
        return toAjax(1);
    }

    /**
     * 复制课程
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:copy')")
    @Log(title = "课程", businessType = BusinessType.DELETE)
    @GetMapping("/copy/{courseId}")
    public AjaxResult copy(@PathVariable Long courseId) {
        int i = fsUserCourseService.copyFsUserCourse(courseId);
        return toAjax(i);
    }

    /**
     * 删除课程
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:remove')")
    @Log(title = "课程", businessType = BusinessType.DELETE)
    @DeleteMapping("/{courseIds}")
    public AjaxResult remove(@PathVariable Long[] courseIds) {
        fsUserCourseService.deleteFsUserCourseByCourseIds(courseIds);
        redisCacheUtil.delRedisKey("getCourseList");
        return toAjax(1);
    }

    /**
     * 删除课程
     */
    @PreAuthorize("@ss.hasPermi('course:userCourse:publicRemove')")
    @Log(title = "课程", businessType = BusinessType.DELETE)
    @DeleteMapping("/public/{courseIds}")
    public AjaxResult publicRemove(@PathVariable Long[] courseIds) {
        fsUserCourseService.deleteFsUserCourseByCourseIds(courseIds);
        redisCacheUtil.delRedisKey("getCourseList");
        return toAjax(1);
    }


    @GetMapping("/getAllList")
    public R getAllList() {
        List<OptionsVO> list = fsUserCourseService.selectFsUserCourseAllList();
        return R.ok().put("data", list);
    }

    @PreAuthorize("@ss.hasPermi('course:userCourse:updateIsShow')")
    @Log(title = "课程上架", businessType = BusinessType.UPDATE)
    @PostMapping("/updateIsShow")
    public AjaxResult updateIsShow(@RequestBody FsUserCourse fsUserCourse) {
        fsUserCourseService.updateFsUserCourse(fsUserCourse);
        redisCacheUtil.delRedisKey("getCourseList");
        return toAjax(1);
    }

    @PreAuthorize("@ss.hasPermi('course:userCourse:publicUpdateIsShow')")
    @Log(title = "课程上架", businessType = BusinessType.UPDATE)
    @PostMapping("/publicUpdateIsShow")
    public AjaxResult publicUpdateIsShow(@RequestBody FsUserCourse fsUserCourse) {
        fsUserCourseService.updateFsUserCourse(fsUserCourse);
        redisCacheUtil.delRedisKey("getCourseList");
        return toAjax(1);
    }

    @PreAuthorize("@ss.hasPermi('course:userCourse:putOn')")
    @Log(title = "课程批量上架", businessType = BusinessType.UPDATE)
    @PostMapping("/putOn/{courseIds}")
    public AjaxResult putOn(@PathVariable Long[] courseIds) {
        fsUserCourseService.updateFsUserCourseIsShow(courseIds, 1);
        redisCacheUtil.delRedisKey("getCourseList");
        return toAjax(1);
    }

    @PreAuthorize("@ss.hasPermi('course:userCourse:publicPutOn')")
    @Log(title = "课程批量上架", businessType = BusinessType.UPDATE)
    @PostMapping("/publicPutOn/{courseIds}")
    public AjaxResult publicPutOn(@PathVariable Long[] courseIds) {
        fsUserCourseService.updateFsUserCourseIsShow(courseIds, 1);
        redisCacheUtil.delRedisKey("getCourseList");
        return toAjax(1);
    }

    @PreAuthorize("@ss.hasPermi('course:userCourse:putOn')")
    @Log(title = "课程批量下架", businessType = BusinessType.UPDATE)
    @PostMapping("/pullOff/{courseIds}")
    public AjaxResult pullOff(@PathVariable Long[] courseIds) {
        fsUserCourseService.updateFsUserCourseIsShow(courseIds, 0);
        redisCacheUtil.delRedisKey("getCourseList");
        return toAjax(1);
    }

    @PreAuthorize("@ss.hasPermi('course:userCourse:publicPutOff')")
    @Log(title = "课程批量下架", businessType = BusinessType.UPDATE)
    @PostMapping("/publicPutOff/{courseIds}")
    public AjaxResult publicPutOff(@PathVariable Long[] courseIds) {
        fsUserCourseService.updateFsUserCourseIsShow(courseIds, 0);
        redisCacheUtil.delRedisKey("getCourseList");
        return toAjax(1);
    }

    /**
     * 修改配置
     **/
    @PreAuthorize("@ss.hasPermi('course:userCourse:editConfig')")
    @Log(title = "课程配置", businessType = BusinessType.UPDATE)
    @PostMapping("/editConfig")
    public R editConfig(@RequestBody FsUserCourseConfigParam params) {
        fsUserCourseService.editConfig(params.getId(), params.getConfigJson());
        redisCacheUtil.delRedisKey("getCourseList");
        redisCacheUtil.delRedisKey("h5user:course:video:list:all");
        redisCacheUtil.delRedisKey("h5user:course:list:all");
        redisCacheUtil.delRedisKey("cache:video");
        return R.ok();
    }

    /**
     * 同步课程模板
     */
    @PreAuthorize("@ss.hasPermi('course:userCourseVideo:sync')")
    @Log(title = "同步课程模板", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PostMapping("/syncTemplate/{courseId}")
    public AjaxResult syncTemplate(@PathVariable Long courseId) {
        sopTempService.syncTemplate(courseId);
        return toAjax(1);
    }
}
