package com.gxwebsoft.open.mp;

import com.gxwebsoft.common.core.utils.RequestUtil;
import com.gxwebsoft.common.system.entity.User;
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 javax.annotation.Resource;
import java.util.Map;

@Component
public class SubscribeHandler implements WxMpMessageHandler {
    @Autowired
    private RequestUtil requestUtil;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map, WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException {
        String openid = wxMpXmlMessage.getFromUser();
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(openid);
        System.out.println("wxMpUser:" + wxMpUser);
        requestUtil.setTenantId("10559");
        User user = requestUtil.getUserByUnionid(wxMpUser.getUnionId());
//        System.out.println("user:" + user);
        if (user != null) {
            user.setOfficeOpenid(wxMpUser.getOpenId());
            requestUtil.updateUserOfficeOpenidWithoutLogin(user);
        }
        return WxMpXmlOutMessage.TEXT()
                .fromUser(wxMpXmlMessage.getToUser())
                .toUser(wxMpXmlMessage.getFromUser())
                .content("感谢关注！")
                .build();
    }
}
