package com.liquidnet.service.sweet.handler;


import com.fasterxml.jackson.core.type.TypeReference;
import com.liquidnet.common.third.shumei.util.ShumeiUtil;
import com.liquidnet.commons.lang.util.*;
import com.liquidnet.service.adam.dto.vo.AdamUserInfoVo;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.kylin.dto.vo.basicServices.UploadVo;
import com.liquidnet.service.sweet.config.WechatMaConfigure;
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.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.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.Map;

@Component
@Slf4j
public class MaoDengImageHandler implements WxMpMessageHandler {

    @Value("${liquidnet.service.platform.url}")
    private String platformUrl;
    @Autowired
    private WechatUsersRedisUtils redisUtils;
    @Autowired
    private ShumeiUtil shumeiUtil;
    @Autowired
    WechatMaConfigure maConfigure;
    @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().replace("http", "https");//图片urlmao

        //猫登天空活动开启
        if (StringUtil.isNotEmpty(redisUtils.getSweetMaoDengOpen(fromUser))) {

            //图片非法判断
            if (!shumeiUtil.checkImage(fromUser, picUrl)) {
                //图片非法 提示，发送文本消息
                WxMpXmlOutTextMessage build = WxMpXmlOutMessage.TEXT().content("图片无法识别，吸猫上瘾的你一定还有其他的“猫片”，重新发一张吧！")
                        .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                        .build();
                return build;
            }
            SweetMaoDengVo sweetMaoDengVo = SweetMaoDengVo.getNew();
            sweetMaoDengVo.setUserId(fromUser);

            try {
                if (picUrl != null && !picUrl.equals("")) {
                    log.debug("[OLD PIC] = " + picUrl);
                    MultiValueMap<String, String> params = new LinkedMultiValueMap();
                    params.add("pathName", IDGenerator.nextTimeId().concat(".jpeg"));
                    params.add("picUrl", picUrl);
                    String returnData = HttpUtil.post(platformUrl.concat("/platform/basicServices/alOss/uploadUrl"), params);
                    ResponseDto<UploadVo> dto = JsonUtils.fromJson(returnData, new TypeReference<ResponseDto<UploadVo>>() {
                    });
                    picUrl = "https://img.zhengzai.tv/".concat(dto.getData().getOssPath());
                    log.debug("[NEW PIC] = " + picUrl);
                }
            } catch (Exception e) {
                e.getMessage();
            }
            sweetMaoDengVo.setPicUrl(picUrl);
            //活动已开启  持久化  redis
            SweetMaoDengVo sweetMaoDeng = redisUtils.getSweetMaoDengTransfer(fromUser);
            String textMsg = null;
            if (sweetMaoDeng != null) {
                textMsg = sweetMaoDeng.getTextMsg();
                sweetMaoDengVo.setTextMsg(textMsg);
            }

            String maoId = IDGenerator.nextSnowId();
            redisUtils.setSweetMaoDeng(sweetMaoDengVo);

            if (StringUtil.isNotEmpty(textMsg) && StringUtil.isNotEmpty(picUrl)) {
                //redis队列入库
                LinkedList<String> sqls = CollectionUtil.linkedListString();
                LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
                sqls.add(SqlMapping.get("sweet_wechat_maodeng.insert"));
                sqlsDataA.add(new Object[]{maoId, fromUser, textMsg, picUrl, "", LocalDateTime.now()});
                queueUtils.sendMsgByRedis(MQConst.SweetQueue.SWEET_WECHAT_MAODENG_TEXT_INSERT.getKey(), SqlMapping.gets(sqls, sqlsDataA));
            }

            WxMpXmlOutTextMessage build = WxMpXmlOutMessage.TEXT().content("成了！点击上方小程序卡片查看猫咪的隐藏音乐技能。")
                    .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                    .build();
            // 发送活动小程序卡片
            WxMpKefuMessage message = WxMpKefuMessage.MINIPROGRAMPAGE()
                    .appId(maConfigure.getWxMaAppid(4))
                    .pagePath("pages/webview?query=catActivity&maoId=" + maoId) //小程序路径
//                    .thumbMediaId("ov08q51In7bXX6tXv7Few-ud2-J-hyXnDC5NCNSfc_4") // 正在
//                    .thumbMediaId("ttUDFdcsOTnGFPBt5xp-vaYe_hS9Jae5C_YUboXmb4c") //test
                    .thumbMediaId("OFjnPjluDGoHH1KOAdxQ_iMyWpBe_c48V40LlN6VmAQ") //图片地址
                    .title("在猫登天空，每一只猫咪都有自己的隐藏音乐技能！")
                    .toUser(wxMessage.getFromUser())
                    .build();
            wxMpService.getKefuService().sendKefuMessage(message);
            return build;
        }

        return null;
    }
}
