package org.dromara.elevator.wechat.mp.handler;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.wechat.mp.handler.BaseUnsubscribeHandler;
import org.dromara.elevator.service.IEElevatorWechatUserService;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 取消关注事件处理
 *
 * @author ym
 * @version 1.0.0
 * @date 2024-10-18 10:27
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UnsubscribeHandler extends BaseUnsubscribeHandler {

    private final IEElevatorWechatUserService elevatorWechatUserService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {

        log.info("微信公众号取消关注:{},{}", wxMessage, JsonUtils.toJsonString(context));
        try {
            if (StringUtils.isBlank(wxMessage.getOpenId())) {
                return null;
            }
            // 取消订阅
            elevatorWechatUserService.deleteByMpOpenId(wxMessage.getOpenId());
        } catch (Exception e) {
            log.error("wxMp取消关注获取微信用户信息异常:{}", wxMessage, e);
        }

        return null;
    }
}
