/**
 * 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.service.sysmgr.dto.pub.PubInfo;
import com.crunii.micro.service.sysmgr.dto.pub.PubReq;
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 PubJdbcDao {
	@Resource(name = "mainJT")
	protected BaseJdbcTemplate JT;

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

	private static final String pagePubBaseSql = "select a.*,(select b.value_name from tsm_property_value b where b.prop_id=10000 and b.value_code=a.pub_type) pub_type_name "
			+ " from tsm_pub a where 1=1";

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

	public PageRsp<PubInfo> pagePub(PageReq<PubReq> req) {

		StringBuilder sb = new StringBuilder(pagePubBaseSql);
		StringBuilder sbCount = new StringBuilder(pagePubCountSql);
		List<Object> params = new ArrayList<Object>();
		if (StringUtils.hasText(req.getQuery().getPubType())) {
			sb.append(" and a.pub_type=? ");
			sbCount.append(" and a.pub_type=? ");
			params.add(req.getQuery().getPubType());
		}
		if (StringUtils.hasText(req.getQuery().getPubName())) {
			sb.append(" and a.pub_name like concat('%',?,'%') ");
			sbCount.append(" and a.pub_name like concat('%',?,'%') ");
			params.add(req.getQuery().getPubName());
		}
		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<PubInfo> pubs = null;
		String dbType = JT.getDbType();
		if (total > 0) {
			//根据数据库类型设置limit
			SqlUtil.appendLimit(dbType, params, sb, req);

			pubs = JT.queryForBeans(PubInfo.class, sb.toString(), params.toArray());
		} else {
			pubs = new ArrayList<PubInfo>(0);
		}
		PageRsp<PubInfo> page = new PageRsp<PubInfo>();
		page.setPageNo(req.getPageNo());
		page.setPageSize(req.getPageSize());
		page.setTotalNum(total);
		page.setResult(pubs);
		// 为手机计算是否由下一页
		page.next();
		return page;
	}

}
