package cn.iocoder.byzs.module.web.controller.admin.course;

import cn.iocoder.byzs.framework.common.pojo.CommonResult;
import cn.iocoder.byzs.framework.common.util.object.BeanUtils;
import cn.iocoder.byzs.module.bjdx.controller.admin.course.vo.CoursePageReqVO;
import cn.iocoder.byzs.module.bjdx.controller.admin.coursetype.vo.CourseTypeListReqVO;
import cn.iocoder.byzs.module.bjdx.controller.admin.coursetype.vo.CourseTypeRespVO;
import cn.iocoder.byzs.module.bjdx.dal.dataobject.coursetype.CourseTypeDO;
import cn.iocoder.byzs.module.bjdx.service.course.CourseService;
import cn.iocoder.byzs.module.bjdx.service.coursetype.CourseTypeServiceImpl;
import cn.iocoder.byzs.module.web.controller.admin.course.vo.WebCourseAIGenerateVO;
import cn.iocoder.byzs.module.web.controller.admin.course.vo.WebCourseVO;
import cn.iocoder.byzs.module.web.service.course.WebCourseServiceImpl;
import cn.iocoder.byzs.module.web.service.course.WebCourseTypeServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

import static cn.iocoder.byzs.framework.common.pojo.CommonResult.success;

@Tag(name = "Web-前端接口")
@RestController
@RequestMapping("/bjdxWeb/course")
@Validated
public class WebCourseController {

    @Resource
    private CourseService courseService;
    @Resource
    private WebCourseServiceImpl webCourseService;
    @Resource
    private CourseTypeServiceImpl courseTypeService;
    @Resource
    private WebCourseTypeServiceImpl webCourseTypeService;

    @GetMapping("/getTypeGrade")
    @Operation(summary = "获得大纲-根据年级")
    public CommonResult<List<CourseTypeRespVO>> getTypeGrade() {
        CourseTypeListReqVO listReqVO = new CourseTypeListReqVO().setCtTypeNode("0");
        List<CourseTypeDO> list = courseTypeService.getCourseTypeList(listReqVO);
        List<CourseTypeRespVO> listVo = BeanUtils.toBean(list, CourseTypeRespVO.class);
        return success(listVo);
    }

    @GetMapping("/getTypeByGradeIdType")
    @Operation(summary = "获得课程大纲-根据年级、课程类型")
    public CommonResult<List<CourseTypeRespVO>> getTypeByGradeIdType(@RequestParam("id") Integer gradeId, @RequestParam("typeId") String typeId) {
        CourseTypeListReqVO listReqVO = new CourseTypeListReqVO().setCtParentId(gradeId).setCtTypeNode(typeId);
        List<CourseTypeDO> list = webCourseTypeService.selectCourseTypeList(listReqVO);
        List<CourseTypeRespVO> listVo = BeanUtils.toBean(list, CourseTypeRespVO.class);
        return success(listVo);
    }

//    @GetMapping("/getTypeTsByGradeId")
//    @Operation(summary = "获得通识课大纲-根据年级")
//    public CommonResult<List<CourseTypeRespVO>> getTypeTsByGradeId(@RequestParam("id") Integer id) {
//        CourseTypeListReqVO listReqVO = new CourseTypeListReqVO().setCtParentId(id).setCtTypeNode("1");
//        List<CourseTypeDO> list = webCourseTypeService.selectCourseTypeList(listReqVO);
//        List<CourseTypeRespVO> listVo = BeanUtils.toBean(list, CourseTypeRespVO.class);
//        return success(listVo);
//    }
//
//    @GetMapping("/getTypeScByGradeId")
//    @Operation(summary = "获得实操课大纲-根据年级")
//    public CommonResult<List<CourseTypeRespVO>> getTypeScByGradeId(@RequestParam("id") Integer id) {
//        CourseTypeListReqVO listReqVO = new CourseTypeListReqVO().setCtParentId(id).setCtTypeNode("2");
//        List<CourseTypeDO> list = webCourseTypeService.selectCourseTypeList(listReqVO);
//        List<CourseTypeRespVO> listVo = BeanUtils.toBean(list, CourseTypeRespVO.class);
//        return success(listVo);
//    }

