package com.ynfy.buss.course.course.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ynfy.buss.course.course.entity.Course;
import com.ynfy.buss.course.course.service.ICourseService;
import com.ynfy.buss.course.coursecatalog.service.ICourseCatalogService;
import com.ynfy.buss.course.usercoursecatalog.entity.vo.UserCourseStudyVO;
import com.ynfy.buss.course.usercoursecatalog.service.IUserCourseCatalogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.service.ISysPositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: course
 * @Author: jeecg-boot
 * @Date: 2023-10-24
 * @Version: V1.0
 */
@Api(tags = "course")
@RestController
@RequestMapping("/course")
@Slf4j
public class CourseController extends JeecgController<Course, ICourseService> {
    @Autowired
    private ICourseService courseService;

    @Autowired
    private ICourseCatalogService courseCatalogService;

    @Autowired
    private ISysPositionService sysPositionService;

    @Autowired
    private IUserCourseCatalogService userCourseCatalogService;


    /**
     * 分页列表查询
     *
     * @param course
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "course-分页列表查询")
    @ApiOperation(value = "course-分页列表查询", notes = "course-分页列表查询")
    @RequiresPermissions("course:list")
    @GetMapping(value = "/list")
    public Result<IPage<Course>> queryPageList(Course course,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                               HttpServletRequest req) {
        QueryWrapper<Course> queryWrapper = QueryGenerator.initQueryWrapper(course, req.getParameterMap());
        Page<Course> page = new Page<Course>(pageNo, pageSize);
        IPage<Course> pageList = courseService.page(page, queryWrapper);
        courseService.setCategory(pageList);
        return Result.OK(pageList);
    }

    /**
     * 课程保存
     *
     * @param course
     * @return
     */
    @AutoLog(value = "课程保存")
    @ApiOperation(value = "课程保存", notes = "课程保存")
    @RequiresPermissions("course:save")
    @PostMapping(value = "/save")
    public Result<String> save(@RequestBody Course course) {
        courseService.saveCourse(course);
        return Result.OK("保存成功！");
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "course-通过id删除")
    @ApiOperation(value = "course-通过id删除", notes = "course-通过id删除")
    @RequiresPermissions("course:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        courseService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "course-批量删除")
    @ApiOperation(value = "course-批量删除", notes = "course-批量删除")
    @RequiresPermissions("course:delete")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.courseService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "course-通过id查询")
    @ApiOperation(value = "course-通过id查询", notes = "course-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Course> queryById(@RequestParam(name = "id", required = true) String id) {
        Course course = courseService.queryById(id);
        if (course == null) {
            return Result.error("未找到对应数据");
        }
        course.setCatalogList(courseCatalogService.listByCourseId(course.getId()));
        return Result.OK(course);
    }

    /**
     * 获取课程学习明细
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取课程学习明细", notes = "获取课程学习明细")
    @GetMapping(value = "/getCourseStudyDetail")
    public Result<Course> getCourseStudyDetail(@RequestParam String id) {
        Course course = courseService.queryById(id);
        if (course == null) {
            return Result.error("未找到对应数据");
        }
        course.setCatalogList(courseCatalogService.listByCourseId(course.getId()));
        if (StringUtils.isNotBlank(course.getTeacherPost())) {
            course.setTeacherPost(sysPositionService.listByCodes(Arrays.asList(course.getTeacherPost().split(","))));
        }

        //获取课程学习进度
        List<String> courseIdList = new ArrayList<>();
        courseIdList.add(course.getId());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        courseService.setCourseStudyProcess(userCourseCatalogService.getUserCourseStudy(courseIdList, sysUser.getId()), course);

        return Result.OK(course);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param course
     */
    //@RequiresPermissions("course:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Course course) {
        return super.exportXls(request, course, Course.class, "course");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("course:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Course.class);
    }


    /**
     * 课程在线学习
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "课程在线学习")
    @ApiOperation(value = "课程在线学习", notes = "课程在线学习")
    @RequestMapping(value = "/study", method = RequestMethod.GET)
    public Result<IPage<Course>> study(Course course, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Result<IPage<Course>> result = new Result<>();
        Page<Course> page = new Page<>(pageNo, pageSize);
        IPage<Course> pageList = courseService.selectCourseList(page, course);

        //设置课程分类
        courseService.setCategory(pageList);
        if (!CollectionUtils.isEmpty(pageList.getRecords())) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            List<String> courseIdList = pageList.getRecords().stream().map(Course::getId).collect(Collectors.toList());
            List<UserCourseStudyVO> studyList = userCourseCatalogService.getUserCourseStudy(courseIdList, sysUser.getId());
            if (!CollectionUtils.isEmpty(studyList)) {
                pageList.getRecords().forEach((o) -> courseService.setCourseStudyProcess(studyList, o));
            }
        }
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

}
