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.form.SysDeptForm;
import com.dcit.authority.dto.node.BuildTreeNode;
import com.dcit.authority.dto.node.DeptTreeNode;
import com.dcit.authority.exception.AuthException;
import com.dcit.authority.model.SysDept;
import com.dcit.authority.model.SysDeptExample;
import com.dcit.authority.model.SysDeptExample.Criteria;
import com.dcit.authority.service.SysDeptService;
//import com.dcit.authority.shiro.ShiroKit;
import com.dcit.common.enums.ResultEnum;
import com.dcit.common.utils.BeanCopyUtil;
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("/dept")
@Slf4j
public class OrgController {
	
	@Autowired
	private SysDeptService sysDeptService;
	
	@ApiOperation(value = "获取组织机构树")
    @GetMapping("/getDeptInfoTree")
	public ResultVO<Object> getDeptInfoTree(){
		SysDeptExample sysDeptExample = new SysDeptExample();
		sysDeptExample.createCriteria().andStatusEqualTo("0");
		List<SysDept> sysDeptList = sysDeptService.selectByExample(sysDeptExample);
		
		List<DeptTreeNode> deptTree = null;
		
		try {
			List<DeptTreeNode> treeNodeList = new ArrayList<DeptTreeNode>();
			
			DeptTreeNode treeNode = null;
			for(SysDept sysDept : sysDeptList){
				treeNode = new DeptTreeNode();
				BeanUtils.copyProperties(sysDept, treeNode, BeanCopyUtil.getNullOrIgnorePropertyNames(sysDept, null));
				treeNode.setId(sysDept.getId()+"");
				treeNode.setParentId(sysDept.getParentId()+"");
				treeNodeList.add(treeNode);
			}
			
			deptTree = BuildTreeNode.buildTree(treeNodeList);
			
			/*DeptTreeNode parentNode = null;
			for(SysDept sysDept : sysDeptList){
				if("0".equals(sysDept.getParentId()+"") && sysDept.getLevel().equals("1")){
					parentNode = new DeptTreeNode();
					BeanUtils.copyProperties(sysDept, parentNode, BeanCopyUtil.getNullOrIgnorePropertyNames(sysDept, null));
					parentNode.setId(sysDept.getId()+"");
					parentNode.setParentId(sysDept.getParentId()+"");
					parentTreeList.add(parentNode);
				}
			}
			
			for(DeptTreeNode deptTreeNode : parentTreeList){
				List<DeptTreeNode> childTreeList = new ArrayList<DeptTreeNode>();
				DeptTreeNode childNode = null;
				for(SysDept sysDept : sysDeptList){
					if(!"0".equals(sysDept.getParentId()+"") && sysDept.getLevel().equals("2") && (sysDept.getParentId()+"").equals(deptTreeNode.getId())){
						childNode = new DeptTreeNode();
						BeanUtils.copyProperties(sysDept, childNode, BeanCopyUtil.getNullOrIgnorePropertyNames(sysDept, null));
						childNode.setId(sysDept.getId()+"");
						childNode.setParentId(sysDept.getParentId()+"");
						childTreeList.add(childNode);
					}
				}
				
				deptTreeNode.setChildList(childTreeList);
			}*/
		} catch (Exception e) {
			log.error("【获取组织机构树】操作失败,e={}",e.getMessage());
			throw new AuthException(ResultEnum.OPERATION_FAIL);
		}
		
		//前端添加了
		/*DeptTreeNode topNode = new DeptTreeNode();
		topNode.setId("0");
		topNode.setParentId("-1");
		topNode.setLevel("0");
		topNode.setShortName("顶级");
		topNode.setFullName("顶级");
		topNode.setChildList(parentTreeList);*/
		
		return ResultVOUtil.success(deptTree);
	}
	
