package com.testor.module.video.util;

import com.testor.common.constant.IotUrlAttributes;
import com.testor.config.utils.RsaUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@Component
public class RestUtil {
    @Autowired
    private RestTemplate restTemplate;


    @Value("${three.video.url}")
    private String threeVideoUrl;

    private static final String SESSIONID = "sessionId";
    //一些自定义的请求头参数
    public static final String supplierID = "";
    public static final String interfacekey = "";

    /**
     * DLT专用执行方法
     *
     * @param param  请求参数：可以添加一些常量请求值
     * @param url    访问的url
     * @param method 请求的方法
     * @return
     */
    public String execute(Map<String, Object> param, String url, HttpMethod method) {
        HttpHeaders headers = this.getDefaultHeader();
        Map<String, Object> requestor = this.getDefaultParam();
        param.put("requestor", requestor);
        param.put("supplierID", supplierID);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(param, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, method, requestEntity, String.class);
        return response.getBody();
    }

    /**
     * 获取默认的头请求信息
     *
     * @return
     */
    public HttpHeaders getDefaultHeader() {
        String timestamp = "" + System.currentTimeMillis();
        String signature = EncoderByMd5(supplierID + timestamp + interfacekey);
        HttpHeaders headers = new HttpHeaders();
        headers.add("signature", signature);
        headers.add("timestamp", timestamp);
        return headers;
    }


    /**
     * 获取默认的参数
     *
     * @return
     */
    public Map<String, Object> getDefaultParam() {
        Map<String, Object> defParam = new HashMap<>();
        defParam.put("invoker", "xx");
        defParam.put("operatorName", "xx");
        return defParam;
    }


    /**
     * 通过MD5加密
     *
     * @param str
     * @return
     */
    public static String EncoderByMd5(String str) {
        if (str == null) {
            return null;
        }
        try {
            // 确定计算方法
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base64en = new BASE64Encoder();
            // 加密后的字符串
            return base64en.encode(md5.digest(str.getBytes("utf-8"))).toUpperCase();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            return null;
        }
    }


    /**
     * get请求
     *
     * @param
     * @param
     * @return
     */
    public <T> ResponseEntity<T> get(String url, Class<T> responseType) {
        return request(url, HttpMethod.GET, responseType);

    }

//    public <T> ResponseEntity<T> get(String url, Map<String, String> param, Class<T> responseType) {
//        if (StringUtils.isEmpty(url)) {
//            throw new IllegalArgumentException();
//        }
//        Set<Map.Entry<String, String>> entries = param.entrySet();
//        //设置http的header
//        HttpHeaders headers = new HttpHeaders();
//        //headers.setContentType(MediaType.valueOf(MediaType.TEXT_PLAIN_VALUE));
//        headers.add(SESSIONID, apisixProperties.getToken());
//        HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers);
//        ResponseEntity<T> exchange = null;
//        System.out.println(url);
//        try {
//            exchange = restTemplate.getForEntity("http://" + url, responseType, param);
//        } catch (Exception e) {
//
//        }
//        return exchange;
//
//
//    }

    /**
     * post请求
     *
     * @param
     * @param jsonData 请求参数
     * @return
     */
    public <T> ResponseEntity<T> post(String url, String jsonData, Class<T> responseType) {

        return request(url, jsonData, HttpMethod.POST, responseType);
    }

    /**
     * patch请求
     *
     * @param
     * @param jsonData 请求参数
     * @return
     */
    public <T> ResponseEntity<T> patch(String url, String jsonData, Class<T> responseType) {

        return request(url, jsonData, HttpMethod.PATCH, responseType);
    }

    /**
     * put请求
     *
     * @param
     * @param jsonData 请求参数
     * @return
     */
    public <T> ResponseEntity<T> put(String url, String jsonData, Class<T> responseType) {
        return request(url, jsonData, HttpMethod.PUT, responseType);
    }

    /**
     * delete请求
     *
     * @param
     * @return
     */
    public <T> ResponseEntity<T> delete(String url, Class<T> responseType) {
        return request(url, HttpMethod.DELETE, responseType);
    }

    /**
     * 发送请求带参数
     *
     * @param url        请求地址
     * @param jsonData   请求参数
     * @param httpMethod 请求方法
     * @return
     */
    private <T> ResponseEntity<T> request(String url, String jsonData, HttpMethod httpMethod, Class<T> responseType) {
        ResponseEntity<T> response;
        try {
            if (StringUtils.isEmpty(url)) {

                throw new IllegalArgumentException();
            }
            //设置http的header
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            //String sessionId = CacheUtil.getIfPresent(SESSIONID);
            String token = CacheUtil.getIfPresent("token");
            if (!StringUtils.isNotBlank(token)) {
                //缓存中没有登录信息，先登录获取登录信息
                this.toLogin();
            }
            //headers.add(SESSIONID, CacheUtil.getIfPresent(SESSIONID));
            headers.add("X-Access-Token", token);
            headers.add("Authorization", "Bearer " + token);
            headers.add("Keep-Alive", "timeout=20");
            HttpEntity<String> requestEntity;
            if (!StringUtils.isNotBlank(jsonData)) {
                requestEntity = new HttpEntity<String>(headers);
            } else {
                requestEntity = new HttpEntity(jsonData, headers);
            }
            response = restTemplate.exchange(threeVideoUrl + url, httpMethod, requestEntity, responseType);
            return response;
        } catch (Exception ex) {
            ex.printStackTrace();
            response = new ResponseEntity<>(HttpStatus.BAD_GATEWAY);
            return response;
        }
    }

    /**
     * @param url        请求的url
     * @param httpMethod
     * @return
     */
    private <T> ResponseEntity<T> request(String url, HttpMethod httpMethod, Class<T> responseType) {
        return this.request(url, null, httpMethod, responseType);
    }

    private void toLogin() {
        //请求头信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        String userName = "safetyenvironment";
        String password = "";
        try {
            password = RsaUtils.encryptByPublicKey("pp*Du1LnZHH#k=");
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 创建一个包含账号和密码的请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("username", userName);
        requestBody.put("password", password);

        // 创建HttpEntity对象，将请求体和请求头添加到其中
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);


        ResponseEntity<Map> exchange = restTemplate.exchange(threeVideoUrl + IotUrlAttributes.LOGIN_PATH, HttpMethod.POST, requestEntity, Map.class);
        if (exchange.getStatusCode() == HttpStatus.OK) {
            if ("200".equals(exchange.getBody().get("code").toString())) {
                Map<String, String> data = (Map<String, String>) exchange.getBody().get("result");
                //CacheUtil.put(SESSIONID, data.get("sessionId"));
                CacheUtil.put("token", data.get("token"));
            }
        }
    }
}
