心理咨询第一阶段系统后端

package org.example.controller;

import lombok.RequiredArgsConstructor;
import org.example.entity.Counselor;
import org.example.service.CounselorService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/counselors")
@RequiredArgsConstructor
public class CounselorController {

private final CounselorService counselorService;

// ============ 页面片段 ============
@GetMapping("/list-view")
public String getCounselorListView(Model model) {
    System.out.println("=== 加载咨询师列表视图 ===");
    List<Counselor> counselors = counselorService.getAllCounselors();
    System.out.println("获取到 " + counselors.size() + " 个咨询师");

    // 打印每个咨询师的信息以便调试
    for (Counselor c : counselors) {
        System.out.println("咨询师: ID=" + c.getId() +
                ", 姓名=" + c.getRealName() +
                ", 状态=" + c.getStatus() +
                ", 专业领域=" + c.getSpecialization());
    }

    model.addAttribute("counselors", counselors);
    return "fragments/counselor-list";
}

@GetMapping("/add-view")
public String getAddCounselorView() {
    return "fragments/add-counselor";
}

@GetMapping("/{id}/edit-view")
public String getEditCounselorView(@PathVariable Long id, Model model) {
    Counselor counselor = counselorService.getCounselorById(id);
    model.addAttribute("counselor", counselor);
    return "fragments/edit-counselor";
}

// ============ API接口 ============
@GetMapping("/api/all")
@ResponseBody
public List<Counselor> getAllCounselorsApi() {
    return counselorService.getAllCounselors();
}

@GetMapping("/api/{id}")
@ResponseBody
public Counselor getCounselorByIdApi(@PathVariable Long id) {
    return counselorService.getCounselorById(id);
}

// 添加咨询师
@PostMapping
@ResponseBody
public Map<String, Object> addCounselor(@RequestBody Counselor counselor) {
    System.out.println("=== 添加咨询师 ===");
    System.out.println("接收到的数据:");
    System.out.println("姓名: " + counselor.getRealName());
    System.out.println("经验: " + counselor.getExperienceYears());
    System.out.println("专业领域: " + counselor.getSpecialization());
    System.out.println("咨询方式: " + counselor.getConsultationMethods());
    System.out.println("价格: " + counselor.getPricePerHour());
    System.out.println("状态: " + counselor.getStatus());

    try {
        Counselor savedCounselor = counselorService.addCounselor(counselor);
        System.out.println("咨询师添加成功,ID: " + savedCounselor.getId());

        return Map.of(
                "success", true,
                "message", "咨询师添加成功!",
                "id", savedCounselor.getId()
        );
    } catch (Exception e) {
        System.err.println("添加失败: " + e.getMessage());
        e.printStackTrace();

        return Map.of(
                "success", false,
                "message", "添加失败: " + e.getMessage()
        );
    }
}



// 更新咨询师
@PutMapping("/{id}")
@ResponseBody
public Map<String, Object> updateCounselor(
        @PathVariable Long id,
        @RequestBody Map<String, Object> updates) {
    try {
        counselorService.updateCounselor(id, updates);
        return Map.of(
                "success", true,
                "message", "咨询师更新成功!"
        );
    } catch (Exception e) {
        return Map.of(
                "success", false,
                "message", "更新失败: " + e.getMessage()
        );
    }
}

// 更新咨询师状态
@PutMapping("/{id}/status")
@ResponseBody
public Map<String, Object> updateCounselorStatus(
        @PathVariable Long id,
        @RequestBody Map<String, String> request) {
    try {
        String status = request.get("status");
        counselorService.updateCounselorStatus(id, status);
        return Map.of(
                "success", true,
                "message", "状态更新成功!"
        );
    } catch (Exception e) {
        return Map.of(
                "success", false,
                "message", "更新失败: " + e.getMessage()
        );
    }
}

// 删除咨询师(可选,如果要简单可以不要)
@DeleteMapping("/{id}")
@ResponseBody
public Map<String, Object> deleteCounselor(@PathVariable Long id) {
    try {
        counselorService.deleteCounselor(id);
        return Map.of(
                "success", true,
                "message", "咨询师删除成功!"
        );
    } catch (Exception e) {
        return Map.of(
                "success", false,
                "message", "删除失败: " + e.getMessage()
        );
    }
}

}
package org.example.controller;

