package com.sikey.wa04.business.application.service.message;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sikey.wa04.business.application.converter.MessageConverter;
import com.sikey.wa04.business.domain.adapter.DeviceBindStateAdapter;
import com.sikey.wa04.business.domain.entity.ChildId;
import com.sikey.wa04.business.domain.entity.UserId;
import com.sikey.wa04.business.domain.entity.message.Message;
import com.sikey.wa04.business.domain.entity.message.MessageId;
import com.sikey.wa04.business.infrastructure.adapter.CacheConnectionStateManager;
import com.sikey.wa04.business.infrastructure.adapter.RedisMessageIdIncrementingAdapter;
import com.sikey.wa04.common.dto.message.ActivateCloudPhotoAlbumMessage;
import com.sikey.wa04.common.dto.message.NotifyParentsSuccessfulActivationMessage;
import com.sikey.wa04.common.dto.message.ReloginOnWwatchMessage;
import com.sikey.wa04.common.enums.MessageType;
import com.sikey.wa04.common.exception.BusinessException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.time.Instant;
import java.util.List;
import java.util.Objects;


/**
 * @Author: nelson
 * @Date: 2025/6/13
 * @Description: 移动云盘
 */
@Slf4j
@Service
public class McDiskMessageService {

    @Resource
    private CacheConnectionStateManager cacheConnectionStateManager;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private RedisMessageIdIncrementingAdapter messageIdIncrementingAdapter;

    @Resource
    private DeviceBindStateAdapter deviceBindStateAdapter;

    /**
     * 开通成功通知家长
     *
     * @param notifyParentsSuccessfulActivationMessage 请求
     * @return
     */
    public void notifyParentsSuccessfulActivation(NotifyParentsSuccessfulActivationMessage notifyParentsSuccessfulActivationMessage) {
        Message message = new Message()
                .setId(new MessageId(messageIdIncrementingAdapter.incr()))
                .setType(MessageType.NOTIFY_PARENTS_SUCCESSFUL_ACTIVATION)
                .setContent(notifyParentsSuccessfulActivationMessage.getContent())
                .setSenderId(notifyParentsSuccessfulActivationMessage.getSendId())
                .setReceiverId(List.of(notifyParentsSuccessfulActivationMessage.getRecvId()))
                .setSendTime(Instant.now());
        log.info("[开通成功通知家长]参数：{}", JSONUtil.toJsonPrettyStr(message));
        if (cacheConnectionStateManager.isOnline(new UserId(notifyParentsSuccessfulActivationMessage.getRecvId()))) {
            log.info("[开通成功通知家长]在线");
            WebSocketSession session = cacheConnectionStateManager.getSession(new UserId(notifyParentsSuccessfulActivationMessage.getRecvId()));
            if (Objects.nonNull(session)) {
                try {
                    session.sendMessage(
                            new TextMessage(objectMapper.writeValueAsString(MessageConverter.toMessaging(message))));
                } catch (Exception e) {
                    throw new BusinessException(HttpStatus.HTTP_INTERNAL_ERROR, e.getMessage());
                }
            }
        }
    }

    /**
     * 手表重新登录
     *
     * @param request 请求
     * @return
     */
    public void reloginOnWwatch(ReloginOnWwatchMessage request) {
        Message message = new Message()
                .setId(new MessageId(messageIdIncrementingAdapter.incr()))
                .setType(MessageType.RELOGIN_ON_WWATCH)
                .setContent(request.getContent())
                .setSenderId(request.getSendId())
                .setReceiverId(List.of(request.getRecvId()))
                .setSendTime(Instant.now());
        log.info("[手表重新登录]参数：{}", JSONUtil.toJsonPrettyStr(message));
        ChildId childId = deviceBindStateAdapter.getBinder(request.getRecvId());
        if (cacheConnectionStateManager.isOnline(new UserId(childId.getId()))) {
            log.info("[手表重新登录]在线");
            WebSocketSession session = cacheConnectionStateManager.getSession(new UserId(childId.getId()));
            if (Objects.nonNull(session)) {
                try {
                    message.setReceiverId(List.of(childId.getId()));
                    session.sendMessage(
                            new TextMessage(objectMapper.writeValueAsString(MessageConverter.toMessaging(message))));
                    log.info("[手表重新登录]发送消息成功");
                } catch (Exception e) {
                    throw new BusinessException(HttpStatus.HTTP_INTERNAL_ERROR, e.getMessage());
                }

            }
        }
    }

    /**
     * 通知手表开通云相册服务
     *
     * @param request 请求
     * @return
     */
    public void activateCloudPhotoAlbum(ActivateCloudPhotoAlbumMessage request) {
        Message message = new Message()
                .setId(new MessageId(messageIdIncrementingAdapter.incr()))
                .setType(MessageType.ACTIVATE_CLOUD_PHOTO_ALBUM_SERVICE)
                .setContent(request.getContent())
                .setSenderId(request.getSendId())
                .setReceiverId(List.of(request.getRecvId()))
                .setSendTime(Instant.now());
        log.info("[通知手表开通云相册服务]参数：{}", JSONUtil.toJsonPrettyStr(message));
        ChildId childId = deviceBindStateAdapter.getBinder(request.getRecvId());
        log.info("[通知手表开通云相册服务]参数childId：{}", JSONUtil.toJsonPrettyStr(childId));
        if (Objects.nonNull(childId)) {
            if (cacheConnectionStateManager.isOnline(new UserId(childId.getId()))) {
                WebSocketSession session = cacheConnectionStateManager.getSession(new UserId(childId.getId()));
                log.info("[通知手表开通云相册服务]获取会话：{}", JSONUtil.toJsonPrettyStr(cacheConnectionStateManager.getSession(new UserId(childId.getId()))));
                if (Objects.nonNull(session)) {
                    try {
                        message.setReceiverId(List.of(childId.getId()));
                        session.sendMessage(
                                new TextMessage(objectMapper.writeValueAsString(MessageConverter.toMessaging(message))));
                        log.info("[通知手表开通云相册服务]发送成功");
                    } catch (Exception e) {
                        throw new BusinessException(HttpStatus.HTTP_INTERNAL_ERROR, e.getMessage());
                    }
                }
            }
        }

    }

    /**
     * 通知家长授权
     *
     * @param request 请求
     * @return
     */
    public void notifyParentsAuthorization(NotifyParentsSuccessfulActivationMessage request) {
        Message message = new Message()
                .setId(new MessageId(messageIdIncrementingAdapter.incr()))
                .setType(MessageType.NOTIFY_PARENTS_AUTHORIZATION)
                .setContent(request.getContent())
                .setSenderId(request.getSendId())
                .setReceiverId(List.of(request.getRecvId()))
                .setSendTime(Instant.now());
        // log.info("[通知家长授权]入参：{}", JSONUtil.toJsonPrettyStr(message));
        if (cacheConnectionStateManager.isOnline(new UserId(request.getRecvId()))) {
            WebSocketSession session = cacheConnectionStateManager.getSession(new UserId(request.getRecvId()));
          //  log.info("[通知家长授权]参数：{}，会话：{}", JSONUtil.toJsonPrettyStr(message), session);
            if (Objects.nonNull(session)) {
                try {
                    log.info("[通知家长授权]参数：{}，会话：{}", JSONUtil.toJsonPrettyStr(message), session);
                    session.sendMessage(
                            new TextMessage(objectMapper.writeValueAsString(MessageConverter.toMessaging(message))));
                } catch (Exception e) {
                    throw new BusinessException(HttpStatus.HTTP_INTERNAL_ERROR, e.getMessage());
                }
            }
        }
    }
}
