package com.snack.server.module.chat.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.snack.server.common.Result;
import com.snack.server.module.chat.dto.req.ChatAckReq;
import com.snack.server.module.chat.dto.req.ChatSendMessageReq;
import com.snack.server.module.chat.dto.req.ChatSessionPageReq;
import com.snack.server.module.chat.dto.req.QuickReplySaveReq;
import com.snack.server.module.chat.entity.ChatSession;
import com.snack.server.module.chat.service.ChatMessageService;
import com.snack.server.module.chat.service.ChatOnlineService;
import com.snack.server.module.chat.service.ChatSessionService;
import com.snack.server.module.chat.service.QuickReplyService;
import com.snack.server.module.chat.vo.ChatMessageVO;
import com.snack.server.module.chat.vo.ChatSessionDetailVO;
import com.snack.server.module.chat.vo.ChatSessionVO;
import com.snack.server.module.chat.vo.QuickReplyVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 客服聊天 - 管理端 API
 */
@Tag(name = "08. 客服聊天")
@RestController
@RequestMapping("/api/admin/chat")
@RequiredArgsConstructor
public class ChatAdminController {

    private final ChatSessionService chatSessionService;
    private final ChatMessageService chatMessageService;
    private final QuickReplyService quickReplyService;
    private final ChatOnlineService chatOnlineService;

    // ==================== 会话管理 ====================

    @Operation(summary = "分页查询会话")
    @SaCheckLogin
    @GetMapping("/session/page")
    public Result<Page<ChatSessionVO>> pageSessions(ChatSessionPageReq req) {
        Long adminId = StpUtil.getLoginIdAsLong();
        return Result.ok(chatSessionService.pageSessions(req, adminId));
    }

    @Operation(summary = "会话详情")
    @SaCheckLogin
    @GetMapping("/session/{id}")
    public Result<ChatSessionDetailVO> sessionDetail(@PathVariable Long id) {
        return Result.ok(chatSessionService.getDetail(id));
    }

    @Operation(summary = "客服接管会话")
    @SaCheckLogin
    @PostMapping("/session/{id}/accept")
    public Result<ChatSessionVO> accept(@PathVariable Long id) {
        Long adminId = StpUtil.getLoginIdAsLong();
        ChatSession session = chatSessionService.acceptByAdmin(id, adminId, "");
        return Result.ok(chatSessionService.toVO(session));
    }

    @Operation(summary = "转接给其他客服")
    @SaCheckLogin
    @PostMapping("/session/{id}/transfer")
    public Result<ChatSessionVO> transfer(
            @PathVariable Long id,
            @RequestParam Long toAdminId) {
        Long adminId = StpUtil.getLoginIdAsLong();
        ChatSession session = chatSessionService.transferToAdmin(id, adminId, toAdminId);
        return Result.ok(chatSessionService.toVO(session));
    }

    @Operation(summary = "更新会话状态（已解决 / 已关闭）")
    @SaCheckLogin
    @PutMapping("/session/{id}/status/{status}")
    public Result<Void> updateStatus(
            @PathVariable Long id,
            @PathVariable Integer status) {
        Long adminId = StpUtil.getLoginIdAsLong();
        chatSessionService.updateStatus(id, status, adminId);
        return Result.ok();
    }

    @Operation(summary = "关闭会话")
    @SaCheckLogin
    @PutMapping("/session/{id}/close")
    public Result<Void> close(@PathVariable Long id) {
        Long adminId = StpUtil.getLoginIdAsLong();
        chatSessionService.closeSession(id, adminId, true);
        return Result.ok();
    }

    // ==================== 消息管理 ====================

    @Operation(summary = "获取会话历史消息")
    @SaCheckLogin
    @GetMapping("/session/{id}/messages")
    public Result<List<ChatMessageVO>> messages(
            @PathVariable Long id,
            @RequestParam(required = false) Long afterSeq,
            @RequestParam(defaultValue = "200") int limit) {
        return Result.ok(chatMessageService.getMessages(id, afterSeq, limit));
    }

    @Operation(summary = "发送消息（客服端）")
    @SaCheckLogin
    @PostMapping("/session/{id}/message")
    public Result<ChatMessageVO> sendMessage(
            @PathVariable Long id,
            @Valid @RequestBody ChatSendMessageReq req) {
        req.setSessionId(id);
        Long adminId = StpUtil.getLoginIdAsLong();
        return Result.ok(chatMessageService.toVO(
                chatMessageService.sendMessage(req, adminId, 1)));
    }

    @Operation(summary = "已读确认（客服端）")
    @SaCheckLogin
    @PutMapping("/session/{id}/ack")
    public Result<Void> ack(@PathVariable Long id, @Valid @RequestBody ChatAckReq req) {
        req.setSessionId(id);
        chatMessageService.handleAck(req, true);
        return Result.ok();
    }

    // ==================== 快捷回复 ====================

    @Operation(summary = "启用快捷回复列表")
    @SaCheckLogin
    @GetMapping("/quick-reply/list")
    public Result<List<QuickReplyVO>> quickReplyList(
            @RequestParam(required = false) String category) {
        return Result.ok(quickReplyService.listActiveReplies(category));
    }

    @Operation(summary = "快捷回复详情")
    @SaCheckLogin
    @GetMapping("/quick-reply/{id}")
    public Result<QuickReplyVO> quickReplyDetail(@PathVariable Long id) {
        return Result.ok(quickReplyService.getById(id));
    }

    @Operation(summary = "创建快捷回复")
    @SaCheckLogin
    @PostMapping("/quick-reply")
    public Result<Long> createQuickReply(@Valid @RequestBody QuickReplySaveReq req) {
        Long adminId = StpUtil.getLoginIdAsLong();
        return Result.ok(quickReplyService.create(req, adminId));
    }

    @Operation(summary = "更新快捷回复")
    @SaCheckLogin
    @PutMapping("/quick-reply")
    public Result<Void> updateQuickReply(@Valid @RequestBody QuickReplySaveReq req) {
        quickReplyService.update(req);
        return Result.ok();
    }

    @Operation(summary = "删除快捷回复")
    @SaCheckLogin
    @DeleteMapping("/quick-reply/{id}")
    public Result<Void> deleteQuickReply(@PathVariable Long id) {
        quickReplyService.delete(id);
        return Result.ok();
    }

    // ==================== 在线状态 ====================

    @Operation(summary = "客服在线心跳")
    @SaCheckLogin
    @PostMapping("/heartbeat")
    public Result<Void> heartbeat() {
        Long adminId = StpUtil.getLoginIdAsLong();
        chatOnlineService.markOnline(adminId, true);
        return Result.ok();
    }

    @Operation(summary = "获取在线客服数（简版）")
    @SaCheckLogin
    @GetMapping("/admin/online/count")
    public Result<Long> onlineAdminCount() {
        var all = chatOnlineService.getAllOnline();
        long count = all.stream()
                .filter(o -> o.toString().startsWith("admin:"))
                .count();
        return Result.ok(count);
    }
}
