package vip.xiaonuo.coldchain.core.alarm.service.messagepush.impl;

import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;
import vip.xiaonuo.coldchain.core.alarm.bean.SensorAlarm;
import vip.xiaonuo.coldchain.core.alarm.bean.SensorAlarmUser;
import vip.xiaonuo.coldchain.core.alarm.service.messagepush.MessagePushService;
import vip.xiaonuo.coldchain.modular.push.param.AlarmPushParam;
import vip.xiaonuo.coldchain.modular.push.utils.PushUtil;

import java.util.Date;
import java.util.stream.Collectors;

/**
 * 微信公众号通知推送服务
 *
 * @author jackzhou
 */
@Service("WECHAT")
public class WechatMessagePushService implements MessagePushService {

    @Override
    public boolean sendAlarmMessage(SensorAlarm alarm/*, SensorAlarmUser user*/) {
        AlarmPushParam pushParam = null;
        if (alarm.getValue() == 0 || alarm.getThreshold() == 0) {
            pushParam = new AlarmPushParam();
            pushParam.setValue("Device Offline or Power Failure");
        } else {
            //数据异常
            pushParam = new AlarmPushParam(alarm.getValue() + "/" + alarm.getThreshold());
        }
        if (alarm.getMessage().length() > 17) {
            pushParam.setContext(alarm.getMessage().substring(0, 17) + "...");
        } else {
            pushParam.setContext(alarm.getMessage());
        }
        // 添加房间名称
        if (StrUtil.isNotBlank(alarm.getRoomName())) {
            pushParam.setDeviceName(alarm.getSource() + "(" + alarm.getRoomName() + ")");
        } else {
            pushParam.setDeviceName(alarm.getSource());
        }
        pushParam.setDeviceName(alarm.getSource());
        pushParam.setNoticeTime(new Date());
        pushParam.setType(alarm.getAlarmType());
        pushParam.setUserIdList(alarm.getAlarmUsers().stream().map(SensorAlarmUser::getOpenId).collect(Collectors.toSet()));
        //推送到公众号
        String pushCode = PushUtil.alarmPush(pushParam);
        alarm.setWeixinRequestCode(pushCode);
        return !StrUtil.isBlank(pushCode);
    }
}
