package shop.alien.lawyer.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawyerChatSession;
import shop.alien.lawyer.service.LawyerChatSessionService;
import shop.alien.util.myBaticsPlus.QueryBuilder;

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

/**
 * 聊天会话 前端控制器
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"律师平台-聊天会话"})
@ApiSort(15)
@CrossOrigin
@RestController
@RequestMapping("/lawyer/chatSession")
@RequiredArgsConstructor
public class LawyerChatSessionController {

    private final LawyerChatSessionService chatSessionService;

    @ApiOperation("新增聊天会话")
    @ApiOperationSupport(order = 1)
    @PostMapping("/addChatSession")
    public R<LawyerChatSession> addChatSession(@RequestBody LawyerChatSession chatSession) {
        log.info("LawyerChatSessionController.addChatSession?chatSession={}", chatSession);
        return chatSessionService.addChatSession(chatSession);
    }

    @ApiOperation("编辑聊天会话")
    @ApiOperationSupport(order = 2)
    @PostMapping("/editChatSession")
    public R<LawyerChatSession> editChatSession(@RequestBody LawyerChatSession chatSession) {
        log.info("LawyerChatSessionController.editChatSession?chatSession={}", chatSession);
        return chatSessionService.editChatSession(chatSession);
    }

    @ApiOperation("删除聊天会话")
    @ApiOperationSupport(order = 3)
    @DeleteMapping("/deleteChatSession")
    public R<Boolean> deleteChatSession(@RequestParam(value = "id") Integer id) {
        log.info("LawyerChatSessionController.deleteChatSession?id={}", id);
        return chatSessionService.deleteChatSession(id);
    }

    @ApiOperation("保存或更新聊天会话")
    @ApiOperationSupport(order = 4)
    @PostMapping("/saveOrUpdate")
    public R<LawyerChatSession> saveOrUpdate(@RequestBody LawyerChatSession chatSession) {
        log.info("LawyerChatSessionController.saveOrUpdate?chatSession={}", chatSession);
        boolean result = chatSessionService.saveOrUpdate(chatSession);
        if (result) {
            return R.data(chatSession);
        }
        return R.fail("操作失败");
    }

    @ApiOperation("通用列表查询")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "consultationOrderId", value = "咨询订单ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "clientUserId", value = "客户端用户ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "lawyerUserId", value = "律师用户ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "会话状态", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_Start", value = "创建时间开始（范围查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_End", value = "创建时间结束（范围查询）", dataType = "String", paramType = "query")
    })
    @GetMapping("/getList")
    public R<List<LawyerChatSession>> getList(@ModelAttribute LawyerChatSession chatSession) {
        log.info("LawyerChatSessionController.getList?chatSession={}", chatSession);
        List<LawyerChatSession> list = QueryBuilder.of(chatSession)
                .build()
                .list(chatSessionService);
        return R.data(list);
    }

    @ApiOperation("通用分页查询")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数（默认1）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页容（默认10）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "主键", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "consultationOrderId", value = "咨询订单ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "clientUserId", value = "客户端用户ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "lawyerUserId", value = "律师用户ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "会话状态", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_Start", value = "创建时间开始（范围查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_End", value = "创建时间结束（范围查询）", dataType = "String", paramType = "query")
    })
    @GetMapping("/getPage")
    public R<IPage<LawyerChatSession>> getPage(@ModelAttribute LawyerChatSession chatSession,
                                               @RequestParam(defaultValue = "1") int page,
                                               @RequestParam(defaultValue = "10") int size) {
        log.info("LawyerChatSessionController.getPage?chatSession={},page={},size={}", chatSession, page, size);
        int pageNum = page > 0 ? page : 1;
        int pageSize = size > 0 ? size : 10;
        IPage<LawyerChatSession> pageResult = QueryBuilder.of(chatSession)
                .page(pageNum, pageSize)
                .build()
                .page(chatSessionService);
        return R.data(pageResult);
    }

    @ApiOperation("获取聊天历史记录")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sessionId", value = "会话ID（可选，不传则获取所有会话列表）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码（默认1）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量（默认20）", dataType = "int", paramType = "query")
    })
    @GetMapping("/history")
    public R<Map<String, Object>> getChatHistory(
            @RequestParam(required = false) String sessionId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int pageSize) {
        log.info("LawyerChatSessionController.getChatHistory?sessionId={},page={},pageSize={}", sessionId, page, pageSize);
        return chatSessionService.getChatHistory(sessionId, page, pageSize);
    }

    @ApiOperation("保存聊天消息")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sessionId", value = "会话ID（可选，不传则创建新会话）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "content", value = "消息内容", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "type", value = "消息类型：user或ai", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "clientUserId", value = "客户端用户ID（当type=user时必填）", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "consultationOrderId", value = "咨询订单ID（可选）", dataType = "Integer", paramType = "query")
    })
    @PostMapping("/saveMessage")
    public R<Map<String, Object>> saveChatMessage(
            @RequestParam(required = false) String sessionId,
            @RequestParam String content,
            @RequestParam String type,
            @RequestParam(required = false) Integer clientUserId,
            @RequestParam(required = false) Integer consultationOrderId) {
        log.info("LawyerChatSessionController.saveChatMessage?sessionId={},content={},type={},clientUserId={},consultationOrderId={}",
                sessionId, content, type, clientUserId, consultationOrderId);
        return chatSessionService.saveChatMessage(sessionId, content, type, clientUserId, consultationOrderId);
    }

    @ApiOperation("删除聊天消息")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "messageIds", value = "消息ID数组（逗号分隔）", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "sessionId", value = "会话ID（可选）", dataType = "String", paramType = "query")
    })
    @PostMapping("/deleteMessage")
    public R<String> deleteChatMessages(
            @RequestParam String messageIds,
            @RequestParam(required = false) String sessionId) {
        log.info("LawyerChatSessionController.deleteChatMessages?messageIds={},sessionId={}", messageIds, sessionId);
        return chatSessionService.deleteChatMessages(messageIds, sessionId);
    }

    @ApiOperation("删除会话（通过会话ID）")
    @ApiOperationSupport(order = 10)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sessionId", value = "会话ID", dataType = "String", paramType = "query", required = true)
    })
    @PostMapping("/deleteSessionById")
    public R<String> deleteChatSession(@RequestParam String sessionId) {
        log.info("LawyerChatSessionController.deleteChatSession?sessionId={}", sessionId);
        return chatSessionService.deleteChatSessionBySessionId(sessionId);
    }
}