import lombok.RequiredArgsConstructor;
import org.example.dto.QuestionDTO;
import org.example.entity.Question;
import org.example.entity.QuestionCategory;
import org.example.service.QuestionCategoryService;
import org.example.service.QuestionService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/questions")
@RequiredArgsConstructor
public class QuestionController {

private final QuestionService questionService;
private final QuestionCategoryService categoryService;

// ============ 页面渲染接口 ============

/**
 * 题目列表页面
 */
@GetMapping("/list-view")
public String listView(Model model) {
    // 直接查询所有题目
    List<Question> questions = questionService.findAll();
    model.addAttribute("questions", questions);
    return "fragments/question-list";
}

/**
 * 添加题目页面
 */
@GetMapping("/add-view")
public String addView(Model model) {
    model.addAttribute("question", new QuestionDTO());
    return "fragments/question-form";
}

/**
 * 编辑题目页面
 */
@GetMapping("/{id}/edit-view")
public String editView(@PathVariable Long id, Model model) {
    Question question = questionService.findById(id);
    QuestionDTO dto;
    try {
        dto = questionService.convertEntityToDTO(question);
    } catch (Exception e) {
        throw new RuntimeException("转换题目数据失败");
    }
    model.addAttribute("question", dto);
    return "fragments/question-form";
}

// ============ API接口 ============

/**
 * 获取题目列表(API)
 */
// QuestionController.java 修改
@PostMapping
@ResponseBody
public ResponseEntity<Map<String, Object>> createQuestion(@RequestBody Map<String, Object> request) {

    System.out.println("=== 收到创建题目请求 ===");
    System.out.println("请求数据: " + request);

    try {
        // 验证question_text字段
        Object questionTextObj = request.get("question_text");
        System.out.println("question_text字段值: " + questionTextObj);
        System.out.println("question_text字段类型: " + (questionTextObj != null ? questionTextObj.getClass().getName() : "null"));

        if (questionTextObj == null || questionTextObj.toString().trim().isEmpty()) {
            System.out.println("❌ question_text为空");
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "题目内容不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        // 创建QuestionDTO - 使用正确的字段映射
        QuestionDTO dto = new QuestionDTO();

        // 设置questionText - 确保不为空
        String questionText = questionTextObj.toString().trim();
        System.out.println("设置questionText: " + questionText);
        dto.setQuestionText(questionText);

        // 设置其他字段
        Object questionType = request.get("question_type");
        if (questionType != null) {
            try {
                dto.setQuestionType(Question.QuestionType.valueOf(questionType.toString()));
            } catch (IllegalArgumentException e) {
                dto.setQuestionType(Question.QuestionType.SINGLE_CHOICE);
            }
        }

        Object difficulty = request.get("difficulty");
        if (difficulty != null) {
            try {
                dto.setDifficulty(Question.Difficulty.valueOf(difficulty.toString()));
            } catch (IllegalArgumentException e) {
                dto.setDifficulty(Question.Difficulty.MEDIUM);
            }
        }

        // 设置options
        Object optionsObj = request.get("options");
        if (optionsObj instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, String> options = (Map<String, String>) optionsObj;
            dto.setOptions(options);
        }

        // 设置correct_answer
        Object correctAnswer = request.get("correct_answer");
        if (correctAnswer != null) {
            dto.setCorrectAnswer(correctAnswer.toString());
        }

        // 设置explanation
        Object explanation = request.get("explanation");
        if (explanation != null) {
            dto.setExplanation(explanation.toString());
        }

        // 设置is_active
        Object isActive = request.get("is_active");
        if (isActive != null) {
            if (isActive instanceof Boolean) {
                dto.setIsActive((Boolean) isActive);
            } else if (isActive instanceof String) {
                dto.setIsActive(Boolean.parseBoolean((String) isActive));
            }
        }

        System.out.println("转换后的DTO: " + dto);

        // 调用Service
        Question question = questionService.createQuestion(dto);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "创建成功");
        response.put("data", question.getId());

        return ResponseEntity.ok(response);

    } catch (Exception e) {
        e.printStackTrace();
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", "创建失败: " + e.getMessage());
        return ResponseEntity.badRequest().body(response);
    }
}

/**
 * 获取题目详情
 */
@GetMapping("/{id}")
@ResponseBody
public ResponseEntity<Map<String, Object>> getQuestion(@PathVariable Long id) {
    try {
        Question question = questionService.findById(id);
        QuestionDTO dto = questionService.convertEntityToDTO(question);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", dto);

        return ResponseEntity.ok(response);
    } catch (Exception e) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", e.getMessage());
        return ResponseEntity.badRequest().body(response);
    }
}



/**
 * 更新题目
 */
@PutMapping("/{id}")
@ResponseBody
public ResponseEntity<Map<String, Object>> updateQuestion(
        @PathVariable Long id,
        @Valid @RequestBody QuestionDTO dto,
        BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", bindingResult.getFieldError().getDefaultMessage());
        return ResponseEntity.badRequest().body(response);
    }

    try {
        Question question = questionService.updateQuestion(id, dto);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "更新成功");
        response.put("data", question.getId());

        return ResponseEntity.ok(response);
    } catch (Exception e) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", e.getMessage());
        return ResponseEntity.badRequest().body(response);
    }
}

