package com.ruoyi.jarvis.service.impl;

import com.ruoyi.jarvis.domain.WeComInboundTrace;
import com.ruoyi.jarvis.domain.dto.WeComChatSession;
import com.ruoyi.jarvis.domain.dto.WeComInboundRequest;
import com.ruoyi.jarvis.domain.dto.WeComTestDataCleanRequest;
import com.ruoyi.jarvis.mapper.WeComInboundTraceMapper;
import com.ruoyi.jarvis.service.IWeComChatSessionService;
import com.ruoyi.jarvis.service.ILogisticsService;
import com.ruoyi.jarvis.service.IWeComInboundTraceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class WeComInboundTraceServiceImpl implements IWeComInboundTraceService {

    private static final Logger log = LoggerFactory.getLogger(WeComInboundTraceServiceImpl.class);

    @Resource
    private WeComInboundTraceMapper weComInboundTraceMapper;
    @Resource
    private IWeComChatSessionService weComChatSessionService;
    @Resource
    private ILogisticsService logisticsService;

    @Override
    public void recordInbound(WeComInboundRequest request, String reply) {
        if (request == null || !StringUtils.hasText(request.getFromUserName())) {
            return;
        }
        try {
            String from = request.getFromUserName().trim();
            WeComInboundTrace trace = new WeComInboundTrace();
            trace.setMsgId(request.getMsgId());
            trace.setAgentId(request.getAgentId());
            trace.setCorpId(request.getToUserName());
            trace.setFromUserName(from);
            trace.setContent(request.getContent());
            Long wxSec = request.getWxCreateTime();
            if (wxSec != null && wxSec > 0) {
                trace.setWxMsgTime(new Date(wxSec * 1000L));
            }
            trace.setReplyContent(reply != null ? reply : "");

            WeComChatSession session = weComChatSessionService.get(from);
            trace.setSessionActive(session != null ? 1 : 0);
            if (session != null) {
                trace.setSessionScene(session.getScene());
                trace.setSessionStep(session.getStep());
            }
            weComInboundTraceMapper.insertWeComInboundTrace(trace);
        } catch (Exception e) {
            log.warn("企微消息追踪落库失败: {}", e.toString());
        }
    }

    @Override
    public WeComInboundTrace selectWeComInboundTraceById(Long id) {
        return weComInboundTraceMapper.selectWeComInboundTraceById(id);
    }

    @Override
    public List<WeComInboundTrace> selectWeComInboundTraceList(WeComInboundTrace query) {
        return weComInboundTraceMapper.selectWeComInboundTraceList(query);
    }

    @Override
    public int deleteWeComInboundTraceByIds(Long[] ids) {
        return weComInboundTraceMapper.deleteWeComInboundTraceByIds(ids);
    }

    @Override
    public Map<String, Object> cleanTestData(WeComTestDataCleanRequest options) {
        if (options == null) {
            options = new WeComTestDataCleanRequest();
        }
        boolean trace = options.getClearTraceTable() == null || options.getClearTraceTable();
        boolean sessions = options.getClearWecomSessions() == null || options.getClearWecomSessions();
        boolean adhoc = options.getClearAdhocQueue() == null || options.getClearAdhocQueue();
        Map<String, Object> r = new LinkedHashMap<>();
        if (trace) {
            int n = weComInboundTraceMapper.deleteAllWeComInboundTrace();
            r.put("traceRowsDeleted", n);
            log.info("企微消息追踪表已清空 deletedRows={}", n);
        }
        if (sessions) {
            int n = weComChatSessionService.deleteAllWecomSessionsForTest();
            r.put("wecomSessionKeysDeleted", n);
        }
        if (adhoc) {
            logisticsService.clearAdhocPendingQueue();
            r.put("adhocQueueCleared", Boolean.TRUE);
        }
        return r;
    }
}
