package com.pj.project4sp.menu;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.pj.current.satoken.AuthConst;
import com.pj.project4sp.SP;
import com.pj.utils.sg.AjaxError;
import com.pj.utils.sg.AjaxJson;
import com.pj.utils.so.SoMap;

import cn.dev33.satoken.annotation.SaCheckPermission;


/**
 * Controller: sp_menu -- 菜单表
 * @author click33 
 */
@RestController
@RequestMapping("/SpMenu/")
public class SpMenuController {

	/** 底层 Mapper 对象 */
	@Autowired
	SpMenuMapper spMenuMapper;

	/** 增 */  
	@RequestMapping("add")
	@SaCheckPermission({SpMenu.PERMISSION_CODE, AuthConst.ROOT})
	@Transactional(rollbackFor = Exception.class)
	public AjaxJson add(SpMenu s){
		SpMenuUtil.checkAndSet(s);
		spMenuMapper.add(s);
		s = spMenuMapper.getById(s.getId());
		return AjaxJson.getSuccessData(s);
	}

	/** 删 */  
	@RequestMapping("delete")
	@Transactional(rollbackFor = Exception.class)
	@SaCheckPermission({SpMenu.PERMISSION_CODE, AuthConst.ROOT})
	public AjaxJson delete(String id){
		
		// 把它的所有子级移动到它的父级 
		String parentId = SP.publicMapper.getColumnById(SpMenu.TABLE_NAME, "parent_id", id);
		SP.publicMapper.updateColumnBy(
				SpMenu.TABLE_NAME, 
				"parent_id", parentId, 
				"parent_id", id
				);
		
		// 删了它 
		int line = spMenuMapper.delete(id);
		AjaxError.notLine(line, "删除菜单 " + id + " 失败");
		
		// 返回 
		return AjaxJson.getSuccess();
	}
	
	/** 改 */  
	@RequestMapping("update")
	@SaCheckPermission({SpMenu.PERMISSION_CODE, AuthConst.ROOT})
	public AjaxJson update(SpMenu s){
		SpMenuUtil.checkAndSet(s);
		int line = spMenuMapper.update(s);
		return AjaxJson.getByLine(line);
	}

	/** 查 - 根据id */  
	@RequestMapping("getById")
	@SaCheckPermission(SpMenu.PERMISSION_CODE)
	public AjaxJson getById(String id){
		SpMenu s = spMenuMapper.getById(id);
		return AjaxJson.getSuccessData(s);
	}

	/** 查集合 - 根据条件（参数为空时代表忽略指定条件） */  
	@RequestMapping("getList")
	@SaCheckPermission(SpMenu.PERMISSION_CODE)
	public AjaxJson getList() { 
		SoMap so = SoMap.getRequestSoMap();
		List<SpMenu> list = spMenuMapper.getList(so);
		return AjaxJson.getSuccessData(list);
	}
	
	/** 改 - 排序索引值 */  
	@RequestMapping("updateSort")
	@SaCheckPermission({SpMenu.PERMISSION_CODE, AuthConst.ROOT})
	public AjaxJson updateSort(String id, long value){
		int line = SP.publicMapper.updateColumnById(SpMenu.TABLE_NAME, "sort", value, id);
		return AjaxJson.getByLine(line);
	}
	
}
