package com.casic.missiles.service.Impl.system;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.core.application.context.AbstractPermissionContext;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.system.PushUserMessage;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.sys.MessagePushMapper;
import com.casic.missiles.model.system.UserPush;
import com.casic.missiles.model.workbench.WorkbenchRemindMessage;
import com.casic.missiles.service.system.IMessagePushService;
import com.casic.missiles.utils.PushList;
import com.gexin.rp.sdk.base.IPushResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;

@Slf4j
@Service
@AllArgsConstructor
public class MessagePushServiceImpl extends ServiceImpl<MessagePushMapper, UserPush> implements IMessagePushService {

    private final AbstractPermissionContext permissionService;

    /**
     * 注册个推信息
     */
    @Override
    public ReturnDTO registerGeTui(String clientid) {
        Long userId = permissionService.getAuthService().getLoginUser().getId();
        UserPush userPush = initUserPush(userId, clientid);
        UserPush old = this.baseMapper.getPushByUserId(userId, userPush.getType());
        int addFlag = 0;
        if (ObjectUtil.isEmpty(old)) {
            addFlag = this.baseMapper.insert(userPush);
        }
        if (addFlag > 0) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public ReturnDTO setEnable(int enable) {
        QueryWrapper<UserPush> pushQueryWrapper = new QueryWrapper<>();
        Long userId = permissionService.getAuthService().getLoginUser().getId();
        pushQueryWrapper.eq("user_id", userId);
        UserPush userPush = new UserPush();
        userPush.setEnable(enable);
        int updateFlag = this.baseMapper.update(userPush, pushQueryWrapper);
        if (updateFlag > 0) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    /**
     * 获取用户推送信息
     */
    @Override
    public ReturnDTO<UserPush> getUserPush() {
        Long userId = permissionService.getAuthService().getLoginUser().getId();
        QueryWrapper<UserPush> pushQueryWrapper = new QueryWrapper<>();
        pushQueryWrapper.eq("user_id", userId);
        List<UserPush> userPushList = this.baseMapper.selectList(pushQueryWrapper);
        Optional<UserPush> userPushOptional = userPushList.stream().findFirst();
        UserPush userPush = userPushOptional.isPresent() ? userPushOptional.get() : null;
        return ObjectUtil.isNotEmpty(userPush) ? ReturnUtil.success(userPush) :
                ReturnUtil.failed(BusinessExceptionEnum.HANDLE_FAILED.getMessage());
    }


    @Override
    public Boolean pushToUser(WorkbenchRemindMessage remindMessage) {
        PushUserMessage pushUserMessage = pushToUserTemplate(remindMessage);
        List<String> enableClientList = this.baseMapper.getEnableClientList(pushUserMessage.getUserIds());
        if (enableClientList.size() > 0) {
            IPushResult pushResult = PushList.doPushToUser(enableClientList, pushUserMessage.getTitle(), pushUserMessage.getAppMsg());
            if ("ok".equals(pushResult.getResponse().get("result").toString())) {
                log.debug("APP消息推送成功，客户端列表为{}",JSONObject.toJSON(enableClientList));
                return true;
            }
        }
        log.info("APP消息推送推送失败，发送客户端缺失或发送失败，客户端列表为{}",JSONObject.toJSON(enableClientList));
        return false;
    }

    private PushUserMessage pushToUserTemplate(WorkbenchRemindMessage remindMessage) {
        PushUserMessage pushUserMessage = new PushUserMessage();
        List<Long> userIds=new ArrayList<>();
        if ("部门检测".equals(remindMessage.getMessageTopic())) {
            userIds.addAll(this.baseMapper.getUserIdsByDeptId(remindMessage.getRemindDeptId()));
        } else {
            userIds.add(remindMessage.getRemindId());
        }
        pushUserMessage.setUserIds(userIds);
        pushUserMessage.setTitle(remindMessage.getMessageTitle());
        pushUserMessage.setAppMsg(JSONObject.toJSONString(remindMessage));
        return pushUserMessage;
    }

    private UserPush initUserPush(Long userId, String clientid) {
        UserPush userPush = new UserPush();
        userPush.setType("GT");
        userPush.setUserId(userId);
        userPush.setClientId(clientid);
        userPush.setEnable(1);
        return userPush;
    }

}
