package com.izouma.dingdong.service;

import com.izouma.dingdong.dto.Send;
import com.izouma.dingdong.service.tencent.UserSigService;
import com.tencent.xinge.XingeApp;
import com.tencent.xinge.bean.AudienceType;
import com.tencent.xinge.bean.Message;
import com.tencent.xinge.bean.MessageType;
import com.tencent.xinge.push.app.PushAppRequest;
import com.tencentyun.TLSSigAPIv2;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.*;

@SpringBootTest
@RunWith(SpringRunner.class)
public class UserSigServiceTest {
    @Autowired
    private UserSigService userSigService;

    @Test
    public void test() {
//        System.out.println(userSigService.generateUserSig(2244L));
        TLSSigAPIv2 api = new TLSSigAPIv2(1400375593, "7fe225c3b41cf2e7f0c79ebaf0e3b7ec60f6c7188e1561dcfddacb4767654417");
        System.out.println(api.genSig("2244", 30000));
    }

    @Test
    public void test1() {
//        String url1 = "https://console.tim.qq.com/v4/openim/batchsendmsg?random=99999999&contenttype=json";
//        String url2 = "&sdkappid=1400375593&identifier=administrator&usersig=eJw1jrEOgjAURf*ls4GWV0ogcXFgwmgCRgcWYot5KohtAzXGf7cBvdu9Jye5b1IVZaDcgFqRDKjPap5GpUlGooCSpRt5a4YBJckYpxSSOE5hIShVb7HFWWhkhz0aqxv70H8VL544XZScTdVrd3Z1KKAOT8oIzmyRX8VB7vPnSO*RmTbHdmvWP9Vi52*xOOUJAGP88wUitDTf";
//        url1 = url1 + url2;
        String url1 = "https://console.tim.qq.com/v4/all_member_push/im_push?sdkappid=1400375593&identifier=administrator&usersig=eJw1jkEKwjAURO*SrVJTkzS04EIwQsFdqm7cBJLqR9t*0kSk4t0trc5u5vFg3qQ66MS9ELwjBaNjltP0dJ4UZJ1QMvfe3g0iWFKknFImhcjZTMC6NkANk2BsAy30wZvQ*b8K15EMZleyWIMe8HbWj7Ly1T5TaDRGWPDLinGmhi4qPG2Pm58ZoBlfpSKXGedSys8XCL808Q__&random=99999999&contenttype=json";

        String result = "";
        try {
            URL url = new URL(url1);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            // 腾讯地图使用GET
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            // 获取地址解析结果
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            System.out.println(line);
            in.close();
        } catch (Exception e) {
            e.getMessage();
        }
        System.out.println(result);
    }

    @Test
    public void test2() {
        XingeApp xingeApp = new XingeApp.Builder()
                .appId("1400375593")
                .secretKey("7fe225c3b41cf2e7f0c79ebaf0e3b7ec60f6c7188e1561dcfddacb4767654417")
                .domainUrl("https://api.tpns.tencent.com/")
                .build();

        PushAppRequest pushAppRequest = new PushAppRequest();
        //完善PushAppRequest  消息
        pushAppRequest.setMessage_type(MessageType.notify);
        pushAppRequest.setAudience_type(AudienceType.all);

        Message message = new Message();
        message.setTitle("系统消息");
        message.setContent("提现成功！！");
        pushAppRequest.setMessage(message);

        JSONObject ret = xingeApp.pushApp(pushAppRequest);
        System.out.println(ret);
    }

    @Test
    public void test3() {
//        String PayDomain = "https://console.tim.qq.com";
        String url = "https://console.tim.qq.com/v4/all_member_push/im_push?sdkappid=1400375593&identifier=administrator&usersig=eJw1js8LgjAcxf*XXQvZD9dw0EXxEIQEdvK22Movoo45cxH97w2td3vv8eG9N7qe68QEC84gyXDUfo2exiGJaILR5ifdKWtBI0lSjJngPGNbA9oMHu6wAkr3MMDknfKj*6PwiE3NqDo14wzpXJXVjvS6nDvyavMCbsXS4HAJ7VD6thPL8Qd66OMpwjMRJyk5fL7E9jS*&random=99999999&contenttype=json";
//        String url1 = "/v4/openim/sendmsg";

        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        //设置公共参数

        Map<String, Object> mgsCon = new HashMap<>();
        mgsCon.put("Text", "hello");

        Map<String, Object> mgs = new HashMap<>();
        mgs.put("MsgType", "TIMTextElem");
        mgs.put("MsgContent", mgsCon);

        Map<String, Object> params = new HashMap<>();
        params.put("SyncOtherMachine", 2);
        params.put("To_Account", "2244");
        params.put("MsgRandom", "99999");
        params.put("MsgBody", mgs);


        System.out.println(params.toString());
        //回调
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String value = String.valueOf(params.get(name));
            urlParameters.add(new BasicNameValuePair(name, value));
        }
//        String sign = KsherSign(params);
//        urlParameters.add(new BasicNameValuePair("sign", sign));
//        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        try {
            HttpResponse response = client.execute(post);
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            rd.close();
            System.out.println(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }


//        com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(result.toString());
//        boolean isVerify = KsherVerify(json.getJSONObject("data"), json.getString("sign"));
//        if (isVerify) {
//        System.out.println(result.toString());
//        } else {
//            throw new Exception("verify signature failed");
//        }
    }

    @Test
    public void testP() {
        String url = "https://console.tim.qq.com/v4/openim/sendmsg" +
                "?sdkappid=1400375593&identifier=test" +
                "&usersig=eJwtzEELgjAYxvHvsnPIu*mrTuiUFyMvGoFHy9VexBpuxCL67sn0*Pwe*H-Z*dRGbzWzgokI2C5sGtTT0Z0CO2Xd5nYYe2NoYAVPAOIMUcbro7yhWS2OiAIAVnU0BZNZmqQyEVuFHkv2oMv601Riahu8Wt5djshFn*u6A8-n1y2ryAsjR13me-b7A*ggMII_" +
                "&random=99999999&contenttype=json";

        Send send = new Send();
        send.setMsgRandom(99999);
        send.setToAccount("2105");
        Send.MsgBody msgBody = Send.MsgBody.builder()
                .msgType("TIMTextElem")
                .msgContent(Send.MsgBody.MsgContent.builder()
                        .text("beauty")
                        .build())
                .build();

        Send.MsgBody[] msg =  {msgBody};
        send.setMsgBody(msg);


        String s1 = com.alibaba.fastjson.JSONObject.toJSONString(send);

        System.out.println(s1);

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);

        //添加请求头
        post.setHeader("User-Agent", "Mozilla/5.0");
        post.setHeader("Content-type", "application/json");

        StringEntity s = new StringEntity(s1, "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));


/*        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("MsgBody", mgs.toString()));
        urlParameters.add(new BasicNameValuePair("MsgRandom", "99999"));
        urlParameters.add(new BasicNameValuePair("To_Account", "2244"));
        urlParameters.add(new BasicNameValuePair("SyncOtherMachine", "2"));*/

        try {
            post.setEntity(s);
//            post.setEntity(new UrlEncodedFormEntity(urlParameters));

            HttpResponse response = client.execute(post);
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + post.getEntity());
            System.out.println("Response Code : " +
                    response.getStatusLine().getStatusCode());

            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));

            StringBuilder result = new StringBuilder();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }

            System.out.println(result.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test5(){
        userSigService.sendSms(2105L,"voice_667;订单来啦！注意查收!!!");
        //System.out.println(LocalDateTime.now().plusSeconds(86400));
    }
}
