package com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.http.sdgk;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson2.JSONObject;
import com.cico.nest.lcdp.boot.core.qxsd.infrastructure.common.constatnt.SdgkConstants;
import com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.http.sdgk.dto.SdgkBaseResult;
import com.cico.nest.lcdp.framework.common.util.json.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

/**
 * 隧道管控-认证
 */
@Slf4j
@Service
public class SdgkAuthMapper {

    @Value("${qxsd.sdgk.base-url}")
    private String sdgkBaseUrl;
    @Value("${qxsd.sdgk.loginName}")
    private String sdgkLoginName;
    @Value("${qxsd.sdgk.password}")
    private String sdgkLoginPwd;

    private String loginPath = "/server/base/login/form?loginName=%s&password=%s";

    public String getLoginToken(){
        String requestUrl = sdgkBaseUrl+loginPath;
        requestUrl = String.format(requestUrl,sdgkLoginName,sdgkLoginPwd);
        try {
            HttpResponse response = HttpUtil.createRequest(Method.POST, requestUrl).execute();
            SdgkBaseResult<Map<String, Object>> result = JsonUtils.parseObject(response.body(), SdgkBaseResult.class);
            if (result.getSuccess() && result.getData() != null) {
                Map<String, Object> dataMap = JsonUtils.parseObject(JsonUtils.toJsonString(result.getData()), Map.class);
                Object token= dataMap.get(SdgkConstants.ACCESS_TOKEN);
                return Objects.isNull(token)?null:String.valueOf(token);
            }
        } catch (Exception e) {
            log.error("请求隧道管控登录接口失败:", e);
        }
        return null;
    }

}
