package com.zcloud.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.system.Department;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.check.ListManagerService;
import com.zcloud.service.corp.CorpInfoService;
import com.zcloud.service.system.DepartmentService;
import com.zcloud.service.system.SupervisionDepartmentService;
import com.zcloud.service.system.UsersService;
import com.zcloud.util.*;
import net.sf.json.JSONArray;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * 说明：组织机构
 * 作者：luoxiaobao
 * 官网：www.fhadmin. org
 */
@Controller
@RequestMapping("/department")
public class DepartmentController extends BaseController {

	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private CorpInfoService corpInfoService;
	@Autowired
	private UsersService usersService;
	@Autowired
	private ListManagerService listManagerService;
	@Autowired
	private SupervisionDepartmentService supervisionDepartmentService;

	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	// @RequiresPermissions("department:add")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "企业管理",instructionsOperate = "组织机构",instructionsType = "新增")
	public Object add() throws Exception {
		Map<String, Object> map = new HashMap<>();
		String webSiteStatus = "0"; // 默认状态为正常

		PageData pd = this.getPageData();
		String corpinfoId = Jurisdiction.getCORPINFO_ID();

		try {
			// 获取企业信息
			PageData corpPage = new PageData();
			corpPage.put("CORPINFO_ID", corpinfoId);
			PageData corpInfo = corpInfoService.findById(corpPage);

			// 如果人员定位开启，才进行远程调用，否则跳过远程调用逻辑
			if ("0".equals(corpInfo.getString("PERSONNEL_POSITION"))) {
				// 人员定位开启时进行远程调用逻辑
				corpPage.put("enterpriseName", corpInfo.getString("CORP_NAME"));

				if (Tools.isEmpty(corpInfo.getString("enterpriseId"))) {
					JSONObject body = PLSUtil.GeneralPost("/deploy/enterprise/addDepEnterprise", corpPage, corpinfoId);
					if (body != null && "200".equals(body.getString("code"))) {
						corpPage.put("enterpriseId", body.getString("data"));
						corpInfo.put("enterpriseId", body.getString("data"));
						corpInfoService.updateEnterpriseId(corpPage);
					} else {
						webSiteStatus = "1";  // 远程调用失败
						map.put("webSiteStatus", webSiteStatus);
						map.put("result", "success");
						return map;
					}
				}

				// 新增部门信息
				PageData dept = new PageData();
				dept.put("deptName", pd.getString("NAME"));
				dept.put("enterpriseId", corpInfo.get("enterpriseId"));

				// 进行部门远程调用
				JSONObject body = PLSUtil.GeneralPost("/deploy/dept", dept, corpinfoId);
				if (body != null && "200".equals(body.getString("code"))) {
					pd.put("deptId", body.getString("data"));
				} else {
					webSiteStatus = "1";  // 远程调用失败
					map.put("webSiteStatus", webSiteStatus);
					map.put("result", "success");
					return map;
				}
			}

			// 本地数据库中保存部门信息
			pd.put("DEPARTMENT_ID", this.get32UUID());  // 主键
			pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());  // 企业
			departmentService.save(pd);

			// 存储监管单位
			if (pd != null && pd.get("ISSUPERVISE") != null
					&& Tools.notEmpty(pd.get("ISSUPERVISE").toString())
					&& "1".equals(pd.get("ISSUPERVISE").toString())
					&& pd.get("checkedIds") != null
					&& Tools.notEmpty(pd.get("checkedIds").toString())
					&& pd.get("checkedIds").toString().length() > 0) {

				String[] checkedIds = pd.get("checkedIds").toString().split(",");
				for (String subId : checkedIds) {
					PageData sd = new PageData();
					sd.put("SUPERVISIONDEPARTMENT_ID", this.get32UUID());
					sd.put("SUP_DEPARTMENT_ID", pd.get("DEPARTMENT_ID"));
					sd.put("SUB_DEPARTMENT_ID", subId);
					sd.put("ISDELETE", "0");
					sd.put("CORPINFO_ID", pd.get("CORPINFO_ID"));
					sd.put("CREATOR", Jurisdiction.getName()); // 添加人
					sd.put("CREATTIME", DateUtil.date2Str(new Date())); // 创建时间
					sd.put("OPERATOR", Jurisdiction.getName()); // 修改人
					sd.put("OPERATTIME", DateUtil.date2Str(new Date()));
					supervisionDepartmentService.save(sd);
				}
			}

			// 返回操作结果
			map.put("webSiteStatus", webSiteStatus);  // 返回网站状态
			map.put("result", "success");
			return map;
		} catch (Exception e) {
			// 捕获异常，设置 webSiteStatus 为 1
			webSiteStatus = "1";
			map.put("webSiteStatus", webSiteStatus);
			map.put("result", "success");
			return map;
		}
	}

	/**
	 * 删除
	 * @param DEPARTMENT_ID
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	// @RequiresPermissions("department:del")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "企业管理",instructionsOperate = "组织机构",instructionsType = "删除")
	public Object delete(@RequestParam String DEPARTMENT_ID) throws Exception {
		Map<String, Object> map = new HashMap<>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd.put("DEPARTMENT_ID", DEPARTMENT_ID);

		// 判断是否有子部门
		if (departmentService.listSubDepartmentByParentId(DEPARTMENT_ID).size() > 0) {
			errInfo = "haveChild";
			map.put("msg", "该部门有下级部门，请先删除下级部门");
		}
		// 判断部门是否有用户
		else if (usersService.listUserbyDep(pd).size() > 0) {
			errInfo = "haveUser";
			map.put("msg", "该部门有用户，请先删除用户");
		}
		// 判断部门是否有清单
		else if (listManagerService.listListByDep(pd).size() > 0) {
			errInfo = "havelist";
			map.put("msg", "该部门有清单，请先删除清单");
		} else {
			// 获取企业信息
			pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
			PageData data = corpInfoService.findById(pd);

			if ("0".equals(data.getString("PERSONNEL_POSITION"))) {
				PageData dept = new PageData();
				dept.put("DEPARTMENT_ID", DEPARTMENT_ID);
				PageData byId = departmentService.findById(dept);

				try {
					JSONObject body = PLSUtil.GeneralDelete("/deploy/dept/", byId.getString("deptId"), Jurisdiction.getCORPINFO_ID());
					if (body != null && !"200".equals(body.getString("code"))) {
						return ReturnMap.ok().put("webSiteStatus", "1");
					}
				} catch (Exception e) {
					return ReturnMap.ok().put("webSiteStatus", "1");
				}
			}
			departmentService.delete(pd);
		}

		map.put("result", errInfo); // 返回结果
		return map;
	}



	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	// @RequiresPermissions("department:edit")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "企业管理",instructionsOperate = "组织机构",instructionsType = "修改")
	public Object edit() throws Exception {
		Map<String, Object> map = new HashMap<>();
		String errInfo = "success";
		PageData pd = this.getPageData();
		PageData sfDeptID = new PageData();
		sfDeptID.put("deptId", pd.get("deptId"));
		sfDeptID.put("deptName", pd.get("NAME"));

		// 获取企业信息
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		PageData data = corpInfoService.findById(pd);

		if ("0".equals(data.getString("PERSONNEL_POSITION"))) {
			try {

				JSONObject body = PLSUtil.GeneralPut("/deploy/dept", sfDeptID, Jurisdiction.getCORPINFO_ID());

				if (body == null || !"200".equals(body.getString("code"))) {
					return ReturnMap.ok().put("webSiteStatus", "1");
				}
			} catch (Exception e) {
				return ReturnMap.ok().put("webSiteStatus", "1");
			}
		}

		departmentService.edit(pd);

		// 删除旧的监管单位
		PageData pd2 = new PageData();
		pd2.put("SUP_DEPARTMENT_ID", pd.get("DEPARTMENT_ID"));
		pd2.put("OPERATOR", Jurisdiction.getName()); // 修改人
		pd2.put("OPERATTIME", DateUtil.date2Str(new Date()));
		supervisionDepartmentService.deleteByDept(pd2);

		// 存储新的监管单位
		if (pd != null && pd.get("ISSUPERVISE") != null
				&& Tools.notEmpty(pd.get("ISSUPERVISE").toString())
				&& "1".equals(pd.get("ISSUPERVISE").toString())
				&& pd.get("checkedIds") != null
				&& Tools.notEmpty(pd.get("checkedIds").toString())
				&& pd.get("checkedIds").toString().length() > 0) {

			String[] checkedIds = pd.get("checkedIds").toString().split(",");
			for (String subId : checkedIds) {
				PageData sd = new PageData();
				sd.put("SUPERVISIONDEPARTMENT_ID", this.get32UUID());
				sd.put("SUP_DEPARTMENT_ID", pd.get("DEPARTMENT_ID"));
				sd.put("SUB_DEPARTMENT_ID", subId);
				sd.put("ISDELETE", "0");
				sd.put("CORPINFO_ID", pd.get("CORPINFO_ID"));
				sd.put("CREATOR", Jurisdiction.getName()); // 添加人
				sd.put("CREATTIME", DateUtil.date2Str(new Date())); // 创建时间
				sd.put("OPERATOR", Jurisdiction.getName()); // 修改人
				sd.put("OPERATTIME", DateUtil.date2Str(new Date()));
				supervisionDepartmentService.save(sd);
			}
		}

		map.put("result", errInfo); // 返回结果
		return map;
	}


	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "企业管理",instructionsOperate = "组织机构",instructionsType = "列表")
	public Object list(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String CORPINFO_ID = Jurisdiction.getCORPINFO_ID();
		String KEYWORDS = pd.getString("KEYWORDS");								//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))pd.put("keywords", KEYWORDS.trim());
		String DEPARTMENT_ID = null == pd.get("DEPARTMENT_ID")?"":pd.get("DEPARTMENT_ID").toString();
		pd.put("DEPARTMENT_ID", DEPARTMENT_ID);					//当作上级ID
		pd.put("CORPINFO_ID", CORPINFO_ID);					//当作上级ID
		pd.put("ISMAIN", Jurisdiction.getIS_MAIN());
		pd.put("ISSUPERVISE", Jurisdiction.getISSUPERVISE());
		if(pd.get("ISSUPERVISE").equals(1) && pd.get("DEPARTMENT_ID")==null){
			pd.put("DEPARTMENT_ID", Jurisdiction.getDEPARTMENT_ID());

		} else {
			pd.put("SELECT_DEPARTMENT_ID", Jurisdiction.getDEPARTMENT_ID());

		}
		String DEPTIDS = pd.getString("DEPTIDS");
		if(Tools.notEmpty(DEPTIDS)) {
			String DEPT_IDS[] = DEPTIDS.split(",");
			pd.put("DEPT_IDS", DEPT_IDS);
		}
		page.setPd(pd);
		List<PageData>	varList = departmentService.listForLevelName(page);			//列出Department列表
		if("".equals(DEPARTMENT_ID) || "0".equals(DEPARTMENT_ID)) {
			map.put("PARENT_ID", "0");											//上级ID
		}else {
			map.put("PARENT_ID", departmentService.findById(pd).getString("PARENT_ID"));	//上级ID
		}
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 显示列表ztree
	 * @return
	 */
	@RequestMapping(value="/listTree")
	// @RequiresPermissions("department:list")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "企业管理",instructionsOperate = "组织机构",instructionsType = "显示列表")
	public Object listTree()throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String url = pd.get("url")==null?"department_list.html?DEPARTMENT_ID=":pd.getString("url");

