package org.dromara.talk.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.dromara.talk.domain.bo.WhatsAppHistoryBo;
import org.dromara.talk.domain.vo.WhatsAppHistoryVo;
import org.dromara.talk.domain.WhatsAppHistory;
import org.dromara.talk.mapper.WhatsAppHistoryMapper;
import org.dromara.talk.service.IWhatsAppHistoryService;
import org.dromara.talk.service.IWhatsAppUserService;
import org.dromara.talk.domain.bo.WhatsAppUserBo;
import org.dromara.talk.domain.dto.ConversationMessageRequest;
import com.alibaba.fastjson2.JSON;

import java.util.List;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import com.alibaba.fastjson2.TypeReference;

/**
 * WhatsApp历史记录Service业务层处理
 *
 * @author Lion Li
 *  2026-02-06
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class WhatsAppHistoryServiceImpl implements IWhatsAppHistoryService {

    private final WhatsAppHistoryMapper baseMapper;
    private final IWhatsAppUserService whatsAppUserService;

    /**
     * 查询WhatsApp历史记录
     *
     * @param id 主键
     * @return WhatsApp历史记录
     */
    @Override
    public WhatsAppHistoryVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询WhatsApp历史记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return WhatsApp历史记录分页列表
     */
    @Override
    public TableDataInfo<WhatsAppHistoryVo> queryPageList(WhatsAppHistoryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WhatsAppHistory> lqw = buildQueryWrapper(bo);
        Page<WhatsAppHistoryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的WhatsApp历史记录列表
     *
     * @param bo 查询条件
     * @return WhatsApp历史记录列表
     */
    @Override
    public List<WhatsAppHistoryVo> queryList(WhatsAppHistoryBo bo) {
        LambdaQueryWrapper<WhatsAppHistory> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<WhatsAppHistory> buildQueryWrapper(WhatsAppHistoryBo bo) {
        LambdaQueryWrapper<WhatsAppHistory> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(WhatsAppHistory::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getSessionId()), WhatsAppHistory::getSessionId, bo.getSessionId());
        lqw.eq(StringUtils.isNotBlank(bo.getUserAccount()), WhatsAppHistory::getUserAccount, bo.getUserAccount());
        lqw.eq(bo.getStartTime() != null, WhatsAppHistory::getStartTime, bo.getStartTime());
        return lqw;
    }

    /**
     * 新增WhatsApp历史记录
     *
     * @param bo WhatsApp历史记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(WhatsAppHistoryBo bo) {
        WhatsAppHistory add = MapstructUtils.convert(bo, WhatsAppHistory.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改WhatsApp历史记录
     *
     * @param bo WhatsApp历史记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(WhatsAppHistoryBo bo) {
        WhatsAppHistory update = MapstructUtils.convert(bo, WhatsAppHistory.class);
        return baseMapper.updateById(update) > 0;
    }


    /**
     * 校验并批量删除WhatsApp历史记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 接收并保存WhatsApp消息
     *
     * @param request WhatsApp消息请求
     * @return 是否保存成功
     */
    @Override
    public Boolean receiveConversationMessage(ConversationMessageRequest request) {
        log.info("接收到对话消息 - conversationId: {}, userId: {}, round: {}",
            request.getConversationId(), request.getUserId(), request.getRound());

        // 1. 检查并保存用户
        WhatsAppUserBo userBo = new WhatsAppUserBo();
        userBo.setUserAccount(request.getUserId());
        try {
            whatsAppUserService.insertByBo(userBo);
            log.info("新用户已保存: {}", request.getUserId());
        } catch (Exception e) {
            log.debug("用户可能已存在: {}", request.getUserId());
        }

        // 2. 查询是否已存在该会话的记录
        WhatsAppHistoryBo queryBo = new WhatsAppHistoryBo();
        queryBo.setSessionId(request.getConversationId());
        List<WhatsAppHistoryVo> existingRecords = queryList(queryBo);

        List<Map<String, String>> conversationHistory;
        WhatsAppHistoryBo historyBo;

        if (!existingRecords.isEmpty()) {
            // 已存在记录，读取并追加
            WhatsAppHistoryVo existing = existingRecords.get(0);
            String existingJson = existing.getConversationJson();
            conversationHistory = JSON.parseObject(existingJson, new TypeReference<List<Map<String, String>>>() {});

            historyBo = new WhatsAppHistoryBo();
            historyBo.setId(existing.getId());
        } else {
            // 新会话，创建新记录
            conversationHistory = new ArrayList<>();
            historyBo = new WhatsAppHistoryBo();
            historyBo.setSessionId(request.getConversationId());
            historyBo.setUserAccount(request.getUserId());
            historyBo.setStartTime(new Date());
        }

        // 3. 追加新的对话轮次（user消息 + assistant消息）
        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", request.getQuery());
        userMessage.put("timestamp", request.getTimestamp());
        userMessage.put("round", String.valueOf(request.getRound()));
        conversationHistory.add(userMessage);

        Map<String, String> assistantMessage = new HashMap<>();
        assistantMessage.put("role", "assistant");
        assistantMessage.put("content", request.getAgent());
        assistantMessage.put("timestamp", request.getTimestamp());
        assistantMessage.put("round", String.valueOf(request.getRound()));
        conversationHistory.add(assistantMessage);

        // 4. 按round排序，同一轮内user在assistant之前
        conversationHistory.sort((m1, m2) -> {
            int round1 = Integer.parseInt(m1.getOrDefault("round", "0"));
            int round2 = Integer.parseInt(m2.getOrDefault("round", "0"));
            int roundCompare = Integer.compare(round1, round2);
            if (roundCompare != 0) {
                return roundCompare;
            }
            // 同一轮内，user 在 assistant 之前
            String role1 = m1.getOrDefault("role", "");
            String role2 = m2.getOrDefault("role", "");
            if ("user".equals(role1) && "assistant".equals(role2)) {
                return -1;
            } else if ("assistant".equals(role1) && "user".equals(role2)) {
                return 1;
            }
            return 0;
        });

        // 5. 保存或更新记录
        historyBo.setConversationJson(JSON.toJSONString(conversationHistory));

        if (historyBo.getId() != null) {
            return updateByBo(historyBo);
        } else {
            return insertByBo(historyBo);
        }
    }
}
