package com.seer.teach.mp.handler;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.seer.teach.mp.entity.MpUserSubscribeEntity;
import com.seer.teach.mp.service.IMpUserSubscribeService;
import com.seer.teach.user.api.UserInfoServiceApi;
import com.seer.teach.user.api.dto.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 取消关注的事件处理器
 */
@Component
@Slf4j
public class UnsubscribeHandler implements WxMpMessageHandler {

    @Autowired
    private IMpUserSubscribeService mpUserSubscribeService;

    @Autowired
    private UserInfoServiceApi userInfoServiceApi;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        log.info("[handle][粉丝({}) 取消关注]", wxMessage.getFromUser());

        UserInfoDTO userInfoDTO = userInfoServiceApi.getByOpenId(wxMessage.getFromUser());
        if (userInfoDTO != null) {
            mpUserSubscribeService.update(new LambdaUpdateWrapper<>(MpUserSubscribeEntity.class)
                    .set(MpUserSubscribeEntity::getSubscribeStatus, 0)
                    .set(MpUserSubscribeEntity::getUnsubscribeTime, LocalDateTime.now())
                    .eq(MpUserSubscribeEntity::getUserId, userInfoDTO.getId()));
        }

        return null;
    }
}