//package com.clx.user.aspect;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.TypeReference;
//import com.google.gson.Gson;
//import com.msl.common.base.Optional;
//import com.msl.common.dto.HttpDTO;
//import com.msl.common.result.Result;
//import com.msl.common.utils.EncryptUtil;
//import com.clx.user.dao.ThirdPartyEntryDao;
//import com.clx.user.enums.ThirdRequestStatusEnum;
//import com.clx.user.enums.ThirdRequestTypeEnum;
//import com.clx.user.enums.result.QualityResultEnum;
//import com.clx.user.model.ThirdPartRequestLog;
//import com.clx.user.model.ThirdPartyEntry;
//import com.clx.user.service.ThirdPartRequestLogService;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.StringUtils;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.annotation.Pointcut;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;
//
//import javax.servlet.http.HttpServletRequest;
//import java.io.BufferedReader;
//import java.io.InputStreamReader;
//import java.util.Objects;
//import java.util.UUID;
//
//import static com.clx.user.constant.CommonConstants.*;
//
//
//@Aspect
//@Component
//@Slf4j
//public class HttpAspect {
//
//    @Autowired
//    private ThirdPartyEntryDao thirdPartyEntryDao;
//    @Autowired
//    private ThirdPartRequestLogService thirdPartRequestLogService;
//
//    public HttpAspect() {
//    }
//
//    @Pointcut("execution(public * com.clx.user.controller.encrypt.*.*(..))")
//    public void all() {
//    }
//
//    @Around("all()")
//    public Object trackInfo(ProceedingJoinPoint pjp) throws Throwable {
//        // 从body里面取数据
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
//        String pathUrl = request.getRequestURI();
//        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
//        String line = null;
//        StringBuilder sb = new StringBuilder();
//        while ((line = br.readLine()) != null) {
//            sb.append(line);
//        }
//        br.close();
//
//        HttpDTO httpDTO = JSON.parseObject(sb.toString(), HttpDTO.class);
//        log.info("http接收到的加密参数-->{}", httpDTO);
//        ThirdPartyEntry thirdPartyEntry = thirdPartyEntryDao.getByAppId(httpDTO.getUserNo()).orElseThrow(QualityResultEnum.SIGN_NULL);
//        // 验证签名
//        if (!Objects.equals(httpDTO.getSign(), EncryptUtil.sign(thirdPartyEntry.getAppId(), thirdPartyEntry.getSecret(), httpDTO.getData(), httpDTO.getTimestamp()))) {
//            return back(Result.fail(QualityResultEnum.SIGN_ERROR), null, pathUrl, thirdPartyEntry);
//        }
//
//        // 验证请求时间戳是否超过10分钟
//        long currentTimeMillis = System.currentTimeMillis();
//        if (currentTimeMillis < httpDTO.getTimestamp() || (currentTimeMillis - httpDTO.getTimestamp()) > 600000) {
//            return back(Result.fail(QualityResultEnum.TIMESTAMP_ERROR), null, pathUrl, thirdPartyEntry);
//        }
//
//        // 解密后参数
//        String decrypt = EncryptUtil.decrypt(httpDTO.getData(), thirdPartyEntry.getSecret());
//        String param = JSON.parseObject(decrypt, String.class);
//        log.info("http接收到解密后的参数-->{}", param);
//        request.setAttribute(APP_ID, thirdPartyEntry.getAppId());
//        request.setAttribute(DATA, param);
//
//        Object proceed;
//        try {
//            proceed = pjp.proceed();
//        } catch (Exception e) {
//            log.error("", e);
//            proceed = Result.fail();
//        }
//        return back(proceed, param, pathUrl, thirdPartyEntry);
//    }
//
//    private HttpDTO back(Object obj, String param, String pathUrl, ThirdPartyEntry thirdPartyEntry) throws Exception {
//        Optional.ofNullable(obj)
//                .filter(p -> StringUtils.isNotBlank(param))
//                .filter(p -> Objects.nonNull(thirdPartyEntry))
//                .map(JSON::toJSONString)
//                .mapWithObj(new TypeReference<Result<Object>>() {
//                }, this::covertResult)
//                .peek(p -> thirdPartRequestLogService.save(new ThirdPartRequestLog()
//                        .setRequestId(UUID.randomUUID().toString())
//                        .setAppId(thirdPartyEntry.getAppId())
//                        .setRequestType(ThirdRequestTypeEnum.RECEIVE.getCode())
//                        .setUrl(pathUrl)
//                        .setRequestContent(param)
//                        .setResponseContent(JSON.toJSONString(p))
//                        .setStatusCode(p.getCode())
//                        .setStatus(p.succeed() ? ThirdRequestStatusEnum.SUCCESS.getCode() : ThirdRequestStatusEnum.FAIL.getCode())
//                        .setRetryTimes(0)));
//        return EncryptUtil.buildDTO(thirdPartyEntry.getAppId(), JSON.toJSONString(obj), thirdPartyEntry.getSecret(), System.currentTimeMillis());
//    }
//
//    private <T> Result<T> covertResult(String result, TypeReference<Result<T>> reference) {
//        return new Gson().fromJson(result, reference.getType());
//    }
//}
