package cn.myapps.runtime.department.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.bcxin.saas.domains.entities.DepartmentEntity;
import com.bcxin.saas.domains.readers.DepartmentDbReader;
import com.bcxin.saas.domains.repositories.DepartmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;

import cn.myapps.authtime.common.service.AuthTimeServiceManager;
import cn.myapps.authtime.department.model.DepartmentVO;
import cn.myapps.authtime.department.service.DepartmentProcess;
import cn.myapps.authtime.user.service.UserProcess;
import cn.myapps.common.controller.Resource;
import cn.myapps.common.data.tree.DepartmentNode;
import cn.myapps.common.data.tree.Node;
import cn.myapps.common.util.StringUtil;
import cn.myapps.runtime.common.controller.AbstractRuntimeController;
import cn.myapps.runtime.department.service.DepartmentRunTimeService;
import cn.myapps.util.ProcessFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;

/**
 * 部门选择框RESTful接口
 * @author spy
 */
@Api(tags = "部门执行模块")
@Component
@RequestMapping(path = "/api/runtime/{applicationId}/departments/selectbox", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DepartmentSelectboxController extends AbstractRuntimeController{
	
	@Autowired
	private DepartmentRunTimeService deptService;

	@Autowired
	private DepartmentDbReader departmentDbReader;

	/**
	 * 获取部门树形集合
	 * @param deptId 部门id
	 * @param applicationId 软件id
	 * @param level 显示部门级别(-1:所有,0:一级,1:二级,2:三级)
	 * @param belong 是否只显示当前用户及下属部门(true|false)
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/department")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "获取部门树形集合", notes = "获取部门树形集合")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "deptId",value = "部门id",required = true,paramType = "query",dataType = "string"),
		@ApiImplicitParam(name = "applicationId",value = "软件id",required = true,paramType = "path",dataType = "string"),
		@ApiImplicitParam(name = "level",value = "显示部门级别(-1:所有,0:一级,1:二级,2:三级)",required = false,paramType = "query",dataType = "string"),
		@ApiImplicitParam(name = "belong",value = "是否只显示当前用户及下属部门(true|false)",required = false,paramType = "query",dataType = "boolean")
	})
	public Resource getDepartmentListTree(String deptId, @PathVariable String applicationId, @RequestParam(required=false) int level, @RequestParam(required=false) boolean belong) throws Exception{
		
		List<Node> result = deptService.getDepartmentListTree(getUser(), deptId, applicationId, level, belong);
		return success("ok", result);
	}
	
	/**
	 * 根据父级部门id获取部门用户集合
	 * @param deptId
	 * 		部门id
	 * @param applicationId
	 * 		软件id
	 * @param pageSize
	 * 		每页显示数据数
	 * @param pageNum
	 * 		当前页
	 * @return
	 * 		部门或用户集合
	 * @throws Exception
	 */
	@GetMapping("/user")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "根据父级部门id获取部门用户集合", notes = "根据父级部门id获取部门用户集合")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "deptId",value = "部门id",required = false,paramType = "query",dataType = "string"),
		@ApiImplicitParam(name = "applicationId",value = "软件id",required = true,paramType = "path",dataType = "string"),
		@ApiImplicitParam(name = "pageSize",value = "每页显示数据数",required = false,paramType = "query",dataType = "string",defaultValue="5"),
		@ApiImplicitParam(name = "pageNum",value = "当前页",required = false,paramType = "query",dataType = "string",defaultValue="1"),
		@ApiImplicitParam(name = "isFromMail",value = "是否邮件调用",required = false,paramType = "query",dataType = "string")
	})
	public Resource getDepartmentAndUsers(@RequestParam(required=false) String deptId, @PathVariable String applicationId, @RequestParam(required=false,defaultValue="5") String pageSize, @RequestParam(required=false,defaultValue="1") String pageNum, @RequestParam(required = false) boolean isFromMail) throws Exception{
		if (pageSize == null || "".equals(pageSize) || "null".equals(pageSize)) {
			pageSize = "5";
		}
		if (pageNum == null || "".equals(pageNum) || "null".equals(pageNum)) {
			pageNum = "1";
		}
		int newPageSize = Integer.parseInt(pageSize);
		int newPageNum = Integer.parseInt(pageNum);
		Map<String, Object> result = deptService.getDepartmentAndUsers(applicationId, deptId, getUser(), isFromMail, newPageSize, newPageNum);
		return success("ok", result);
	}
	
	/**
	 * 部门搜索
	 * @param applicationId 软件id
	 * @param keyword 关键字
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/search")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "部门搜索", notes = "部门搜索")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "applicationId",value = "软件id",required = true,paramType = "path",dataType = "string"),
		@ApiImplicitParam(name = "keyword",value = "关键字",required = false,paramType = "query",dataType = "string")
	})
	public Resource searchDeptTree(@PathVariable String applicationId, @RequestParam(required=false) String keyword) throws Exception{
		if (StringUtil.isBlank(keyword)) {
			List<Node> list = new ArrayList<Node>();
			DepartmentProcess process = AuthTimeServiceManager.departmentRuntimeService();
			DepartmentVO dept = process.getRootDepartmentByDomainId(getUser().getDomainid());
			DepartmentNode d = new DepartmentNode();
			d.setId(dept.getId());
			d.setName(dept.getName());
			d.setCode(dept.getCode());
			d.setLevel(dept.getLevel());
			list.add(d);
			return success("ok", list);
		}
		String domainId = getUser().getDomainid();  // 获取当前用户所属企业域id
		List<Node> result = deptService.searchDeptTree(applicationId, domainId, keyword, getUser());
		return success("ok", result);
	}

	/**
	 * 根据父级获取部门集合
	 * @param applicationId 软件id
	 * @param parentId 父级id
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/childs")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "根据父级获取部门集合", notes = "根据父级获取部门集合")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "applicationId",value = "软件id",required = true,paramType = "path",dataType = "string"),
			@ApiImplicitParam(name = "parentId",value = "父级id",required = false,paramType = "query",dataType = "string")
	})
	public Resource getDeptByParent(@PathVariable String applicationId, @RequestParam(required=false) String parentId) throws Exception{
		List<JSONObject> list = new ArrayList<JSONObject>();
		if(StringUtil.isBlank(parentId)){
			DepartmentEntity departmentVO = departmentDbReader.getRootDepartmentByDomainId(getUser().getDomainid());
			JSONObject d = new JSONObject();
			d.put("id", departmentVO.getId());
			d.put("name", departmentVO.getName());
			d.put("userCount", departmentVO.getTotalMember());
			Collection<DepartmentEntity> childs = departmentDbReader.getDepartmentByParentId(departmentVO.getId());
			if(childs == null || childs.isEmpty()){
				d.put("hasChilds", false);
			} else {
				d.put("hasChilds", true);
			}
			list.add(d);
		} else {
			Collection<DepartmentEntity> depts = departmentDbReader.getDepartmentByParentId(parentId);
			for (DepartmentEntity departmentVO : depts) {
				JSONObject d = new JSONObject();
				d.put("id", departmentVO.getId());
				d.put("name", departmentVO.getName());
					d.put("userCount", departmentVO.getTotalMember());
				Collection<DepartmentEntity> childs = departmentDbReader.getDepartmentByParentId(departmentVO.getId());
				if(childs == null || childs.isEmpty()){
					d.put("hasChilds", false);
				} else {
					d.put("hasChilds", true);
				}
				list.add(d);
			}
		}
		return success("ok", list);
	}
}