/**
 * 删除题目
 */
@DeleteMapping("/{id}")
@ResponseBody
public ResponseEntity<Map<String, Object>> deleteQuestion(@PathVariable Long id) {
    try {
        questionService.deleteQuestion(id);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "删除成功");

        return ResponseEntity.ok(response);
    } catch (Exception e) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", e.getMessage());
        return ResponseEntity.badRequest().body(response);
    }
}

/**
 * 切换题目状态
 */
@PutMapping("/{id}/status")
@ResponseBody
public ResponseEntity<Map<String, Object>> toggleStatus(
        @PathVariable Long id,
        @RequestBody Map<String, Boolean> request) {

    try {
        Boolean isActive = request.get("is_active");
        Question question = questionService.toggleQuestionStatus(id, isActive);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "操作成功");
        response.put("data", question.getIsActive());

        return ResponseEntity.ok(response);
    } catch (Exception e) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", e.getMessage());
        return ResponseEntity.badRequest().body(response);
    }
}

/**
 * 获取题目统计
 */
@GetMapping("/stats")
@ResponseBody
public ResponseEntity<Map<String, Object>> getStats() {
    try {
        Map<String, Object> stats = questionService.getQuestionStats();

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", stats);

        return ResponseEntity.ok(response);
    } catch (Exception e) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", e.getMessage());
        return ResponseEntity.badRequest().body(response);
    }
}

// ============ 分类相关接口 ============

/**
 * 获取所有分类(用于下拉选择)
 */
@GetMapping("/categories/list")
@ResponseBody
public ResponseEntity<Map<String, Object>> getCategories() {
    try {
        List<QuestionCategory> categories = categoryService.findAllCategories();

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", categories);

        return ResponseEntity.ok(response);
    } catch (Exception e) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", e.getMessage());
        return ResponseEntity.badRequest().body(response);
    }
}

// 在QuestionController.java中,只保留这个方法:
@GetMapping("/list")
@ResponseBody
public ResponseEntity<Map<String, Object>> getQuestions() {
    try {
        // 最简单的查询:直接查所有
        List<Question> questions = questionService.findAll(); // 你需要创建这个方法

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", Map.of(
                "questions", questions
        ));

        return ResponseEntity.ok(response);

    } catch (Exception e) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", "查询失败: " + e.getMessage());
        return ResponseEntity.badRequest().body(response);
    }
}

}
package org.example.controller;

import lombok.RequiredArgsConstructor;
import org.example.entity.Video;
import org.example.service.VideoService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.;
import java.util.
;

@RestController
@RequestMapping("/api/videos")
@RequiredArgsConstructor
public class VideoApiController {

private final VideoService videoService;

// 1. 获取所有视频
@GetMapping
public ResponseEntity<List<Video>> getAllVideos() {
    List<Video> videos = videoService.getAllVideos();
    return ResponseEntity.ok(videos);
}

// 2. 按标签获取视频
@GetMapping("/by-tag")
public ResponseEntity<List<Video>> getVideosByTag(@RequestParam String tag) {
    List<Video> videos = videoService.getVideosByTag(tag);
    return ResponseEntity.ok(videos);
}

// 3. 获取所有视频分类(从标签中提取)
@GetMapping("/categories")
public ResponseEntity<List<String>> getVideoCategories() {
    List<Video> allVideos = videoService.getAllVideos();
    Set<String> categories = new HashSet<>();

    for (Video video : allVideos) {
        if (video.getTags() != null && !video.getTags().isEmpty()) {
            String[] tags = video.getTags().split(",");
            for (String tag : tags) {
                categories.add(tag.trim());
            }
        }
    }

    return ResponseEntity.ok(new ArrayList<>(categories));
}

// 4. 搜索视频
@GetMapping("/search")
public ResponseEntity<List<Video>> searchVideos(@RequestParam String keyword) {
    List<Video> videos = videoService.searchVideos(keyword);
    return ResponseEntity.ok(videos);
}

// 5. 获取视频详情
@GetMapping("/{id}")
public ResponseEntity<Video> getVideoById(@PathVariable Long id) {
    Video video = videoService.getVideoById(id);
    if (video != null) {
        return ResponseEntity.ok(video);
    } else {
        return ResponseEntity.notFound().build();
    }
}

}
package org.example.controller;

