package com.ywt.outpatient.taihe.rpc.service.common;

import com.google.gson.JsonObject;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.message.SendMPSubscribeMessageRequest;
import com.ywt.gapi.message.SendMPSubscribeMessageResponse;
import com.ywt.gapi.message.SendTemplateMessageRequest;
import com.ywt.gapi.message.WeChatMessageService;
import com.ywt.outpatient.taihe.rpc.core.utils.Checker;
import com.ywt.outpatient.taihe.rpc.core.utils.JsonUtil;
import com.ywt.outpatient.taihe.rpc.service.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 微信公众号模板消息、客服消息提供类
 *
 * @author johnson lin
 * @date 2019/6/27 4:08 PM
 */
@Service
public class WeChatMsgProvider {
    private static Logger logger = LoggerFactory.getLogger(WeChatMsgProvider.class);

    @DubboReference
    private WeChatMessageService weChatMessageServiceBlockingStub;


    /**
     * 发送模板消息
     *
     * @param model {@link MessageModel}
     */
    public void sendTemplateMessage(MessageModel model) {
        try {
            Map<String, Object> data = new HashMap<>();
            data.put("first", new Keyword(model.getFirst()));
            data.put("remark", new Keyword(model.getRemark()));

            if (!Checker.isNone(model.getKeywords())) {
                for (int i = 0; i < model.getKeywords().length; i++) {
                    data.put(String.format("keyword%d", i + 1), new Keyword(model.getKeywords()[i]));
                }
            }

            if (!Checker.isNone(model.getKeynotes())) {
                for (int i = 0; i < model.getKeynotes().length; i++) {
                    data.put(String.format("keynote%d", i + 1), new Keyword(model.getKeynotes()[i]));
                }
            }
            SendTemplateMessageRequest req = SendTemplateMessageRequest.newBuilder()
                    .setData(JsonUtil.toJson(data))
                    .setTemplateCode(model.getTplCode())
                    .setUrl(model.getUrl())
                    .setMiniProgram(model.getMiniProgram())
                    .setUserId(model.getUserId())
                    .build();
            weChatMessageServiceBlockingStub.sendTemplateMessage(req);
        } catch (Exception e) {
            logger.error("sendTemplateMessage(): {}", e.getMessage(), e);
        }
    }


    /**
     * 模板消息文字
     *
     * @author johnson lin
     * @date 2019/4/29 9:45 PM
     */
    class Keyword {
        /**
         * 文字
         */
        private String value;
        /**
         * 颜色
         */
        private String color;

        Keyword() {
        }

        Keyword(String value) {
            this.value = value;
            this.color = "#000";
        }

        Keyword(String value, String color) {
            this.value = value;
            this.color = color;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }
    }

    public String getNfyybyfyMpParamString(String mpPath) {
        JsonObject object = new JsonObject();
        object.addProperty("appid", Constants.NFYYBYFY_WXMP_APP_ID);// 所需跳转到的小程序appid
        object.addProperty("pagepath", "pages/index/index?entry=" + getEncodedURI(mpPath));// 所需跳转到小程序的具体页面路径
        return object.toString();
    }

    /**
     * 生成模板消息跳转小程序所需的参数
     *
     * @param appId    跳转的小程序appId
     * @param pagePath 页面
     * @return param string
     */
    public String getMiniProgramParam(String appId, String pagePath) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("appid", appId);
        jsonObject.addProperty("pagepath", pagePath);
        return jsonObject.toString();
    }


    private String getEncodedURI(String path) {
        try {
            return URLEncoder.encode(path, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            logger.error("WxProvider#getEncodedURI(path={} ):\n {}", path, e.getMessage(), e);
            return path;
        }
    }

    public void sendMPSubscribeMessage(int terminal, String openId, String templateId, String page, Map<String, String> keywordMap) {
        List<SendMPSubscribeMessageRequest.Keyword> keywordList = new LinkedList<>();
        for (String key : keywordMap.keySet()) {
            SendMPSubscribeMessageRequest.Keyword keyword = SendMPSubscribeMessageRequest.Keyword.newBuilder()
                    .setColor("#000")
                    .setValue(keywordMap.get(key))
                    .setKey(key)
                    .build();
            keywordList.add(keyword);
        }
        SendMPSubscribeMessageRequest req = SendMPSubscribeMessageRequest.newBuilder()
                .setTerminal(terminal)
                .setTouser(openId)
                .setTemplateId(templateId)
                .setPage(page)
                .addAllKeywords(keywordList)
                .build();
        SendMPSubscribeMessageResponse res = weChatMessageServiceBlockingStub.sendMPSubscribeMessage(req);
        if (res.getCode() != ResultCode.SUCCEED_VALUE) {
            logger.info("sendMPSubscribeMessage({})发送失败: {}", req, res.getInfo());
        }
    }

}