//		String ZDEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
//		ZDEPARTMENT_ID = "".equals(ZDEPARTMENT_ID)?"0":ZDEPARTMENT_ID;
//		List<Department> zdepartmentPdList = new ArrayList<Department>();
//
//		PageData dept = new PageData();
//		dept.put("DEPARTMENT_ID",ZDEPARTMENT_ID);
//		dept=this.departmentService.findById(dept);

		//获取部门下拉树
		List<Department> zdepartmentPdList = new ArrayList<Department>();
		PageData dept = new PageData();
		dept.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		dept=this.departmentService.findByCorpId(dept);

		Department depar = new Department();
		depar.setDEPARTMENT_ID(dept.getString("DEPARTMENT_ID"));
		depar.setPARENT_ID(dept.getString("PARENT_ID"));
		depar.setNAME(dept.getString("NAME"));
		if(pd.get("rootDisabled")!= null && pd.get("rootDisabled").toString().equals("Y")){
			depar.setDISABLED(true);
		}else {
			depar.setDISABLED(false);
		}
		depar.setTreeurl(url+depar.getDEPARTMENT_ID());
		PageData pd2 = new PageData();
		pd2.put("parentId", depar.getDEPARTMENT_ID());
		pd2.put("SUP_DEPARTMENT_ID", Jurisdiction.getDEPARTMENT_ID());
		String isMain = Jurisdiction.getIS_MAIN();
		pd.put("USER_ID",Jurisdiction.getUSER_ID());
		PageData cpd = new PageData();
		PageData npd = new PageData();
		cpd = usersService.findById(pd);
		if(cpd.getString("ISLEADER") != null && cpd.getString("ISLEADER").equals("1")){
			String DEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
			String ids = departmentService.getDEPARTMENT_IDS(DEPARTMENT_ID);
			ids=Jurisdiction.getDEPARTMENT_ID()+","+ids;   //把自己部门插入进去
			if(ids!=null && Tools.notEmpty(ids)&& ids.lastIndexOf(",")>-1) {
				ids = ids.substring(0,ids.lastIndexOf(","));
				pd2.put("DEPARTMENT_IDS", ids.split(","));
			}else {
				pd2.put("DEPARTMENT_IDS", DEPARTMENT_ID);
			}
		}
		pd2.put("ISLEADER",cpd.getString("ISLEADER"));
		depar.setSubDepartment(this.departmentService.listAllDep(pd2,url,isMain));

		depar.setTarget("treeFrame");
		depar.setIcon("../../../assets/images/user.gif");
		zdepartmentPdList.add(depar);
