package com.ematou.wxservice.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ematou.wxservice.api.WeChatApi;
import com.ematou.wxservice.api.WeChatApiRestTemplate;
import com.ematou.wxservice.common.constant.WeChatAccount;
import com.ematou.wxservice.config.WeChatGeneralConfig;
import com.ematou.wxservice.entity.vo.AccessToken;
import com.ematou.wxservice.mp.message.WeChatMessage;
import com.ematou.wxservice.mp.handler.WeChatMessageHandler;
import com.ematou.wxservice.mp.message.WeChatMpXmlOutMessage;
import com.ematou.wxservice.mp.router.WeChatMessageHandlerRouter;
import com.ematou.wxservice.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lhm
 * @version 1.0
 * 2021-05-11 16:19
 */
@Service
public class WeChatMessageService {

    @Autowired
    WeChatGeneralConfig weChatGeneralConfig;

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    WeChatApiRestTemplate weChatApiRestTemplate;
    @Value ("${wechat}")
    String wechat;
    private static final Logger logger = LoggerFactory.getLogger(WeChatMessageHandlerRouter.class);

    /**
     * 处理消息
     * @param weChatMessage 微信推送的消息
     * @return  响应给用户的消息
     */
    public WeChatMpXmlOutMessage handleMessage(WeChatMessage weChatMessage) {
        logger.info("wxservice接收到微信平台推送的消息：" + JSON.toJSONString(weChatMessage));

        WeChatMessageHandler handler = WeChatMessageHandlerRouter.router(weChatMessage);

        if (null == handler) {
            logger.warn("暂不支持" + weChatMessage.getMsgType() + "类型或事件的处理");
            return null;
        }
        WeChatMpXmlOutMessage outMessage = handler.handlerMessage(weChatMessage);
        logger.info("wxservice处理完响应给用户的消息：" + JSON.toJSONString(outMessage));
        return outMessage;

    }

    /**
     * 生成二维码信息
     */
    public String generateqRcodeService(JSONObject msgmap) {
        String response = weChatApiRestTemplate.getForOther(String.format(WeChatApi.GET_TOKEN_NEW.getUrl(), wechat));
        AccessToken accessToken = JSON.parseObject(response).getObject("data", AccessToken.class);
        String msg = HttpUtils.sendPost(" https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accessToken.getAccessToken(),msgmap.toJSONString());
        logger.info("请求微信接口生成二维码图片，微信返回信息：" + msg);
        return msg;

    }




}
