package com.luojia_channel.modules.feedback.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luojia_channel.common.domain.page.PageRequest;
import com.luojia_channel.common.domain.page.PageResponse;
import com.luojia_channel.modules.feedback.dto.FeedbackTicketBasicInfoDTO;
import com.luojia_channel.modules.feedback.dto.FeedbackTicketPageQueryDTO;
import com.luojia_channel.modules.feedback.entity.FeedbackTicket;
import com.luojia_channel.modules.feedback.mapper.FeedbackTicketMapper;
import com.luojia_channel.modules.feedback.mq.domain.DelayHandleTicketMessage;
import com.luojia_channel.modules.feedback.mq.producer.FeedbackMessageProducer;
import com.luojia_channel.modules.feedback.service.FeedbackTicketService;
import com.luojia_channel.modules.user.entity.User;
import com.luojia_channel.modules.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class FeedbackTicketServiceImpl extends ServiceImpl<FeedbackTicketMapper, FeedbackTicket> implements FeedbackTicketService {

    private final UserMapper userMapper;
    private final FeedbackMessageProducer feedbackMessageProducer;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createFeedbackTicket(FeedbackTicket feedbackTicket) {
        feedbackTicket.setCreateTime(LocalDateTime.now());
        feedbackTicket.setStatus(1);
        if(!save(feedbackTicket))
            throw new RuntimeException("保存工单失败");
        // 发送延时消息
        feedbackMessageProducer.sendMessage(BeanUtil.copyProperties(feedbackTicket, DelayHandleTicketMessage.class));
        return feedbackTicket.getId();
    }

    @Override
    public void updateFeedbackTicket(FeedbackTicket feedbackTicket) {
        updateById(feedbackTicket);
    }

    @Override
    public List<FeedbackTicket> getPersonalFeedbackTickets(Long userId) {
        LambdaQueryWrapper<FeedbackTicket> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FeedbackTicket::getUserId, userId);
        return list(queryWrapper);
    }

    @Override
    public PageResponse<FeedbackTicketBasicInfoDTO> pageFeedbackTicket(FeedbackTicketPageQueryDTO feedbackTicketPageQueryDTO) {
        LambdaQueryWrapper<FeedbackTicket> queryWrapper = new LambdaQueryWrapper<>();
        if (feedbackTicketPageQueryDTO.getFeedbackType() != null) {
            queryWrapper.eq(FeedbackTicket::getFeedbackType, feedbackTicketPageQueryDTO.getFeedbackType());
        }
        if (feedbackTicketPageQueryDTO.getStatus() != null) {
            queryWrapper.eq(FeedbackTicket::getStatus, feedbackTicketPageQueryDTO.getStatus());
        }
        queryWrapper.orderByDesc(FeedbackTicket::getCreateTime);

        Page<FeedbackTicket> page = new Page<>(feedbackTicketPageQueryDTO.getCurrent(), feedbackTicketPageQueryDTO.getSize());
        IPage<FeedbackTicket> feedbackTicketPage = baseMapper.selectPage(page, queryWrapper);

        List<Long> userIds = new ArrayList<>();
        feedbackTicketPage.getRecords().forEach(ticket -> userIds.add(ticket.getUserId()));
        List<User> users = userMapper.selectBatchIds(userIds);
        Map<Long, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getId, user -> user));

        List<FeedbackTicketBasicInfoDTO> feedbackTicketBasicInfoDTOS = new ArrayList<>();
        feedbackTicketPage.getRecords().forEach(ticket -> {
            FeedbackTicketBasicInfoDTO dto = new FeedbackTicketBasicInfoDTO();
            BeanUtil.copyProperties(ticket, dto);
            User user = userMap.getOrDefault(ticket.getUserId(), new User());
            dto.setUserName(user.getUsername());
            dto.setUserAvatar(user.getAvatar());
            feedbackTicketBasicInfoDTOS.add(dto);
        });

        return PageResponse.<FeedbackTicketBasicInfoDTO>builder()
                .current(feedbackTicketPage.getCurrent())
                .size(feedbackTicketPage.getSize())
                .total(feedbackTicketPage.getTotal())
                .records(feedbackTicketBasicInfoDTOS)
                .build();
    }

    @Override
    public void processDelayedFeedback(Long ticketId) {
        // 查询工单
        FeedbackTicket ticket = getById(ticketId);
        if (ticket == null || ticket.getStatus().equals(3)) {
            return;
        }
        // 处理延时任务，更新工单状态为超时
        ticket.setStatus(4); //
        updateById(ticket);
        // TODO 向管理员发送消息

    }
}
