package com.seer.teach.mp.handler;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import com.seer.teach.mp.entity.MpActivityEntity;
import com.seer.teach.mp.entity.MpAgentActivityParticipantEntity;
import com.seer.teach.mp.service.IMpActivityService;
import com.seer.teach.mp.service.IMpAgentActivityRelationService;
import lombok.extern.slf4j.Slf4j;
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.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

@Slf4j
public abstract class AbstractHandler {

    @Autowired
    private IMpAgentActivityRelationService mpAgentActivityRelationService;

    @Autowired
    private IMpActivityService mpActivityService;


    protected boolean isAgentActivityScanEvent(WxMpXmlMessage wxMessage) {
        String eventKey = wxMessage.getEventKey();
        log.info("[handle][用户({})] 获取用户二维码信息:[{}]", wxMessage.getFromUser(), eventKey);
        if (StringUtils.hasText(eventKey) && eventKey.startsWith("agentId") && eventKey.contains("activityId")) {
            return true;
        }
        return false;
    }

    protected WxMpXmlOutMessage buildAgentActivityOutMessage(WxMpXmlMessage wxMessage) {
        String eventKey = wxMessage.getEventKey();
        Map<String, String> paramMap = HttpUtil.decodeParamMap(eventKey, StandardCharsets.UTF_8);
        Integer agentId = MapUtil.getInt(paramMap, "agentId", 0);
        Integer activityId = MapUtil.getInt(paramMap, "activityId", 0);
        if (agentId > 0 && activityId > 0) {
            MpAgentActivityParticipantEntity participantsByActivityAndAgent = mpAgentActivityRelationService.getParticipantsByActivityAndAgent(activityId, agentId);
            MpActivityEntity activity = mpActivityService.getById(activityId);
            if (Objects.nonNull(participantsByActivityAndAgent)) {
                WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
                item.setTitle(activity.getActivityName());
                item.setDescription(activity.getDescription());
                item.setPicUrl(participantsByActivityAndAgent.getQrCodeUrl());
                item.setUrl("https://mp.seerteach.net/login?" + eventKey);
                WxMpXmlOutNewsMessage build = WxMpXmlOutMessage.NEWS()
                        .addArticle(item)
                        .toUser(wxMessage.getFromUser())
                        .fromUser(wxMessage.getToUser())
                        .build();
                log.info("[handle][扫码处理，内容：{}]", build);
                return build;
            }
        }
        return null;
    }
}