//		zdepartmentPdList.addAll(departmentService.listAllDepartment(ZDEPARTMENT_ID));
		JSONArray arr = JSONArray.fromObject(zdepartmentPdList);
		String json = arr.toString();
		json = json.replaceAll("DEPARTMENT_ID", "id").replaceAll("PARENT_ID", "pId").replaceAll("NAME", "name").replaceAll("subDepartment", "nodes").replaceAll("hasDepartment", "checked").replaceAll("treeurl", "url").replaceAll("DISABLED", "disabled");

		map.put("USER_ID", Jurisdiction.getUSER_ID());
		map.put("zTreeNodes", json);
		map.put("result", errInfo);
		return map;
	}


	/**
	 * 显示列表ztree
	 * @return
	 */
	@RequestMapping(value="/listzTree")
	// @RequiresPermissions("department:list")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "企业管理",instructionsOperate = "组织机构",instructionsType = "显示列表")
	public Object listzTree()throws Exception{

		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String url = pd.get("url")==null?"department_list.html?DEPARTMENT_ID=":pd.getString("url");

//		String ZDEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
//		ZDEPARTMENT_ID = "".equals(ZDEPARTMENT_ID)?"0":ZDEPARTMENT_ID;
//		List<Department> zdepartmentPdList = new ArrayList<Department>();
//
//		PageData dept = new PageData();
//		dept.put("DEPARTMENT_ID",ZDEPARTMENT_ID);
//		dept=this.departmentService.findById(dept);

		//获取部门下拉树
		List<Department> zdepartmentPdList = new ArrayList<Department>();
		PageData dept = new PageData();
		dept.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		dept=this.departmentService.findByCorpId(dept);

		Department depar = new Department();
		if(pd.get("rootDisabled")!= null && pd.get("rootDisabled").toString().equals("Y")){
			depar.setDISABLED(true);
		}else {
			depar.setDISABLED(false);
		}
		depar.setDEPARTMENT_ID(dept.getString("DEPARTMENT_ID"));
		depar.setPARENT_ID(dept.getString("PARENT_ID"));
		depar.setNAME(dept.getString("NAME"));
		depar.setTreeurl(url+depar.getDEPARTMENT_ID());
		depar.setSubDepartment(this.departmentService.listAllDepartment(depar.getDEPARTMENT_ID(),url));
		depar.setTarget("treeFrame");
		depar.setIcon("../../../assets/images/user.gif");
		zdepartmentPdList.add(depar);
//		zdepartmentPdList.addAll(departmentService.listAllDepartment(ZDEPARTMENT_ID));
		JSONArray arr = JSONArray.fromObject(zdepartmentPdList);
		String json = arr.toString();
		json = json.replaceAll("DEPARTMENT_ID", "id").replaceAll("PARENT_ID", "pId").replaceAll("NAME", "name").replaceAll("subDepartment", "nodes").replaceAll("hasDepartment", "checked").replaceAll("treeurl", "url");

		map.put("USER_ID", Jurisdiction.getUSER_ID());
		map.put("zTreeNodes", json);
		map.put("result", errInfo);
		return map;

	}

	/**去新增页面
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goAdd")
	// @RequiresPermissions("department:add")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "企业管理",instructionsOperate = "组织机构",instructionsType = "去新增页面")
	public Object goAdd()throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String DEPARTMENT_ID = null == pd.get("DEPARTMENT_ID")?"":pd.get("DEPARTMENT_ID").toString();
		pd.put("DEPARTMENT_ID", DEPARTMENT_ID);					//上级ID
		map.put("pds",departmentService.findById(pd));					//传入上级所有信息
		map.put("result", errInfo);
		return map;
	}

	 /**去修改页面
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	// @RequiresPermissions("department:edit")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "企业管理",instructionsOperate = "组织机构",instructionsType = "去修改页面获取信息")
	public Object goEdit()throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = departmentService.findById(pd);									//根据ID读取

		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		pd.put("SUP_DEPARTMENT_ID", pd.get("DEPARTMENT_ID"));
		List<PageData> varlist  = supervisionDepartmentService.listAll(pd);	//根据ID读取
		map.put("pd", pd);																//放入视图容器
		map.put("varlist", varlist);
		PageData supPd = new PageData();
		supPd.put("DEPARTMENT_ID", pd.get("PARENT_ID").toString());
		//pd.put("DEPARTMENT_ID",pd.get("PARENT_ID").toString());					//用作上级信息
		map.put("pds",departmentService.findById(supPd));							//传入上级所有信息
		map.put("result", errInfo);
		return map;
	}

	/**判断编码是否存在
	 * @return
	 */
	@RequestMapping(value="/hasBianma")
	@ResponseBody
	public Object hasBianma() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		if(departmentService.findByBianma(pd) != null){
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}
	/** 判断部门等级 如果没有上一级就是1
	 * @return
	 */
	@RequestMapping(value="/parentGrade")
	@ResponseBody
	public Object parentGrade () throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();

		String deptGrade = getparentId(pd.getString("deptGrade")) +"";
		map.put("deptGrade", deptGrade);
		map.put("result", errInfo);				//返回结果
		return map;
	}
	/**
	 * @return
	 */
	public Integer getparentId (String parentId) throws Exception {
		Integer parentGrade =1;

		PageData parentDepePd = new PageData();
		parentDepePd.put("DEPARTMENT_ID", parentId);
		PageData parent = departmentService.findById(parentDepePd);
		if(!Tools.isEmpty(parent)) {
			parentId = parent.getString("PARENT_ID");
			if(!"0".equals(parentId)) {
				parentGrade = getparentId(parentId);
				parentGrade ++;
			}
		}
		return parentGrade ;

	}

	/**判断同等级的名字是否重复
	 * @return
	 */
	@RequestMapping(value="/hasName")
	@ResponseBody
	public Object hasName() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();

		PageData parentDepePd = new PageData();
		parentDepePd.put("NAME", pd.getString("name"));
		parentDepePd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		parentDepePd.put("ISEDIT", "1");
		parentDepePd.put("DEPARTMENT_ID", pd.get("DEPARTMENT_ID"));
		//就是父id相同的名字
		PageData parent = departmentService.findByName(parentDepePd);
		if(!Tools.isEmpty(parent)) {
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;

	}

	/**
	 * 显示列表ztree(只查企业端部门)
	 *
	 * @return
	 */
	@RequestMapping(value = "/listTreeManageAndCorp2")
	@ResponseBody
	public Object listTreeManageAndCorp2() throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd.put("DEPARTMENT_ID", "0");    //查询父节点为0的根节点数据
		List<PageData> rootList = departmentService.listTreeManageAndCorp2(pd);
		JSONArray arr = JSONArray.fromObject(rootList);
		map.put("zTreeNodes", arr.toString());
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 显示列表ztree(只查某几个企业端部门)
	 *
	 * @return
	 */
	@RequestMapping(value = "/listTreeManageAndCorpNum")
	@ResponseBody
	public Object listTreeManageAndCorpNum() throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String[] lists = pd.getString("INVOLVING_CORPS").split(",");
		List<String> corpId = new ArrayList<>();
		for (int i = 0; i < lists.length; i++) {
			corpId.add(lists[i]);
		}
		pd.put("corpId", corpId);
		List<PageData> rootList = departmentService.listTreeManageAndCorpNum(pd);
		JSONArray arr = JSONArray.fromObject(rootList);
		map.put("zTreeNodes", arr.toString());
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 显示列表ztree
	 *
	 * @return
	 */
	@RequestMapping(value = "/scanlistTree")
	@ResponseBody
	public Object scanlistTree() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String url = pd.get("url") == null ? "department_list.html?DEPARTMENT_ID=" : pd.getString("url");
		//获取部门下拉树
		List<Department> zdepartmentPdList = new ArrayList<Department>();
		PageData dept = new PageData();
		dept.put("CORPINFO_ID", "13cf0f4ec77e4d98ae8cdd9c3386ae0c");
		dept = this.departmentService.findByCorpId(dept);
		Department depar = new Department();
		depar.setDEPARTMENT_ID(dept.getString("DEPARTMENT_ID"));
		depar.setPARENT_ID(dept.getString("PARENT_ID"));
		depar.setBIANMA(dept.getString("BIANMA"));
		depar.setNAME(dept.getString("NAME"));
		depar.setTreeurl(url + depar.getDEPARTMENT_ID());
		depar.setSubDepartment(this.departmentService.listAllDepartment(depar.getDEPARTMENT_ID(), url));
		depar.setTarget("treeFrame");
		depar.setIcon("../../../assets/images/user.gif");
		zdepartmentPdList.add(depar);
