package com.clx.performance.component;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.msl.common.dto.HttpDTO;
import com.msl.common.result.Result;
import com.msl.common.utils.EncryptUtil;
import com.msl.common.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;

import java.security.GeneralSecurityException;

@Slf4j
public class ThirdComponent {

    public static final String TRANSPORT_USER = "13403503399";
    public static final String TRANSPORT_KEY = "9Y1N5AUP8N2TI359";

//    @Autowired
//    private HttpLogService httpLogService;

//    /**
//     * post请求
//     *
//     * @param host
//     * @param httpEnum
//     * @param param
//     * @param httpLog
//     * @param isEncrypt
//     */
//    @Transactional(propagation = Propagation.NOT_SUPPORTED)
//    public Result<?> postRequest(String host, HttpEnum httpEnum, String param, HttpLog httpLog, boolean isEncrypt) {
//        if (Objects.nonNull(httpLog)) {
//            httpLog.setTryCount(httpLog.getTryCount() + 1);
//            httpLogService.updateHttpLogTryCount(httpLog);
//        } else {
//            httpLog = new HttpLog()
//                    .setMsgId(UUID.randomUUID().toString())
//                    .setType(httpEnum.getCode())
//                    .setRemark(httpEnum.getMark())
//                    .setUrl(httpEnum.getUrl())
//                    .setParam(param)
//                    .setStatus(HttpStatusEnum.HAVING.getCode())
//                    .setTryCount(1);
//            httpLogService.saveHttpLog(httpLog);
//        }
//        return isEncrypt ? encryptPost(host + httpLog.getUrl(), httpLog.getParam(), httpLog.getId()) : asyncPost(host + httpLog.getUrl(), httpLog.getParam(), httpLog.getId());
//    }
//
//    @Transactional(propagation = Propagation.NOT_SUPPORTED)
//    public Result<?> postRequestBroker(String host, HttpEnum httpEnum, String param, HttpLog httpLog, Map<String, Object> headers) {
//        if (Objects.nonNull(httpLog)) {
//            httpLog.setTryCount(httpLog.getTryCount() + 1);
//            httpLogService.updateHttpLogTryCount(httpLog);
//        } else {
//            httpLog = new HttpLog()
//                    .setMsgId(UUID.randomUUID().toString())
//                    .setType(httpEnum.getCode())
//                    .setRemark(httpEnum.getMark())
//                    .setUrl(httpEnum.getUrl())
//                    .setParam(param)
//                    .setStatus(HttpStatusEnum.HAVING.getCode())
//                    .setTryCount(1)
//                    .setHeader(JSON.toJSONString(headers));
//            httpLogService.saveHttpLog(httpLog);
//        }
//        return asyncPostBroker(host + httpLog.getUrl(), httpLog.getParam(), httpLog.getId(), headers);
//    }
//
//    /**
//     * get请求
//     *
//     * @param host
//     * @param httpEnum
//     * @param headers
//     * @param param
//     * @return
//     */
//    @Transactional(propagation = Propagation.NOT_SUPPORTED)
//    public Result<?> getRequest(String host, HttpEnum httpEnum, Map<String, Object> headers, HttpLog httpLog, Object... param) {
//        if (Objects.nonNull(httpLog)) {
//            httpLog.setTryCount(httpLog.getTryCount() + 1);
//            httpLogService.updateHttpLogTryCount(httpLog);
//        } else {
//            httpLog = new HttpLog()
//                    .setMsgId(UUID.randomUUID().toString())
//                    .setType(httpEnum.getCode())
//                    .setRemark(httpEnum.getMark())
//                    .setUrl(String.format(httpEnum.getUrl(), param))
//                    .setHeader(JSON.toJSONString(headers))
//                    .setParam("")
//                    .setStatus(HttpStatusEnum.HAVING.getCode())
//                    .setTryCount(1);
//            httpLogService.saveHttpLog(httpLog);
//        }
//        return asyncGet(host + httpLog.getUrl(), headers, httpLog.getId());
//    }
//
//    private Result<?> asyncGet(String url, Map<String, Object> headers, Integer httpLogId) {
//        try {
//            return Optional.ofBlank(HttpClientUtil.httpGetRequest(url, headers))
//                    .map(res -> JSON.parseObject(res, Result.class))
//                    .peek(result -> httpLogService.updateHttpLogStatus(httpLogId, result))
//                    .filter(Result::succeed)
//                    .orElse(new Result<>(ResultCodeEnum.FAIL));
//        } catch (Exception e) {
//            log.error("http请求错误---->httpLogId:{},url:{}", httpLogId, url, e);
//        }
//        return new Result<>(ResultCodeEnum.FAIL);
//    }
//
//    private Result<?> asyncPost(String url, String param, Integer httpLogId) {
//        try {
//            return Optional.ofBlank(HttpClientUtil.httpPostRequest(url, param))
//                    .map(res -> JSON.parseObject(res, Result.class))
//                    .peek(result -> httpLogService.updateHttpLogStatus(httpLogId, result))
//                    .filter(Result::succeed)
//                    .orElse(new Result<>(ResultCodeEnum.FAIL));
//        } catch (Exception e) {
//            log.error("http请求错误---->httpLogId:{},url:{},param:{}", httpLogId, url, param, e);
//        }
//        return new Result<>(ResultCodeEnum.FAIL);
//    }
//
//    private Result<?> asyncPostBroker(String url, String param, Integer httpLogId, Map<String, Object> headers) {
//        try {
//            String s = HttpClientUtil.httpPostRequestBroker(url, param, headers);
//            return Optional.ofBlank(s)
//                    .map(res -> JSON.parseObject(res, Result.class))
//                    .peek(result -> httpLogService.updateHttpLogStatus(httpLogId, result))
//                    .filter(Result::succeed)
//                    .orElse(new Result<>(ResultCodeEnum.FAIL));
//        } catch (Exception e) {
//            log.error("http请求错误---->httpLogId:{},url:{},param:{}", httpLogId, url, param, e);
//        }
//        return new Result<>(ResultCodeEnum.FAIL);
//    }

    public static String encrypt(String param) throws Exception {

        HttpDTO httpDTO = EncryptUtil.buildDTO(TRANSPORT_USER, param, TRANSPORT_KEY, System.currentTimeMillis());
        return JSONUtil.parse(httpDTO).toString();

    }

    public static String decrypt(String data) {
        try {
            return EncryptUtil.decrypt(data, TRANSPORT_KEY);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }

    public static Result<?> encryptPost(String url, String param, Integer httpLogId) {
        try {
            return HttpUtil.post(url, null,
                            EncryptUtil.buildDTO(TRANSPORT_USER, param, TRANSPORT_KEY, System.currentTimeMillis()))
                    .map(r -> JSON.parseObject(r, new TypeReference<HttpDTO>() {
                    }))
                    .peek(dto -> log.info("http请求返回------dto->{}", dto))
                    .mapTry(dto -> EncryptUtil.decrypt(dto.getData(), TRANSPORT_KEY))
                    .map(t -> {
                                return JSONUtil.toBean(t, Result.class);
                            }
                    ).get();

//                    .peek(result -> httpLogService.updateHttpLogStatus(httpLogId, result))
        } catch (GeneralSecurityException e) {
            log.error("解密失败", e);
            throw new RuntimeException();
        }
    }

}
