package mobvista.dmp.datasource.ali;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaBaichuanAsoQueryRequest;
import com.taobao.api.response.AlibabaBaichuanAsoQueryResponse;
import mobvista.dmp.util.PropertyUtil;
import org.apache.commons.lang.StringUtils;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @package: mobvista.dmp.datasource.ali
 * @author: wangjf
 * @date: 2020/4/29
 * @time: 5:42 下午
 * @email: jinfeng.wang@mobvista.com
 * @phone: 152-1062-7698
 */
public class AliServer {

    static String asoServerUrl = "http://gw.api.taobao.com/router/rest";

    static String appKey = "27831402";

    static String appSecret = "fe7d464abab8c4e57ea426916b974f22";

    /**
     * @param appId 应用ID，1-tmail,2-taobao
     * @param appOs 设备ID类型，1-android,2-ios
     * @throws ApiException
     * @returngetDspFeature(v)
     */
    public static AlibabaBaichuanAsoQueryResponse asoRequest(String appId, String appOs, Set<String> deviceSet) throws ApiException {
        String serverUrl = PropertyUtil.getProperty("config.properties", "http.server.url");
        //  可替换为您的沙箱环境应用的AppKey
        String appKey = PropertyUtil.getProperty("config.properties", "http.server.appKey");
        //  可替换为您的沙箱环境应用的AppSecret
        String appSecret = PropertyUtil.getProperty("config.properties", "http.server.appSecret");
        TaobaoClient client = new DefaultTaobaoClient(serverUrl, appKey, appSecret);
        AlibabaBaichuanAsoQueryRequest req = new AlibabaBaichuanAsoQueryRequest();
        /**
         *  1-tmail,2-taobao
         */
        req.setAppId(appId);
        /**
         *  1-android,2-ios
         */
        req.setAppOs(Long.parseLong(appOs));
        //  the array size of deviceInfoList must be less than 20.
        List<AlibabaBaichuanAsoQueryRequest.ASODeviceInfoDO> list = new ArrayList<>();
        for (String deviceId : deviceSet) {
            AlibabaBaichuanAsoQueryRequest.ASODeviceInfoDO obj = new AlibabaBaichuanAsoQueryRequest.ASODeviceInfoDO();
            list.add(obj);
            if (StringUtils.isNotBlank(deviceId)) {
                if (Integer.parseInt(appOs) == 1) {
                    obj.setImei(deviceId);
                } else {
                    obj.setIdfa(deviceId.toUpperCase());
                }
            }
        }
        req.setDeviceInfoList(list);
        AlibabaBaichuanAsoQueryResponse rsp = client.execute(req);
        return rsp;
    }

    static String serverUrl = "https://bombonera-dsp.taobao.com/cpm/ask";
    static String channel = "2015";
    static String adid = "0";

    public static JSONObject dspRequest(String deviceId, int appOs) {

        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", deviceId));
        } else if (appOs == 2) {
            formparams.add(new BasicNameValuePair("idfa", deviceId.toUpperCase()));
        } else {
            formparams.add(new BasicNameValuePair("imeiMd5", deviceId));
        }
        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) {
            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 (IOException ex) {
                jsonObject.put("result", true);
            }
        } finally {
            post.abort();
        }
        return jsonObject;
    }
}
