package com.liquidnet.service.sweet.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.sweet.entity.SweetWechatUser;
import com.liquidnet.service.sweet.mapper.SweetWechatUserMapper;
import com.liquidnet.service.sweet.utils.RedisDataUtils;
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.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 me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * <p>
 * 关注
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-07-31 5:06 下午
 */
@Component
@Slf4j
public class SubscribeHandler implements WxMpMessageHandler {
    @Autowired
    private SweetWechatUserMapper sweetWechatUserMapper;
    @Autowired
    private RedisDataUtils redisDataUtils;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        log.info("接收到一个扫码订阅事件:[{}]", wxMessage.toString());
        // 1、获取微信用户信息
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(wxMessage.getFromUser());
        if (null == wxMpUser) {
            log.warn("从微信公众号获取用户(FromUser)信息:[{}]失败.", wxMessage.getFromUser());
            return null;
        }
        log.info("根据 openId:[{}]获取到的微信用户信息:[{}]", wxMessage.getFromUser(), wxMpUser.toString());
        // 记录用户信息
        SweetWechatUser userInfo = sweetWechatUserMapper.selectOne(Wrappers.lambdaQuery(SweetWechatUser.class).eq(SweetWechatUser::getOpenId, wxMpUser.getOpenId()));
        SweetWechatUser sweetWechatUser = SweetWechatUser.getNew();
        sweetWechatUser.setOpenId(wxMpUser.getOpenId());
        sweetWechatUser.setUnionId(wxMpUser.getUnionId());
        sweetWechatUser.setNickname(wxMpUser.getNickname());
        sweetWechatUser.setSexDesc(wxMpUser.getSexDesc());
        sweetWechatUser.setSex(wxMpUser.getSex());
        sweetWechatUser.setHeadImgUrl(wxMpUser.getHeadImgUrl());
        sweetWechatUser.setLanguage(wxMpUser.getLanguage());
        sweetWechatUser.setCountry(wxMpUser.getCountry());
        sweetWechatUser.setProvince(wxMpUser.getProvince());
        sweetWechatUser.setCity(wxMpUser.getCity());
        sweetWechatUser.setSubscribeTime(DateUtil.ofEpochMilli(wxMpUser.getSubscribeTime()));
        sweetWechatUser.setSubscribeScene(wxMpUser.getSubscribeScene());
        if (null == userInfo) {
            sweetWechatUser.setUserId(IDGenerator.nextSnowId());
            sweetWechatUserMapper.insert(sweetWechatUser);
        } else {
            sweetWechatUser.setUpdatedAt(LocalDateTime.now());
            sweetWechatUserMapper.update(sweetWechatUser, Wrappers.lambdaUpdate(SweetWechatUser.class).eq(SweetWechatUser::getUserId, userInfo.getUserId()));
        }
        String unionId = wxMpUser.getUnionId();
        if (!unionId.isEmpty()) {
            if (null != userInfo) {
                sweetWechatUser.setMid(userInfo.getMid());
                sweetWechatUser.setUserId(userInfo.getUserId());
                sweetWechatUser.setCreatedAt(userInfo.getCreatedAt());
            }
            redisDataUtils.setSweetWechatUser(sweetWechatUser);
        }

        return null;
    }
}
