package com.jpsoft.shinestar.modules.wechat.callback;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Data
public class EventCallback {
    private String code;
    private String callbackUrl;
    private String message;

    public EventCallback(){

    }

    public EventCallback(String code, String callbackUrl){
        this.code = code;
        this.callbackUrl = callbackUrl;
//        this.message = message;
    }

    public boolean process(String wechatId, String openId, String eventKey){
        boolean result = false;

        try {
            StringBuilder urlBuilder = new StringBuilder();

            urlBuilder.append(this.callbackUrl);

            HttpPost httpPost = new HttpPost(urlBuilder.toString());

            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(5000)
                    .setConnectTimeout(5000)
                    .setConnectionRequestTimeout(5000)
                    .build();

            CloseableHttpClient httpClient = HttpClientBuilder.create()
                    .setDefaultRequestConfig(requestConfig)
                    .build();

            List<NameValuePair> list = new ArrayList<NameValuePair>();
            list.add(new BasicNameValuePair("eventKey", eventKey));
            list.add(new BasicNameValuePair("wechatId", wechatId));
            list.add(new BasicNameValuePair("openId", openId));

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
            httpPost.setEntity(entity);

            HttpResponse res = httpClient.execute(httpPost);

            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String content = EntityUtils.toString(res.getEntity());
                this.setMessage(content);

                result = true;
            }
            else{
                this.setMessage("发送请求到业务平台失败!");
            }
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);

            result = false;
            this.setMessage(ex.getMessage());
        }

        return result;
    }
}
