package com.kiisoo.ic.wx.service;

import com.google.gson.Gson;
import com.kiisoo.ic.common.utils.WeixinApi;
import com.kiisoo.ic.wx.entity.WeChatCardDataDO;
import com.kiisoo.ic.wx.entity.WeChatTaskDataDO;
import com.kiisoo.ic.wx.entity.WeChatUrlDataDO;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * 企业微信发送消息service
 * @author yechenhao
 * @date 2020-03-11 17：09
 */
@Service
public class WeChatMsgService {
    private CloseableHttpClient httpClient;
    /**
     *  用于提交登陆数据
     */
    private HttpPost httpPost;
    /**
     *  用于获得登录后的页面
     */
    private HttpGet httpGet;


    public static final String CONTENT_TYPE = "Content-Type";


    public static final String CONTENT_TYPE_JSON = "application/json";


    public static final String TEXT_CARD = "textcard";


    public static final String TASK_CARD = "taskcard";


    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    private static Gson gson = new Gson();

    private String corpid = "wwc8b3e81998fe5394";

    private String corpsecret = "scb9m8DEtSwJpB_ZFXg4J9WE91yH-WNBBQ4Vxv1NYy4";

    private String applicationid = "1000037";


    /**
     * 微信授权请求，GET类型，获取授权响应，用于其他方法截取token
     * @param Get_Token_Url
     * @return String 授权响应内容
     * @throws IOException
     */
    protected String toAuth(String Get_Token_Url) throws IOException {


        httpClient = HttpClients.createDefault();
        httpGet = new HttpGet(Get_Token_Url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String resp;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
        LoggerFactory.getLogger(getClass()).info(" resp:{}", resp);
        return resp;
    }


    /**corpid应用组织编号   corpsecret应用秘钥
     * 获取toAuth(String Get_Token_Url)返回结果中键值对中access_token键的值
     * @param
     */
    public  String getToken() throws IOException {
        WeChatMsgService sw = new WeChatMsgService();
        WeChatUrlDataDO uData = new WeChatUrlDataDO();
        uData.setGet_Token_Url(corpid,corpsecret);
        String token = WeixinApi.readToken();
        return token;
    }




    /**
     * @Title:创建微信发送请求post数据
     * touser发送消息接收者    ，msgtype消息类型（文本/图片等），
     * application_id应用编号。
     * 本方法适用于text型微信消息，contentKey和contentValue只能组一对
     * @return String
     */
    public String createPostCardData(String touser,String toparty,String totag, Map<String,String> content) {
        WeChatCardDataDO wcd = new WeChatCardDataDO();
        if (StringUtils.isNotBlank(touser)){
            wcd.setTouser(touser);
        }
        if (StringUtils.isNotBlank(toparty)){
            wcd.setToparty(toparty);
        }
        if (StringUtils.isNotBlank(totag)){
            wcd.setTotag(totag);
        }
        wcd.setAgentid(Integer.valueOf(applicationid));
        wcd.setMsgtype(TEXT_CARD);
        wcd.setTextcard(content);
        return gson.toJson(wcd);
    }
    /**
     * @Title:创建微信发送请求post数据
     * touser发送消息接收者    ，msgtype消息类型（文本/图片等），
     * application_id应用编号。
     * 本方法适用于text型微信消息，contentKey和contentValue只能组一对
     * @return String
     */
    public String createPostTaskData(String touser,String toparty,String totag, Map<String,Object> content) {
        WeChatTaskDataDO wcd = new WeChatTaskDataDO();
        if (StringUtils.isNotBlank(touser)){
            wcd.setTouser(touser);
        }
        if (StringUtils.isNotBlank(toparty)){
            wcd.setToparty(toparty);
        }
        if (StringUtils.isNotBlank(totag)){
            wcd.setTotag(totag);
        }
        wcd.setAgentid(Integer.valueOf(applicationid));
        wcd.setMsgtype(TASK_CARD);
        wcd.setTaskcard(content);
        return gson.toJson(wcd);
    }


    /**
     * @Title  创建微信发送请求post实体
     * charset消息编码    ，contentType消息体内容类型，
     * url微信消息发送请求地址，data为post数据，token鉴权token
     * @return String
     */
    public String post(String charset, String contentType, String url,
                       String data,String token) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        httpPost = new HttpPost(url+token);
        httpPost.setHeader(CONTENT_TYPE, contentType);
        httpPost.setEntity(new StringEntity(data, charset));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        String resp;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, charset);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
        LoggerFactory.getLogger(getClass()).info("call [{}], param:{}, resp:{}", url, data, resp);
        return resp;
    }
}
