package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base;

import cn.estsh.i3plus.ext.mes.api.base.ISxHttpRequestService;
import cn.estsh.i3plus.ext.mes.apiservice.util.SxMesHttpUtil;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.JsonUtilTool;
import cn.estsh.i3plus.pojo.base.bean.BaseResultBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;


/**
 * @Author : wangjie
 * @CreateDate : 2022-02-15
 * @Modify:
 **/
@Service
public class SxHttpRequestService implements ISxHttpRequestService {

    @Override
    public BaseResultBean getBaseResultBeanByRequestUrl(String requestUrl, Map<String, String> params) {
        String data = SxMesHttpUtil.doPost(requestUrl, params);
        BaseResultBean baseResultBean;
        if (!StringUtils.isEmpty(data)) {
            baseResultBean = JsonUtilTool.decode(data, BaseResultBean.class);
        } else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.QMS.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("HTTP接口[%s]调用异常", requestUrl)
                    .build();
        }
        if (null != baseResultBean && baseResultBean.success) {
            return baseResultBean;
        } else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.QMS.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("%s", null == baseResultBean ? "[null]" : baseResultBean.getErrorMsg())
                    .build();
        }
    }
}
