package com.xunhong.erp.turbo.facade.app.executor.handler;

import com.xunhong.erp.turbo.api.facade.dto.qry.WxMaOpenidQry;
import com.xunhong.erp.turbo.api.user.api.UserAuthServiceI;
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.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.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class SubscribeHandler implements WxMpMessageHandler {

	@DubboReference(version = "1.0.0")
	private final UserAuthServiceI userAuthService;

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

		log.info("新关注用户 OPENID: {}", wxMpXmlMessage.getFromUser());

		// 获取微信用户基本信息
		WxMpUser userWxInfo = wxMpService.getUserService().userInfo(wxMpXmlMessage.getFromUser(), null);

		if (userWxInfo != null) {
			log.info("用户基本信息: {}", userWxInfo);

			WxMaOpenidQry wxMaOpenidQry = new WxMaOpenidQry();
			wxMaOpenidQry.setMpOpenid(userWxInfo.getOpenId());
			wxMaOpenidQry.setUnionid(userWxInfo.getUnionId());
			userAuthService.wxMaCodeLogin(wxMaOpenidQry);
		}

		WxMpXmlOutMessage responseResult = null;
		try {
			responseResult = handleSpecial(wxMpXmlMessage);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		if (responseResult != null) {
			return responseResult;
		}

		try {
			return WxMpXmlOutMessage.TEXT().content("感谢关注")
				.fromUser(wxMpXmlMessage.getToUser()).toUser(wxMpXmlMessage.getFromUser())
				.build();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return null;
	}

	/**
	 * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
	 */
	protected WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage) throws Exception {
		//TODO
		return null;
	}
}
