package com.mmc.iuav.user.service.impl;

import com.mmc.iuav.page.PageResult;
import com.mmc.iuav.response.ResultBody;
import com.mmc.iuav.user.dao.MessageDao;
import com.mmc.iuav.user.dao.UserServiceDao;
import com.mmc.iuav.user.entity.*;
import com.mmc.iuav.user.model.qo.MessageQO;
import com.mmc.iuav.user.model.qo.MessageUserQO;
import com.mmc.iuav.user.model.vo.SystemMessageVO;
import com.mmc.iuav.user.model.vo.UserMessageVO;
import com.mmc.iuav.user.service.MessageService;
import com.mmc.iuav.user.util.ScheduledTaskUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private UserServiceDao userServiceDao;

    @Autowired
    private ScheduledTaskUtil scheduledTaskUtil;
    @Override
    public ResultBody insertSystemMessage(SystemMessageVO messageVO) {
        SystemMessageDO systemMessageDO = new SystemMessageDO(messageVO);
        if(messageDao.insertSystemMessage(systemMessageDO) != 0){
            return ResultBody.success("消息发布成功");
        }
        return ResultBody.error("消息发布失败");
    }

    @Override
    public ResultBody selectSystemMessageById(Integer id) {
        return ResultBody.success(messageDao.selectSystemMessageById(id));
    }

    @Override
    public PageResult selectAllSystemMessage(MessageQO messageQO) {
        int count = messageDao.countSystemMessage();
        if (count == 0) {
            return PageResult.buildPage(messageQO.getPageNo(), messageQO.getPageSize(), count);
        }
        Integer pageNo = messageQO.getPageNo();
        messageQO.buildCurrentPage();
        List<SystemMessageDO> messageList = messageDao.selectAllSystemMessage(messageQO);
        return PageResult.buildPage(pageNo, messageQO.getPageSize(), count, messageList);
    }
    @Override
    public ResultBody removeMessage(Integer id) {
        if(messageDao.removeMessage(id) != 0){
            messageDao.removeReceiverMessageByMessageId(id);
            return ResultBody.success("删除成功");
        }
        return ResultBody.error("删除失败");
    }
    @Override
    public PageResult selectAllSystemMessageByReceive(Integer userId, MessageQO messageQO) {
        if(userId == null){
            ResultBody.error("未登录");
        }
        int count = messageDao.countSystemMessage();
        if (count == 0) {
            return PageResult.buildPage(messageQO.getPageNo(), messageQO.getPageSize(), count);
        }
        Integer pageNo = messageQO.getPageNo();
        messageQO.buildCurrentPage();
        List<SystemMessageDO> messagesDO = new ArrayList<>();
        List<SystemMessageDO> messages = messageDao.selectAllSystemMessage(messageQO);
        for (SystemMessageDO message : messages) {
            if(messageDao.selectReceiverMessage(userId, message.getId()) != 0){
                // 已读
                message.setRead(true);
            }
            // 读过但是已经删除
            if(messageDao.selectReceiverMessageByDel(userId, message.getId()) != 0){
                continue;
            }
            messagesDO.add(message);
        }
        return PageResult.buildPage(pageNo, messageQO.getPageSize(), count, messagesDO);
    }

    @Override
    public ResultBody showSystemMessageByUser(Integer userId, Integer messageId) {
        if(userId == null){
            ResultBody.error("未登录");
        }
        SystemMessageDO message = messageDao.selectSystemMessageById(messageId);
        if(message == null){
            return ResultBody.success(message);
        }
        //没有读过,查看之后标为已读
        if(messageDao.selectReceiverMessage(userId, messageId) == 0){
            messageDao.insertReceiverMessage(userId,messageId);
        }
        message.setRead(true);
        // 读过但是已经删除
        if(messageDao.selectReceiverMessageByDel(userId, message.getId()) != 0){
            message = null;
        }
        return ResultBody.success(message);
    }

    @Override
    public ResultBody removeMessageByUser(Integer userId, Integer messageId) {
        if(messageDao.removeReceiverMessage(userId, messageId) != 0){
            return ResultBody.success("删除成功");
        }
        return ResultBody.error("删除失败");
    }

    @Override
    public ResultBody insertUserMessage(UserMessageVO messageVO,Integer senderUserId) {
        UserMessageDO userMessageDO = new UserMessageDO(messageVO);
        if(senderUserId == null){
            return ResultBody.success("消息发送失败,请先登录");
        }
        userMessageDO.setSenderUserId(senderUserId);
        if(messageDao.insertUserMessage(userMessageDO) != 0){
            UserAccountDO userAccount = userServiceDao.getUserAccountById(userMessageDO.getReceiverUserId());
            UserDO userDO = userAccount.buildUserDO();
            scheduledTaskUtil.create(userDO);
            if(messageDao.isUserMessageLog(userMessageDO.getReceiverUserId(), userMessageDO.getSenderUserId()) == null){
                UserMessageLogDO userMessageLogDO = new UserMessageLogDO();
                userMessageLogDO.setSenderUserId(userMessageDO.getSenderUserId());
                userMessageLogDO.setReceiverUserId(userMessageDO.getReceiverUserId());
                messageDao.insertUserMessageLog(userMessageLogDO);
            }
            Integer logId = messageDao.isUserMessageLog(userMessageDO.getSenderUserId(),userMessageDO.getReceiverUserId());
            if(logId == null){
                UserMessageLogDO userMessageLogDO = new UserMessageLogDO();
                userMessageLogDO.setSenderUserId(userMessageDO.getReceiverUserId());
                userMessageLogDO.setReceiverUserId(userMessageDO.getSenderUserId());
                userMessageLogDO.setMessageCount(1);
                messageDao.insertUserMessageLog(userMessageLogDO);
            }else {
                messageDao.updateUserMessageLog(logId);
            }
            return ResultBody.success("消息发送成功");
        }
        return ResultBody.error("消息发送失败");
    }

    @Override
    public PageResult selectUserMessage(MessageUserQO messageQO,Integer senderUserId) {
        scheduledTaskUtil.destroy(senderUserId);
        int count = messageDao.countUserMessage(messageQO.getReceiverUserId(),senderUserId);
        if (count == 0) {
            return PageResult.buildPage(messageQO.getPageNo(), messageQO.getPageSize(), count);
        }
        Integer pageNo = messageQO.getPageNo();
        messageQO.buildCurrentPage();
        List<UserMessageDO> messageList = messageDao.selectUserMessage(messageQO,senderUserId);
//        Integer logId = messageDao.isUserMessageLog(senderUserId,messageQO.getReceiverUserId());
//        if(logId != null){
//            messageDao.updateUserMessageCount(logId);
//        }
        Integer logId2 = messageDao.isUserMessageLog(messageQO.getReceiverUserId(),senderUserId);
        if(logId2 != null){
            messageDao.updateUserMessageCount(logId2);
        }
        return PageResult.buildPage(pageNo, messageQO.getPageSize(), count, messageList);
    }

    @Override
    public ResultBody selectUserList(Integer senderUserId) {
        List<UserDO> userAccountDOList = new ArrayList<>();
        List<UserMessageLogDO> list = messageDao.selectUserList(senderUserId);
        for (UserMessageLogDO userMessageLogDO : list) {
            UserAccountDO userAccount = userServiceDao.getUserAccountById(userMessageLogDO.getReceiverUserId());
            UserDO userDO = userAccount.buildUserDO();
            userDO.setUnreadCount(userMessageLogDO.getMessageCount());
            UserMessageDO userMessageDO = messageDao.selectEndUserMessage(userMessageLogDO.getReceiverUserId(), senderUserId);
            if(userMessageDO.getContent() != null){
                userDO.setEndMessage(userMessageDO.getContent());
            }else {
                userDO.setEndMessage(userMessageDO.getImgUrl());
            }
            userAccountDOList.add(userDO);
        }
        return ResultBody.success(userAccountDOList);
    }

    @Override
    public ResultBody removeUserMessage(Integer id) {
        UserMessageDO userMessageDO = messageDao.selectUserMessageById(id);
        Date createTime = userMessageDO.getCreateTime();
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTime);
        if(isOverThreeMinutes(time)){
            return ResultBody.error("消息发送已经超过三分钟，撤回失败");
        }
        if(messageDao.removeUserMessage(id) != 0){
            Integer logId = messageDao.isUserMessageLog(userMessageDO.getSenderUserId(),userMessageDO.getReceiverUserId());
            if(logId != null){
                messageDao.removeUserMessageCount(logId);
            }
            return ResultBody.success("消息撤回成功已撤回");
        }
        return ResultBody.error("消息撤回失败");
    }

    @Override
    public ResultBody removeUser(Integer senderUserId, Integer receiverUserId) {
        Integer logId = messageDao.isUserMessageLog(receiverUserId,senderUserId);
        if(logId != null){
            messageDao.removeUserMessageLog(logId);
            return ResultBody.success("删除成功");
        }
        return ResultBody.error("删除失败");
    }

    public static boolean isOverThreeMinutes(String createTime) {
        // 定义日期时间格式化对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 将字符串格式的时间转换为 LocalDateTime 对象
        LocalDateTime createDateTime = LocalDateTime.parse(createTime, formatter);
        // 计算当前时间与创建时间的时间差（单位：秒）
        long secondsDiff = ChronoUnit.SECONDS.between(createDateTime, LocalDateTime.now());
        // 如果时间差大于 180 秒（即三分钟），返回 true
        return secondsDiff > 180;
    }
}
