package com.ruoyi.hezhi.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.hezhi.domain.TbCourse;
import com.ruoyi.hezhi.domain.TbExam;
import com.ruoyi.hezhi.domain.TbTypeCourse;
import com.ruoyi.hezhi.domain.vo.CaseTypeVO;
import com.ruoyi.hezhi.mapper.TbExamMapper;
import com.ruoyi.hezhi.service.ITbCaseService;
import com.ruoyi.hezhi.service.ITbCaseTypeService;
import com.ruoyi.hezhi.service.ITbCourseService;
import com.ruoyi.hezhi.service.ITbTypeCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 课程Controller
 *
 * @author ruoyi
 * @date 2024-09-14
 */
@RestController
@RequestMapping("/hezhi/course")
public class TbCourseController extends BaseController
{
    @Autowired
    private ITbCourseService tbCourseService;
    @Autowired
    private ITbTypeCourseService tbTypeCourseService;
    @Autowired
    private ITbCaseTypeService tbCaseTypeService;
    @Autowired
    private TbExamMapper tbExamMapper;

    /**
     * 查询课程列表
     */
    @PreAuthorize("@ss.hasPermi('hezhi:course:list')")
    @GetMapping("/list")
    public TableDataInfo list(TbCourse tbCourse)
    {
        startPage();
        List<TbCourse> list = tbCourseService.selectTbCourseList(tbCourse);
        return getDataTable(list);
    }

    /**
     * 导出课程列表
     */
    @PreAuthorize("@ss.hasPermi('hezhi:course:export')")
    @Log(title = "课程", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbCourse tbCourse)
    {
        List<TbCourse> list = tbCourseService.selectTbCourseList(tbCourse);
        ExcelUtil<TbCourse> util = new ExcelUtil<TbCourse>(TbCourse.class);
        util.exportExcel(response, list, "课程数据");
    }

    /**
     * 获取课程详细信息
     */
    @PreAuthorize("@ss.hasPermi('hezhi:course:query')")
    @GetMapping(value = "/{courseId}")
    public AjaxResult getInfo(@PathVariable("courseId") Long courseId)
    {
        AjaxResult ajax = AjaxResult.success();
        // 全部分类list
        List<CaseTypeVO> allList = tbCaseTypeService.getCaseTypeList();
        TbCourse tbCourse = tbCourseService.selectTbCourseByCourseId(courseId);
        ajax.put("classList", allList);
        if (tbCourse != null) {
            ajax.put(AjaxResult.DATA_TAG, tbCourse);

//            TbTypeCourse tbTypeCourse = new TbTypeCourse();
//            tbTypeCourse.setCourseId(courseId);
//            List<TbTypeCourse> typeCourseList = tbTypeCourseService.selectTbTypeCourseList(tbTypeCourse);

//            ajax.put("classIds", typeCourseList.stream().map(TbTypeCourse::getCaseTypeId).collect(Collectors.toList()));
        }
        return ajax;

        // return success(tbCourseService.selectTbCourseByCourseId(courseId));
    }

    /**
     * 新增课程
     */
    @PreAuthorize("@ss.hasPermi('hezhi:course:add')")
    @Log(title = "课程", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbCourse tbCourse)
    {
        if (tbCourse.getMajorId() == null) {
            return AjaxResult.error("请选择专业分类");
        }
        tbCourse.setViewsNum(0);
        tbCourseService.insertTbCourse(tbCourse);
        Long[] longs = {tbCourse.getMajorId()};
        tbTypeCourseService.batchInsertTbTypeCourse(longs, tbCourse.getCourseId());

        return AjaxResult.success();
    }

    /**
     * 新增课程
     */
    @PreAuthorize("@ss.hasPermi('hezhi:course:add')")
    @Log(title = "课程-专业介绍", businessType = BusinessType.INSERT)
    @PostMapping("/addCourseMajor")
    public AjaxResult addCourseMajor(@RequestBody TbCourse tbCourse)
    {
        TbCourse course = tbCourseService.selectTbCourseByCourseId(tbCourse.getCourseId());
        if (null == course) {
            return AjaxResult.error("课程不存在，请检查后重试");
        }
        tbCourseService.updateTbCourseById(tbCourse);
        return AjaxResult.success();
    }

    /**
     * 修改课程
     */
    @PreAuthorize("@ss.hasPermi('hezhi:course:edit')")
    @Log(title = "课程", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbCourse tbCourse)
    {
        if (tbCourse.getMajorId() == null) {
            return AjaxResult.error("请选择课程分类");
        }
        tbTypeCourseService.deleteTbTypeCourseByCourseId(tbCourse.getCourseId());
        Long[] longs = {tbCourse.getMajorId()};
        tbTypeCourseService.batchInsertTbTypeCourse(longs, tbCourse.getCourseId());
        return toAjax(tbCourseService.updateTbCourse(tbCourse));
    }

    /**
     * 删除课程
     */
    @PreAuthorize("@ss.hasPermi('hezhi:course:remove')")
    @Log(title = "课程", businessType = BusinessType.DELETE)
	@DeleteMapping("/{courseIds}")
    public AjaxResult remove(@PathVariable Long[] courseIds)
    {
        return toAjax(tbCourseService.deleteTbCourseByCourseIds(courseIds));
    }

    /**
     * 所有课程列表(排除以被选择课程)
     * @return
     */
    @GetMapping("/getAllCourseListByQuery")
    public AjaxResult getAllCourseListByQuery(TbCourse tbCourse) {
        List<TbCourse> courseList = tbCourseService.getAllCourseList();
        if (courseList == null || courseList.isEmpty()) {
            return AjaxResult.success(new ArrayList<>());
        }

        List<TbExam> tbExamList = tbExamMapper.selectTbExamListAll();
        // 使用Set提高查找效率
        Set<Long> careerIdSet = tbExamList.stream()
                .map(TbExam::getCareerId)
                .collect(Collectors.toSet());

        // 如果tbCourse参数中的CareerId不为空，从careerIdSet中移除该值
        if (tbCourse != null && tbCourse.getCareerId() != null) {
            careerIdSet.remove(tbCourse.getCareerId());
        }

        // 过滤掉在careerIdSet中存在的课程
        List<TbCourse> result = courseList.stream()
                .filter(course -> !careerIdSet.contains(course.getCourseId()))
                .collect(Collectors.toList());

        return AjaxResult.success(result);
    }

    /**
     * 所有课程列表
     * @return
     */
    @GetMapping("/getAllCourseList")
    public AjaxResult getAllCourseList() {
        List<TbCourse> courseList = tbCourseService.getAllCourseList();
        return AjaxResult.success(courseList);
    }
}
