package org.mp.api.wxsendmsg;

import com.alibaba.fastjson.JSON;
import com.cftech.core.constants.MpApiConstants;
import com.cftech.core.util.DateUtils;
import com.cftech.core.util.OKHttpUtils;
import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.mp.api.core.exception.WexinReqException;
import org.mp.api.core.req.WeiXinReqService;
import org.mp.api.core.req.model.message.*;
import org.mp.api.core.util.HttpRequestProxy;
import org.mp.api.core.util.WeiXinConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 模板消息接口
 *
 * @author lizr
 */
public class JwTemplateMessageAPI {

    private static Logger logger = LoggerFactory
            .getLogger(JwTemplateMessageAPI.class);

    private static String templateMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?1=1";

    /**
     * 设置行业信息
     *
     * @param accessToken
     * @param industry_id1
     * @param industry_id2
     * @return
     * @throws WexinReqException
     */
    public static String setIndustry(String accessToken, String industry_id1, String industry_id2) throws WexinReqException {
        IndustryTemplateSet s = new IndustryTemplateSet();
        s.setAccess_token(accessToken);
        s.setIndustry_id1(industry_id1);
        s.setIndustry_id2(industry_id2);
        JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(s);
        String msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG);
        return msg;
    }

    /**
     * 添加模板信息
     *
     * @param accessToken
     * @param template_id_short
     * @return
     * @throws WexinReqException
     */
    public static String addTemplate(String accessToken, String template_id_short) throws WexinReqException {
        IndustryTemplateAdd t = new IndustryTemplateAdd();
        t.setAccess_token(accessToken);
        t.setTemplate_id_short(template_id_short);
        JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(t);
        String msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG);
        if ("ok".equalsIgnoreCase(msg)) {
            msg = result.getString("template_id");
        }

        return msg;
    }

    /**
     * 发送客服模板消息
     *
     * @param industryTemplateMessageSend
     * @return
     * @throws WexinReqException
     */
    public static String sendTemplateMsg(IndustryTemplateMessageSend industryTemplateMessageSend) throws WexinReqException {
        JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(industryTemplateMessageSend);
        String msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG);
        return msg;
    }

    /**
     * 发送模板消息
     */
    public static String sendTemplateMsgJson(String objectStr, String access_token) {
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("access_token", access_token);
        Long longnum = System.currentTimeMillis();
        logger.info("处理模板消息"+longnum+"***" + objectStr);
        String result = HttpRequestProxy.doJsonPost(templateMsgUrl, parameters, objectStr);
        logger.info("微信推送消息返回：" + result);
        logger.info("模板消息返回"+longnum+"***" + objectStr);
        return result;
    }

    public static void sendMessage(String templateId, String token, String openId, String first, String remark, String[] keywords, String url) {
        IndustryTemplateMessageSend mc = new IndustryTemplateMessageSend();
        mc.setTemplate_id(templateId);
        mc.setTouser(openId);
        mc.setAccess_token(token);
        mc.setUrl(url);
        StringBuffer json = new StringBuffer();
        Gson gson = new Gson();
        String objJson = gson.toJson(mc);
        json.append(objJson);
        json.setLength(json.length() - 1);
        json.append(",");
        json.append("\"data\":{");
        TemplateData template = new TemplateData();
        template.setValue(first);
        //template.setColor("#ffAADD");
        objJson = gson.toJson(template);
        json.append(" \"first\":");
        json.append(objJson);
        json.append(",");
        if (keywords != null && keywords.length > 0) {
            for (int i = 0; i < keywords.length; i++) {
                template.setValue(keywords[i]);
                objJson = gson.toJson(template);
                json.append(" \"keyword" + (i + 1) + "\":");
                json.append(objJson);
                json.append(",");
            }
        }
        template.setValue(remark);
        objJson = gson.toJson(template);
        json.append(" \"remark\":");
        json.append(objJson);
        json.append("}}");
        JwTemplateMessageAPI.sendTemplateMsgJson(json.toString(), token);
    }

    public static void main(String[] args) {
      String token ="13_x6v-V-hfRPsAqKVUBVopbWSqGIIMF0A8uErTf7VYma0TCZDvsC1zzXbgJ2n3KOPPSUWzdz3gnJp3r1hFvs4Xz73DsUID3PdYAOvGalN1QB3H1J6Na08n8qzMpZE1m07Z4EMkjYZKDF7dfrZOKYSgAIAQEY";
      String fistData = "尊敬的张园，您的参会行程还未提交。";
      String remarks = "如您需要接送站服务，请点击详情提交行程信息↓";
      String[] keywordss = {"2018舍弗勒大中华区技术研讨会","2018月11月21日-23日","苏州太湖万豪酒店"};
      //String openId = "oUl3rs0f32nzyel9c72MtnWHQprI";
      String openId="oUl3rs5SCV77OGUGTyAs7TecnX6M";
      String url = "http://www.baidu.com";
      sendMessage("nOeCI9f1DNc2la6BUDWsoFedhnubsxHbU1cEur-LJko",token,openId,fistData,remarks,keywordss,url);

    }

    }
