package com.liquidnet.service.sweet.handler;

import com.liquidnet.common.third.shumei.util.ShumeiUtil;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.common.third.shumei.util.ShumeiUtil;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.sweet.config.WechatMaConfigure;
import com.liquidnet.service.sweet.constant.SweetConstant;
import com.liquidnet.service.sweet.utils.WechatUsersRedisUtils;
import com.liquidnet.service.sweet.vo.SweetMaoDengVo;
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.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * <p>
 * 文本消息
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-11-25
 */
@Component
@Slf4j
public class TextMsgHandler implements WxMpMessageHandler {

    @Autowired
    private WechatUsersRedisUtils redisUtils;

    @Autowired
    WechatMaConfigure maConfigure;

    @Autowired
    private ShumeiUtil shumeiUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        String openId = wxMessage.getFromUser();
        String content = wxMessage.getContent();

        // 2021草莓音乐节海报活动
        if (StringUtil.trim(content).equals("白日梦")) {
            redisUtils.delSweetMaoDengOpen(openId);
            redisUtils.setStrawberryPosterClick(wxMessage.getFromUser(), 10 * 60);

            return WxMpXmlOutMessage.TEXT().content("参与活动之前，请先告诉我你的昵称！（直接在对话框输入即可\uD83D\uDC47，9个字以内）")
                    .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                    .build();
        } else if (redisUtils.getStrawberryPosterClick(openId)) {
            // 验证
            if (content.length() > 9) {
                return WxMpXmlOutMessage.TEXT().content("昵称要9个字以内～")
                        .fromUser(wxMessage.getToUser()).toUser(openId)
                        .build();
            }
            if (!shumeiUtil.checkText(openId, content)) {
                return WxMpXmlOutMessage.TEXT().content("无法识别，换个昵称吧！（请勿使用表情等特殊字符）")
                        .fromUser(wxMessage.getToUser()).toUser(openId)
                        .build();
            }

            // 发送文本消息
            /*WxMpXmlOutTextMessage build = WxMpXmlOutMessage.TEXT().content("你好，".concat(content).concat("！点击下方小程序卡片开始搭建你梦想的草莓音乐节阵容！"))
                    .fromUser(wxMessage.getToUser()).toUser(openId)
                    .build();*/
            WxMpKefuMessage message = WxMpKefuMessage.TEXT().content("你好，".concat(content).concat("！点击下方小程序卡片开始搭建你梦想的草莓音乐节阵容！"))
                    .toUser(openId).build();
            wxMpService.getKefuService().sendKefuMessage(message);
            // 发送活动小程序卡片
            WxMpKefuMessage message1 = WxMpKefuMessage.MINIPROGRAMPAGE()
                    .appId(maConfigure.getWxMaAppid(4))
                    .pagePath("/pages/webview?query=strawberryMusic&voteWhere=2&nickname=".concat(content))
//                    .thumbMediaId("ov08q51In7bXX6tXv7Few8cBjTW0osSV_t9FCLg8Q1Q") // 正在
//                    .thumbMediaId("ttUDFdcsOTnGFPBt5xp-vaYe_hS9Jae5C_YUboXmb4c") // test
                    .thumbMediaId("OFjnPjluDGoHH1KOAdxQ_vfMiIKRu2Eo9QFhI5TOtHE") // 摩登
                    .title("做一场白日梦，挑选你心水的草莓阵容！")
                    .toUser(openId)
                    .build();
            wxMpService.getKefuService().sendKefuMessage(message1);
        }


        if (content.equals("猫登天空")) {
            redisUtils.delStrawberryPosterClick(openId);
            redisUtils.setSweetMaoDengOpen(openId, 10 * 60);
            WxMpXmlOutTextMessage build = WxMpXmlOutMessage.TEXT().content("没想到吧，你的喵星人主子在玩耍逗喵棒之外，也有一个隐秘的音乐人分身呢！\n" +
                            "看看TA到底是怎样一只音乐喵！\n" +
                            "参与活动之前，请先告诉我们猫咪的名字！（直接在对话框输入即可👇，8个汉字或8个英文字符以内）\n")
                    .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                    .build();
            return build;
        } else if (StringUtil.isNotEmpty(redisUtils.getSweetMaoDengOpen(openId))) { //是否参加了活动
            //敏感词判断
            if (!shumeiUtil.checkText(openId, content)) {
                //文字敏感 提示，发送文本消息
                WxMpXmlOutTextMessage build = WxMpXmlOutMessage.TEXT().content("无法识别，TA是不是还有别的名字呢！（请勿使用表情等特殊字符）")
                        .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                        .build();
                return build;
            }

            if (content.length() > 8) {
                return WxMpXmlOutMessage.TEXT().content("昵称要8个字以内～")
                        .fromUser(wxMessage.getToUser()).toUser(openId)
                        .build();
            }
            if (!shumeiUtil.checkText(openId, content)) {
                return WxMpXmlOutMessage.TEXT().content("无法识别，换个昵称吧！（请勿使用表情等特殊字符）")
                        .fromUser(wxMessage.getToUser()).toUser(openId)
                        .build();
            }

            SweetMaoDengVo sweetMaoDengVo = SweetMaoDengVo.getNew();
            sweetMaoDengVo.setUserId(openId);
            sweetMaoDengVo.setTextMsg(content);
            SweetMaoDengVo sweetMaoDeng = redisUtils.getSweetMaoDengTransfer(openId);
            if (sweetMaoDeng != null) {
                String picUrl = sweetMaoDeng.getPicUrl();
                sweetMaoDengVo.setPicUrl(picUrl);
            }
            //获取过期时间
            long expire = redisUtil.getExpire(SweetConstant.REDIS_KEY_SWEET_WECHAT_MAODENG_OPEN_POSTER + openId);
            redisUtils.setSweetMaoDengTransfer(sweetMaoDengVo, expire);

            WxMpXmlOutTextMessage build = WxMpXmlOutMessage.TEXT().content("再发给我们一张猫咪的可爱照片吧！")
                    .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                    .build();
            return build;
        }


        return null;
    }
}