package com.horizon.wf.util;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
//import com.shanxinsoft.modules.log.dao.InfLogOperationDao;
//import com.shanxinsoft.modules.log.entity.InfLogOperationEntity;
import org.apache.commons.lang3.StringUtils;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 宝信信使工具类
 */
@Component
public class BaoSightMessengerUtils {

    private static String preUrl = "http://10.19.12.248/open-api";

    // 这些字符在JavaScript的encodeURIComponent中不会被编码
    private static final String SAFE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~*'()";


//    static InfLogOperationDao logOperationDao;


    // 静态注入日志Dao
//    @Autowired
//    public void setLogOperationDao(InfLogOperationDao logOperationDao) {
//        BaoSightMessengerUtils.logOperationDao = logOperationDao;
//    }


    public static Boolean sendWithLog(String operation, String url, String jsonBody, String businessId) {
        // 记录日期
        long beginTime = System.currentTimeMillis();
        Map<String, String> headerMap = new HashMap<>();
        String token = getToken();
        System.err.println(token);
        if (StringUtils.isNotBlank(token)) {
            headerMap.put("Authorization", "Bearer" + " " + token);
            url = preUrl + url;
            System.err.println("------");
            System.err.println(url);
            String result = HttpRequest.post(url).addHeaders(headerMap).body(jsonBody).execute().body();
            System.err.println(jsonBody);
            System.err.println(result);
            System.err.println("------");

            // 开始保存日志
//            InfLogOperationEntity logEntity = new InfLogOperationEntity();
//            logEntity.setProducer("费控系统");
//            logEntity.setConsumer("宝信信使");
//            logEntity.setRequestMethod("POST");
//            logEntity.setOperation(operation);
//            logEntity.setBusinessId(businessId);
//            logEntity.setRequestUri(url);
//            logEntity.setRequestParams(jsonBody);
//            logEntity.setRequestHeaders(JSONUtil.toJsonStr(headerMap));
//            logEntity.setCreateDate(new Date());
//            logEntity.setStatus(0);
//            logEntity.setResult(result);
//            //执行时长(毫秒)
            long time = System.currentTimeMillis() - beginTime;
//            logEntity.setRequestTime((int) time);
            boolean flag = isResultSuccess(result);
//            if (!flag) {
//                logEntity.setStatus(1);
//            }
//            logOperationDao.insert(logEntity);
            return flag;
        }
        return false;
    }


    public static boolean isResultSuccess(String result) {
        if (StringUtils.isNotBlank(result)) {
            Map resultMap = JSONUtil.toBean(result, Map.class);
            if (resultMap != null && resultMap.containsKey("statusCode")) {
                int statusCode = (int) resultMap.get("statusCode");
                if (statusCode == 1) {
                    return true;
                }
            }
        }
        return false;
    }


    public static String getToken() {
        String clientId = "sgsteel_intelligence";
        String clientSecret = "f42fc4bebd4641d09f426e80a1882a2ef261e1a80c7232bef11a1ff255934bac";
        String url = "http://10.19.12.248/uaa/oauth/token?grant_type=client_credentials&client_id="+clientId+"&client_secret="+clientSecret;
        String resultBody = HttpRequest.post(url).execute().body();
        if (StringUtils.isNotBlank(resultBody)) {
            Map resultMap = JSONUtil.toBean(resultBody, Map.class);
            if (resultMap.containsKey("access_token")) {
                return resultMap.get("access_token").toString();
            }
        }
        return null;
    }


    /**
     * 模仿JavaScript的encodeURIComponent方法
     *
     * @param s 要编码的字符串
     * @return 编码后的字符串
     * @throws UnsupportedEncodingException 如果不支持UTF-8编码
     */
    public static String encodeURIComponent(String s) throws UnsupportedEncodingException {
        if (s == null) {
            return null;
        }
        // 使用URLEncoder进行编码，但之后我们会替换掉不需要编码的字符
        String encoded = URLEncoder.encode(s, "UTF-8");
        // 创建一个Pattern来匹配所有需要被替换回原样的字符
        Pattern pattern = Pattern.compile("%([0-9A-Fa-f]{2})");
        StringBuilder result = new StringBuilder();
        Matcher matcher = pattern.matcher(encoded);
        int last = 0;
        while (matcher.find()) {
            // 提取出%编码的字符
            String hex = matcher.group(1);
            // 将其转换回字符
            char ch = (char) Integer.parseInt(hex, 16);
            // 如果这个字符在SAFE_CHARS中，则将其替换回原字符
            if (SAFE_CHARS.indexOf(ch) != -1) {
                result.append(encoded.substring(last, matcher.start()));
                result.append(ch);
                last = matcher.end();
            }
        }
        // 添加最后一个匹配项之后的所有内容
        result.append(encoded.substring(last));

        return result.toString();
    }


//    public static void saveErrorLog(String operation, String error, String businessId) {
//        InfLogOperationEntity entity = new InfLogOperationEntity();
//        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//        if (ObjectUtil.isNotNull(request)) {
//            entity.setIp(IpUtils.getIpAddr(request));
//            entity.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
//            entity.setRequestHeaders(JSONUtil.toJsonStr(request.getHeaderNames()));
//            entity.setRequestUri(request.getRequestURI());
//            entity.setRequestMethod(request.getMethod());
//        }
//        entity.setOperation(operation);
//        entity.setStatus(1);
//        if (error.length() > 3500) {
//            error = error.substring(0, 3499);
//        }
//        entity.setProducer("费控系统");
//        entity.setConsumer("宝信信使");
//        entity.setErrorInfo(error);
//        entity.setBusinessId(businessId);
//        entity.setCreateDate(new Date());
//
//        logOperationDao.insert(entity);
//
//    }


}