	@ApiOperation(value = "获取组织机构列表")
    @GetMapping("/getSysDeptList")
	public ResultVO<Object> getSysDeptList(@RequestParam(required=false, defaultValue="") String deptId, @RequestParam(required=false, defaultValue="") String deptName,
			@RequestParam(required = false, defaultValue = "1") int page,
			@RequestParam(required = false, defaultValue = "10") int size){
		
		ModelMap modelMap = new ModelMap();
		
		try {
			PageHelper.startPage(page,size);
			SysDeptExample sysDeptExample = new SysDeptExample();
			Criteria criteria = sysDeptExample.createCriteria();
			Criteria orCriteria = sysDeptExample.createCriteria();
			criteria.andStatusEqualTo("0");
			orCriteria.andStatusEqualTo("0");
			if(!StringUtils.isEmpty(deptName)){
				criteria.andFullNameLike("%"+ deptName +"%");
				orCriteria.andFullNameLike("%"+ deptName +"%");
			}
			if(!StringUtils.isEmpty(deptId)){
				criteria.andParentIdEqualTo(Integer.parseInt(deptId));
				orCriteria.andParentIdsLike("%["+ deptId +"]%");
				sysDeptExample.or(orCriteria);
			}
			
			List<SysDept> sysDeptList = sysDeptService.selectByExample(sysDeptExample);
			PageInfo<SysDept> pageInfo = new PageInfo<SysDept>(sysDeptList);
	        
	        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(modelMap);
	}
	
	
	@ApiOperation(value = "根据id获取组织机构信息")
    @GetMapping("/getDeptInfoById/{id}")
	public ResultVO<Object> getDeptInfoById(@PathVariable Integer id){
		SysDept sysDept = sysDeptService.selectByPrimaryKey(id);
		return ResultVOUtil.success(sysDept);
	}
	
	@ApiOperation(value = "新增编辑组织机构信息")
    @PostMapping("/addOrEditDeptInfo")
	public ResultVO<Object> addOrEditDeptInfo(@RequestBody SysDeptForm sysDeptForm, BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			log.error("【新增编辑组织机构信息】参数不正确,sysDeptForm={}",sysDeptForm);
			throw new AuthException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
		}
    	
		SysDept sysDept = null;
		
		try {
			if(StringUtils.isEmpty(sysDeptForm.getId())){
				sysDept = new SysDept();
				BeanUtils.copyProperties(sysDeptForm, sysDept, BeanCopyUtil.getNullOrIgnorePropertyNames(sysDeptForm, null));
				//sysDept.setCreateUser(ShiroKit.getUserId());
				sysDeptService.insertSelective(sysDept);
			}else{
				sysDept = sysDeptService.selectByPrimaryKey(sysDeptForm.getId());
				if(null != sysDept){
					BeanUtils.copyProperties(sysDeptForm, sysDept, BeanCopyUtil.getNullOrIgnorePropertyNames(sysDeptForm, null));
					sysDept.setUpdateTime(new Date());
					//sysDept.setUpdateUser(ShiroKit.getUserId());
					
					sysDeptService.updateByPrimaryKey(sysDept);
				}else{
					log.error("【编辑组织机构信息】操作出错,记录不存在,sysDept={},sysDeptForm={}",sysDept,sysDeptForm);
    				throw new AuthException(ResultEnum.NOT_EXIST);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【新增编辑组织机构信息】操作出错,error={},sysDeptForm={}",e.getMessage(),sysDeptForm);
			throw new AuthException(ResultEnum.OPERATION_FAIL);
		}
		
		return ResultVOUtil.success(sysDept);
	}
	
	@ApiOperation(value = "删除组织机构")
    @GetMapping("/delDeptInfoById/{id}")
	public ResultVO<Object> delDeptInfoById(@PathVariable Integer id){
		try {
			SysDept sysDept = sysDeptService.selectByPrimaryKey(id);
			if(null != sysDept){
				sysDept.setStatus("1");
				sysDept.setUpdateTime(new Date());
				sysDeptService.updateByPrimaryKey(sysDept);
			}else{
				log.error("【删除组织机构】操作出错,记录不存在,id={}",id);
				throw new AuthException(ResultEnum.NOT_EXIST);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【删除组织机构】操作出错,error={},id={}",e.getMessage(),id);
			throw new AuthException(ResultEnum.OPERATION_FAIL);
		}
		
		return ResultVOUtil.success();
	}

}