import lombok.RequiredArgsConstructor;
import org.example.entity.Video;
import org.example.service.VideoService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@RequiredArgsConstructor
public class VideoController {

private final VideoService videoService;

// ============ 主页面 ============
@GetMapping
public String adminHome() {
    return "index";
}

// ============ 页面片段(简化) ============
@GetMapping("/videos/list-view")
public String getVideoListView(Model model) {
    List<Video> videos = videoService.getAllVideos();
    model.addAttribute("videos", videos);
    return "fragments/video-list";
}

@GetMapping("/videos/add-view")
public String getAddVideoView() {
    return "fragments/add-video";
}

@GetMapping("/videos/{id}/edit-view")
public String getEditVideoView(@PathVariable Long id, Model model) {
    Video video = videoService.getVideoById(id);
    model.addAttribute("video", video);System.out.println("=== 调试信息 ===");
    System.out.println("视频ID: " + id);
    System.out.println("视频标题: " + video.getTitle());
    System.out.println("尝试加载模板: fragments/edit-video");

    return "fragments/edit";
}

// ============ API接口(简化) ============

// 1. 上传视频(简化参数)
@PostMapping("/videos")
@ResponseBody
public Map<String, Object> addVideo(


        @RequestParam("title") String title,
        @RequestParam("description") String description,
        @RequestParam("tags") String tags,
        @RequestParam("videoFile") MultipartFile videoFile,
        @RequestParam(value = "coverFile", required = false) MultipartFile coverFile) {
    System.out.println("=== 接收到上传请求 ===");
    System.out.println("标题: " + title);
    System.out.println("描述: " + description);
    System.out.println("标签: " + tags);
    System.out.println("视频文件: " + (videoFile != null && !videoFile.isEmpty() ? "有" : "无"));
    System.out.println("封面文件: " + (coverFile != null && !coverFile.isEmpty() ? "有" : "无"));
    try {
        Video video = new Video();
        video.setTitle(title);
        video.setDescription(description);
        video.setTags(tags);

        Video savedVideo = videoService.saveVideo(video, videoFile, coverFile);

        return Map.of(
                "success", true,
                "message", "视频上传成功!",
                "video", savedVideo
        );
    } catch (Exception e) {
        return Map.of(
                "success", false,
                "message", "上传失败: " + e.getMessage()
        );
    }
}

// 2. 更新视频(简化)
// 2. 更新视频(修复PUT方法)
@PostMapping("/videos/{id}")  // 改为POST方法,更容易处理文件上传
@ResponseBody
public Map<String, Object> updateVideo(
        @PathVariable Long id,
        @RequestParam("title") String title,
        @RequestParam("description") String description,
        @RequestParam("tags") String tags,
        @RequestParam(value = "videoFile", required = false) MultipartFile videoFile,
        @RequestParam(value = "coverFile", required = false) MultipartFile coverFile) {

    System.out.println("=== 接收到更新请求 ===");
    System.out.println("视频ID: " + id);
    System.out.println("标题: " + title);
    System.out.println("描述: " + description);
    System.out.println("标签: " + tags);
    System.out.println("视频文件: " + (videoFile != null && !videoFile.isEmpty() ? "有" : "无"));
    System.out.println("封面文件: " + (coverFile != null && !coverFile.isEmpty() ? "有" : "无"));

    try {
        Video video = new Video();
        video.setTitle(title);
        video.setDescription(description);
        video.setTags(tags);

        Video updatedVideo = videoService.updateVideo(id, video, videoFile, coverFile);
        return Map.of(
                "success", true,
                "message", "视频更新成功!",
                "video", updatedVideo
        );
    } catch (Exception e) {
        e.printStackTrace(); // 添加详细日志
        return Map.of(
                "success", false,
                "message", "更新失败: " + e.getMessage()
        );
    }
}

// 3. 删除视频(保持原样)
@DeleteMapping("/videos/{id}")
@ResponseBody
public Map<String, Object> deleteVideo(@PathVariable Long id) {
    try {
        videoService.deleteVideo(id);
        return Map.of(
                "success", true,
                "message", "视频删除成功!"
        );
    } catch (Exception e) {
        return Map.of(
                "success", false,
                "message", "删除失败: " + e.getMessage()
        );
    }
}

// ============ REST API(简化) ============
@GetMapping("/videos/api/all")
@ResponseBody
public List<Video> getAllVideosApi() {
    return videoService.getAllVideos();
}

@GetMapping("/videos/api/{id}")
@ResponseBody
public Video getVideoByIdApi(@PathVariable Long id) {
    return videoService.getVideoById(id);
}

// 按标签获取视频(新增)
@GetMapping("/videos/api/by-tag/{tag}")
@ResponseBody
public List<Video> getVideosByTag(@PathVariable String tag) {
    return videoService.getVideosByTag(tag);
}

}

posted @ 2026-01-02 16:18  ytr123  阅读(3)  评论(0)    收藏  举报