package cn.com.ctop.common.module.service.impl;

import cn.com.ctop.common.module.entity.IpPool;
import cn.com.ctop.common.module.mapper.IpPoolMapper;
import cn.com.ctop.common.module.service.IIpPoolService;
import cn.com.ctop.common.module.utils.HttpClientUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author jeecg-boot
 * 2019年12月5日20:20:36
 */
@Slf4j
@Service
@Primary
public class IpPoolServiceImpl extends ServiceImpl<IpPoolMapper, IpPool> implements IIpPoolService {

    @Override
    public IpPool getAvaliableIp() {
        QueryWrapper<IpPool> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.gt("expire_time", new Date());
        queryWrapper.orderByAsc("last_use_time");
        IpPool ipPool = this.getOne(queryWrapper);
        if (ipPool == null) {
            return null;
        } else {
            ipPool.setLastUseTime(new Date());
            this.updateById(ipPool);
        }
        return ipPool;
    }

    private void syncIpPool() {
        HttpClientUtils httpClientUtils = new HttpClientUtils();
        try {
            String result = httpClientUtils.get("http://api.qingtingip.com/ip?app_key=31f9e03d6c362cb926d6c5d911e01387&num=10&ptc=http&fmt=json&lb=\\r\\n&port=0&mr=2&");
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readTree(result);
            if (jsonNode.get("code").asInt() == 200) {
                List<IpPool> ipList = JSON.parseObject(jsonNode.get("data").toString(), new TypeReference<List<IpPool>>() {
                });
                if (ipList != null && ipList.size() > 0) {
                    for (IpPool ipPool : ipList) {
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                Boolean avaliable = httpClientUtils.checkProxyIp(ipPool.getIp(), ipPool.getPort());
                                if (!avaliable) {
                                    ipPool.setStatus(2);
                                    log.info("ip" + ipPool.getIp() + " is not avaliable");
                                }
                                save(ipPool);
                            }
                        };
                        thread.start();
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
