package com.bofeng.wx;

import com.bofeng.Consts;
import com.bofeng.entity.ScanParam;
import com.bofeng.service.PlaceService;
import com.bofeng.service.UserService;
import com.bofeng.support.WeChatProperties;
import com.yvan.platform.Conv;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import me.chanjar.weixin.common.api.WxConsts;
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.message.WxMpXmlOutNewsMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
@Slf4j
public class ScanHandler implements WxMpMessageHandler {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    @Lazy
    private QrCodeService qrCodeService;

    @Autowired
    private PlaceService placeService;

    @Autowired
    private UserService userService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> map,
                                    WxMpService wxService, WxSessionManager wxSessionManager) throws WxErrorException {
        // 扫码事件处理
        String openId = wxMessage.getFromUser();
        val content = qrCodeService.getContent(wxMessage.getTicket(), ScanParam.class);
        log.info("扫码进来 OPENID: " + openId);

        val place = placeService.getById(Conv.NL(content.placeId));
        if (place == null) {
            return WxMpXmlOutMessage.TEXT().content("系统错误:没有找到对应场地").build();
        }

        val item = new WxMpXmlOutNewsMessage.Item();
        if (content.getType().equals(Consts.USER_TYPE_L1)) {
            item.setTitle("点击绑定 (" + place.getPlaceName() + " 一级)");

        } else if (content.getType().equals(Consts.USER_TYPE_L2)) {
            val user = userService.getUserById(Conv.NL(content.higherId));
            if (user == null) {
                return WxMpXmlOutMessage.TEXT().content("系统错误:没有找到一级分销信息").build();
            }
            item.setTitle("点击绑定 (" + place.getPlaceName() + " " + user.getStaffName() + ")");
        }

        item.setUrl(
                wxService.oauth2buildAuthorizationUrl(weChatProperties.getDomain() +
                                "/cust/user_bind.html?userType=" + content.getType() + "&higherId=" + content.getHigherId() + "&placeId=" + content.getPlaceId(),
                        WxConsts.OAuth2Scope.SNSAPI_USERINFO, null));

        return WxMpXmlOutMessage.NEWS().addArticle(item)
                .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                .build();
    }
}
