package thyyxxk.webserver.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.constants.sidicts.SiTj;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.scheduled.SiTjToken;

/**
 * <p>
 * 描述： 封装体检请求
 * </p>
 *
 * @author xc
 * @date 2021-07-13 17:28
 */
@Slf4j
@Service
public class SiTjResTemplate {
    @Autowired
    private SiTjToken token;

    public ResultVo<Object> getSiTjRest(String tailUrl, SiTj cmd, JSONObject param) {
        try {
            //设置请求超时时间
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            requestFactory.setConnectTimeout(30 * 1000);
            requestFactory.setReadTimeout(30 * 1000);
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", token.getSiTjToken());
            JSONObject json = new JSONObject();
            json.put("cmd", cmd.getCmd());
            json.put("code", "");
            json.put("type", "1");
            json.put("data", param);
            log.info("请求参数：{}", json);
            JSONObject responseEntity = restTemplate.postForObject(tailUrl, new HttpEntity<>(json, headers), JSONObject.class);
            log.info("返回参数：{}", responseEntity);
            if (responseEntity == null) {
                return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
            }
            if (responseEntity.getIntValue("code") == 0) {
                return ResultVoUtil.success(responseEntity.get("data"));
            }
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, responseEntity.getString("msg"));
        } catch (Exception e) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR, "市体检请求超时。");

        }


    }
}