    @GetMapping("/getCourseByTypeId")
    @Operation(summary = "根据大纲类型获得课程列表")
    @Parameter(name = "typeId", description = "编号", required = true, example = "1024")
    public CommonResult<List<WebCourseVO>> getCourseByTypeId(@RequestParam("typeId") Long typeId) {
//        List<CoursePageReqVO> courseList = courseService.getCourseList(new CoursePageReqVO().setCourseType(typeId));

        List<WebCourseVO> courseVoList = webCourseService.getCourseVoByTypeId(typeId);
        return success(courseVoList);
    }

    @GetMapping("/getCourseTypeTree")
    @Operation(summary = "获取课程类型树结构(配置权限使用)")
    public CommonResult<List<TreeNode>> getCourseTypeTree() {
        // 获取所有课程类型
        List<CourseTypeDO> allCourseTypes = courseTypeService.getCourseTypeList(new CourseTypeListReqVO());
        // 获取所有课程
        List<CoursePageReqVO> allCourses = courseService.getCourseList(new CoursePageReqVO());
        
        // 构建课程类型ID到课程类型的映射
        Map<Long, CourseTypeDO> courseTypeMap = new HashMap<>();
        for (CourseTypeDO courseType : allCourseTypes) {
            courseTypeMap.put(courseType.getId(), courseType);
        }
        
        // 构建课程类型树节点
        List<TreeNode> treeNodes = new ArrayList<>();
        
        // 处理根节点 (parentId = 0)
        for (CourseTypeDO courseType : allCourseTypes) {
            if (CourseTypeDO.CT_PARENT_ID_ROOT.equals(courseType.getCtParentId())) {
                TreeNode node = new TreeNode();
                node.setId(courseType.getId());
                node.setParentId(courseType.getCtParentId());
                node.setName(courseType.getCtType() + "（年级）");
                node.setType("年级");
                treeNodes.add(node);
            }
        }
        
        // 递归添加子节点
        for (TreeNode node : treeNodes) {
            addChildNodes(node, allCourseTypes, allCourses, courseTypeMap);
        }
        
        return success(treeNodes);
    }
    
    /**
     * 递归添加子节点
     */
    private void addChildNodes(TreeNode parentNode, List<CourseTypeDO> allCourseTypes, 
                             List<CoursePageReqVO> allCourses, Map<Long, CourseTypeDO> courseTypeMap) {
        List<TreeNode> children = new ArrayList<>();
        
        // 添加子课程类型
        for (CourseTypeDO courseType : allCourseTypes) {
            if (parentNode.getId().equals(courseType.getCtParentId())) {
                TreeNode childNode = new TreeNode();
                childNode.setId(courseType.getId());
                childNode.setParentId(courseType.getCtParentId());
                String nodeType = courseType.getCtTypeNode().equals("1") ? "通识课" : "实操课";
                childNode.setName(courseType.getCtType() + "（类型）");
                childNode.setType(nodeType);
                children.add(childNode);
                
                // 递归添加子节点的子节点
                addChildNodes(childNode, allCourseTypes, allCourses, courseTypeMap);
            }
        }
        
        // 添加关联的课程
        for (CoursePageReqVO course : allCourses) {
            if (parentNode.getId().equals(course.getCourseType())) {
                TreeNode childNode = new TreeNode();
                childNode.setId(course.getId()*100);
                childNode.setParentId(course.getCourseType());
                childNode.setName(course.getCourseName());
                childNode.setType("course");
                children.add(childNode);
            }
        }
        
        parentNode.setChildren(children);
    }
    
    /**
     * 树节点类，用于表示课程类型树结构
     */
    @Data
    public static class TreeNode {
        private Long id;
        private Long parentId;
        private String name;
        private String type; // courseType 或 course
        private List<TreeNode> children = new ArrayList<>();
    }


    /**
     * AI生成课程
     */
    @PostMapping("/aIGenerateCourse")
    @Operation(summary = "AI生成课程")
    public CommonResult<Boolean> generateCourseByAI(@RequestBody WebCourseAIGenerateVO reqVO) {
        return success(webCourseService.generateCourseByAI(reqVO));
    }
}