package org.dromara.main.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.main.domain.CsMessage;
import org.dromara.main.domain.CsTicket;
import org.dromara.main.domain.bo.CsTicketBo;
import org.dromara.main.domain.vo.CsTicketVo;
import org.dromara.main.mapper.CsMessageMapper;
import org.dromara.main.mapper.CsTicketMapper;
import org.dromara.main.service.ICsTicketService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collection;

@RequiredArgsConstructor
@Service
public class CsTicketServiceImpl implements ICsTicketService {
    private final CsTicketMapper baseMapper;
    private final CsMessageMapper messageMapper;
    @Override
    public CsTicketVo queryById(String id) {
        CsTicketVo vo = baseMapper.selectVoById(id);
        if (vo != null && vo.getSessionId() != null) {
            // 根据 sessionId 关联查询所有沟通消息，按时间正序
            LambdaQueryWrapper<CsMessage> lqw = Wrappers.lambdaQuery();
            lqw.eq(CsMessage::getSessionId, vo.getSessionId());
            lqw.orderByAsc(CsMessage::getSendTime);
            vo.setMessages(messageMapper.selectVoList(lqw));
        }
        return vo;
    }
    @Override
    public TableDataInfo<CsTicketVo> queryPageList(CsTicketBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CsTicket> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getId()), CsTicket::getId, bo.getId());
        lqw.eq(StringUtils.isNotBlank(bo.getUserId()), CsTicket::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getSource()), CsTicket::getSource, bo.getSource());
        lqw.eq(StringUtils.isNotBlank(bo.getCategory()), CsTicket::getCategory, bo.getCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), CsTicket::getStatus, bo.getStatus());
        lqw.orderByDesc(CsTicket::getCreateTime);

        Page<CsTicketVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }
    @Override
    public Boolean handleTicket(CsTicketBo bo) {
        CsTicket update = BeanUtil.toBean(bo, CsTicket.class);
        // 如果状态变更为 已完成 或 已废弃，记录结束时间
        if ("completed".equals(bo.getStatus()) || "abandoned".equals(bo.getStatus())) {
            update.setFinishTime(LocalDateTime.now());
        }
        return baseMapper.updateById(update) > 0;
    }
    @Override
    public Boolean deleteByIds(Collection<String> ids) {
        return baseMapper.deleteByIds(ids) > 0;
    }
}
