package com.cy.guoyan.admin.module.ai.controller.admin.chatmessage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONObject;
import com.cy.guoyan.admin.module.ai.controller.admin.chatmessage.vo.ChatMessagePageReqVO;
import com.cy.guoyan.admin.module.ai.controller.admin.chatmessage.vo.ChatMessageRespVO;
import com.cy.guoyan.admin.module.ai.controller.admin.chatmessage.vo.ChatMessageSaveReqVO;
import com.cy.guoyan.admin.module.ai.controller.admin.chatmessage.vo.ChatMessageSendReqVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import com.cy.guoyan.admin.framework.common.pojo.PageParam;
import com.cy.guoyan.admin.framework.common.pojo.PageResult;
import com.cy.guoyan.admin.framework.common.pojo.CommonResult;
import com.cy.guoyan.admin.framework.common.util.object.BeanUtils;
import static com.cy.guoyan.admin.framework.common.pojo.CommonResult.success;
import com.cy.guoyan.admin.framework.excel.core.util.ExcelUtils;
import com.cy.guoyan.admin.framework.apilog.core.annotation.ApiAccessLog;
import static com.cy.guoyan.admin.framework.apilog.core.enums.OperateTypeEnum.*;
import com.cy.guoyan.admin.module.ai.dal.dataobject.chatmessage.ChatMessageDO;
import com.cy.guoyan.admin.module.ai.service.chatmessage.ChatMessageService;

@Tag(name = "管理后台 - AI聊天消息")
@RestController
@RequestMapping("/chatAi/chat-message")
@Validated
public class ChatMessageController {

    @Resource
    private ChatMessageService chatMessageService;

    @PostMapping("/create")
    @Operation(summary = "创建AI聊天消息")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-message:create')")
    public CommonResult<Long> createChatMessage(@Valid @RequestBody ChatMessageSaveReqVO createReqVO) {
        return success(chatMessageService.createChatMessage(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新AI聊天消息")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-message:update')")
    public CommonResult<Boolean> updateChatMessage(@Valid @RequestBody ChatMessageSaveReqVO updateReqVO) {
        chatMessageService.updateChatMessage(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除AI聊天消息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('chatAi:chat-message:delete')")
    public CommonResult<Boolean> deleteChatMessage(@RequestParam("id") Long id) {
        chatMessageService.deleteChatMessage(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得AI聊天消息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-message:query')")
    public CommonResult<ChatMessageRespVO> getChatMessage(@RequestParam("id") Long id) {
        ChatMessageDO chatMessage = chatMessageService.getChatMessage(id);
        return success(BeanUtils.toBean(chatMessage, ChatMessageRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得AI聊天消息分页")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-message:query')")
    public CommonResult<PageResult<ChatMessageRespVO>> getChatMessagePage(@Valid ChatMessagePageReqVO pageReqVO) {
        PageResult<ChatMessageDO> pageResult = chatMessageService.getChatMessagePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ChatMessageRespVO.class));
    }

    @GetMapping("/list")
    @Operation(summary = "获得AI聊天消息")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-message:query')")
    public CommonResult<List<ChatMessageRespVO>> getChatMessageList(@Valid ChatMessagePageReqVO pageReqVO) {
        List<ChatMessageDO> result = chatMessageService.getChatMessageList(pageReqVO);

        List<ChatMessageRespVO> respVOS = new ArrayList<>();
        for (ChatMessageDO doItem : result) {
            ChatMessageRespVO respVO = new ChatMessageRespVO();
            // 复制除 metadataJson 以外的属性
            BeanUtil.copyProperties(doItem, respVO, CopyOptions.create().setIgnoreProperties("metadataJson"));
            // 处理 metadataJson 字符串转 JSONObject
            if (StringUtils.isNotBlank(doItem.getMetadataJson())) {
                respVO.setMetadataJson(JSONObject.parseObject(doItem.getMetadataJson()));
            }
            respVOS.add(respVO);
        }


        return success(respVOS);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出AI聊天消息 Excel")
    @PreAuthorize("@ss.hasPermission('chatAi:chat-message:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportChatMessageExcel(@Valid ChatMessagePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ChatMessageDO> list = chatMessageService.getChatMessagePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "AI聊天消息.xls", "数据", ChatMessageRespVO.class,
                        BeanUtils.toBean(list, ChatMessageRespVO.class));
    }



    @PostMapping(value = "/send-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Operation(summary = "发送聊天消息（流式）")
    public void sendChatMessage(@RequestBody @Valid ChatMessageSendReqVO sendReqVO,
            HttpServletResponse response) throws IOException {

        // 设置响应头 SSE
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");

        chatMessageService.sendChatMessageStream(sendReqVO, response);
    }

    @PostMapping("/send-block")
    @Operation(summary = "发送聊天消息（阻塞式）")
    public CommonResult<ChatMessageRespVO> sendChatBlock(@RequestBody ChatMessageSendReqVO sendReqVO) throws IOException{
            return success(chatMessageService.sendChatMessageBlock(sendReqVO));
    }




}