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.MapTools;
import com.bocloud.database.core.intf.impl.BasicGenericDao;
import com.bocloud.database.utils.QueryBuilder;
import com.bocloud.ims.entity.resource.AliCost;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

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

@Repository("aliCostRepository")
public class AliCostRepository extends BasicGenericDao<AliCost, Long> {

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

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

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

	public List<AliCost> list(int page, int rows, List<Param> params, Map<String, String> sorter) throws Exception {
		String sql = "select * from ali_cost a where 1=1";
		sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		return this.list(AliCost.class, sql, paramMap);
	}

	public List<AliCost> listByVid(Long vendorId, String period, String periodTime) throws Exception {
		String sql = "select a.*, b.name vendor_name from ali_cost a left join cloud_vendor b on a.vendor_id = b.id where a.vendor_id = :vendorId and a.period = :period and a.period_time = :periodTime";
		Map<String, Object> paramMap = MapTools.simpleMap(Common.VENDORID, vendorId);
		paramMap.put("period", period);
		paramMap.put("periodTime", periodTime);
		List<AliCost> list = this.list(AliCost.class, sql, paramMap);
		if (list.isEmpty()) {
			return new ArrayList<>();
		}
		return list;
	}

}
