package com.blueland.sys.power.web;


import java.util.*;
/**
 * @author 代码自动生成工具
 * @version 1.0
 * @since  
 */

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blueland.constant.RedisConstant;
import cn.hutool.core.util.ObjectUtil;
import com.blueland.annotation.Log;
import com.blueland.model.TPfApplication;
import com.blueland.model.TPfMenu;
import com.blueland.result.R;
import com.blueland.service.IApplicationService;
import com.blueland.service.IMenuService;
import com.blueland.service.SysRedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.blueland.bo.MenuEntity;

import io.swagger.annotations.Api;

import static com.blueland.constant.CommonConstant.*;
import static com.blueland.constant.ResponseConstant.*;

@Slf4j
@Api(value = "menu")
@RestController
@RequestMapping(value = "/menu")
public class MenuRest {
	@Autowired
	private IMenuService menuService;
	@Autowired
	private IApplicationService appService;

	@Autowired
	private SysRedisService sysRedisService;
	
	/** 
	 * 搜索对象 
	 **/
	@RequestMapping(value = "",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<Page<MenuEntity>> list(MenuEntity menuEntity) {
		Page<MenuEntity> page = this.menuService.findPage(menuEntity);
		return R.ok(page);
	}

	
	/** 
	 * 查看对象
	 **/
	@RequestMapping(value = "/{menuId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<TPfMenu> view(@PathVariable String menuId)  {
		TPfMenu menuEntity  = menuService.getById(menuId);
		return R.ok(menuEntity);
	}
	
	/** 
	 * 查看下级菜单
	 **/
	@RequestMapping(value = "/{menuId}/menuId/{appId}/resource",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public Map<String, Object> viewParent(@PathVariable("menuId") String menuId,@PathVariable("appId")String appId)  {
		Map < String , Object > result = new HashMap< String , Object>(); 
		List<MenuEntity> menuEntryList = null;
		try {
			menuEntryList = menuService.getParent(menuId,appId);
			result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
			result.put("resultMsg", "处理成功");
			result.put("result", menuEntryList);
		} catch (Exception e) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "系统内部异常");
			e.printStackTrace();
		}
		return result;
	}
	
