package shop.alien.lawyer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawyerChatMessage;
import shop.alien.entity.store.LawyerChatSession;
import shop.alien.lawyer.service.LawyerChatMessageService;
import shop.alien.lawyer.service.LawyerChatSessionService;
import shop.alien.mapper.LawyerChatSessionMapper;
import shop.alien.util.myBaticsPlus.QueryBuilder;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 聊天会话 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Transactional
@Service
@RequiredArgsConstructor
public class LawyerChatSessionServiceImpl extends ServiceImpl<LawyerChatSessionMapper, LawyerChatSession> implements LawyerChatSessionService {

    private final LawyerChatSessionMapper chatSessionMapper;
    private final LawyerChatMessageService chatMessageService;
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    @Override
    public R<IPage<LawyerChatSession>> getChatSessionList(int pageNum, int pageSize, Integer consultationOrderId,
                                                          Integer clientUserId, Integer lawyerUserId, Integer status) {
        log.info("LawyerChatSessionServiceImpl.getChatSessionList?pageNum={},pageSize={},consultationOrderId={},clientUserId={},lawyerUserId={},status={}",
                pageNum, pageSize, consultationOrderId, clientUserId, lawyerUserId, status);
        Page<LawyerChatSession> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<LawyerChatSession> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawyerChatSession::getDeleteFlag, 0);
        if (consultationOrderId != null) {
            queryWrapper.eq(LawyerChatSession::getConsultationOrderId, consultationOrderId);
        }
        if (clientUserId != null) {
            queryWrapper.eq(LawyerChatSession::getClientUserId, clientUserId);
        }
        if (lawyerUserId != null) {
            queryWrapper.eq(LawyerChatSession::getLawyerUserId, lawyerUserId);
        }
        if (status != null) {
            queryWrapper.eq(LawyerChatSession::getStatus, status);
        }
        queryWrapper.orderByDesc(LawyerChatSession::getLastMessageTime);
        IPage<LawyerChatSession> pageResult = this.page(page, queryWrapper);
        return R.data(pageResult);
    }

    @Override
    public LawyerChatSession getByOrderId(Integer consultationOrderId) {
        log.info("LawyerChatSessionServiceImpl.getByOrderId?consultationOrderId={}", consultationOrderId);
        LambdaQueryWrapper<LawyerChatSession> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawyerChatSession::getConsultationOrderId, consultationOrderId)
                .eq(LawyerChatSession::getDeleteFlag, 0)
                .last("LIMIT 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public R<LawyerChatSession> addChatSession(LawyerChatSession chatSession) {
        log.info("LawyerChatSessionServiceImpl.addChatSession?chatSession={}", chatSession);
        boolean result = this.save(chatSession);
        if (result) {
            return R.data(chatSession);
        }
        return R.fail("新增失败");
    }

    @Override
    public R<LawyerChatSession> editChatSession(LawyerChatSession chatSession) {
        log.info("LawyerChatSessionServiceImpl.editChatSession?chatSession={}", chatSession);
        boolean result = this.updateById(chatSession);
        if (result) {
            return R.data(chatSession);
        }
        return R.fail("修改失败");
    }

    @Override
    public R<Boolean> deleteChatSession(Integer id) {
        log.info("LawyerChatSessionServiceImpl.deleteChatSession?id={}", id);
        boolean result = this.removeById(id);
        if (result) {
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }

    @Override
    public R<Map<String, Object>> getChatHistory(String sessionId, int page, int pageSize) {
        log.info("LawyerChatSessionServiceImpl.getChatHistory?sessionId={},page={},pageSize={}", sessionId, page, pageSize);

        Map<String, Object> result = new HashMap<>();

        if (StringUtils.hasText(sessionId)) {
            // 返回该会话的消息列表
            LawyerChatMessage query = new LawyerChatMessage();
            query.setChatSessionId(Integer.parseInt(sessionId));

            int pageNum = page > 0 ? page : 1;
            int pageSizeNum = pageSize > 0 ? pageSize : 20;

            IPage<LawyerChatMessage> pageResult = QueryBuilder.of(query)
                    .page(pageNum, pageSizeNum)
                    .build()
                    .page(chatMessageService);

            List<Map<String, Object>> messages = pageResult.getRecords().stream().map(msg -> {
                Map<String, Object> msgMap = new HashMap<>();
                msgMap.put("id", msg.getId());
                msgMap.put("content", msg.getMessageContent());
                msgMap.put("type", msg.getSenderType() == 0 ? "user" : "ai");  // 0:客户端用户, 1:律师用户，这里假设AI消息
                msgMap.put("time", msg.getMessageTimestamp() != null ?
                        DATE_FORMAT.format(msg.getMessageTimestamp()) : "");
                msgMap.put("sessionId", sessionId);
                // TODO: 处理图片和视频URL数组
                msgMap.put("images", new ArrayList<>());
                msgMap.put("videos", new ArrayList<>());
                return msgMap;
            }).collect(Collectors.toList());

            result.put("messages", messages);
        } else {
            // 返回会话列表
            QueryWrapper<LawyerChatSession> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("delete_flag", 0)
                    .orderByDesc("last_message_time", "created_time");

            int pageNum = page > 0 ? page : 1;
            int pageSizeNum = pageSize > 0 ? pageSize : 20;
            Page<LawyerChatSession> pageObj = new Page<>(pageNum, pageSizeNum);
            IPage<LawyerChatSession> pageResult = this.page(pageObj, queryWrapper);

            List<Map<String, Object>> sessions = pageResult.getRecords().stream().map(session -> {
                Map<String, Object> sessionMap = new HashMap<>();
                sessionMap.put("id", session.getId().toString());
                // TODO: 获取会话标题（通常是第一条消息）
                sessionMap.put("title", "咨询会话");
                // TODO: 获取最后一条消息内容
                sessionMap.put("lastMessage", "");
                sessionMap.put("lastMessageTime", session.getLastMessageTime() != null ?
                        DATE_FORMAT.format(session.getLastMessageTime()) : "");
                // TODO: 获取消息数量
                sessionMap.put("messageCount", 0);
                return sessionMap;
            }).collect(Collectors.toList());

            result.put("sessions", sessions);
        }

        return R.data(result);
    }

    @Override
    public R<Map<String, Object>> saveChatMessage(String sessionId, String content, String type, Integer clientUserId, Integer consultationOrderId) {
        log.info("LawyerChatSessionServiceImpl.saveChatMessage?sessionId={},content={},type={},clientUserId={},consultationOrderId={}",
                sessionId, content, type, clientUserId, consultationOrderId);

        Integer chatSessionId = null;
        if (StringUtils.hasText(sessionId)) {
            chatSessionId = Integer.parseInt(sessionId);
        } else {
            // 创建新会话
            LawyerChatSession newSession = new LawyerChatSession();
            newSession.setClientUserId(clientUserId);
            newSession.setConsultationOrderId(consultationOrderId);
            newSession.setStatus(1);  // 进行中
            this.save(newSession);
            chatSessionId = newSession.getId();
        }

        // 保存消息
        LawyerChatMessage message = new LawyerChatMessage();
        message.setChatSessionId(chatSessionId);
        message.setConsultationOrderId(consultationOrderId);
        message.setSenderId(clientUserId);
        message.setSenderType("user".equals(type) ? 0 : 1);  // 0:客户端用户, 1:律师用户
        message.setMessageContent(content);
        message.setMessageType(0);  // 文本消息
        message.setMessageTimestamp(new Date());
        message.setReadStatus(0);  // 未读

        chatMessageService.save(message);

        // 更新会话的最后消息时间和ID
        LawyerChatSession session = this.getById(chatSessionId);
        if (session != null) {
            session.setLastMessageId(message.getId());
            session.setLastMessageTime(new Date());
            this.updateById(session);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("messageId", message.getId());
        result.put("sessionId", chatSessionId.toString());
        result.put("time", DATE_FORMAT.format(message.getMessageTimestamp()));

        return R.data(result);
    }

    @Override
    public R<String> deleteChatMessages(String messageIds, String sessionId) {
        log.info("LawyerChatSessionServiceImpl.deleteChatMessages?messageIds={},sessionId={}", messageIds, sessionId);

        String[] ids = messageIds.split(",");
        List<Integer> idList = Arrays.stream(ids)
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        if (!idList.isEmpty()) {
            chatMessageService.removeByIds(idList);
        }

        return R.success("删除成功");
    }

    @Override
    public R<String> deleteChatSessionBySessionId(String sessionId) {
        log.info("LawyerChatSessionServiceImpl.deleteChatSessionBySessionId?sessionId={}", sessionId);

        this.removeById(Integer.parseInt(sessionId));

        return R.success("删除成功");
    }
}

