package com.ynfy.app.api.v1.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.app.api.v1.annoation.IgnoreAuth;
import com.ynfy.app.api.v1.entity.dto.CourseCategoryDTO;
import com.ynfy.app.api.v1.entity.dto.CourseDTO;
import com.ynfy.buss.course.category.entity.CourseCategory;
import com.ynfy.buss.course.category.service.ICourseCategoryService;
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.UserCourseCatalog;
import com.ynfy.buss.course.usercoursecatalog.entity.vo.CatalogTimeVO;
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.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.service.ISysPositionService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Api(tags = "course")
@RestController
@RequestMapping("/api/v1/course")
@Slf4j
public class ApiCourseController extends ApiBaseController {
    @Autowired
    private ICourseService courseService;

    @Autowired
    private ICourseCatalogService courseCatalogService;

    @Autowired
    private ISysPositionService sysPositionService;

    @Autowired
    private IUserCourseCatalogService userCourseCatalogService;

    @Autowired
    private ISysUserService sysUserService;


    @Autowired
    private ICourseCategoryService courseCategoryService;

    /**
     * 课程分类-分页列表查询
     *
     * @return
     */
    @ApiOperation(value = "课程分类-分页列表查询", notes = "课程分类-分页列表查询")
    @IgnoreAuth
    @PostMapping(value = "/courseCategory/rootList")
    public Result<IPage<CourseCategory>> queryPageList(@RequestBody CourseCategoryDTO dto) {
        String hasQuery = dto.getHasQuery();
        if (hasQuery != null && "true".equals(hasQuery)) {
            QueryWrapper<CourseCategory> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(dto.getName())) {
                queryWrapper.eq("name", dto.getName());
            }
            List<CourseCategory> list = courseCategoryService.queryTreeListNoPage(queryWrapper);
            IPage<CourseCategory> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } else {
            CourseCategory courseCategory = new CourseCategory();
            if (StringUtils.isNotBlank(dto.getPid())) {
                courseCategory.setPid(dto.getPid());
            }
            String parentId = courseCategory.getPid();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            courseCategory.setPid(null);
            QueryWrapper<CourseCategory> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(dto.getName())) {
                queryWrapper.eq("name", dto.getName());
            }
            // 使用 eq 防止模糊查询
            queryWrapper.eq("pid", parentId);
            Page<CourseCategory> page = new Page<>(dto.getPageNo(), dto.getPageSize());
            IPage<CourseCategory> pageList = courseCategoryService.page(page, queryWrapper);
            List<CourseCategory> records = pageList.getRecords();
            if (!CollectionUtils.isEmpty(records)) {
                List<String> parentIdList = records.stream().map(CourseCategory::getId).collect(Collectors.toList());
                QueryWrapper<CourseCategory> queryParentWrapper = new QueryWrapper<>();
                queryParentWrapper.in("pid", parentIdList);
                List<CourseCategory> parentCategoryList = courseCategoryService.list(queryParentWrapper);
                records.forEach(item -> item.setChildren(parentCategoryList.stream().filter(p ->
                        p.getPid().equals(item.getId())).collect(Collectors.toList())));
            }
            return Result.OK(pageList);
        }
    }

    /**
     * 分页列表查询
     *
     * @return
     */
    @ApiOperation(value = "course-分页列表查询", notes = "course-分页列表查询")
    @IgnoreAuth
    @PostMapping(value = "/list")
    public Result<IPage<Course>> queryPageList(@RequestBody CourseDTO dto) {
        Page<Course> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        Course course = new Course();
        course.setName(dto.getName());
        if (StringUtils.isNotBlank(dto.getCategoryId())) {
            course.setCategoryId(dto.getCategoryId());
        }
        LoginUser user = sysUserService.getLoginUser(TokenUtil.getToken(request));
        IPage<Course> pageList = courseService.selectCourseList(page, course, user);

        //设置课程分类
        courseService.setCategory(pageList);
        if (!CollectionUtils.isEmpty(pageList.getRecords())) {
            List<String> courseIdList = pageList.getRecords().stream().map(Course::getId).collect(Collectors.toList());
            List<UserCourseStudyVO> studyList = userCourseCatalogService.getUserCourseStudy(courseIdList, TokenUtil.getUserId(TokenUtil.getToken(request)));
            if (!CollectionUtils.isEmpty(studyList)) {
                pageList.getRecords().forEach((o) -> courseService.setCourseStudyProcess(studyList, o));
            }
        }
        return Result.OK(pageList);
    }

    /**
     * 通过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());
        courseService.setCourseStudyProcess(userCourseCatalogService.getUserCourseStudy(courseIdList, TokenUtil.getUserId(TokenUtil.getToken(request))), course);

        return Result.OK(course);
    }

    /**
     * 计算任务学习时长
     *
     * @return
     */
    @AutoLog(value = "计算任务学习时长")
    @ApiOperation(value = "计算任务学习时长", notes = "计算任务学习时长")
    @PostMapping(value = "/calcStudyTime")
    public Result<String> calcStudyTime(@RequestBody CatalogTimeVO catalogTimeVO) {
        userCourseCatalogService.calcStudyTime(catalogTimeVO, TokenUtil.getUserId(TokenUtil.getToken(request)));
        return Result.OK();
    }


    /**
     * 获取课程任务学习进度
     *
     * @return
     */
    @AutoLog(value = "获取课程任务学习进度")
    @ApiOperation(value = "获取课程任务学习进度", notes = "获取课程任务学习进度")
    @GetMapping(value = "/getCourseStudyProcess")
    public Result<?> getCourseStudyProcess(@RequestParam String courseId) {
        return Result.OK(userCourseCatalogService.getCourseStudyProcess(courseId, TokenUtil.getUserId(TokenUtil.getToken(request))));
    }

    /**
     * 获取任务学习记录
     *
     * @return
     */
    @AutoLog(value = "获取任务学习记录")
    @ApiOperation(value = "获取任务学习记录", notes = "获取任务学习记录")
    @GetMapping(value = "/findUserCatalog")
    public Result<?> findUserCatalog(@RequestParam String courseCatalogId) {
        return Result.OK(userCourseCatalogService.findUserCatalog(TokenUtil.getUserId(TokenUtil.getToken(request)), courseCatalogId));
    }

    /**
     * 检查上一个任务是否完成
     *
     * @param id
     * @return
     */
    @GetMapping("/checkPreTaskComplete")
    public Result<?> checkPreTaskComplete(@RequestParam String id) {
        LoginUser user = sysUserService.getLoginUser(TokenUtil.getToken(request));
        return Result.OK(courseCatalogService.checkPreTaskComplete(id, user));
    }

    @ApiOperation(value = "用户课程任务学习情况-分页列表查询", notes = "用户课程任务学习情况-分页列表查询")
    @PostMapping(value = "/userCourseCatalog/list")
    public Result<IPage<UserCourseCatalog>> userCourseList(@RequestBody CourseDTO dto) {
        Page<UserCourseCatalog> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        UserCourseCatalog userCourseCatalog = new UserCourseCatalog();
        userCourseCatalog.setCourseName(dto.getName());
        userCourseCatalog.setUserId(TokenUtil.getUserId(TokenUtil.getToken(request)));
        IPage<UserCourseCatalog> pageList = userCourseCatalogService.selectPageList(page, userCourseCatalog);
        return Result.OK(pageList);
    }

}
