/**
 * 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 cn.hutool.core.util.ObjectUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
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.post.PostPageReqVO;
import com.crunii.micro.service.sysmgr.dto.post.PostRespVO;
import org.springframework.stereotype.Repository;

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

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

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

	private static final String pagePubBaseSql = "select *,case when state=1 then '有效' when state=0 then '无效' else null end as stateName" +
			" from tsm_post where del_flag='0'";
	private static final String pagePubCountSql = "select count(*) from tsm_post  where del_flag='0'";

	public PageRsp<PostRespVO> pagePost(PageReq<PostPageReqVO> req) {

		StringBuilder sb = new StringBuilder(pagePubBaseSql);
		StringBuilder sbCount = new StringBuilder(pagePubCountSql);
		List<Object> params = new ArrayList<Object>();
		PostPageReqVO query = req.getQuery();
		if (ObjectUtil.isNotEmpty(query)){
			//职务编码
			if (StringUtils.isNotEmpty(query.getCode())){
				sb.append(" and code like concat('%',?,'%')");
				sbCount.append(" and code like concat('%',?,'%')");
				params.add(query.getCode());
			}
			//职务名称
			if (StringUtils.isNotEmpty(query.getName())){
				sb.append(" and name like concat('%',?,'%')");
				sbCount.append(" and name like concat('%',?,'%')");
				params.add(query.getName());
			}
			//职务状态
			if (ObjectUtil.isNotNull(query.getState())){
				sb.append(" and state=?");
				sbCount.append(" and state=?");
				params.add(query.getState());
			}
			sb.append(" order by sort,create_time desc");
		}

		int total = JT.queryForInt(sbCount.toString(), params.toArray());
		List<PostRespVO> pubs = null;
		String dbType = JT.getDbType();
		if (total > 0) {
			//根据数据库类型设置limit
			SqlUtil.appendLimit(dbType, params, sb, req);

			pubs = JT.queryForBeans(PostRespVO.class, sb.toString(), params.toArray());
		} else {
			pubs = new ArrayList<PostRespVO>(0);
		}

		PageRsp<PostRespVO> page = new PageRsp<PostRespVO>();
		page.setPageNo(req.getPageNo());
		page.setPageSize(req.getPageSize());
		page.setTotalNum(total);
		page.setResult(pubs);
		// 为手机计算是否由下一页
		page.next();
		return page;
	}

}
