package com.hz.pm.sync.open.manage;

import com.google.common.base.Joiner;
import com.hz.pm.sync.scheduler.model.dto.ForwardDTO;
import com.hz.pm.sync.common.constant.BizConst;
import com.hz.pm.sync.common.utils.CryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @Classname IrsManage
 * @Description
 * @Date 2023/9/1 15:15
 * @Author PoffyZhang
 */
@Component
@Slf4j
public class IrsManage {


        /**
         * 转发IRS请求
         * @param dto
         * @return
         */
    public String forward(ForwardDTO dto) {
        try{
            String url = dto.getUrl();
            String appkey = dto.getAppKey();
            long timestamp = System.currentTimeMillis();
            String requestSecret = dto.getSecret();
            String sign = CryptUtils.MD5Encode(appkey + requestSecret + timestamp);
            url = url + "?requestTime=" + timestamp + "&sign=" + sign + "&" +  asUrlParams(dto.getData());
            log.info("url :{}",url);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
            log.info(forEntity.getBody());
            return forEntity.getBody();
        }catch (Exception e){
            log.error("e:" + e);
        }
        return BizConst.OP_FAIL;
    }

    public static String asUrlParams(Map<String, Object> source){
        return Joiner.on("&")
                // 用指定符号代替空值,key 或者value 为null都会被替换
                .useForNull("")
                .withKeyValueSeparator("=")
                .join(source);
    }
}
