package com.bocloud.ims.service.rpc;

import com.alibaba.fastjson.JSON;
import com.bocloud.ims.entity.resource.Ip;
import com.bocloud.ims.repository.resource.IpRepository;
import com.bocloud.rpc.interfaces.ims.ImsRpcService;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ImsRpcServiceImpl implements ImsRpcService {
    @Autowired
    LockFactory lockFactory;

    @Autowired
    IpRepository ipRepository;

    @Override
    public void preemptOrFreeIp(List<String> ipsToPreempt, List<String> ipsToFree) {
        String path = Ip.class.getSimpleName() + "_" + "preemptOrFreeIp";
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            log.info("接收到ip信息");
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            List<Ip> ipList = new ArrayList<>();
            if (ipsToPreempt != null) {
                for (int i = 0;i < ipsToPreempt.size(); i++) {
                    //可以直接查询出单个数据。one会sql中增加limie
                    Ip ip1 = ipRepository.queryProxy().col(Ip::getIp).eq(ipsToPreempt.get(i)).oneOrNull();
                    Assert.isTrue(ip1.getStatus().equals(Ip.IpStatus.free), "当前ip:" +ip1.getIp()+ "已被占用");
                    ip1.setStatus(Ip.IpStatus.preempt);
                    ipList.add(ip1);
                }
            }
            if (ipsToFree != null) {
                for (int i = 0;i < ipsToFree.size(); i++) {
                    //可以直接查询出单个数据。one会sql中增加limie
                    Ip ip1 = ipRepository.queryProxy().col(Ip::getIp).eq(ipsToFree.get(i)).oneOrNull();
                    ip1.setStatus(Ip.IpStatus.free);
                    ipList.add(ip1);
                }
            }
            ipRepository.batchUpdate(ipList);
            log.info("ip变更成功:" + JSON.toJSONString(ipList));
        } catch (Exception e) {
            log.error("Get error message", e);
        }
    }
}
