package com.bocloud.ims.repository.topology;

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.topology.Category;
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;

/**
 * Category dao层接口实现类
 *
 * @author lyy
 * @Version 1.0
 * @since 2017年9月13日
 */
@Repository("categoryDao")
public class CategoryRepository extends BasicGenericDao<Category, Long> {

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

    public List<Category> list(int page, int rows, List<Param> params, Map<String, String> sorter) throws Exception {
        String sql = "select * from ci_category where 1=1";
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        List<Category> list = this.list(Category.class, sql, paramMap);
        List<Category> categories = new ArrayList<>();
        Category category = null;
        for (Object obj : list) {
            category = (Category) obj;
            categories.add(category);
        }
        return categories;
    }

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

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

    public List<Category> list() throws Exception {
        String sql = "select * from ci_category where 1=1";
        List<Category> list = this.list(Category.class, sql, null);
        return list;
    }

}