	/** 
	 * 查看对象
	 * 根据app_id获取资源
	 **/
	@RequestMapping(value = "/{appId}/resource",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public  Map<String, Object> listMenuAll(@PathVariable("appId") String appId,@RequestParam Map<String,Object> queryParams,HttpServletRequest request,HttpServletResponse response)  {
		Map < String , Object > result = new HashMap< String , Object>(); 
		List<MenuEntity> menuEntryList = null;
		
		try {
			if(StringUtils.isBlank(appId)){
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "输入参数异常");
			}else{
				TPfApplication app = appService.getById(appId);
			    if(app==null){
			    	result.put("resultCode", RESULT_CODE_ERROR_CODE);
					result.put("resultMsg", "应用ID错误");
				}else{
					String menuName = null;
					String parentName = null;
					String menuType = null;
					if(queryParams.containsKey("menuName")) {
						menuName = queryParams.get("menuName").toString();
					}
					if(queryParams.containsKey("parentName")) {
						parentName = queryParams.get("parentName").toString();
					}
					if(queryParams.containsKey("menuType")) {
						menuType = queryParams.get("menuType").toString();
					}
					
					menuEntryList = menuService.getMenuChildren(appId,menuName,parentName,menuType);
					result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
					result.put("resultMsg", "处理成功");
					result.put("result", menuEntryList);
				}
			}
		} catch (Exception e) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "系统内部异常");
			e.printStackTrace();
		}
		return result;
	}
	
	/** 
	 * 查看对象
	 * 根据app_id获取资源
	 **/
	@RequestMapping(value = "/{appId}/menuList",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public  Map<String, Object> menuList(@PathVariable("appId") String appId,@RequestParam Map<String,Object> queryParams,HttpServletRequest request,HttpServletResponse response)  {
		Map < String , Object > result = new HashMap< String , Object>(); 
		List<MenuEntity> menuEntryList = null;
		
		try {
			if(StringUtils.isBlank(appId)){
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "输入参数异常");
			}else{
				TPfApplication app = appService.getById(appId);
			    if(app==null){
			    	result.put("resultCode", RESULT_CODE_ERROR_CODE);
					result.put("resultMsg", "应用ID错误");
				}else{
					String menuName = null;
					String parentName = null;
					String menuType = null;
					if(queryParams.containsKey("menuName")) {
						menuName = queryParams.get("menuName").toString();
					}
					if(queryParams.containsKey("parentName")) {
						parentName = queryParams.get("parentName").toString();
					}
					if(queryParams.containsKey("menuType")) {
						menuType = queryParams.get("menuType").toString();
					}
					
					menuEntryList = menuService.getMenuList(appId,menuName,parentName,menuType);
					result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
					result.put("resultMsg", "处理成功");
					result.put("result", menuEntryList);
				}
			}
		} catch (Exception e) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "系统内部异常");
			e.printStackTrace();
		}
		return result;
	}


	/** 
	 * 查看对象（支持多条件查询）
	 **/
	@RequestMapping(value = "get",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<TPfMenu> get(MenuEntity model)  {
		TPfMenu menuEntity  = menuService.get(model);
		return R.ok(menuEntity);
	}

	/** 
	 * 新增对象
	 **/
	@Log(busiType = "新增菜单", opType = SAVE, type = "web")
	@RequestMapping(value = "/save",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<MenuEntity> save(@RequestBody MenuEntity model,HttpServletRequest request,HttpServletResponse response)  {
		TPfMenu menu = BeanUtil.copyProperties(model, TPfMenu.class);
		if(StringUtils.isNotBlank(model.getMenuParentId())) {
            int menuLvevl = menuService.getMenuLevel(model.getMenuParentId());
			menu.setMenuLevel(menuLvevl+1);
        }else {
			menu.setMenuLevel(1);
        }
		menu.setCreateDate(new Date());
		menu.setUpdateDate(new Date());
        menuService.save(menu);
		sysRedisService.saveOrUpdateMenu(model);
        return R.ok(model);
	}

	/**
	 * 更新对象
	 * @return 
	 **/
	@Log(busiType = "更新菜单", opType = UPDATE, type = "web")
	@RequestMapping(value = "/update",method = RequestMethod.PUT,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<MenuEntity> update(@RequestBody MenuEntity model,HttpServletRequest request)  {
		TPfMenu menu = BeanUtil.copyProperties(model, TPfMenu.class);
		menu.setUpdateDate(new Date());
        menuService.updateById(menu);
		sysRedisService.saveOrUpdateMenu(model);
        return R.ok(model);
	}
	
	/**
	 * 删除对象
	 * @return 
	 **/
	@Log(busiType = "删除菜单", opType = DELETE, type = "web")
	@RequestMapping(value = "/delete/{menuId}",method = RequestMethod.DELETE,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<Boolean> delete(@PathVariable String menuId,HttpServletRequest request) {
		menuService.removeById(menuId);
		try {
			// 刷新缓存
			sysRedisService.flushMenu();
        }catch (Exception e){
            log.info("删除redis数据失败->参数:"+menuId+"，位置: MenuRest.delete");
        }
		return R.ok();
	}
	
	/**
	 *  批量删除对象
	 * @return 
	 **/
	@Log(busiType = "批量删除菜单", opType = DELETE, type = "web")
	@RequestMapping(value = "deleteBatch",method = RequestMethod.DELETE,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<Boolean> deleteBatch(String[] ids,HttpServletRequest request) {
		if (ObjectUtil.isEmpty(ids)) {
			throw new RuntimeException("id不能为空");
		}
		menuService.removeByIds(Arrays.asList(ids));
		// 刷新缓存
		sysRedisService.flushMenu();
		return R.ok();
	}
	
	/** 
	 * 根据角色和应用获取权限
	 **/
	@RequestMapping(value = "/getbyRoleAndApp/{roleId}/{appId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<List<MenuEntity>> getByRoleIdAndAppId(
			@PathVariable String roleId,@PathVariable String appId
	) {
		List<MenuEntity> list = this.menuService.getMenuByRoleIdAndAppId(appId, roleId);
		return R.ok(list);
	}
	
}



