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.WhatsAppMessageRequest;
import com.alibaba.fastjson2.JSON;

import java.util.List;
import java.util.Collection;
import java.util.Date;

/**
 * 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());
        lqw.eq(bo.getEndTime() != null, WhatsAppHistory::getEndTime, bo.getEndTime());
        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 receiveMessage(WhatsAppMessageRequest request) {
        log.info("接收到WhatsApp消息 - sessionId: {}, userAccount: {}",
            request.getSessionId(), request.getUserAccount());

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

        // 2. 保存对话历史
        WhatsAppHistoryBo historyBo = new WhatsAppHistoryBo();
        historyBo.setSessionId(request.getSessionId());
        historyBo.setUserAccount(request.getUserAccount());
        historyBo.setConversationJson(JSON.toJSONString(request.getConversationHistory()));
        historyBo.setStartTime(new Date());

        return insertByBo(historyBo);
    }
}
