package cn.pluss.platform.sxf.impl;

import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.util.SxfConfg;
import cn.pluss.platform.sxf.SxfService;
import cn.pluss.platform.util.RSAUtils;
import cn.pluss.platform.util.SignUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
@RequiredArgsConstructor
public class SxfServiceImpl implements SxfService {

    private final RestTemplate restTemplate;

    @Override
    public JSONObject requestApi(String url, JSONObject reqData) {
        try {
            JSONObject paramMap = new JSONObject();
            paramMap.put("orgId", SxfConfg.ORG_ID);
            paramMap.put("reqId", UUID.randomUUID().toString().replaceAll("-", ""));
            paramMap.put("version", "1.0");
            paramMap.put("timestamp", DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
            paramMap.put("reqData", reqData);
            paramMap.put("signType", "RSA");
            String signContent = SignUtils.getSignContent(paramMap);
            paramMap.put("sign", RSAUtils.sign(SxfConfg.PRIVATE_KEY, signContent));
            log.info("===================>【随行付】请求参数:{}<================",paramMap);

            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, paramMap, JSONObject.class);
            // 检查网络请求状态
            if (!HttpStatus.OK.equals(responseEntity.getStatusCode())) {
                throw new MsgException("请求失败，请求状态异常");
            }

            log.info("=============return_info============");
            if (responseEntity.getBody() != null) {
                log.info(responseEntity.getBody().toJSONString());
            }
            return responseEntity.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            throw new MsgException("随行付接口异常");
        }
    }

    @Override
    public boolean checkSign(JSONObject responseData) throws Exception {
        // TODO 暂时先将验签的代码屏蔽
        String signContent = SignUtils.getSignContent(responseData);
        String sign = responseData.getString("sign");
        if (sign == null) {
            // 没有加签就不校验签名
            return true;
        }
        return RSAUtils.checkSign(SxfConfg.PUBLIC_KEY, signContent, sign);

//        return true;
    }
}