package cn.teammodel.controller.frontend;

import cn.teammodel.common.IdRequest;
import cn.teammodel.common.R;
import cn.teammodel.model.dto.ai.*;
import cn.teammodel.model.dto.ai.comment.ChatCommentsDto;
import cn.teammodel.model.dto.ai.comment.ChatTeacherCommentDto;
import cn.teammodel.model.entity.TmdUserDetail;
import cn.teammodel.model.entity.ai.ChatApp;
import cn.teammodel.model.entity.ai.ChatSession;
import cn.teammodel.security.utils.SecurityUtil;
import cn.teammodel.service.ChatAppService;
import cn.teammodel.service.ChatMessageService;
import cn.teammodel.service.ChatSessionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/ai")
@Api(tags = "AI 科大讯飞 能力")
public class AiController {
    @Resource
    private ChatSessionService chatSessionService;
    @Resource
    private ChatMessageService chatMessageService;
    @Resource
    private ChatAppService chatAppService;


    @PostMapping("api/chat/completion")
    @ApiOperation("与 spark 的流式对话")
    public SseEmitter chatCompletionToApi(@RequestBody @Valid ChatCompletionReqDto chatCompletionReqDto) {
        String userId = ((TmdUserDetail) SecurityUtil.getAuthentication().getPrincipal()).getClaims().getSubject();
        return chatMessageService.chatCompletion(chatCompletionReqDto, userId);
    }
    @PostMapping("chat/completion")
    @ApiOperation("与 spark 的流式对话")
    public SseEmitter chatCompletion(@RequestBody @Valid ChatCompletionReqDto chatCompletionReqDto) {
        return chatMessageService.chatCompletion(chatCompletionReqDto, null);
    }

