<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2013-Now http://jeesite.com All rights reserved.
     No deletion without permission, or be held responsible to law. -->
<template>
	<name>controller</name>
	<filePath>${moduleName}/src/main/java/${packageName}/${moduleName}/web/${subModuleName}</filePath>
	<fileName>${ClassName}Controller.java</fileName>
	<content><![CDATA[
package ${packageName}.${moduleName}.web${isNotEmpty(subModuleName)?'.'+subModuleName:''};

<% if (table.isTreeEntity){ %>
import java.util.List;
import java.util.Map;
<% }else{ %>
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
<% } %>

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
<% if(table.isTreeEntity){ %>
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.modules.sys.utils.UserUtils;
<% }else{ %>
import com.jeesite.common.entity.Page;
<% } %>
<% if (table.tplCategory == 'crud_select'){ %>
import com.alibaba.fastjson.JSONValidator;
import com.jeesite.common.codec.EncodeUtils;
<% } %>
import com.jeesite.common.web.BaseController;
import ${packageName}.${moduleName}.entity${isNotEmpty(subModuleName)?'.'+subModuleName:''}.${ClassName};
<% for (child in table.childList){ %>
import ${packageName}.${moduleName}.entity${isNotEmpty(subModuleName)?'.'+subModuleName:''}.${@StringUtils.cap(child.className)};
<% } %>
import ${packageName}.${moduleName}.service${isNotEmpty(subModuleName)?'.'+subModuleName:''}.${ClassName}Service;

/**
 * ${functionName}Controller
 * @author ${functionAuthor}
 * @version ${functionVersion}
 */
@Controller
@RequestMapping(value = "\${adminPath}/${urlPrefix}")
public class ${ClassName}Controller extends BaseController {

	@Autowired
	private ${ClassName}Service ${className}Service;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public ${ClassName} get(<% for(pk in table.pkList){ %>${pkLP.index!=1?', ':''}${pk.simpleAttrType} ${pk.simpleAttrName}<% } %>, boolean isNewRecord) {
		<% if (table.pkList.~size == 1){ %>
		return ${className}Service.get(<% for(pk in table.pkList){ %>${pkLP.index!=1?', ':''}${pk.simpleAttrName}<% } %>, isNewRecord);
		<% }else{ %>
		${ClassName} ${className} = new ${ClassName}();
		<% for(pk in table.pkList){ %>
		${className}.set${@StringUtils.cap(pk.simpleAttrName)}(${pk.simpleAttrName});
		<% } %>
		${className}.setIsNewRecord(isNewRecord);
		return ${className}Service.getAndValid(${className});
		<% } %>
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("${permissionPrefix}:view")
	@RequestMapping(value = {"list", ""})
	public String list(${ClassName} ${className}, Model model) {
		model.addAttribute("${className}", ${className});
		return "${lastPackageName}/${viewPrefix}List";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("${permissionPrefix}:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	<% if(table.isTreeEntity){ %>
	public List<${ClassName}> listData(${ClassName} ${className}) {
		if (StringUtils.isBlank(${className}.getParentCode())) {
			${className}.setParentCode(${ClassName}.ROOT_CODE);
		}
		<% for(c in table.columnList){ %>
			<% if(c.isQuery == "1" && !c.isTreeEntityColumn && c.attrName != 'status'){ %>
				<% if(c.attrType == 'String'){ %>
		if (StringUtils.isNotBlank(${className}.${c.attrNameForGetMethod})){
			${className}.setParentCode(null);
		}
				<% }else{ %>
		if (${className}.${c.attrNameForGetMethod} != null){
			${className}.setParentCode(null);
		}
				<% } %>
			<% } %>
		<% } %>
		List<${ClassName}> list = ${className}Service.findList(${className});
		return list;
	}
	<% }else{ %>
	public Page<${ClassName}> listData(${ClassName} ${className}, HttpServletRequest request, HttpServletResponse response) {
		${className}.setPage(new Page<>(request, response));
		Page<${ClassName}> page = ${className}Service.findPage(${className});
		return page;
	}
	<% } %>
	<% for (child in table.childList){ %>
	
	/**
	 * 查询子表数据
	 */
	@RequiresPermissions("${permissionPrefix}:view")
	@RequestMapping(value = "${@StringUtils.uncap(child.className)}ListData")
	@ResponseBody
	public Page<${@StringUtils.cap(child.className)}> subListData(${@StringUtils.cap(child.className)} ${@StringUtils.uncap(child.className)}, HttpServletRequest request, HttpServletResponse response) {
		${@StringUtils.uncap(child.className)}.setPage(new Page<>(request, response));
		Page<${@StringUtils.cap(child.className)}> page = ${className}Service.findSubPage(${@StringUtils.uncap(child.className)});
		return page;
	}
	<% } %>

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("${permissionPrefix}:view")
	@RequestMapping(value = "form")
	public String form(${ClassName} ${className}, Model model) {
		<% if(table.isTreeEntity){ %>
		// 创建并初始化下一个节点信息
		${className} = createNextNode(${className});
		<% } %>
		model.addAttribute("${className}", ${className});
		return "${lastPackageName}/${viewPrefix}Form";
	}
	<% if(table.isTreeEntity){ %>
	
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("${permissionPrefix}:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public ${ClassName} createNextNode(${ClassName} ${className}) {
		if (StringUtils.isNotBlank(${className}.getParentCode())){
			${className}.setParent(${className}Service.get(${className}.getParentCode()));
		}
		if (${className}.getIsNewRecord()) {
			${ClassName} where = new ${ClassName}();
			where.setParentCode(${className}.getParentCode());
			${ClassName} last = ${className}Service.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				${className}.setTreeSort(last.getTreeSort() + 30);
				<% if(table.isPkCustom){ %>
				${className}.set${@StringUtils.cap(table.treeViewCodeAttrName)}(IdGen.nextCode(last.get${@StringUtils.cap(table.treeViewCodeAttrName)}()));
			}else if (${className}.getParent() != null){
				${className}.set${@StringUtils.cap(table.treeViewCodeAttrName)}(${className}.getParent().get${@StringUtils.cap(table.treeViewCodeAttrName)}() + "001");
				<% } %>
			}
		}
		// 以下设置表单默认数据
		if (${className}.getTreeSort() == null){
			${className}.setTreeSort(${ClassName}.DEFAULT_TREE_SORT);
		}
		return ${className};
	}
	<% } %>

	/**
	 * 保存数据
	 */
	@RequiresPermissions("${permissionPrefix}:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated ${ClassName} ${className}) {
		${className}Service.save(${className});
		return renderResult(Global.TRUE, text("保存${functionNameSimple}成功！"));
	}
	<% if(toBoolean(table.optionMap['isHaveDisableEnable'])){ %>
	
	/**
	 * 停用数据
	 */
	@RequiresPermissions("${permissionPrefix}:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(${ClassName} ${className}) {
		<% if(table.isTreeEntity){ %>
		${ClassName} where = new ${ClassName}();
		where.setStatus(${ClassName}.STATUS_NORMAL);
		where.setParentCodes("," + ${className}.getId() + ",");
		long count = ${className}Service.findCount(where);
		if (count > 0) {
			return renderResult(Global.FALSE, text("该${functionNameSimple}包含未停用的子${functionNameSimple}！"));
		}
		<% } %>
		${className}.setStatus(${ClassName}.STATUS_DISABLE);
		${className}Service.updateStatus(${className});
		return renderResult(Global.TRUE, text("停用${functionNameSimple}成功"));
	}
	
	/**
	 * 启用数据
	 */
	@RequiresPermissions("${permissionPrefix}:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(${ClassName} ${className}) {
		${className}.setStatus(${ClassName}.STATUS_NORMAL);
		${className}Service.updateStatus(${className});
		return renderResult(Global.TRUE, text("启用${functionNameSimple}成功"));
	}
	<% } %>
	<% if(toBoolean(table.optionMap['isHaveDelete'])){ %>
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("${permissionPrefix}:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(${ClassName} ${className}) {
		${className}Service.delete(${className});
		return renderResult(Global.TRUE, text("删除${functionNameSimple}成功！"));
	}
	<% } %>
	<% if(table.isTreeEntity){ %>
	
	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("${permissionPrefix}:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		List<${ClassName}> list = ${className}Service.findList(new ${ClassName}());
		for (int i=0; i<list.size(); i++){
			${ClassName} e = list.get(i);
			<% if (table.statusExists){ %>
			// 过滤非正常的数据
			if (!${ClassName}.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			<% } %>
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.get${@StringUtils.cap(table.treeViewCodeAttrName)}(), e.get${@StringUtils.cap(table.treeViewNameAttrName)}()));
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("${permissionPrefix}:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(${ClassName} ${className}){
		if (!UserUtils.getUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		${className}Service.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}
	<% } %>
	<% if (table.tplCategory == 'crud_select'){ %>
	
	/**
	 * 列表选择对话框
	 */
	@RequiresPermissions("${permissionPrefix}:view")
	@RequestMapping(value = "${className}Select")
	public String ${className}Select(${ClassName} ${className}, String selectData, Model model) {
		String selectDataJson = EncodeUtils.decodeUrl(selectData);
		if (selectDataJson != null && JSONValidator.from(selectDataJson).validate()){
			model.addAttribute("selectData", selectDataJson);
		}
		model.addAttribute("${className}", ${className});
		return "${lastPackageName}/${viewPrefix}Select";
	}
	<% } %>
	
}]]>
	</content>
</template>