package com.seer.teach.mp.handler;

import com.seer.teach.common.constants.CommonConstant;
import com.seer.teach.common.enums.UserRelationEnum;
import com.seer.teach.mp.convert.WxMpUserConvert;
import com.seer.teach.mp.entity.MpUserSubscribeEntity;
import com.seer.teach.mp.service.IMpUserSubscribeService;
import com.seer.teach.user.api.UserInfoServiceApi;
import com.seer.teach.user.api.UserRelationServiceApi;
import com.seer.teach.user.api.dto.UserInfoDTO;
import com.seer.teach.user.api.dto.UserRelationDTO;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;


/**
 * 关注事件处理
 * <a href='https://developers.weixin.qq.com/doc/service/guide/product/message/Receiving_event_pushes.html'>扫描带参数二维码事件</a>
 *
 */
@Component
@Slf4j
public class SubscribeHandler implements WxMpMessageHandler {

    @Autowired
    private UserInfoServiceApi userInfoServiceApi;

    @Autowired
    private UserRelationServiceApi userRelationServiceApi;

    @Autowired
    private IMpUserSubscribeService mpUserSubscribeService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        log.info("[handle][用户({}) 关注]", wxMessage.getFromUser());
        WxMpUser wxMpUser = null;
        try {
            wxMpUser = wxMpService.getUserService().userInfo(wxMessage.getFromUser());

            log.info("[handle][用户({})] 获取用户信息成功！", wxMessage.getFromUser());
            UserInfoDTO userInfoDTO = WxMpUserConvert.INSTANCE.convertOne(wxMpUser);
            log.info("[handle][用户({})] 转换用户信息成功！", wxMessage.getFromUser());
            Integer userId = userInfoServiceApi.save(userInfoDTO);
            log.info("[handle][用户({})] 保存用户信息成功！", wxMessage.getFromUser());
            String eventKey = wxMessage.getEventKey();
            if(StringUtils.hasText(eventKey) && eventKey.startsWith(CommonConstant.WX_MP_QR_SCENE_PREFIX)){
                log.info("[handle][用户({})] 获取用户二维码信息:[{}]", wxMessage.getFromUser(), eventKey);
                String userIdStr = eventKey.substring(CommonConstant.WX_MP_QR_SCENE_PREFIX.length());
                UserRelationDTO userRelationDTO = new UserRelationDTO();
                userRelationDTO.setUserId(userId);
                userRelationDTO.setRelationId(Integer.parseInt(userIdStr));
                userRelationDTO.setType(UserRelationEnum.PARENT_CHILD.getDescription());
                boolean relationResult = userRelationServiceApi.saveUserRelation(userRelationDTO);
                log.info("[handle][用户({})] 保存用户关系结果:{}！", wxMessage.getFromUser(),relationResult);
            }
            String appId = wxMpService.getWxMpConfigStorage().getAppId();
            MpUserSubscribeEntity mpUserSubscribeEntity = WxMpUserConvert.INSTANCE.convertOne(wxMpUser, userId);
            mpUserSubscribeEntity.setAppId(appId);
            boolean saved = mpUserSubscribeService.save(mpUserSubscribeEntity);
            log.info("[handle][用户({})] 保存用户关注信息结果:{}！", wxMessage.getFromUser(),saved);


        } catch (WxErrorException e) {
            log.error("[handle][用户({})] 获取用户信息失败！", wxMessage.getFromUser(), e);
        }

        return WxMpXmlOutMessage.TEXT().content("欢迎关注【SeerTeachAI】服务号")
                .fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser())
                .build();
    }
}