package org.springblade.modules.app.manager;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.wn.common.perfmonitor.annotation.ServiceTimeLog;
import com.wn.common.validator.Validator;
import org.springblade.modules.app.common.dto.AppUserIdDTO;
import org.springblade.modules.app.common.dto.MessageLoggingDTO;
import org.springblade.modules.app.common.enums.MessageEnum;
import org.springblade.modules.app.common.enums.MessageStatusEnum;
import org.springblade.modules.app.common.query.AppUserIdQuery;
import org.springblade.modules.app.constant.ErrorCode;
import org.springblade.modules.app.service.IAppUserIdService;
import org.springblade.modules.app.service.IMessageLoggingService;
import org.springblade.modules.app.utils.ErrorMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author huyinuo
 */
@Slf4j
@Component
public class MessageLoggingManager {

    @Autowired
    private PushApi pushApi;

    @Autowired
    private IAppUserIdService appUserIdService;

    @Autowired
    private IMessageLoggingService messageLoggingService;

    /**
     * 消息处理
     *
     * @param
     * @return
     */
    @ServiceTimeLog
    @Async
    public void messageHandling(Long userId, int messageCode) {
        Validator.notNull(userId, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(messageCode, ErrorCode.INPUT_PARAMETERS_NULL);

        // 获取用户最新的cid
        AppUserIdQuery appUserIdQuery = new AppUserIdQuery();
        appUserIdQuery.setUserId(userId);
        List<AppUserIdDTO> appUserIdDTOList = appUserIdService.listAppUserIdByUserId(appUserIdQuery);
        Optional<AppUserIdDTO> appUserIdDTO = appUserIdDTOList.stream().max(Comparator.comparing(AppUserIdDTO::getModifiedTime));
//        String clientId = appUserIdDTO.get().getClientId();
        String clientId = appUserIdDTO.orElse(new AppUserIdDTO()).getClientId();

        if (ObjectUtils.isEmpty(clientId)) {
            log.info("消息处理对象无cid，对象id为：{}", userId);
            return;
        }

        // 进行信息推送
        Validator.notNull(MessageEnum.findByCode(messageCode), ErrorMsg.NEW("传入消息编码超出枚举范围！"));
        Boolean result = geTui(messageCode, clientId);

        // 记录本次消息推送至数据库
        MessageLoggingDTO messageLoggingDTO = new MessageLoggingDTO();
        messageLoggingDTO.setUserId(userId);
        messageLoggingDTO.setClientId(clientId);
        messageLoggingDTO.setMessageCode((long) messageCode);
        messageLoggingDTO.setMessageContent(MessageEnum.findByCode(messageCode).getText());

        messageLoggingDTO.setStatus(result ? MessageStatusEnum.SUCCESS.getCode() : MessageStatusEnum.FAILED.getCode());
        messageLoggingService.addMessageLogging(messageLoggingDTO);
    }

    /**
     * 通过cid向用户发送消息
     *
     * @param
     * @return
     */
    public Boolean geTui(int messageCode, String clientId) {
        //根据cid进行单推
        PushDTO<Audience> pushDTO = new PushDTO<>();
        // 设置推送参数
        pushDTO.setRequestId(System.currentTimeMillis() + "");

        PushMessage pushMessage = new PushMessage();
        pushDTO.setPushMessage(pushMessage);
        GTNotification notification = new GTNotification();
        pushMessage.setNotification(notification);
        notification.setTitle("畜牧通消息");
        notification.setBody(MessageEnum.findByCode(messageCode).getText());
        notification.setClickType("startapp");

        // 设置接收人信息
        Audience audience = new Audience();
        pushDTO.setAudience(audience);
        audience.addCid(clientId);

        // 进行cid单推
        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
        if (apiResult.isSuccess()) {
            log.info("消息推送成功，推送结果：{}", apiResult.getData());
            return true;
        } else {
            log.info("消息推送失败，推送码为：{}， 推送消息为：{}", apiResult.getCode(), apiResult.getMsg());
            return false;
        }
    }
}
