package com.citygis.web.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.citygis.web.domain.TabIp;
import com.citygis.web.domain.TabIpResult;
import com.citygis.web.mapper.TabIpResultMapper;
import com.citygis.web.service.ITabIpResultService;
import com.citygis.web.service.ITabIpService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * ip监测结果表 服务实现类
 * </p>
 *
 * @author citygis
 * @since 2025-01-17
 */
@Service
public class TabIpResultServiceImpl extends ServiceImpl<TabIpResultMapper, TabIpResult> implements ITabIpResultService {

    @Resource
    TabIpResultMapper tabIpResultMapper;

    @Resource
    ITabIpService tabIpService;

    @Override
    public List<TabIpResult> getTabIpResultList(TabIpResult tabIpResult) {
        return tabIpResultMapper.getTabIpResultList(tabIpResult);
    }

    @Override
    public List<TabIpResult> getTabIpResultDetailByIpAndPort(TabIpResult tabIpResult) {
        return tabIpResultMapper.getTabIpResultDetailByIpAndPort(tabIpResult);
    }

    @Override
    public void insertTabIpResult() {
        List<TabIpResult> tabIpResultList = new ArrayList<>();

        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        Socket socket = new Socket();

        List<TabIp> list = tabIpService.list();

        list.forEach(tabIp -> {
            TabIpResult tabIpResult = new TabIpResult();

            tabIpResult.setId(snowflake.nextId());

            String ip = tabIp.getIp();
            Integer port = tabIp.getPort();

            tabIpResult.setIp(ip);
            tabIpResult.setPort(port);

            if (port != null) {
                SocketAddress socketAddress = new InetSocketAddress(ip, port);
                try {
                    socket.connect(socketAddress, 3000); // 超过3秒则视为失败
                    tabIpResult.setResult("true");
                    socket.close();

                } catch (IOException e) {
                    tabIpResult.setResult("false");
                }
            } else {
                InetAddress inetAddress = null;
                try {
                    inetAddress = InetAddress.getByName(ip);
                    tabIpResult.setResult(String.valueOf(inetAddress.isReachable(3000)));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }


            }
            tabIpResult.setDescription(tabIp.getDescription());
            tabIpResult.setCreateTime(new Date());
            tabIpResultList.add(tabIpResult);
        });

        this.saveBatch(tabIpResultList);
    }
}
