package com.liquidnet.service.sweet.handler;

import com.liquidnet.common.third.shumei.util.ShumeiUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.sweet.utils.QueueUtils;
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.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;

@Component
@Slf4j
public class MaoDengImageHandler implements WxMpMessageHandler {

    @Autowired
    private WechatUsersRedisUtils redisUtils;
    @Autowired
    private ShumeiUtil shumeiUtil;
    @Autowired
    QueueUtils queueUtils;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> map, WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException {
        String fromUser = wxMessage.getFromUser();//用户id
        String picUrl = wxMessage.getPicUrl();//图片url
        String maoId = IDGenerator.nextSnowId();

        //图片非法判断
        //此处判断不需要用户登录，所以使用时间代替
        String currentUid = DateUtil.now().getTime()+"";
        if (!shumeiUtil.checkImage(currentUid, picUrl)) {
            //图片非法 提示，发送文本消息
            WxMpXmlOutTextMessage build = WxMpXmlOutMessage.TEXT().content("无法识别，TA是不是还有别的照片呀！")
                    .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                    .build();
            return null;
        }
        SweetMaoDengVo sweetMaoDengVo = SweetMaoDengVo.getNew();
        sweetMaoDengVo.setUserId(fromUser);
        sweetMaoDengVo.setPicUrl(picUrl);
        String i = redisUtils.getSweetMaoDengOpen(fromUser);
        if (StringUtil.isNotEmpty(i)){
            //活动已开启  持久化  redis
            SweetMaoDengVo sweetMaoDeng = redisUtils.getSweetMaoDeng(fromUser);

            if (sweetMaoDeng != null){
                String textMsg = sweetMaoDeng.getTextMsg();
                sweetMaoDengVo.setTextMsg(textMsg);
            }
            redisUtils.setSweetMaoDeng(sweetMaoDengVo);
            return null;
        }
       return null;
    }
}
