package com.liquidnet.service.sweet.handler;

import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.sweet.config.WechatMpConfigure;
import com.liquidnet.service.sweet.service.impl.SweetWechatTemplateServiceImpl;
import com.liquidnet.service.sweet.utils.QueueUtils;
import com.liquidnet.service.sweet.utils.WechatUsersRedisUtils;
import com.liquidnet.service.sweet.vo.SweetWechatUsersVo;
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 java.util.LinkedList;
import java.util.Map;

/**
 * <p>
 * 关注
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-07-31 5:06 下午
 */
@Component
@Slf4j
public class SubscribeHandler implements WxMpMessageHandler {
    @Autowired
    private WechatUsersRedisUtils redisUtils;
    @Autowired
    private QueueUtils queueUtils;
    @Autowired
    WechatMpConfigure wechatMpConfigure;

    @Autowired
    private SweetWechatTemplateServiceImpl sweetWechatTemplateService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        String zhengzaiAppId = wechatMpConfigure.getWxMpService(1).getWxMpConfigStorage().getAppId();
        String otherAppId = wxMpService.getWxMpConfigStorage().getAppId();

        log.info("接收到一个订阅事件:[{}]", wxMessage.toString());
        // 1、获取微信用户信息
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(wxMessage.getFromUser());
        if (null == wxMpUser) {
            log.error("从微信公众号获取用户(FromUser)信息:[{}]失败.", wxMessage.getFromUser());
            return null;
        }
        log.info("根据 openId:[{}]获取到的微信用户信息:[{}]", wxMessage.getFromUser(), wxMpUser.toString());
        // 记录用户信息
        Integer type = 0;
        if (zhengzaiAppId.equals(otherAppId)) {// 正在服务号
            type = 1;
        } else {// 摩登服务号
            type = 2;
        }
        SweetWechatUsersVo sweetWechatUsers = redisUtils.getSweetWechatUsers(wxMpUser.getUnionId(), type);
        if (null == sweetWechatUsers) {
            SweetWechatUsersVo sweetWechatUsersVo = SweetWechatUsersVo.getNew();
            sweetWechatUsersVo.setWechatUserId(IDGenerator.nextSnowId());
            sweetWechatUsersVo.setType(type);
            sweetWechatUsersVo.setOpenId(wxMpUser.getOpenId());
            sweetWechatUsersVo.setUnionId(wxMpUser.getUnionId());
            sweetWechatUsersVo.setNickname(wxMpUser.getNickname());
            sweetWechatUsersVo.setSexDesc(wxMpUser.getSexDesc());
            sweetWechatUsersVo.setSex(wxMpUser.getSex());
            sweetWechatUsersVo.setHeadImgUrl(wxMpUser.getHeadImgUrl());
            sweetWechatUsersVo.setLanguage(wxMpUser.getLanguage());
            sweetWechatUsersVo.setCountry(wxMpUser.getCountry());
            sweetWechatUsersVo.setProvince(wxMpUser.getProvince());
            sweetWechatUsersVo.setCity(wxMpUser.getCity());
            sweetWechatUsersVo.setSubscribeTime(DateUtil.ofEpochMilli(wxMpUser.getSubscribeTime()));
            sweetWechatUsersVo.setSubscribeScene(wxMpUser.getSubscribeScene());

            LinkedList<String> sqls = CollectionUtil.linkedListString();
            LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
            sqls.add(SqlMapping.get("sweet_wechat_users.insert"));
            sqlsDataA.add(new Object[]{
                    sweetWechatUsersVo.getWechatUserId(), type, sweetWechatUsersVo.getOpenId(), sweetWechatUsersVo.getUnionId(), sweetWechatUsersVo.getNickname(),
                    sweetWechatUsersVo.getSexDesc(), sweetWechatUsersVo.getSex(), sweetWechatUsersVo.getHeadImgUrl(), sweetWechatUsersVo.getLanguage(),
                    sweetWechatUsersVo.getCountry(), sweetWechatUsersVo.getProvince(), sweetWechatUsersVo.getCity(),
                    sweetWechatUsersVo.getSubscribeTime(), sweetWechatUsersVo.getSubscribeScene()
            });
            queueUtils.sendMsgByRedis(MQConst.SweetQueue.SWEET_WECHAT_USER_INSERT.getKey(),
                    SqlMapping.gets(sqls, sqlsDataA));
            // 入缓存
            redisUtils.setSweetWechatUsers(sweetWechatUsersVo);
            //发送模版消息
            sweetWechatTemplateService.subscribeSend(wxMpService, sweetWechatUsersVo);
        }

        return null;
    }
}
