package com.dcit.authority.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dcit.authority.dto.SysResourcesDTO;
import com.dcit.authority.dto.form.SysResourcesForm;
import com.dcit.authority.exception.AuthException;
import com.dcit.authority.model.SysResources;
import com.dcit.authority.model.SysResourcesExample;
import com.dcit.authority.model.SysResourcesExample.Criteria;
import com.dcit.authority.service.SysResourcesService;
//import com.dcit.authority.shiro.ShiroKit;
import com.dcit.common.enums.ResultEnum;
import com.dcit.common.utils.BeanCopyUtil;
import com.dcit.common.utils.KeyUtil;
import com.dcit.common.utils.ResultVOUtil;
import com.dcit.common.vo.ResultVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(value="系统资源管理API")
@RestController
@RequestMapping("/resource")
@Slf4j
public class ResourcesController {

	@Autowired
	private SysResourcesService sysResourcesService;
	
	@ApiOperation(value = "获取系统资源列表")
    @GetMapping("/getResourcesList/{resourceType}")
	public ResultVO<Object> getResourcesList(@PathVariable String resourceType, 
			@RequestParam(required=false,defaultValue="") String resourceName){
		
		//ModelMap modelMap = new ModelMap();
    	
		List<SysResourcesDTO> parentTreeList = new ArrayList<SysResourcesDTO>();
		
		try {
			//PageHelper.startPage(page,size);
	        SysResourcesExample example = new SysResourcesExample();
	        Criteria criteria = example.createCriteria();
	        criteria.andStatusEqualTo("0").andResourceTypeEqualTo(resourceType);
	        if(!StringUtils.isEmpty(resourceName)){
	        	criteria.andResourceNameLike("%"+ resourceName +"%");
	        }
	        example.setOrderByClause(" sort+0 ASC ");
	        List<SysResources> sysResourcesList = sysResourcesService.selectByExample(example);
	        SysResourcesDTO parentDTO = null;
	        for(SysResources sysResources : sysResourcesList){
	        	if(!StringUtils.isEmpty(sysResources.getParentId()) && sysResources.getParentId().equals("0")){
	        		parentDTO = new SysResourcesDTO();
		        	BeanUtils.copyProperties(sysResources, parentDTO, BeanCopyUtil.getNullOrIgnorePropertyNames(sysResources, null));
		        	parentTreeList.add(parentDTO);
	        	}
	        }
	        
	        for(SysResourcesDTO dto : parentTreeList){
	        	
	        	List<SysResourcesDTO> childTreeList = new ArrayList<SysResourcesDTO>();
	        	for(SysResources sysResources : sysResourcesList){
	        		SysResourcesDTO childDTO = null;
		        	if(!StringUtils.isEmpty(sysResources.getParentId()) && sysResources.getParentId().equals(dto.getId())){
		        		childDTO = new SysResourcesDTO();
			        	BeanUtils.copyProperties(sysResources, childDTO, BeanCopyUtil.getNullOrIgnorePropertyNames(sysResources, null));
			        	childTreeList.add(childDTO);
		        	}
		        }
	        	
	        	dto.setChildList(childTreeList);
	        }
	        
	        //PageInfo<SysResources> pageInfo = new PageInfo<SysResources>(sysResourcesList);
	        
	        //modelMap.put("pageData", pageInfo.getList());
	        //modelMap.put("total", pageInfo.getTotal());
		} catch (Exception e) {
			log.error("【获取系统资源列表】操作失败,e={}",e.getMessage());
			throw new AuthException(ResultEnum.OPERATION_FAIL);
		}
       
        
        return ResultVOUtil.success(parentTreeList);
	}
	
	@ApiOperation(value = "根据id获取资源详情")
    @GetMapping("/getResourceInfoById/{id}")
	public ResultVO<Object> getResourceInfoById(@PathVariable String id){
		SysResources sysResources = sysResourcesService.selectByPrimaryKey(id);
		return ResultVOUtil.success(sysResources);
	}
	
	@ApiOperation(value = "新增编辑系统资源")
    @PostMapping("/addOrEditResourcesInfo")
	public ResultVO<Object> addOrEditResourcesInfo(@RequestBody SysResourcesForm sysResourcesForm, BindingResult bindingResult){
    	
    	if(bindingResult.hasErrors()){
			log.error("【新增编辑系统资源信息】参数不正确,sysResourcesForm={}",sysResourcesForm);
			throw new AuthException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
		}
    	
    	SysResources sysResources = null;
    	
    	try {
			if(StringUtils.isEmpty(sysResourcesForm.getId())){
				sysResources = new SysResources();
				
				BeanUtils.copyProperties(sysResourcesForm, sysResources, BeanCopyUtil.getNullOrIgnorePropertyNames(sysResourcesForm, null));
				sysResources.setId(KeyUtil.getUUIDKey());
				//sysResources.setCreateUser(ShiroKit.getUserId());
				sysResourcesService.insertSelective(sysResources);
			}else{
				sysResources = sysResourcesService.selectByPrimaryKey(sysResourcesForm.getId());
				if(null != sysResources){
					BeanUtils.copyProperties(sysResourcesForm, sysResources, BeanCopyUtil.getNullOrIgnorePropertyNames(sysResourcesForm, null));
					sysResources.setUpdateTime(new Date());
					//sysResources.setUpdateUser(ShiroKit.getUserId());
					sysResourcesService.updateByPrimaryKey(sysResources);
				}else{
					log.error("【编辑系统资源】操作出错,记录不存在,sysResources={},sysResourcesForm={}",sysResources,sysResourcesForm);
    				throw new AuthException(ResultEnum.NOT_EXIST);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【新增编辑系统资源】操作出错,error={},sysResourcesForm={}",e.getMessage(),sysResourcesForm);
			throw new AuthException(ResultEnum.OPERATION_FAIL);
		}
		
		return ResultVOUtil.success(sysResources);
		
	}
	
	@ApiOperation(value = "删除系统资源")
    @GetMapping("/delResourcesById/{id}")
	public ResultVO<Object> delResourcesById(@PathVariable String id){
		try {
			SysResources sysResources = sysResourcesService.selectByPrimaryKey(id);
			if(null != sysResources){
				sysResources.setStatus("1");
				sysResources.setUpdateTime(new Date());
				sysResourcesService.updateByPrimaryKeySelective(sysResources);
				
				//??级联删除角色资源里面的数据
				
			}else{
				log.error("【删除系统资源】操作出错,记录不存在,id={}",id);
				throw new AuthException(ResultEnum.NOT_EXIST);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【删除系统资源】操作出错,error={}",e.getMessage());
			throw new AuthException(ResultEnum.OPERATION_FAIL);
		}
		
		return ResultVOUtil.success();
	}
	
}
