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.ResourceAccount;
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;

@Repository
public class ResourceAccountRepository extends BasicGenericDao<ResourceAccount, Long> {

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

    public List<ResourceAccount> listByResourceId(Long resourceId) {
        String sql = "select * from resource_account where is_deleted = 0 and resource_id = :resourceId";
        Map<String, Object> params = MapTools.simpleMap("resourceId", resourceId);
        return this.list(ResourceAccount.class, sql, params);
    }

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

    public List<ResourceAccount> list(int page, int rows, List<Param> params, Map<String, String> sorter) {
        String sql = "select v.*, b.name as resource_name " +
            "from resource_account v " +
            "left join resource b on v.resource_id = b.id " +
            "where v.is_deleted = 0";
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "v");
        return this.list(ResourceAccount.class, sql);
    }

    public boolean remove(Long id) {
        String sql = "update resource_account set is_deleted = true where is_deleted = 0 and id = :id";
        Map<String, Object> params = MapTools.simpleMap("id", id);
        return this.execute(sql, params) > 0;
    }

    public ResourceAccount query(Long id) {
        String sql = "select * from resource_account where is_deleted = 0 and id = :id";
        Map<String, Object> params = MapTools.simpleMap(Common.ID, id);
        return this.list(ResourceAccount.class, sql, params).stream().findFirst().orElse(null);
    }
}