    @PostMapping("chat/test/completion")
    @ApiOperation("与 spark 的流式对话")
    public SseEmitter testCompletion(@RequestBody @Valid ChatCompletionReqDto chatCompletionReqDto) throws IOException, InterruptedException {
        SseEmitter sseEmitter = new SseEmitter();
        CompletableFuture.runAsync(() -> {
            try {
                sseEmitter.send("曾经以为我们");
                Thread.sleep(1000);
                sseEmitter.send("开始了就会走到最后，可是当分手之后才明白我想的");
                Thread.sleep(1000);
                sseEmitter.send("你不一定能做到，当我开始去遗忘我们");
                Thread.sleep(1500);
                sseEmitter.send("的经历时，却不知道遗忘已变成另一种开始，");
                Thread.sleep(800);
                sseEmitter.send("回忆是淡了，可是痛却还在，还是最真实。放手的时候微笑着说无所谓");
                Thread.sleep(800);
                sseEmitter.send("，离开了你我还可以过的很好");
                Thread.sleep(1000);
                sseEmitter.send("，而你却不知道微笑只是用来掩盖疼痛的伤疤。");
                Thread.sleep(1200);
                sseEmitter.send("离开你之后的自己陷入一种无助的状态，空洞的");
                Thread.sleep(1300);
                sseEmitter.send("双眼回忆不起曾经的你，那时候以为与世隔绝或许才是维护自己的最好方式。");
                Thread.sleep(1100);
                sseEmitter.send("[DONE]");
                sseEmitter.complete();

            } catch (IOException | InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        return sseEmitter;
    }

    @GetMapping("api/session/my")
    @ApiOperation("查询我的聊天会话")
    public R<List<ChatSession>> listMySession() {
        String userId = ((TmdUserDetail) SecurityUtil.getAuthentication().getPrincipal()).getClaims().getSubject();
        List<ChatSession> sessions = chatSessionService.listMySession(userId);
        return R.success(sessions);
    }

    @GetMapping("api/chat/history/{sessionId}")
    @ApiOperation("查询我的聊天记录")
    public R<List<ChatSession.Message>> getHistory(@PathVariable String sessionId) {
        String userId = ((TmdUserDetail) SecurityUtil.getAuthentication().getPrincipal()).getClaims().getSubject();
        List<ChatSession.Message> history = chatSessionService.listHistory(sessionId, userId);
        return R.success(history);
    }
    @PostMapping("api/session/create")
    @ApiOperation("创建聊天会话")
    public R<String> createSession() {
        String userId = ((TmdUserDetail) SecurityUtil.getAuthentication().getPrincipal()).getClaims().getSubject();
        String name = (String) ((TmdUserDetail) SecurityUtil.getAuthentication().getPrincipal()).getClaims().get("name");
        name = StringUtils.isBlank(name) ? "老师" : name;
        String sessionId = chatSessionService.createSession(userId, name);
        return R.success(sessionId);
    }

    @PostMapping("api/session/remove")
    @ApiOperation("删除聊天会话")
    public R<String> removeSession(@RequestBody @Valid IdRequest idRequest) {
        String userId = ((TmdUserDetail) SecurityUtil.getAuthentication().getPrincipal()).getClaims().getSubject();
        chatSessionService.deleteSession(idRequest.getId(), userId);
        return R.success("删除会话成功");
    }
    @PostMapping("api/session/update")
    @ApiOperation("更新聊天会话")
    public R<ChatSession> updateSession(@RequestBody @Valid UpdateSessionDto updateSessionDto) {
        String userId = ((TmdUserDetail) SecurityUtil.getAuthentication().getPrincipal()).getClaims().getSubject();
        ChatSession session = chatSessionService.updateSession(updateSessionDto, userId);
        return R.success(session);
    }

    @PostMapping("app/list")
    @ApiOperation("查询聊天应用列表")
    public R<List<ChatApp>> listApp(@RequestBody @Valid SearchAppDto  searchAppDto) {
        List<ChatApp> chatApps = chatAppService.listApp(searchAppDto);
        return R.success(chatApps);
    }

    @PostMapping("app/create")
    @ApiOperation("创建聊天应用")
    public R<ChatApp> createApp(@RequestBody @Valid CreateChatAppDto createChatAppDto) {
        ChatApp chatApp = chatAppService.createApp(createChatAppDto);
        return R.success(chatApp);
    }

    @PostMapping("app/update")
    @ApiOperation("更新聊天应用")
    public R<ChatApp> updateApp(@RequestBody @Valid UpdateChatAppDto updateChatAppDto) {
        ChatApp chatApp = chatAppService.updateApp(updateChatAppDto);
        return R.success(chatApp);
    }

    @PostMapping("app/remove")
    @ApiOperation("删除聊天应用")
    public R<String> updateApp(@RequestBody @Valid IdRequest idRequest) {
        chatAppService.deleteApp(idRequest);
        return R.success("删除应用成功");
    }

    @PostMapping("chat/comments")
    @ApiOperation("学生设置评语")
    public SseEmitter chatComments(@RequestBody @Valid ChatCommentsDto chatCommentsDto) {
        //String userId = ((TmdUserDetail) SecurityUtil.getAuthentication().getPrincipal()).getClaims().getSubject();
        // 获取getClaims时为空
        String userId = ((TmdUserDetail) SecurityUtil.getAuthentication().getPrincipal()).getUser().getId();
        String userName = ((TmdUserDetail) SecurityUtil.getAuthentication().getPrincipal()).getUser().getName();

        //获取会话id 看是否有sessionId 有则直接赋值 没有则赋值userId
        String sessionId = StringUtils.isBlank(chatCommentsDto.getSessionId()) ? userId: chatCommentsDto.getSessionId();
        chatCommentsDto.setSessionId(sessionId);
        int repeat = chatCommentsDto.getRepeat();
        if (repeat <= 1)
        {
            chatCommentsDto.setRepeat(repeat);
        }
        return chatMessageService.chatComments(chatCommentsDto, userId, userName);
    }

    /**
     * ai评语
     */
    @PostMapping("chat/teacherComment")
    @ApiOperation("教师Ai评语")
    public SseEmitter chatTeacherComment(@RequestBody @Valid ChatTeacherCommentDto chatTeacherCommentDto){
        String userId = ((TmdUserDetail) SecurityUtil.getAuthentication().getPrincipal()).getUser().getId();
        String userName = ((TmdUserDetail) SecurityUtil.getAuthentication().getPrincipal()).getUser().getName();

        //获取会话id 看是否有sessionId 有则直接赋值 没有则赋值userId
        String sessionId = StringUtils.isBlank(chatTeacherCommentDto.getSessionId()) ? userId: chatTeacherCommentDto.getSessionId();
        chatTeacherCommentDto.setSessionId(sessionId);

        return chatMessageService.chatTeacherComment(chatTeacherCommentDto,userId, userName);
    }


}