package mobvista.dmp.datasource.baichuan;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import mobvista.dmp.util.PropertyUtil;
import org.apache.http.Consts;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * @package: mobvista.dmp.datasource.baichuan
 * @author: wangjf
 * @date: 2019-08-26
 * @time: 15:44
 * @email: jinfeng.wang@mobvista.com
 * @phone: 152-1062-7698
 */

public class BaiChuanServerV2 {

    private static String serverUrl = PropertyUtil.getProperty("config.properties", "dsp.taobao.server.url");
    private static String channel = PropertyUtil.getProperty("config.properties", "dsp.taobao.server.channel");
    private static String adid = PropertyUtil.getProperty("config.properties", "dsp.taobao.server.adid");

    public static JSONObject request(Logger logger, AsoDevice asoDevice, int appOs) throws NoSuchAlgorithmException, KeyManagementException {
        SSLUtil.turnOffSsl();
        CloseableHttpClient client = HttpClients.createDefault();
        List<BasicNameValuePair> formparams = new ArrayList<>();
        formparams.add(new BasicNameValuePair("channel", channel));
        formparams.add(new BasicNameValuePair("adid", adid));
        if (appOs == 1) {
            formparams.add(new BasicNameValuePair("imei", asoDevice.getDeviceId()));
        } else if (appOs == 2) {
            formparams.add(new BasicNameValuePair("idfa", asoDevice.getDeviceId()));
        } else {
            formparams.add(new BasicNameValuePair("imeiMd5", asoDevice.getDeviceId()));
        }

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000).setConnectionRequestTimeout(1000)
                .setSocketTimeout(1000).build();
        HttpPost post = new HttpPost(serverUrl);
        JSONObject jsonObject = new JSONObject();
        CloseableHttpResponse response;
        try {
            post.setConfig(requestConfig);
            post.setEntity(entity);
            response = client.execute(post);
            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            jsonObject = JSON.parseObject(result.toString());
        } catch (Exception e) {
            jsonObject.put("result", true);
        } finally {
            post.abort();
        }
        return jsonObject;
    }

    public static void main(String[] args) throws JoranException {

        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(context);
        context.reset();
        configurator.doConfigure(BaiChuanServer.class.getClassLoader().getResourceAsStream("logback-syslog.xml"));
        Logger logger = context.getLogger("baichuan");

        /*
        String[] deviceIds = {"7E6C6738-9911-4F2A-9A3F-38CA18E93A48", "7E6C7D96-5738-4034-B3B6-C34AB262F09F", "7E6C9685-2A81-49D8-98B7-63EE23911310", "7E6CA0FF-2795-48E1-AABE-F772F3F96DF9",
                "7E6CB2C7-F793-4D45-9FD5-51545BFCD2A6", "7E6CC03D-84DB-44DA-84AF-90D654B09B18", "7E6CC45B-671E-4D5F-9E45-3710E3F26C04", "7E6CC640-F0A6-4E60-8DC8-3ADD2E294DB8", "7E6CF4A0-BC05-4F2B-B8B0-E01FA030441C",
                "7E6D1661-DF63-43C5-B686-4E1366E3168F"};
        String[] deviceIds = {"7469d0a9beeaf02a640b786777a5d7b3", "0f2dfff5f1a5a8a9ee7a1f64004e7f80", "fcc82d399a68bc3f34baac90eeb8bc52", "48be8c3d0364abd1efcc7ddb584e4dcf",
                "85299e58bd8038c340d8f4e3c513bbbe", "99a61b76692427b174b35af965525b45", "549dc723069ce38adbcb14eb1656bf56"};


        String[] deviceIds = {"863388035513055", "867771030124950", "866939037784479", "355085080884135", "866250038018309", "867676035339877", "865631037762776", "863894032393417", "868874033544924", "868917034034013", "253057267226036"};
        */
        String[] deviceIds = {"D280F1BD-C32E-4AAD-B3CD-E1D1EAAA7E1F",
                "F181E87C-9E4B-4CD5-81C9-AD64B9BD1A7B",
                "73073946-20B9-4804-A106-6193F89FA763",
                "8CA22FCA-A244-42F3-894A-331781876E04",
                "EF036591-55CB-4F90-8949-A8698BEC410C",
                "8E668447-521B-4ABA-AAB2-C4B3B32C8CFB",
                "9A230116-EEF2-4B7D-BD89-87B53D1215BC",
                "9ECBAE40-FAB8-4C23-B574-F373BA24C58B",
                "C9CD4B81-43A2-4672-8809-1035E3AA3947"};

        /**
         * 因百川并发限制，设置总线程数为 200
         */
        /*
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("ali-%d").build();
        ExecutorService aliPool = new ThreadPoolExecutor(10, 10,
                120L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
        //  CloseableHttpClient client = HttpClients.createDefault();
        for (int reqId = 0; reqId < 7; reqId++) {
            int finalReqId = reqId;
            aliPool.execute(() -> {
                //  runJob(finalIpId, map.get(finalReqId));
                try {
                    Random random = new Random();
                    KV kv = new KV();
                    String deviceId = deviceIds[random.nextInt(7)];
                    kv.setDeviceId(deviceId);
                    kv.setAppOs(1);
                    JsonObject jsonObject = request(logger, serverUrl, channel, adid, kv);
                    logger.info(deviceId + "  ===  " + jsonObject.toString());
                    Thread.sleep(200);
                } catch (InterruptedException | NoSuchAlgorithmException | KeyManagementException e) {
                    e.printStackTrace();
                }
            });
        }
        aliPool.shutdown();
        */
        //  Set<String> deviceSet = new HashSet<>();
        for (String deviceId : deviceIds) {
            //  deviceSet.add(deviceId);
            //  AsoDevice asoDevice = BaiChuanMainV2.returnClass("2", "1", deviceId);
            //  JSONObject jsonObject = BaiChuanServerV2.request(logger, asoDevice, 1);
            //  System.out.println(jsonObject);
        }
        /*
        try {
            AlibabaBaichuanAsoQueryResponse rsp = AliServer.asoRequest("2", "2", deviceSet);
            if (rsp != null && rsp.getResult() != null && rsp.getResult().getSuccess()) {
                for (AlibabaBaichuanAsoQueryResponse.AsoDeviceCheckResult checkResult : rsp.getResult().getResults()) {
                    AsoDevice asoDevice = new AsoDevice();
                    System.out.println(checkResult.getIsNewDevice());
                }
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        */
    }
}