//		zdepartmentPdList.addAll(departmentService.listAllDepartment(ZDEPARTMENT_ID));
		JSONArray arr = JSONArray.fromObject(zdepartmentPdList);
		String json = arr.toString();
		json = json.replaceAll("DEPARTMENT_ID", "id").replaceAll("PARENT_ID", "pId").replaceAll("NAME", "name").replaceAll("subDepartment", "nodes").replaceAll("hasDepartment", "checked").replaceAll("treeurl", "url").replaceAll("BIANMA", "LEVEL");

		//map.put("USER_ID", Jurisdiction.getUSER_ID());
		map.put("zTreeNodes", json);
		map.put("result", errInfo);
		return map;
	}

	@RequestMapping(value = "/listAllByState")
	@ResponseBody
	public Object listAllDict() throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		List<PageData> deptByState = departmentService.listAll(pd);
		JSONArray arr = JSONArray.fromObject(deptByState);
		String json = arr.toString();
		json = json.replaceAll("DEPARTMENT_ID", "id").replaceAll("PARENT_ID", "pId").replaceAll("NAME", "name").replaceAll("subDict", "nodes").replaceAll("hasDict", "checked").replaceAll("treeurl", "url");
		map.put("zTreeNodes", json);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 显示列表ztree
	 *
	 * @return
	 */
	@RequestMapping(value = "/listTreeCorpDept")
	@ResponseBody
	public Object listTreeCorpDept() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		pd.put("DEPARTMENT_ID", Jurisdiction.getCORPINFO_ID());    //查询父节点为0的根节点数据
		List<PageData> rootList = departmentService.listTreeCorpDept(pd);
		JSONArray arr = JSONArray.fromObject(rootList);
		map.put("zTreeNodes", arr.toString());
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 去修改页面
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/goUserByLeaderOrCharge")
	// @RequiresPermissions("department:edit")
	@ResponseBody
	public Object goUserByLeaderOrCharge() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData goEditPd = new PageData();
		PageData depart = departmentService.findById(pd);
		PageData user = new PageData();
		if (!Tools.isEmpty(depart)) {
			PageData userPd = new PageData();
			if ("".equals(pd.getString("type"))) {
				userPd.put("USER_ID", depart.getString("HEADMAN"));
			}
			if ("".equals(pd.getString("type"))) {
				userPd.put("USER_ID", depart.getString("LEADER_CHARGE"));
			}
			user = usersService.findById(userPd);
		}
		map.put("departPerson", user);
		map.put("result", "success");
		return map;
	}

	/**
	 * 列表
	 *
	 * @throws Exception
	 */
	@RequestMapping(value = "/listForDoor")
	@ResponseBody
	public Object listForDoor() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String CORPINFO_ID = Jurisdiction.getCORPINFO_ID();
		pd.put("CORPINFO_ID", CORPINFO_ID);                    //当作上级ID
		List<PageData> varList = departmentService.listForDoor(pd);            //列出Department列表
		map.put("list", varList);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 导出到excel
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/excels")
	// @RequiresPermissions("toExcel")
	public ModelAndView exportExcels() throws Exception {
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		Map<String, Object> dataMap = new HashMap<String, Object>();
		List<String> titles = new ArrayList<String>();
		titles.add("名称"); //1
		titles.add("负责人");    //2
		titles.add("部门级别");    //3
		dataMap.put("titles", titles);
		List<PageData> varOList = departmentService.islistAll(pd);
		List<PageData> varList = new ArrayList<PageData>();
		for (int i = 0; i < varOList.size(); i++) {
			PageData vpd = new PageData();
			vpd.put("var1", varOList.get(i).getString("NAME"));        //1
			vpd.put("var2", varOList.get(i).getString("HEADMAN_NAME"));        //2
			vpd.put("var3", varOList.get(i).getString("leName"));        //3
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		dataMap.put("filename", "部门信息");
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv, dataMap);
		return mv;
	}

	/**
	 * 显示列表ztree
	 *
	 * @return
	 */
	@RequestMapping(value = "/listTreeV2")
	// @RequiresPermissions("department:list")
	@ResponseBody
	public Object listTreeV2() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String url = pd.get("url") == null ? "department_list.html?DEPARTMENT_ID=" : pd.getString("url");
		JSONArray arr = JSONArray.fromObject(this.departmentService.listAllDepartmentV2("0", url));
		String json = arr.toString();
		json = json.replaceAll("DEPARTMENT_ID", "id").replaceAll("PARENT_ID", "pId").replaceAll("NAME", "name").replaceAll("subDepartment", "nodes").replaceAll("hasDepartment", "checked").replaceAll("treeurl", "url").replaceAll("BIANMA", "LEVEL");

		map.put("USER_ID", Jurisdiction.getUSER_ID());
		map.put("zTreeNodes", json);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 显示列表ztree(只查监管端部门)
	 *
	 * @return
	 */
	@RequestMapping(value = "/listTreeManageAndCorp1")
	@ResponseBody
	public Object listTreeManageAndCorp1() throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd.put("DEPARTMENT_ID", "0");	//查询父节点为0的根节点数据
		List<PageData> rootList = departmentService.listTreeManageAndCorp1(pd);
		JSONArray arr = JSONArray.fromObject(rootList);
		map.put("zTreeNodes", arr.toString());
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 显示列表ztree(集团部门+子公司部门)
	 *
	 * @return
	 */
	@RequestMapping(value = "/listTreeManageAndCorpForPcPunishThePerson")
	@ResponseBody
	public Object listTreeManageAndCorpForPcPunishThePerson() throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String ids = pd.getString("ids");
		if (!Tools.isEmpty(ids)) {
			List<String> list = JSONObject.parseArray(ids,String.class);
			if (list.size()==0){
				map.put("zTreeNodes", "[]");
				map.put("result", errInfo);
				return map;
			}else {
				pd.put("ids", list);
			}
		}

		pd.put("DEPARTMENT_ID", "0");	//查询父节点为0的根节点数据

		List<PageData> rootList = departmentService.listTreeManageAndCorpForPcPunishThePerson(pd);
		JSONArray arr = JSONArray.fromObject(rootList);
		map.put("zTreeNodes", arr.toString());
		map.put("result", errInfo);
		return map;
	}

}
