package com.bocloud.ims.repository.resource;

import com.bocloud.common.model.Pager;
import com.bocloud.common.model.Param;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.ListTool;
import com.bocloud.common.utils.MapTools;
import com.bocloud.database.core.intf.impl.BasicGenericDao;
import com.bocloud.database.utils.QueryBuilder;
import com.bocloud.ims.entity.resource.ResourceEvent;
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 wangyu
 * @version 1.0
 * @since 2020年5月15日
 *
 */
@Repository("resourceEventRepository")
public class ResourceEventRepository extends BasicGenericDao<ResourceEvent, Long> {

	public ResourceEventRepository(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) {
		super(jdbcTemplate, npJdbcTemplate);
	}

	public List<ResourceEvent> list(int page, int rows, List<Param> params, Map<String, String> sorter)
			throws Exception {
		String sql = "select a.*,b.name operator from resource_event a left join users b on a.operator_id = b.id where 1=1";
		sql = QueryBuilder.build(sql, new Pager(page, rows, params, sorter), "");
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		return this.list(ResourceEvent.class, sql, paramMap);
	}

	public int count(List<Param> params) throws Exception {
		String sql = "select count(1) from resource_event where 1=1";
		sql = QueryBuilder.build(sql, params, null, "");
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		return this.countQuery(sql, paramMap).intValue();
	}

	public ResourceEvent query(Long id) throws Exception {
		String sql = "select * from resource_event where id = :id";
		Map<String, Object> params = MapTools.simpleMap(Common.ID, id);
		List<ResourceEvent> list = this.list(ResourceEvent.class, sql, params);
		return ListTool.isEmpty(list) ? null : list.get(0);
	}

	public ResourceEvent queryByVmId(Long resourceId) throws Exception {
		String sql = "select * from resource_event where resource_id = :resourceId";
		Map<String, Object> params = MapTools.simpleMap("resourceId", resourceId);
		List<ResourceEvent> list = this.list(ResourceEvent.class, sql, params);
		return ListTool.isEmpty(list) ? null : list.get(0);
	}

}
