package cn.iocoder.yudao.module.remote.service.login;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.remote.util.IpUtils;
import cn.iocoder.yudao.module.system.api.remote.RemoteLoginApi;
import cn.iocoder.yudao.module.system.api.remote.dto.LoginCheckDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    private String checkUrl = "/admin-api/system/remote/controller-information/checkAddress";

    @Resource
    private RemoteLoginApi remoteLoginApi;

    /**
     * 测试通讯
     *
     * @param loginCheckDTO
     * @return
     */
    @Override
    public Boolean checkCommunication(LoginCheckDTO loginCheckDTO) {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(2 * 1000);
        RestTemplate restTemplate = new RestTemplate(factory);
        String url = "http://" + loginCheckDTO.getSystemIp() + ":" + loginCheckDTO.getSystemPort() + checkUrl;
        LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Tenant-Id", "1");
        headers.add("Content-Type", "application/json");
        Map<String, String> map = new HashMap<>();
        map.put("systemIp", loginCheckDTO.getSystemIp());
        HttpEntity<String> request = new HttpEntity<String>(JSONUtil.toJsonStr(map), headers);
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.postForEntity(url, request, String.class);
        } catch (Exception e) {
        }
        return ObjectUtil.isNotEmpty(response) && loginCheckDTO.getSystemIp().equals(response.getBody());
    }

    /**
     * 保存IP和端口
     *
     * @param loginCheckDTO
     */
    @Override
    public void saveIpAndPort(LoginCheckDTO loginCheckDTO, HttpServletRequest request) {
        String ip = IpUtils.getIp(request);
        loginCheckDTO.setRemoteIp(ip);
        remoteLoginApi.saveIpAndPort(loginCheckDTO);
    }

    @Override
    public LoginCheckDTO getIpAndPort(HttpServletRequest request) {
        String ip = IpUtils.getIp(request);
        return remoteLoginApi.getIpAndPort(ip);
    }


}
