package org.dromara.mp.handler;

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 me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 扫描事件处理
 *
 * @author Peng Les
 */
@Component
public class ScanHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> map,
                                    WxMpService wxMpService, WxSessionManager wxSessionManager) {
        return doHandle(wxMessage, map, wxMpService, wxSessionManager);
    }

    @Override
    protected WxMpXmlOutMessage doHandle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
        String eventKey = wxMessage.getEventKey();
        String openId = wxMessage.getFromUser();
        if (StringUtils.isBlank(eventKey) || StringUtils.isBlank(openId)) {
            return buildTextMessage("参数缺失，绑定失败。", wxMessage, wxMpService);
        }
        // 处理二维码场景值
        String scene = eventKey;
        if (scene.startsWith("qrscene_")) {
            scene = scene.substring("qrscene_".length());
        }
        if (!scene.startsWith("sys_user:")) {
            return buildTextMessage("二维码场景不匹配，未执行绑定。", wxMessage, wxMpService);
        }
        String userIdStr = scene.substring("sys_user:".length());
        Long userId = null;
        try {
            userId = Long.valueOf(userIdStr);
        } catch (Exception e) {
            return buildTextMessage("用户标识解析失败，绑定终止。", wxMessage, wxMpService);
        }

        String unionId = null;
        try {
            WxMpUser user = wxMpService.getUserService().userInfo(openId);
            unionId = user.getUnionId();
        } catch (Exception ignore) {
        }

        String msg = "绑定请求已识别。\nopenid：" + openId +
                (StringUtils.isNotBlank(unionId) ? ("\nunionId：" + unionId) : "") +
                "\n请在后台完成管理员微信绑定。";
        return buildTextMessage(msg, wxMessage, wxMpService);
    }
}
