/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.cqcis.com</a>
 */
package com.crunii.micro.service.sysmgr.jdbc;

import com.crunii.micro.common.dto.PageReq;
import com.crunii.micro.common.dto.PageRsp;
import com.crunii.micro.common.utils.SqlUtil;
import com.crunii.micro.domain.common.jdbc.BaseJdbcTemplate;
import com.crunii.micro.domain.common.jdbc.BaseNPJdbcTemplate;
import com.crunii.micro.domain.entity.main.TEncryptConfig;
import com.crunii.micro.service.sysmgr.dto.enc.EncryptConfigReq;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 田平 create 2017年8月11日下午12:44:04
 */
@Repository
public class EncryptConfigJdbcDao {
	@Resource(name = "mainJT")
	protected BaseJdbcTemplate JT;

	@Resource(name = "mainNPJT")
	protected BaseNPJdbcTemplate NPJT;

	private static final String pageEncryptBaseSql = "select * from t_encrypt_config a where 1=1 ";

	private static final String pageEncryptCountSql = "select count(*) from t_encrypt_config a where 1=1 ";

	public PageRsp<TEncryptConfig> pageEncryptConfig(PageReq<EncryptConfigReq> req) {
		StringBuilder sb = new StringBuilder(pageEncryptBaseSql);
		StringBuilder sbCount = new StringBuilder(pageEncryptCountSql);
		List<Object> params = new ArrayList<>();
		if (StringUtils.hasText(req.getQuery().getTabName())) {
			sb.append(" and a.tab_name like concat('%',?,'%') ");
			sbCount.append(" and a.tab_name like concat('%',?,'%') ");
			params.add(req.getQuery().getTabName());
		}
		if (StringUtils.hasText(req.getQuery().getColName())) {
			sb.append(" and a.col_name like concat('%',?,'%') ");
			sbCount.append(" and a.col_name like concat('%',?,'%') ");
			params.add(req.getQuery().getColName());
		}
		if (req.getQuery().getState() != null) {
			sb.append(" and a.state =? ");
			sbCount.append(" and a.state =? ");
			params.add(req.getQuery().getState());
		}

		int total = JT.queryForInt(sbCount.toString(), params.toArray());
		List<TEncryptConfig> configs = null;
		String dbType = JT.getDbType();
		if (total > 0) {
			//根据数据库类型设置limit
			SqlUtil.appendLimit(dbType, params, sb, req);
			configs = JT.queryForBeans(TEncryptConfig.class, sb.toString(), params.toArray());
		} else {
			configs = new ArrayList<>(0);
		}
		PageRsp<TEncryptConfig> page = new PageRsp<>();
		page.setPageNo(req.getPageNo());
		page.setPageSize(req.getPageSize());
		page.setTotalNum(total);
		page.setResult(configs);
		// 为手机计算是否由下一页
		page.next();

		return page;
	}

}
