package com.chenyang.nse.bussiness.dao.table.core;

import com.chenyang.nse.bussiness.dao.BaseDao;
import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.DgCommandRule;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

@Repository
public class DgCommandRuleDao extends BaseDao<DgCommandRule, String> {
   public List<Map<String, Object>> queryAllDbRule(PageInfo pageInfo, String ruletype, String createuser, String datasourceid) {
      StringBuilder sqlcount = new StringBuilder();
      StringBuilder sql = new StringBuilder();
      sqlcount.append("SELECT COUNT(1) from T_CORE_DG_COMMAND_RULE_CUSTOM t where 1 = 1 ");
      sql.append("SELECT  t.id,t.name,t.rule_type,t.discription,t.create_time,t.database_id,t.rule_json,t.create_user,t.data_source_id,").append(" (select sysname from t_core_datasystem where id = t.data_source_id ) as sysname,(select dataarea from t_core_dataarea where id = t.data_area_id ) as dataarea ").append(" from T_CORE_DG_COMMAND_RULE_CUSTOM t where 1 = 1 ");
      if (StringUtils.isNotBlank(ruletype)) {
         sql.append(" AND t.rule_type = '").append(ruletype).append("'");
         sqlcount.append(" AND t.rule_type = '").append(ruletype).append("'");
      }

      if (StringUtils.isNotBlank(createuser)) {
         sql.append(" AND t.create_user like '%").append(createuser).append("%'");
         sqlcount.append(" AND t.create_user like '%").append(createuser).append("%'");
      }

      if (StringUtils.isNotBlank(datasourceid)) {
         sql.append(" AND t.data_source_id = '").append(datasourceid).append("'");
         sqlcount.append(" AND t.data_source_id = '").append(datasourceid).append("'");
      }

      sql.append(" order by t.create_time desc");
      long count = (long)((BigInteger)this.getSession().createNativeQuery(sqlcount.toString()).getSingleResult()).intValue();
      pageInfo.setCount(count);
      return this.getSession().createNativeQuery(sql.toString()).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).setFirstResult(pageInfo.getOffset()).setMaxResults(pageInfo.getPagesize()).getResultList();
   }
}
