package com.pcloud.common.utils.httpclient;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pcloud.common.utils.rsa.MD5;
import com.pcloud.common.utils.string.StringUtil;
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.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author：songx
 * @date：2017年12月4日,下午4:58:39
 */
public class UrlUtils {

    /**
     *
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(UrlUtils.class);

    /**
     * 请求地址(新郎接口)
     */
    private static final String REQUEST_URL = "https://api.weibo.com/2/short_url/shorten.json?source=1681459862&url_long=";

    /**
     * 请求地址(OWN)
     */
    private static final String REQUEST_URL2 = "https://rays.5rs.me/convert/v1.0/url/shorten";

    /**
     * 获取短链接(新浪)
     *
     * @param long_url
     * @return
     */
    public static String getShortUrl(String long_url) {
        String result = callHttp(long_url);
        if (StringUtil.isEmpty(result)) {
            return null;
        }
        JSONObject resultObject = JSONObject.parseObject(result);
        JSONArray array = resultObject.getJSONArray("urls");
        JSONObject object = array.getJSONObject(0);
        return object.getString("url_short");
    }

    /**
     * 发送请求(新浪)
     *
     * @param long_url
     * @return
     */
    private static String callHttp(String long_url) {
        LOGGER.info("【URL】短链接转换(新浪),<START>.[long_url]=" + long_url);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(REQUEST_URL + long_url);
        String resContent = null;
        try {
            CloseableHttpResponse response = httpclient.execute(httpGet);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                resContent = EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            LOGGER.error("【URL】短链接转换失败(新浪):" + e.getMessage(), e);
        }
        LOGGER.info("【URL】短链接转换(新浪),<END>.[resContent]=" + resContent);
        return resContent;
    }

    /**
     * 获取短链接(OWN)
     *
     * @param long_url
     * @return
     */
    public static String getShortUrl4Own(String long_url) {
        String result = callHttp4Own(long_url);
        if (StringUtil.isEmpty(result)) {
            return null;
        }
        JSONObject resultObject = JSONObject.parseObject(result);
        JSONObject dataObject = resultObject.getJSONObject("data");
        return dataObject == null ? null : dataObject.getString("shortUrl");
    }

    /**
     * 发送请求(OWN)
     *
     * @param long_url
     * @return
     */
    private static String callHttp4Own(String long_url) {
        LOGGER.info("【URL】短链接转换(OWN),<START>.[long_url]=" + long_url);
        if (StringUtil.isEmpty(long_url)) {
            return null;
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(REQUEST_URL2);
        String resContent = null;
        try {
            //设置参数到请求对象中
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("originUrl", long_url);
            StringEntity stringEntity = new StringEntity(jsonObject.toJSONString(), Charset.forName("UTF-8"));
            httpPost.setEntity(stringEntity);
            //设置header信息
            //指定报文头【Content-type】、【User-Agent】
            httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
            CloseableHttpResponse response = httpclient.execute(httpPost);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                resContent = EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            LOGGER.error("【URL】短链接转换失败(OWN):" + e.getMessage(), e);
        }
        LOGGER.info("【URL】短链接转换(OWN),<END>.[resContent]=" + resContent);
        return resContent;
    }

    /**
     * 缩短链接
     *
     * @param url
     * @return
     */
    public static String[] shortenUrl(String url) {
        // 可以自定义生成 MD5 加密字符传前的混合 KEY
        String key = "lgsc1205";
        // 要使用生成 URL 的字符
        String[] chars = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
                "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z"

        };
        // 对传入网址进行 MD5 加密
        String hex = MD5.getMD5Str(key + url);

        String[] resUrl = new String[4];
        for (int i = 0; i < 4; i++) {

            // 把加密字符按照 8 位一组 16 进制与 0x3FFFFFFF 进行位与运算
            String sTempSubString = hex.substring(i * 8, i * 8 + 8);

            // 这里需要使用 long 型来转换，因为 Inteper .parseInt() 只能处理 31 位 , 首位为符号位 ,
            // 如果不用long ，则会越界
            long lHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16);
            String outChars = "";
            for (int j = 0; j < 7; j++) {
                // 把得到的值与 0x0000003D 进行位与运算，取得字符数组 chars 索引
                long index = 0x0000003D & lHexLong;
                // 把取得的字符相加
                outChars += chars[(int) index];
                // 每次循环按位右移 4 位
                lHexLong = lHexLong >> 4;
            }
            // 把字符串存入对应索引的输出数组
            resUrl[i] = outChars;
        }
        return resUrl;
    }

}
