/**
 * 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.domain.common.jdbc.BaseJdbcTemplate;
import com.crunii.micro.domain.common.jdbc.BaseNPJdbcTemplate;
import com.crunii.micro.service.sysmgr.dto.sysmgr.MenuLeaf;
import com.google.common.base.Strings;
import org.springframework.stereotype.Repository;

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

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

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

	private static final String getNextMenuCodeSql = "select menu_code from tsm_menu where parent_menu_code=? ";

	public String getNextMenuCode(String parentMenuCode) {
		String code;
		List<String> codes = JT.queryForRawObjects(String.class, getNextMenuCodeSql, parentMenuCode);
		if (codes.isEmpty()) {
			code = parentMenuCode + "001";
		} else {
			code = getNextCode(codes);
		}
		return code;
	}

	private static String getNextCode(List<String> codes) {
		Collections.sort(codes);
		String last = codes.get(codes.size() - 1);
		Integer next = Integer.valueOf(last.substring(last.length() - 3)) + 1;
		return last.substring(0, last.length() - 3) + Strings.padStart(next.toString(), 3, '0');
	}

	public Boolean findIsLeaf(String menuCode) {
		String sql = "SELECT if(count(1),FALSE,true) FROM TSM_MENU WHERE parent_menu_code = ?";
		return JT.queryForRawObject(Boolean.class,sql,menuCode);
	}
}
