package com.palmnest.webapp.controller;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.OutTreeDTO;
import com.palmnest.model.*;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.AppUserService;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.FloorInfoManager;
import com.palmnest.service.outer.KafkaOuterService;
import com.palmnest.service.property.PropertyManager;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 管理者内部
 * 系统组织架构管理（包含：公司、部门、团队等等）
 *
 * @author yubing
 * @since 2014-09-11
 */
@Controller
@RequestMapping("admin/organization/*")
public class OrganizationController extends BaseFormController {

	@Autowired
	private OrganizationManager organizationManager;
	@Autowired
	private UserManager         userManager;
	@Autowired
	private PropertyManager     propertyManager;
	@Autowired
	private FloorInfoManager    floorManager;
	@Autowired
	private KafkaOuterService   kafkaOuterService;
	@Autowired
	private AppUserService      appUserService;

	/**
	 * 公司列表查询
	 */
	@RequestMapping(value = "/companylist")
	public ModelAndView companyList(HttpServletRequest request,
									HttpServletResponse response) throws Exception {
		initFunctionOperate(request);       //初始化功能操作权限

		Model        model   = new ExtendedModelMap();
		StringBuffer sbf     = new StringBuffer(" where 1=1");
		String       pageNo  = request.getParameter("pageNo");
		String       keyName = request.getParameter("keyName");
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isNotEmpty(keyName)) {
			sbf.append(" and name like '%" + keyName + "%' or code like '%" + keyName + "%'");
			model.addAttribute("keyName", keyName);
		}
		sbf.append(" and isEnabled='" + ElementConstant.YESORNO_1 + "'");
		//管理物业组织的权限过滤
//		sbf.append(" and id in("+getUserRelationCompanyIdsStr(request)+")");
		Page page = organizationManager.queryCompanyList(Integer.parseInt(pageNo), sbf.toString());
		model.addAttribute("page", page);
		return new ModelAndView("admin/companyList", model.asMap());
	}

	/**
	 * 公司管理新增、更新
	 *
	 * @param tbCompany
	 */
	@RequestMapping(value = "/companyForm")
	public ModelAndView companyForm(@ModelAttribute("tbCompany") TbCompany tbCompany,
									HttpServletRequest request, HttpServletResponse response) {
		Model  model   = new ExtendedModelMap();
		String actType = request.getParameter("actType");
		//新增或者更新
		if ("save".equals(actType)) {
//			String buildIds=request.getParameter("buildIds");
			tbCompany.setType(request.getParameter("type"));
			tbCompany.setCreator(request.getRemoteUser());
			tbCompany.setCreateTime(new Date());
			tbCompany.setIsenabled(ElementConstant.YESORNO_1);

//			String retCode=organizationManager.saveOrUpdateCompany(tbCompany, buildIds.split(";"));
			String retCode = organizationManager.saveOrUpdateCompany(tbCompany);
			if ("2".equals(retCode)) {
				model.addAttribute("errormsg", "更新成功");
			} else {
				model.addAttribute("errormsg", "新增成功");
			}
			//发送到消息通道，同步到子系统
			kafkaOuterService.syncCompany(tbCompany);
		}
		List<Element> companyTypeGroup = this.getElementGroupManager().getElementsByGroupName("companyTypeGroup");
		model.addAttribute("companyTypeGroup", companyTypeGroup);
		model.addAttribute("funcid", request.getParameter("funcid"));
		return new ModelAndView("admin/companyForm", model.asMap());
	}

	/**
	 * 更新公司信息
	 *
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/updateTbCompany/{id}&{funcid}")
	public String update(@PathVariable int id, @PathVariable long funcid, Model model) {
		List<Element> companyTypeGroup = this.getElementGroupManager().getElementsByGroupName("companyTypeGroup");
		model.addAttribute("companyTypeGroup", companyTypeGroup);
		model.addAttribute(organizationManager.getCompanyById(id));
		model.addAttribute("funcid", funcid);
		return "admin/companyForm";
	}

	/**
	 * 删除公司，逻辑删除
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/deleteTbCompany/{id}&{funcid}")
	public String deleteTbCompany(@PathVariable int id, @PathVariable long funcid, HttpServletRequest request) {
		TbCompany company = organizationManager.getCompanyById(id);
		company.setModifier(request.getRemoteUser());
		company.setModifyTime(new Date());
		company.setIsenabled(ElementConstant.YESORNO_0);
		organizationManager.updateModel(company);

		//发送到消息通道，同步到子系统
		kafkaOuterService.sendMessage(null, "deleteCompany", "{id:" + company.getId() + "}");
		return "redirect:/admin/organization/companylist?funcid=" + funcid;
	}

	/**
	 * 部门信息列表查询
	 */
	@RequestMapping(value = "/deptlist")
	public ModelAndView deptList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		User  user  = (User) request.getSession().getAttribute("UserCache");
		if (!user.isAdmin()) {
			// 是项目管理员或普通管理员,项目只有一个
			List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());
			model.addAttribute("org", dtos.get(0));
		}

		initPageOrgInfo(request, model);
		return new ModelAndView("admin/deptList", model.asMap());
	}

	/**
	 * 部门管理新增、更新
	 *
	 * @param
	 */
	@RequestMapping(value = "/deptForm")
	public ModelAndView deptForm(@ModelAttribute("dept") TbDept dept, HttpServletRequest request, HttpServletResponse response) {
		Model  model   = new ExtendedModelMap();
		String actType = request.getParameter("actType");
		//新增或者更新
		if ("save".equals(actType)) {
			String buildIds = request.getParameter("buildIds");
			String compId   = request.getParameter("compId");

			dept.setCreator(request.getRemoteUser());
			dept.setCreateTime(new Date());
			dept.setIsenabled(ElementConstant.YESORNO_1);
			dept.setCompany(organizationManager.getCompanyById(Integer.parseInt(compId)));

			String retCode = organizationManager.saveOrUpdateDept(dept, buildIds.split(";"));
			if ("2".equals(retCode)) {
				model.addAttribute("errormsg", "更新成功");
			} else {
				model.addAttribute("errormsg", "新增成功");
			}
		}
		model.addAttribute("companyList", getUserRelationCompanyList(request));
		model.addAttribute("funcid", request.getParameter("funcid"));
		return new ModelAndView("admin/deptForm", model.asMap());
	}

	/**
	 * 更新部门信息
	 *
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/updateDept/{id}&{funcid}")
	public String updateDept(@PathVariable int id, @PathVariable long funcid, Model model, HttpServletRequest request) {
		model.addAttribute("companyList", getUserRelationCompanyList(request));
		model.addAttribute("dept", organizationManager.getDept(id));
		model.addAttribute("funcid", funcid);
		return "admin/deptForm";
	}

	/**
	 * 删除部门，逻辑删除
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/deleteDept/{id}&{funcid}")
	public String deleteDept(@PathVariable int id, @PathVariable long funcid, HttpServletRequest request) {
		TbDept dept = organizationManager.getDept(id);
		dept.setModifier(request.getRemoteUser());
		dept.setModifyTime(new Date());
		dept.setIsenabled(ElementConstant.YESORNO_0);
		organizationManager.updateModel(dept);
		return "redirect:/admin/organization/deptlist?funcid=" + funcid;
	}

	/**
	 * 查询部门树菜单
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/depttree", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> queryMenuTree(HttpServletRequest request,
								   HttpServletResponse response) {
		String compName = request.getParameter("compName");
		String compId   = request.getParameter("compId");         //当前公司id

		Set<TbDept>      deptList = organizationManager.getCompanyById(Integer.parseInt(compId)).getDepts();
		List<OutTreeDTO> trees    = new ArrayList<OutTreeDTO>();
		for (TbDept dept : deptList) {
			if (ElementConstant.YESORNO_1.equals(dept.getIsenabled())) {
				OutTreeDTO obj = new OutTreeDTO();
				obj.setId(dept.getCode());      //当前节点code
				obj.setName(dept.getName());    //节点名称
				obj.setpId(dept.getParentCode());   //父节点code
				trees.add(obj);
			}
		}
		//根节点
		OutTreeDTO obj1 = new OutTreeDTO();
		obj1.setId("0");
		obj1.setName(compName);
		obj1.setpId("-1");
		trees.add(obj1);
		return trees;
	}

	/**
	 * 异步获取部门信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/ajaxGetDeptInfo", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	TbDept ajaxGetDeptInfo(HttpServletRequest request, HttpServletResponse response) {
		String treeCode   = request.getParameter("treeCode");
		String parentCode = request.getParameter("parentCode");
		TbDept dept       = organizationManager.getDept(treeCode, parentCode);
		return dept;
	}

	/**
	 * 根据公司id，异步获取部门集合
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/ajaxGetDeptList", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody
	List<TbDept> ajaxGetDeptList(HttpServletRequest request,
								 HttpServletResponse response) {
		String compid = request.getParameter("compid");
		if (StringUtils.isEmpty(compid)) {
			return null;
		} else {
			List<TbDept> list    = new ArrayList<TbDept>();
			TbCompany    company = organizationManager.getCompanyById(Integer.parseInt(compid));
			for (TbDept tbDept : company.getDepts()) {
				if (ElementConstant.YESORNO_1.equals(tbDept.getIsenabled())) {
					tbDept.setCompany(null);//双向关联,防止返回json死循环
					list.add(tbDept);
				}
			}
			return list;
		}
	}

	/**
	 * 查询项目组织架构信息
	 *
	 * @param request
	 * @param response List<OutTreeDTO>
	 */
	@RequestMapping(value = "/getOrganizationBuildTree", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> getOrganizationBuildTree(HttpServletRequest request,
											  HttpServletResponse response) {
		String queryType = request.getParameter("queryType");
		String companyId = request.getParameter("companyId");
		String deptId    = request.getParameter("deptId");

		if (ElementConstant.USER_ORG_COMPANY.equals(queryType)) {//运营中心
			if (StringUtils.isNotEmpty(companyId)) {
				return propertyManager.getOrganizationBuildTree(queryType, null, null, Integer.valueOf(companyId));
			} else {
				return propertyManager.getOrganizationBuildTree(queryType, null, null, null);
			}
		} else {//部门
			if (StringUtils.isNotEmpty(deptId)) {
				return propertyManager.getOrganizationBuildTree(queryType, null, Integer.valueOf(deptId), Integer.valueOf(companyId));
			} else {
				return propertyManager.getOrganizationBuildTree(queryType, null, null, Integer.valueOf(companyId));
			}
		}
	}

	/**
	 * 查询运营中心所管辖项目组织结构信息
	 *
	 * @param request
	 */
	@RequestMapping(value = "/getCompanyOrgTree", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> getOrganizationBuildTree(HttpServletRequest request) {
		String companyId = request.getParameter("companyId");
		String userId    = request.getParameter("userId");//所选择修改用户的id
		User   user      = (User) request.getSession().getAttribute("UserCache");//当前登录用户
		if (StringUtils.isNotEmpty(companyId)) {
			Integer uid = null;
			if (StringUtils.isNotBlank(userId)) {
				uid = Integer.valueOf(userId);
			}
			return propertyManager.getCompanyOrgTree(Integer.valueOf(companyId), uid, user);
		}

		return null;
	}

	/**
	 * 系统用户关联的组织信息
	 *
	 * @param request
	 * @param response List<OutTreeDTO>
	 */
	@RequestMapping(value = "/usersRelationOrg", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> usersRelationOrg(HttpServletRequest request,
									  HttpServletResponse response) {
		//物业组织集合
		List<TbCompany>  compList = organizationManager.getCompanyList("1");
		List<OutTreeDTO> trees    = new ArrayList<OutTreeDTO>();

		String     pId  = "-1";
		OutTreeDTO obj1 = new OutTreeDTO();
		obj1.setId(pId);
		obj1.setpId("");
		obj1.setName("物业管理处");
		obj1.setLevel("0");
		trees.add(obj1);

		//用户ID
		String                           userid           = request.getParameter("userid");
		List<AppUserOrgnizationRelation> userOrgRelations = null;
		if (StringUtils.isNotEmpty(userid)) {
			//用户-组织关联
			userOrgRelations = userManager.getUserOrgByUserId(Long.parseLong(userid));
		}
		for (TbCompany company : compList) {
			OutTreeDTO obj = new OutTreeDTO();
			obj.setId("c_" + company.getId());
			obj.setpId(pId);
			obj.setName(company.getName());
			obj.setLevel("1");
			if (!CollectionUtils.isEmpty(userOrgRelations)) {
				for (AppUserOrgnizationRelation re : userOrgRelations) {
					if (re.getOrgId().intValue() == company.getId().intValue()) {
						obj.setChecked(true);
					}
				}
			}
			trees.add(obj);

			Set<TbDept> depts = company.getDepts();
			for (TbDept dept : depts) {
				if (ElementConstant.YESORNO_1.equals(dept.getIsenabled())) {
					OutTreeDTO obj2 = new OutTreeDTO();
					obj2.setId(dept.getId().toString());
					obj2.setpId("c_" + company.getId());
					obj2.setName(dept.getName());
					obj2.setLevel("2");
					if (!CollectionUtils.isEmpty(userOrgRelations)) {
						for (AppUserOrgnizationRelation re : userOrgRelations) {
							if (re.getOrgId().intValue() == dept.getId().intValue()) {
								obj2.setChecked(true);
							}
						}
					}
					trees.add(obj2);
				}
			}
		}
		return trees;
	}


	/**
	 * 系统用户关联的楼宇楼层
	 *
	 * @param request
	 * @param response List<OutTreeDTO>
	 */
	@RequestMapping(value = "/usersRelationFloor", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> usersRelationFloor(HttpServletRequest request,
										HttpServletResponse response) {
		//楼宇楼层集合**************************************
//		List<TbCompany> compList=organizationManager.getCompanyList("1");


		//1.获取所有楼宇信息,楼层信息
		List<TbOrganization> orgList   = propertyManager.queryTbOrganizationList();
		List<FloorInfo>      floorList = floorManager.getFloorAll();
		//2.创建返回OutTreeDTO类
		List<OutTreeDTO> trees = new ArrayList<OutTreeDTO>();
		//3.创建第一层选择
		String     pId  = "-1";
		OutTreeDTO obj1 = new OutTreeDTO();
		obj1.setId(pId);
		obj1.setpId("");
		obj1.setName("所有楼栋");
		obj1.setLevel("0");
		trees.add(obj1);

		//4.创建第二层,楼宇选择(用户已选择信息)
		//用户ID
		String userid = request.getParameter("userid");
//		List<AppUserOrgRelation> userOrgRelations=null;
		List<AppUserFloorRelation> userOrgRelations = null;

		if (StringUtils.isNotEmpty(userid)) {
			//用户所有 楼宇-楼层 关系信息
			userOrgRelations = userManager.getAppUserFloorByUserId(Integer.parseInt(userid));
		}
		for (TbOrganization org : orgList) {
			OutTreeDTO obj = new OutTreeDTO();
			//楼宇id加入"c_"标志
			obj.setId("c_" + org.getId());
			//pId父类id,第一层,与第二层 都为-1
			obj.setpId(pId);
			obj.setName(org.getName());
			obj.setLevel("1");
			if (!CollectionUtils.isEmpty(userOrgRelations)) {
				for (AppUserFloorRelation re : userOrgRelations) {
					if (re.getOrg_id().intValue() == org.getId().intValue()) {
						obj.setChecked(true);
					}
				}
			}
			trees.add(obj);

			//获取所有楼层信息
//			List<FloorInfo> floorList = floorManager.getAll();
//			Set<TbDept> depts=company.getDepts();

			for (FloorInfo floor : floorList) {
				//循环所有楼层,判断该 楼层 是否属于该 楼宇 
				boolean flag = org.getId() == new Long(floor.getOrganizationId()).intValue();
				if (flag) {

					OutTreeDTO obj2 = new OutTreeDTO();
					obj2.setId(floor.getId() + "");
					obj2.setpId("c_" + org.getId());
					obj2.setName(floor.getName());
					obj2.setLevel("2");
					if (!CollectionUtils.isEmpty(userOrgRelations)) {
						for (AppUserFloorRelation re : userOrgRelations) {
							if (re.getFloor_id().intValue() == floor.getId().intValue()) {
								obj2.setChecked(true);
							}
						}
					}
					trees.add(obj2);

				}
			}
		}
		return trees;
	}

	@RequestMapping(value = "/test")
	public void test(HttpServletRequest request, HttpServletResponse response) {
		String id    = request.getParameter("id");
		String msgid = request.getParameter("msgid");
		try {
//			List<TbOrganization> list = propertyManager.queryTbOrganizationList();
//			List<AppUserFloorRelation> list = propertyManager.queryUserOrgFloorList();
//			List<FloorInfo> floorList = floorManager.getAll();

			List<TbOrganization>            list = propertyManager.queryTbOrganizationList();
			ArrayList<ArrayList<FloorInfo>> all  = new ArrayList<ArrayList<FloorInfo>>();
			for (TbOrganization org : list) {
//				all.add((ArrayList<FloorInfo>) org.getFloors());
			}

			JSONObject json = new JSONObject();
			json.put("code", "200");
			json.put("msg", "success");
			json.put("data", all);
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}


	@RequestMapping(value = "/saveBuildingFloor", method = RequestMethod.GET, produces = "application/json")
	public void saveBuildingFloor(HttpServletRequest request, HttpServletResponse response) {

		try {

			String buildIds = request.getParameter("buildId");
			String floorIds = request.getParameter("floorId");
			String userId   = request.getParameter("userid");

			//*****************
			//根据userid删除所有原本记录
			if (StringUtils.isNotEmpty(userId)) {
				propertyManager.delectOrgFloorRelationByUserId(userId);
				//*****************

				String[] buildIdsSplit = buildIds.split(";");
				//1,c_10;2,c_10;3,c_10;   楼层,c_楼宇;楼层,c_楼宇;
				String[] floorIdsSplit = floorIds.split(";");

				for (int i = 0; i < floorIdsSplit.length; i++) {
					String[]             relationSp           = floorIdsSplit[i].split(",");
					AppUserFloorRelation appUserFloorRelation = new AppUserFloorRelation();
					appUserFloorRelation.setFloor_id(Integer.parseInt(relationSp[0]));
					appUserFloorRelation.setOrg_id(Integer.parseInt(relationSp[1].substring(2)));
					appUserFloorRelation.setUser_id(Integer.parseInt(userId));
					appUserFloorRelation.setCreateTime(new Date());
					propertyManager.save(appUserFloorRelation);
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
