package com.jeesharp.business.modules.ai.application;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.ai.convert.AiChatFeedbackConvert;
import com.jeesharp.business.modules.ai.dto.AiChatFeedbackSaveDTO;
import com.jeesharp.business.modules.ai.entity.AiChatFeedback;
import com.jeesharp.business.modules.ai.service.AiChatFeedbackService;
import com.jeesharp.business.modules.ai.service.AiChatMessageService;
import com.jeesharp.business.modules.ai.service.AiChatSessionService;
import com.jeesharp.business.modules.ai.vo.AiChatFeedbackInfoVO;
import com.jeesharp.business.modules.ai.vo.AiChatFeedbackListVO;
import com.jeesharp.business.modules.ai.vo.AiChatFeedbackQueryVO;
import com.jeesharp.business.modules.member.service.MemberService;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.pojo.query.PageRespVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * AI 客服反馈应用服务：后台反馈查询、维护及会话/消息/会员展示信息编排。
 *
 * @author jeesharp
 * @since 2026-06-04
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class AiChatFeedbackApplicationService {

    private final AiChatFeedbackService aiChatFeedbackService;
    private final AiChatSessionService aiChatSessionService;
    private final AiChatMessageService aiChatMessageService;
    private final MemberService memberService;

    public AiChatFeedbackInfoVO get(String id) {
        AiChatFeedback entity = aiChatFeedbackService.get(id);
        if (entity == null) {
            return null;
        }
        AiChatFeedbackInfoVO vo = AiChatFeedbackConvert.INSTANCE.toInfoVO(entity);
        enrichInfoDisplay(vo);
        return vo;
    }

    public PageRespVO<AiChatFeedbackListVO> findPage(Page<AiChatFeedback> page, AiChatFeedbackQueryVO query) {
        AiChatFeedbackQueryVO prepared = prepareQuery(query);
        if (prepared == null) {
            return emptyPage(page);
        }
        Page<AiChatFeedback> result = aiChatFeedbackService.findPage(page, prepared);
        PageRespVO<AiChatFeedbackListVO> pageVo = AiChatFeedbackConvert.INSTANCE.toPageRespVO(result);
        enrichListDisplay(pageVo.getRecords());
        return pageVo;
    }

    @Transactional(readOnly = false)
    public void save(AiChatFeedbackSaveDTO dto) {
        AiChatFeedback entity = AiChatFeedbackConvert.INSTANCE.toEntity(dto);
        if (StrUtil.isBlank(dto.getId())) {
            aiChatFeedbackService.createFeedback(entity);
            return;
        }
        aiChatFeedbackService.updateFeedback(entity);
    }

    @Transactional(readOnly = false)
    public void delete(String ids) {
        aiChatFeedbackService.batchDelete(StrUtil.splitTrim(ids, ','));
    }

    /**
     * 管理端名称类筛选：会话标题/编码、消息内容、会员关键词 → 主键 IN。
     */
    private AiChatFeedbackQueryVO prepareQuery(AiChatFeedbackQueryVO query) {
        AiChatFeedbackQueryVO q = query != null ? query : new AiChatFeedbackQueryVO();
        if (StrUtil.isNotBlank(q.getMemberKeyword())) {
            List<String> memberIds = memberService.findIdsByKeyword(q.getMemberKeyword().trim());
            q.setMemberKeyword(null);
            if (CollUtil.isEmpty(memberIds)) {
                return null;
            }
            q.setMemberIdIn(memberIds);
        }
        if (StrUtil.isNotBlank(q.getSessionTitle())) {
            List<String> sessionIds = aiChatSessionService.findIdsByTitleOrCodeLike(q.getSessionTitle().trim());
            q.setSessionTitle(null);
            if (CollUtil.isEmpty(sessionIds)) {
                return null;
            }
            q.setSessionIdIn(sessionIds);
        }
        if (StrUtil.isNotBlank(q.getMessageContent())) {
            List<String> messageIds = aiChatMessageService.findIdsByContentLike(q.getMessageContent().trim());
            q.setMessageContent(null);
            if (CollUtil.isEmpty(messageIds)) {
                return null;
            }
            q.setMessageIdIn(messageIds);
        }
        return q;
    }

    private void enrichListDisplay(List<AiChatFeedbackListVO> rows) {
        if (CollUtil.isEmpty(rows)) {
            return;
        }
        memberService.enrichMemberDisplay(rows);
        List<String> sessionIds = rows.stream()
            .map(AiChatFeedbackListVO::getSessionId)
            .filter(StrUtil::isNotBlank)
            .distinct()
            .toList();
        List<String> messageIds = rows.stream()
            .map(AiChatFeedbackListVO::getMessageId)
            .filter(StrUtil::isNotBlank)
            .distinct()
            .toList();
        Map<String, String> sessionLabelMap = aiChatSessionService.mapSessionLabelByIds(sessionIds);
        Map<String, String> messagePreviewMap = aiChatMessageService.mapMessageContentPreviewByIds(messageIds);
        for (AiChatFeedbackListVO row : rows) {
            if (StrUtil.isNotBlank(row.getSessionId())) {
                String sessionTitle = sessionLabelMap.get(row.getSessionId());
                row.setSessionTitle(StrUtil.blankToDefault(sessionTitle, row.getSessionId()));
            }
            if (StrUtil.isNotBlank(row.getMessageId())) {
                row.setMessageContent(messagePreviewMap.get(row.getMessageId()));
            }
        }
    }

    private void enrichInfoDisplay(AiChatFeedbackInfoVO vo) {
        if (vo == null) {
            return;
        }
        memberService.enrichMemberDisplay(vo);
        if (StrUtil.isNotBlank(vo.getSessionId())) {
            Map<String, String> sessionMap = aiChatSessionService.mapSessionLabelByIds(List.of(vo.getSessionId()));
            vo.setSessionTitle(sessionMap.get(vo.getSessionId()));
        }
        if (StrUtil.isNotBlank(vo.getMessageId())) {
            Map<String, String> messageMap = aiChatMessageService.mapMessageContentPreviewByIds(List.of(vo.getMessageId()));
            vo.setMessageContent(messageMap.get(vo.getMessageId()));
        }
    }

    private static PageRespVO<AiChatFeedbackListVO> emptyPage(Page<AiChatFeedback> page) {
        PageRespVO<AiChatFeedbackListVO> empty = new PageRespVO<>();
        empty.setRecords(Collections.emptyList());
        empty.setTotal(0L);
        empty.setPageNo(page != null ? page.getPageNo() : 1L);
        empty.setPageSize(page != null ? page.getPageSize() : 10L);
        return empty;
    }
}
