package com.bocloud.ims.repository.resource;

import com.bocloud.common.exception.BoCloudDBException;
import com.bocloud.common.utils.ListTool;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.entity.resource.PortGroupRelation;
import com.bocloud.orm.OrmGenericDaoImpl;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * 资源池端口组网络关联
 *
 * @author tyl
 * @since 2021/4/22 10:00
 */
@Repository("portGroupRelationRepository")
public class PortGroupRelationRepository extends OrmGenericDaoImpl<PortGroupRelation,Long> {
    public PortGroupRelationRepository(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) {
        super(jdbcTemplate, npJdbcTemplate);
    }

    public PortGroupRelation query(Long id) throws BoCloudDBException{
        String sql = "select * from port_group_relation where id = :id";
        Map<String, Object> paramsMap = MapTools.simpleMap("id", id);
        return this.list(PortGroupRelation.class,sql,paramsMap).stream().findFirst().orElse(null);
    }

    public boolean remove(Long groupId) throws BoCloudDBException{
        String sql = "delete from port_group_relation where pool_group_id = :groupId";
        Map<String, Object> paramsMap = MapTools.simpleMap("groupId", groupId);
        return  this.execute(sql,paramsMap)>0;
    }

    public List<PortGroupRelation> listByGroupId(Long groupId)throws BoCloudDBException{
        String sql = "select a.*,b.name  ip_pool_name,b.cidr cidr,c.name port_group_name ,b.version version from port_group_relation a " +
                " left join ip_pool b on a.ip_pool_id = b.id left join port_group c on a.port_group_id = c.id" +
                " where a.pool_group_id = :groupId ";
        Map<String, Object> paramsMap = MapTools.simpleMap("groupId", groupId);
        return this.list(PortGroupRelation.class,sql,paramsMap);
    }

    public PortGroupRelation listByIpPoolId(Long ipPoolId)throws BoCloudDBException{
        String sql = "select a.*,b.name  ip_pool_name,b.cidr cidr,b.gateway gate_way, c.name port_group_name ,b.version version from port_group_relation a " +
                " left join ip_pool b on a.ip_pool_id = b.id left join port_group c on a.port_group_id = c.id" +
                " where a.ip_pool_id = :ipPoolId ";
        Map<String, Object> paramsMap = MapTools.simpleMap("ipPoolId", ipPoolId);
        List<PortGroupRelation> list = this.list(PortGroupRelation.class, sql, paramsMap);
        if (ListTool.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }
}
