package com.cf.imes.framework.ip.core.service.imp;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.cf.imes.framework.common.exception.ErrorCode;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.ip.core.enums.ErrorCodeConstants;
import com.cf.imes.framework.ip.core.property.IPQueryProperties;
import com.cf.imes.framework.ip.core.service.IPQueryService;
import com.cf.imes.framework.ip.core.service.dto.IPQueryDataRespDTO;
import com.cf.imes.framework.ip.core.service.dto.IPQueryRespDTO;
import lombok.extern.slf4j.Slf4j;

import jakarta.annotation.Resource;

/**
 * @author Gqr
 * @since 2024/10/30 11:02
 */
@Slf4j
public class IPQueryServiceImpl implements IPQueryService {

    @Resource
    private IPQueryProperties ipQueryProperties;


    @Override
    public boolean serviceEnable() {
        return ipQueryProperties.isEnable();
    }

    @Override
    public IPQueryDataRespDTO querySource(String ip) {
        // 校验是否内部ip
        if (NetUtil.isInnerIP(ip)) {
            return new IPQueryDataRespDTO().setIp(ip).setProv("未知");
        }
        ErrorCode queryError = ErrorCodeConstants.IP_QUERY_ERROR;
        try {
            String apiUrl = ipQueryProperties.getApiUrl();
            String appCode = ipQueryProperties.getAppCode();
            if (CharSequenceUtil.isEmpty(apiUrl)) {
                log.error("[IPQueryService][querySource]request apiUrl为空");
                throw new ServiceException(queryError);
            }
            if (CharSequenceUtil.isEmpty(appCode)) {
                log.error("[IPQueryService][querySource]request appCode为空");
                throw new ServiceException(queryError);
            }
            log.info("[IPQueryService][querySource]request url：{}", apiUrl);
            log.info("[IPQueryService][querySource]request param, appCode: {}, ip: {}", appCode, ip);
            HttpResponse execute = HttpRequest.get(apiUrl).header("Authorization", "APPCODE " + appCode).form("ip", ip).execute();
            log.info("[IPQueryService][querySource]request status：{}, response: {}", execute.getStatus(), execute.body());
            String respBody = execute.body();
            IPQueryRespDTO ipQueryRespDTO = JSON.parseObject(execute.body(), IPQueryRespDTO.class);
            if (HttpStatus.HTTP_OK == ipQueryRespDTO.getRet()) {
                IPQueryDataRespDTO data = ipQueryRespDTO.getData();
                data.setIp(ip);
                return data;
            } else {
                ServiceException serviceException = new ServiceException(queryError);
                log.error(serviceException.getMessage() + "，状态【{}】，异常：{}", ipQueryRespDTO.getRet(), respBody);
                return null;
            }
        } catch (Exception e) {
            log.error(queryError.getMsg(), e);
            return null;
        }
    }
}
