package com.palmnest.webapp.controller.property;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.bean.Pagenation;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.BeanUtils;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.core.util.hangdian.EncryptionUtils;
import com.palmnest.application.core.util.http.HttpClientResult;
import com.palmnest.application.core.util.http.HttpClientUtils;
import com.palmnest.application.core.util.px.RSAUtils;
import com.palmnest.application.dto.OrgComplexDTO;
import com.palmnest.application.dto.OutRetMsg;
import com.palmnest.application.dto.OutTreeDTO;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.model.CompanyRelationOrg;
import com.palmnest.model.Element;
import com.palmnest.model.TbCompany;
import com.palmnest.model.User;
import com.palmnest.model.property.TbBuild;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.org.OrganizationService;
import com.palmnest.service.outer.KafkaOuterService;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.webapp.controller.BaseFormController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 项目组织架构信息管理前端控制器
 *
 * @author yubing
 * @since 2017-1-5
 */
@Slf4j
@Controller
@RequestMapping("/busi/property/*")
public class PropertyController extends BaseFormController {


	@Autowired
	private PropertyManager     propertyManager;
	@Autowired
	private OrganizationService organizationService;
	@Autowired
	private KafkaOuterService   kafkaOuterService;

	private static String shoppingTopic = PropertiesKit.readPropertiesValue("shoppingTopic", "wechat.properties");

	/**
	 * 跳转项目列表页面
	 */
	@RequestMapping(value = "/propertyList")
	public ModelAndView jumpPropertyListPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		initFunctionOperate(request);       //初始化功能操作权限
		Model model = new ExtendedModelMap();
		User  user  = (User) request.getSession().getAttribute("UserCache");
		model.addAttribute("isAdmin", user.isAdmin());
		model.addAttribute("reviewStatusGroup", this.getElementGroupManager().getElementsByGroupName("reviewStatusGroup"));
		return new ModelAndView("admin/propertyList", model.asMap());
	}


	/**
	 * 获取项目列表
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getPropertyList")
	@ResponseBody
	public WebPageResultDto propertyList(HttpServletRequest request, HttpServletResponse response) {

		List<Criterion> filterList   = new ArrayList<Criterion>();
		String          pageNo       = request.getParameter("pageNo");
		String          pageSize     = request.getParameter("pageSize");
		String          name         = request.getParameter("name");
		String          telephone    = request.getParameter("telephone");
		String          address      = request.getParameter("address");
		String          reviewStatus = request.getParameter("reviewStatus");

		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}
		if (StringUtils.isNotEmpty(name)) {
			filterList.add(Restrictions.like("name", "%" + name + "%"));
		}
		if (StringUtils.isNotEmpty(telephone)) {
			filterList.add(Restrictions.like("telephone", "%" + telephone + "%"));
		}
		if (StringUtils.isNotEmpty(address)) {
			filterList.add(Restrictions.like("address", "%" + address + "%"));
		}
		if (StringUtils.isNotEmpty(reviewStatus)) {
			filterList.add(Restrictions.eq("status", reviewStatus));
		}
		filterList.add(Restrictions.eq("isEnabled", ElementConstant.YESORNO_1));

		//组织权限
		List<TbOrganization> organizationList = getUserRelationOrgList(request);
		List<Integer>        organizationIds  = new ArrayList<Integer>();
		if (!CollectionUtils.isEmpty(organizationList)) {
			for (TbOrganization obj : organizationList) {
				organizationIds.add(obj.getId());
			}
		}
		if (CollectionUtils.isEmpty(organizationIds)) {
			organizationIds.add(-1);
		}
		filterList.add(Restrictions.in("id", organizationIds));

		try {
			Pagenation<TbOrganization> pagenation = propertyManager.queryTbOrganizaitonPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize), filterList);
			WebPageResultDto           dto        = new WebPageResultDto("200", "成功", pagenation.getItems());
			dto.setCount((long) pagenation.getTotalCount());
			return dto;
		} catch (Exception e) {
			log.error("查询项目列表失败 getList ===>" + e.getMessage());
		}

		return new WebPageResultDto("100", "查询项目列表失败", null);
	}


	/**
	 * 项目信息编辑保存
	 */
	@RequestMapping(value = "/propertyForm")
	public ModelAndView propertyForm(@ModelAttribute("tbOrganization") TbOrganization tbOrganization, HttpServletRequest request,
									 HttpServletResponse response) throws Exception {
		User   user    = (User) request.getSession().getAttribute("UserCache");
		Model  model   = new ExtendedModelMap();
		String actType = request.getParameter("actType");
		String flag    = "default";
		if ("save".equals(actType)) {
			flag = "saveOrUpdate";
			String provinceCode = request.getParameter("provinceSelect");
			String provinceName = request.getParameter("provinceName");
			String cityCode     = request.getParameter("citySelect");
			String cityName     = request.getParameter("cityName");

			tbOrganization.setProvinceCode(provinceCode);
			tbOrganization.setProvinceName(provinceName);
			tbOrganization.setCityCode(cityCode);
			tbOrganization.setCityName(cityName);
			tbOrganization.setStatus("1");
			tbOrganization.setIsEnabled(ElementConstant.YESORNO_1);

			String              companyId    = request.getParameter("companySelect");
			ObjectMapper        objectMapper = new ObjectMapper();
			Map<String, Object> map          = new HashMap<String, Object>();
			if (tbOrganization.getId() != null) {//编辑更新操作
				if (StringUtils.isEmpty(companyId)) {
					CompanyRelationOrg co = propertyManager.getCompanyByOrgId(tbOrganization.getId());
					if (co != null) {
						map.put("companyId", co.getCompanyId());
					}
				}
				tbOrganization.setModifier(request.getRemoteUser());
				tbOrganization.setModifyTime(new Date());
				tbOrganization.setCreateTime(new Date());

				TbOrganization tbOrganizationById = propertyManager.getTbOrganizationById(tbOrganization.getId());
				tbOrganization.setMettingClient(tbOrganizationById.getMettingClient());
				tbOrganization.setPostofficeClient(tbOrganizationById.getPostofficeClient());

				if (tbOrganization.getPassType() == null) {
					tbOrganization.setPassType("0");// 设置默认值
				}
				propertyManager.updateModel(tbOrganization);
				model.addAttribute("errormsg", "更新成功");
				//同步项目到一键服务
				//propertyManager.assignAnsyOrganization(tbOrganization);
				map.put("org", tbOrganization);

				Integer superDeskOrgId = propertyManager.getSuperDeskOrgId(tbOrganization.getId());
				if (superDeskOrgId != null) {
					TbOrganization superDeskOrg = new TbOrganization();
					BeanUtils.copyProperties(superDeskOrg, tbOrganization);
					superDeskOrg.setId(superDeskOrgId);
					map.put("org", superDeskOrg);
				}
				//发送到消息通道，同步到子系统
				kafkaOuterService.syncOrg(map);
			} else {//新增操作

				if (StringUtils.isNotBlank(companyId)) {
					tbOrganization.setCreator(request.getRemoteUser());
					tbOrganization.setCreateTime(new Date());
					if (tbOrganization.getPassType() == null) {
						tbOrganization.setPassType("0");// 设置默认值
					}
					if (propertyManager.saveOrganization(user, tbOrganization, Integer.parseInt(companyId))) {
						model.addAttribute("errormsg", "保存成功");
						//同步项目到一键服务
						//propertyManager.assignAnsyOrganization(tbOrganization);
						//发送到消息通道，同步到子系统
						map.put("companyId", companyId);
						map.put("org", tbOrganization);
						kafkaOuterService.syncOrg(map);
						//为项目创建默认项目管理员角色
						organizationService.addRoleForOrg(tbOrganization.getId());
					} else {
						flag = "default";
						model.addAttribute("errormsg", "保存失败，请稍后再试或者联系管理员");
					}
				} else {
					flag = "default";
					model.addAttribute("errormsg", "保存失败，请选择运营中心");
				}
			}
		}
		List<TbCompany> companyList = organizationService.getCompanyList("1");

		if (user.isAdmin()) {
			model.addAttribute("isAdmin", true);
		} else {
			model.addAttribute("isAdmin", false);
		}
		model.addAttribute("companyList", companyList);
		model.addAttribute("funcid", request.getParameter("funcid"));
		model.addAttribute("flag", flag);
		return new ModelAndView("admin/propertyForm", model.asMap());
	}

	@RequestMapping(value = "/updateProperty/{id}&{funcid}")
	public ModelAndView updateProperty(@PathVariable int id, @PathVariable long funcid, Model model, HttpServletRequest request) throws Exception {
		TbOrganization tbOrganization = propertyManager.getTbOrganizationById(id);
		model.addAttribute("tbOrganization", tbOrganization);
		model.addAttribute("funcid", funcid);
		User user = (User) request.getSession().getAttribute("UserCache");
		if (user.isAdmin()) {
			model.addAttribute("isAdmin", true);
		} else {
			model.addAttribute("isAdmin", false);
		}
		return new ModelAndView("admin/propertyForm", model.asMap());
	}

	/**
	 * 删除项目
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/deleteProperty/{id}&{funcid}")
	public String delete(@PathVariable int id, @PathVariable long funcid, HttpServletRequest request) {
		TbOrganization organization = propertyManager.getTbOrganizationById(id);
		organization.setIsEnabled(ElementConstant.YESORNO_0);
		organization.setModifyTime(new Date());
		organization.setModifier(request.getRemoteUser());

		//发送到消息通道，同步到子系统
		Map<String, Object> map = new HashMap<String, Object>();
		CompanyRelationOrg  co  = propertyManager.getCompanyByOrgId(organization.getId());
		if (co != null) {
			map.put("companyId", co.getCompanyId());
		}
		map.put("org", organization);
		kafkaOuterService.syncOrg(map);

		propertyManager.deleteTbOrganization(organization);
//		kafkaOuterService.sendMessage(shoppingTopic, "addOrUpdateOrg", "{id:"+organization.getId()+"}");
		return "redirect:/busi/property/propertyList?funcid=" + funcid;
	}

	/**
	 * 项目信息审核管理
	 */
	@RequestMapping(value = "/propertyViewForm")
	public ModelAndView propertyViewForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model  model          = new ExtendedModelMap();
		String organizationId = request.getParameter("organizationId");
		String actType        = request.getParameter("actType");
		if ("save".equals(actType)) {
			String status       = request.getParameter("status");
			String reviewRemark = request.getParameter("reviewRemark");

			TbOrganization organization = propertyManager.getTbOrganizationById(Integer.parseInt(organizationId));
			organization.setModifier(request.getRemoteUser());
			organization.setModifyTime(new Date());
			organization.setStatus(status);
			organization.setReviewRemark(reviewRemark);
			String result = propertyManager.updateOrganizationStatus(organization);
			model.addAttribute("organization", organization);
			model.addAttribute("result", result);
		} else {
			model.addAttribute("organization", propertyManager.getTbOrganizationById(Integer.parseInt(organizationId)));
		}
		model.addAttribute("identityGroup", this.getElementGroupManager().getElementsByGroupName("identityGroup"));
		model.addAttribute("reviewStatusGroup", this.getElementGroupManager().getElementsByGroupName("reviewStatusGroup"));
		model.addAttribute("funcid", request.getParameter("funcid"));
		return new ModelAndView("admin/propertyViewForm", model.asMap());
	}

	/**
	 * 跳转楼宇楼栋列表页面
	 */
	@RequestMapping(value = "/buildList")
	public ModelAndView jumpBuildListPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		initFunctionOperate(request);       //初始化功能操作权限
		Model                model            = new ExtendedModelMap();
		List<TbOrganization> organizationList = getUserRelationOrgList(request);

		model.addAttribute("organizationList", organizationList);
		return new ModelAndView("admin/buildList", model.asMap());
	}

	/**
	 * 获取楼宇楼栋列表
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getBuildList")
	@ResponseBody
	public WebPageResultDto buildList(HttpServletRequest request, HttpServletResponse response) {

		User user = (User) request.getSession().getAttribute("UserCache");

		StringBuffer strSbf         = new StringBuffer(" where 1=1");
		String       pageNo         = request.getParameter("pageNo");
		String       pageSize       = request.getParameter("pageSize");
		String       name           = request.getParameter("name");
		String       organizationId = request.getParameter("orgId");

		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}
		if (StringUtils.isNotEmpty(name)) {
			strSbf.append(" and t1.name like '%" + name + "%'");
		}
		if (StringUtils.isNotEmpty(organizationId)) {
			strSbf.append(" and t1.organizationId=" + organizationId);
		}

		String organizationIdStr = getUserManageOrgIds(user);
		if (StringUtils.isBlank(organizationIdStr)) {
			organizationIdStr = "-1";
		}

		strSbf.append(" and t1.isEnabled='" + ElementConstant.YESORNO_1 + "'");
		strSbf.append(" and t1.organizationId in(" + organizationIdStr + ")");


		try {
			Page             pagenation = propertyManager.queryBuildListPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize), strSbf.toString());
			WebPageResultDto dto        = new WebPageResultDto("200", "成功", pagenation.getItems());
			dto.setCount(pagenation.getTotalCount());
			return dto;
		} catch (Exception e) {
			log.error("查询楼宇楼栋列表失败 buildList ===>" + e.getMessage());
		}

		return new WebPageResultDto("100", "查询楼宇楼栋列表失败", null);
	}

	/**
	 * 根据项目异步获取楼宇列表信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getBuildListByOrg", produces = "application/json")
	public @ResponseBody
	List<TbBuild> getBuildListByOrg(HttpServletRequest request, HttpServletResponse response) {
		String        organizationId = request.getParameter("organizationId");
		List<TbBuild> list           = new ArrayList<TbBuild>();
		if (StringUtils.isNotEmpty(organizationId)) {
			list = propertyManager.getTbBuildListByOrgaid(Integer.parseInt(organizationId));
		}
		return list;
	}

	/**
	 * 新增/修改 楼宇楼栋信息
	 *
	 * @param tbBuild
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/buildForm")
	public ModelAndView propertyForm(@ModelAttribute("tbBuild") TbBuild tbBuild, HttpServletRequest request,
									 HttpServletResponse response) throws Exception {
		Model   model     = new ExtendedModelMap();
		String  actType   = request.getParameter("actType");
		Integer companyId = null;
		if ("save".equals(actType)) {
			String organizationId = request.getParameter("organizationId");
			String vip            = request.getParameter("vip");
			if (StringUtils.isNotEmpty(organizationId)) {
				tbBuild.setVip(vip);
				tbBuild.setOrganizationId(Integer.parseInt(organizationId));
				tbBuild.setIsEnabled(ElementConstant.YESORNO_1);
				tbBuild.setCreator(request.getRemoteUser());
				tbBuild.setCreateTime(new Date());

				if (tbBuild.getId() != null) {
					TbBuild bu = propertyManager.getTbBuildById(tbBuild.getId());
					if (!bu.getName().equals(tbBuild.getName())) {//如果现在传过来的名称和历史名称一样，说明修改的是同一个单据，没有该名称
						List<TbBuild> buList = propertyManager.getBuildByOrgIdAndBuildName(Integer.parseInt(organizationId), tbBuild.getName());
						if (buList != null && buList.size() > 0) {
							model.addAttribute("errormsg", "楼宇名称不能重复");
						} else {
							propertyManager.updateModel(tbBuild);
							model.addAttribute("errormsg", "更新成功");
						}
					} else {
						propertyManager.updateModel(tbBuild);
						model.addAttribute("errormsg", "更新成功");
					}


				} else {
					List<TbBuild> buList = propertyManager.getBuildByOrgIdAndBuildName(Integer.parseInt(organizationId), tbBuild.getName());
					if (buList != null && buList.size() > 0) {
						model.addAttribute("errormsg", "楼宇名称不能重复");
					} else {
						propertyManager.saveModel(tbBuild);

//							kafkaOuterService.syncBuild(tbBuild,companyId);
						model.addAttribute("errormsg", "保存成功");
					}
				}
				TbOrganization tbOrg = propertyManager.getTbOrganizationById(tbBuild.getOrganizationId());
				if (tbOrg.getId() != null) {//编辑更新操作
					CompanyRelationOrg co = propertyManager.getCompanyByOrgId(tbOrg.getId());
					if (co != null) {
						companyId = co.getCompanyId();
					}
				}
				//发送到消息通道，同步到子系统
				kafkaOuterService.syncBuild(tbBuild, companyId);
			} else {
				model.addAttribute("errormsg", "项目不能为空");
			}

		}
		//TODO 获取当前管理员的项目权限
		List<TbOrganization> organizationList = getUserRelationOrgList(request);
		List<Element>        vipGroup         = this.getElementGroupManager().getElementsByGroupName("vipGroup");
		model.addAttribute("organizationList", organizationList);
		model.addAttribute("vipGroup", vipGroup);
		model.addAttribute("funcid", request.getParameter("funcid"));
		return new ModelAndView("admin/buildForm", model.asMap());
	}

	/**
	 * 去楼宇楼栋修改页面,查询楼栋信息
	 *
	 * @param id
	 * @param funcid
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateBuild/{id}&{funcid}")
	public ModelAndView updateBuild(@PathVariable int id, @PathVariable long funcid, Model model, HttpServletRequest request) throws Exception {
		TbBuild build = propertyManager.getTbBuildById(id);
		model.addAttribute("tbBuild", build);
		List<TbOrganization> organizationList = getUserRelationOrgList(request);
		List<Element>        vipGroup         = this.getElementGroupManager().getElementsByGroupName("vipGroup");
		model.addAttribute("organizationList", organizationList);
		model.addAttribute("vipGroup", vipGroup);
		model.addAttribute("funcid", funcid);
		return new ModelAndView("admin/buildForm", model.asMap());
	}

	/**
	 * 删除楼栋地址
	 *
	 * @param id
	 */
	@RequestMapping(value = "/deleteBuild/{id}&{funcid}")
	public String deleteBuild(@PathVariable int id, @PathVariable long funcid, HttpServletRequest request) {
		TbBuild build = propertyManager.getTbBuildById(id);
		build.setIsEnabled(ElementConstant.YESORNO_0);
		build.setModifyTime(new Date());
		build.setModifier(request.getRemoteUser());
		propertyManager.updateModel(build);

		//发送到消息通道，同步到子系统
		kafkaOuterService.sendMessage(shoppingTopic, "deleteBuild", "{id:" + build.getId() + "}");
		return "redirect:/busi/property/buildList?funcid=" + funcid;
	}

	/**
	 * 虚拟组织架构（院系信息）管理页面
	 *
	 * @param id     项目ID
	 * @param funcid 功能ID
	 */
	@RequestMapping(value = "/virtualArchForm/{id}&{funcid}")
	public ModelAndView virtualArchForm(@PathVariable int id, @PathVariable long funcid) {
		Model         model           = new ExtendedModelMap();
		List<Element> virtualArcGroup = this.getElementGroupManager().getElementsByGroupName("virtualArcGroup");
		model.addAttribute("virtualArcGroup", virtualArcGroup);
		model.addAttribute("organization", propertyManager.getTbOrganizationById(id));
		model.addAttribute("totalcount", propertyManager.getMaxvirtualArchId());
		model.addAttribute("funcid", funcid);
		return new ModelAndView("admin/virtualArchForm", model.asMap());
	}

	/**
	 * 查询虚拟组织架构（院系信息）树
	 */
	@RequestMapping(value = "/virtualArchTree", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> virtualArchTree(HttpServletRequest request,
									 HttpServletResponse response) {
		String                    organizationName = request.getParameter("organizationName");
		String                    organizationId   = request.getParameter("organizationId");
		List<VirtualArchitecture> list             = propertyManager.getVirtualArchitectureList(Integer.parseInt(organizationId));
		List<OutTreeDTO>          trees            = new ArrayList<OutTreeDTO>();
		for (VirtualArchitecture model : list) {
			OutTreeDTO obj = new OutTreeDTO();
			obj.setId(model.getCode());      //当前节点code
			obj.setName(model.getName());    //节点名称
			obj.setpId(model.getParentCode());   //父节点code
			trees.add(obj);
		}
		//根节点
		OutTreeDTO obj1 = new OutTreeDTO();
		obj1.setId("0");
		obj1.setName(organizationName);
		obj1.setpId("-1");
		trees.add(obj1);
		return trees;
	}

	/**
	 * 查询虚拟组织架构（院系信息）
	 */
	@RequestMapping(value = "/getvirtualArchInfo", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	VirtualArchitecture getvirtualArchInfo(HttpServletRequest request,
										   HttpServletResponse response) {
		String treeCode   = request.getParameter("treeCode");
		String parentCode = request.getParameter("parentCode");
		return propertyManager.getVirtualArchBycode(treeCode, parentCode);
	}

	/**
	 * 新增/更新虚拟组织架构（院系信息）
	 */
	@RequestMapping(value = "/addOrUpdateVirtualArch", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	OutRetMsg addOrUpdateVirtualArch(HttpServletRequest request,
									 HttpServletResponse response) {
		OutRetMsg outmsg  = new OutRetMsg();
		String    actType = request.getParameter("actType");
		try {
			String organizationId = request.getParameter("organizationId");
			String name           = request.getParameter("name");
			String treeCode       = request.getParameter("treeCode");
			String parentCode     = request.getParameter("parentCode");
			String remark         = request.getParameter("remark");
			String type           = request.getParameter("type");
			String codeNumber     = request.getParameter("codeNumber");
			String phone          = request.getParameter("phone");
			String address        = request.getParameter("address");
			String customerNumber = request.getParameter("customerNumber");

			ObjectMapper objectMapper = new ObjectMapper();
			//新增节点
			if ("add".equals(actType)) {
				VirtualArchitecture model = new VirtualArchitecture();
				if ("0".equals(parentCode)) {
					model.setAddress(address);
					model.setCustomerNumber(StringUtils.isNotBlank(customerNumber) == true ? customerNumber.trim() : customerNumber);
					model.setPhone(phone);
				}
				model.setCode(treeCode);
				model.setParentCode(parentCode);
				model.setName(name);
				model.setRemark(remark);
				model.setType(type);
				model.setIsEnabled(ElementConstant.YESORNO_1);
				model.setCreateTime(new Date());
				model.setCreator(request.getRemoteUser());
				model.setOrganizationId(Integer.parseInt(organizationId));
				model.setCodeNumber(codeNumber);
				propertyManager.saveModel(model);
				outmsg.setErrcode("200");
				outmsg.setErrmsg("success");

				//发送到消息通道，同步到子系统
				kafkaOuterService.syncVirtualarchitecture(model);
			} else if ("update".equals(actType)) {
				VirtualArchitecture model = propertyManager.getVirtualArchBycode(treeCode, parentCode);
				if (model == null) {
					outmsg.setErrcode("201");
					outmsg.setErrmsg("not exit, update fail");
				} else {
					if ("0".equals(parentCode)) {
						model.setAddress(address);
						model.setCustomerNumber(customerNumber);
						model.setPhone(phone);
					}
					model.setName(name);
					model.setType(type);
					model.setRemark(remark);
					model.setCodeNumber(codeNumber);
					propertyManager.updateModel(model);

					//发送到消息通道，同步到子系统
					kafkaOuterService.syncVirtualarchitecture(model);

					outmsg.setErrcode("200");
					outmsg.setErrmsg("success");
				}
			}
		} catch (Exception e) {
			outmsg.setErrcode("500");
			outmsg.setErrmsg("fail");
		}
		return outmsg;
	}

	/**
	 * 异步删除虚拟组织架构（院系信息）
	 */
	@RequestMapping(value = "/deleVirtualArch", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	OutRetMsg deleVirtualArch(HttpServletRequest request, HttpServletResponse response) {
		OutRetMsg           outmsg     = new OutRetMsg();
		String              treeCode   = request.getParameter("treeCode");
		String              parentCode = request.getParameter("parentCode");
		VirtualArchitecture model      = propertyManager.getVirtualArchBycode(treeCode, parentCode);
		model.setIsEnabled(ElementConstant.YESORNO_0);
		model.setModifier(request.getRemoteUser());
		model.setModifyTime(new Date());
		propertyManager.updateModel(model);
		outmsg.setErrcode("200");
		outmsg.setErrmsg("success");

		//发送到消息通道，同步到子系统
		kafkaOuterService.sendMessage(shoppingTopic, "deleteVirtualarchitecture", "{id:" + model.getId() + "}");
		return outmsg;
	}

	/**
	 * 异步 获取虚拟组织架构
	 */
	@RequestMapping(value = "/virtualArchList", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<VirtualArchitecture> virtualArchList(HttpServletRequest request, HttpServletResponse response) {
		String                    organizationId = request.getParameter("organizationId");
		List<VirtualArchitecture> list           = propertyManager.getVirtualArchitectureList(Integer.parseInt(organizationId));
		return list;
	}

	/**
	 * 异步 获取虚拟组织架构
	 */
	@RequestMapping(value = "/getvirtualArchList", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<VirtualArchitecture> getvirtualArchList(HttpServletRequest request, HttpServletResponse response) {
		String                    virtualArchId = request.getParameter("virtualArchId");
		List<VirtualArchitecture> list          = propertyManager.getVirtualArchitectureList(virtualArchId);
		return list;
	}

	/**
	 * 异步 获取虚拟组织架构
	 */
	@RequestMapping(value = "/getvirtualArchTypeOne", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
	public @ResponseBody
	List<VirtualArchitecture> getvirtualArchTypeOne(HttpServletRequest request, HttpServletResponse response) {
		String                    organizationId = request.getParameter("organizationId");
		List<VirtualArchitecture> list           = new ArrayList<VirtualArchitecture>();
		if (StringUtils.isNotEmpty(organizationId)) {
			list = propertyManager.getVirtualArchitectureList(Integer.parseInt(organizationId), "1");
		}
		return list;
	}

	/**
	 * 异步 获取虚拟组织架构
	 */
	@RequestMapping(value = "/getAddvirtualArchTypeOne", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
	public @ResponseBody
	List<Map<String, Object>> getAddvirtualArchTypeOne(HttpServletRequest request, HttpServletResponse response) {
		String                    organizationId = request.getParameter("organizationId");
		List<Map<String, Object>> list           = propertyManager.getAddVirtualArchitectureList(Integer.parseInt(organizationId), "1");
		return list;
	}

	/**
	 * 进入批量导入企业页面
	 */
	@RequestMapping(value = "/toBatchImportVirtualArch")
	public ModelAndView toBatchImportCompany(HttpServletRequest request, HttpServletResponse response) {
		Model  model          = new ExtendedModelMap();
		String organizationId = request.getParameter("organizationId");  //项目ID
		String funcid         = request.getParameter("funcid");  //功能的ID

		model.addAttribute("organizationId", organizationId);
		model.addAttribute("funcid", funcid);
		request.getSession().removeAttribute(request.getParameter("dataSessionUid"));
		return new ModelAndView("admin/batchImportVirtualArch", model.asMap());
	}

	/**
	 * 批量导入企业资料
	 *
	 * @param excelFile 文件
	 * @remark @RequestParam("fileToUpload") MultipartFile excelFile
	 */
	@RequestMapping(value = "/batchImportVirtualArch")
	public ModelAndView doImportVirtualArch(@RequestParam("excelFile") MultipartFile excelFile,
											HttpServletRequest request, HttpServletResponse response) {
		Model               model          = new ExtendedModelMap();
		String              organizationId = request.getParameter("organizationId");
		User                user           = (User) request.getSession().getAttribute("UserCache");
		Map<String, Object> retMap         = null;
		try {
			retMap = propertyManager.assiginBatchImportArchitecture(organizationId, excelFile.getInputStream(), user.getUsername());
			model.addAllAttributes(retMap);
			String dataSessionUid = UUID.randomUUID().toString();
			request.getSession().setAttribute(dataSessionUid, retMap.get("data"));
			model.addAttribute("dataSessionUid", dataSessionUid);
		} catch (IOException e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
		}
		model.addAttribute("excelFileName", excelFile.getOriginalFilename());
		model.addAttribute("funcid", request.getParameter("funcid"));
		model.addAttribute("organizationId", organizationId);
		return new ModelAndView("admin/batchImportVirtualArchRs", model.asMap());
	}

	/**
	 * 确认批量导入企业处理
	 */
	@RequestMapping(value = "/confirmImportVirtualArch")
	public ModelAndView confirmImportVirtualArch(HttpServletRequest request, HttpServletResponse response) {
		Model                     model          = new ExtendedModelMap();
		String                    dataSessionUid = request.getParameter("dataSessionUid");
		List<VirtualArchitecture> data           = (List<VirtualArchitecture>) request.getSession().getAttribute(dataSessionUid);
		if (data != null) {
			request.getSession().removeAttribute(dataSessionUid);
			propertyManager.saveBatchArchitecture(data);
		}
		model.addAttribute("funcid", request.getParameter("funcid"));
		return new ModelAndView("redirect:/busi/property/propertyList", model.asMap());
	}

	/**
	 * 异步 获取项目列表信息
	 * 根据运营中心ID
	 */
	@RequestMapping(value = "/getOrganizationListByCompId", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
	public @ResponseBody
	List<TbOrganization> getOrganizationListByCompId(HttpServletRequest request, HttpServletResponse response) {
		String               companyId = request.getParameter("companyId");
		List<TbOrganization> list      = propertyManager.getAppUserOrganizationRelation(companyId);
		return list;
	}

	/**
	 * 项目批量导入
	 * 进入批量导入项目页面
	 */
	@RequestMapping(value = "/toBatchImportOrganization")
	public ModelAndView toBatchImportOrganization(HttpServletRequest request, HttpServletResponse response) {
		Model  model  = new ExtendedModelMap();
		String funcid = request.getParameter("funcid");  //功能的ID

		model.addAttribute("funcid", funcid);
		request.getSession().removeAttribute(request.getParameter("dataSessionUid2"));
		return new ModelAndView("admin/batchImportOrgComplex", model.asMap());
	}

	/**
	 * 批量导入项目资料
	 *
	 * @param excelFile 文件
	 * @remark @RequestParam("fileToUpload") MultipartFile excelFile
	 */
	@RequestMapping(value = "/batchImportOrganization")
	public ModelAndView doImportOrganization(@RequestParam("excelFile") MultipartFile excelFile,
											 HttpServletRequest request, HttpServletResponse response) {
		Model               model  = new ExtendedModelMap();
		Map<String, Object> retMap = null;
		try {
			retMap = propertyManager.assiginBatchImportOrganization(excelFile.getInputStream(), request.getRemoteUser());
			model.addAllAttributes(retMap);
			String dataSessionUid = UUID.randomUUID().toString();
			request.getSession().setAttribute(dataSessionUid, retMap.get("data"));
			model.addAttribute("dataSessionUid2", dataSessionUid);
		} catch (IOException e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
		}
		model.addAttribute("excelFileName", excelFile.getOriginalFilename());
		model.addAttribute("funcid", request.getParameter("funcid"));
		return new ModelAndView("admin/batchImportOrgComplexRs", model.asMap());
	}

	/**
	 * 确认批量导入—项目处理
	 */
	@RequestMapping(value = "/confirmImportOrgComplex")
	public ModelAndView confirmImportOrgComplex(HttpServletRequest request, HttpServletResponse response) {
		Model               model          = new ExtendedModelMap();
		String              dataSessionUid = request.getParameter("dataSessionUid2");
		List<OrgComplexDTO> data           = (List<OrgComplexDTO>) request.getSession().getAttribute(dataSessionUid);
		if (data != null) {
			request.getSession().removeAttribute(dataSessionUid);
			propertyManager.saveBatchOrganization(data);
		}
		model.addAttribute("funcid", request.getParameter("funcid"));
		return new ModelAndView("redirect:/busi/property/propertyList", model.asMap());
	}


	/**
	 * 获取航电派修项目列表信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/hdOrgList")
	@ResponseBody
	public AppResultDto getHdOrgList(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

		String pxUrl = PropertiesKit.readPropertiesValue("pxUrl", "wechat.properties");
		log.info("PropertyController getHdOrgList 获取派修项目列表接口=========>域名前缀为 pxUrl:" + pxUrl);

		String projectName = request.getParameter("projectName");

		if (StringUtils.isBlank(projectName)) {
			return AppResultUtil.createErrorDto("100", "项目名称不能为空");
		}

		//密匙
		String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALLMqFeQ/vpzHU9bBTPefgbcmMUB4kaVmGJX8YSfVkwaBaKjLjYZOMUE2rvWOdB3zJwSs/y5lQ9qiV64JgZZIbRGv00iLcY1SxBAekOR0fsg/DExQf7WMoMZxXp9FbmSdRMrDq+ph8FqBshRI15JPd59F1VafTAtoX86vSViGZkHAgMBAAECgYAmcM24ldnb6qfgiccikbEytHa71F3bownyCspIIyGglu+jOcYTp3SHFzYXsEUZxsfcvkCoExYzDEqgbKLwNnWCOcLUbSWpuWDykTomJ5Q2jvGX+Sy7/IkGAquLkvJS0Agqdl9Q35hZZZi5W64MeCeyn/Svl7evJpfb9QKcCovsoQJBAPd6vSiMf8hs3sC6xRb8tnDw5H1K8slyXbB2ZlNpb8Blci9y0ACN708PcLItf5e6+XwdkAt1mjgkjv6QpIRY/f8CQQC49JRWCROR2P9+t7FSRfxauFwrP8+GNacbTLZdrJ6ptVICzsvyysgTu5Xlig2HdySsigD31Pzc1SgbWbmRjXT5AkEA7L9fS/Y0nCECa6+Asj/prFvWycG0R2CAHjr2It+fx5eEx713HMCraZ+kuN9ry1RULRb+4OeNNB5NKVxn9jBIMwJAEEioTrLZ4DtkszllCUNUJoCYzM3/bWeH4OVuIO0zwulN4SVn22ZzGxmm5uCytDyPJAm6cBd2c9Lohw/tQJ1dsQJBAKs6h3jhGSR6IwZp/tWMe96rQGh+d/Br6yzH11rQ6amht7d56dMSDnUSBiXJgVoA9lgYkFgvbgnKJwtfrYv+CwE=";
		String param      = "LYZC2018";

		byte[] encodedData = new byte[0];
		String sign        = "";
		try {
			encodedData = RSAUtils.encryptByPrivateKey(param.getBytes(), privateKey);
			sign = RSAUtils.sign(encodedData, privateKey);
		} catch (Exception e) {
			log.info("WechatRepairUserController getHdOrgList 参数加密错误======>" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取项目列表失败");
		}

		String url = pxUrl + "/wx/getProjects";

		Map<String, String> map = new HashMap<String, String>();
		map.put("projectName", new String(projectName.getBytes(), "iso-8859-1"));
		map.put("params", param);
		map.put("sign", sign);

		Gson   gson = new Gson();
		String s    = gson.toJson(map);

		try {
			StringEntity entity = new StringEntity(s);
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json");//发送json数据需要设置contentType

			CloseableHttpClient httpclient = HttpClientBuilder.create().build();
			HttpPost            post       = new HttpPost(url);
			post.setEntity(entity);

			HttpResponse res = httpclient.execute(post);

			ArrayList<Map<String, Object>> projectList = new ArrayList<Map<String, Object>>();
			if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String result = EntityUtils.toString(res.getEntity());// 返回json格式：

				Map                            map1 = gson.fromJson(result, Map.class);
				Map                            data = (Map) map1.get("data");
				ArrayList<Map<String, Object>> list = (ArrayList<Map<String, Object>>) data.get("list");
				for (Map<String, Object> m : list) {
					Map<String, Object> object = new HashMap<String, Object>();
					object.put("projectId", m.get("projectNo"));
					object.put("projectName", m.get("projectName"));
					projectList.add(object);
				}
			}

			return AppResultUtil.createSuccesDto(projectList);
		} catch (Exception e) {
			log.info("WechatRepairUserController getHdOrgList 派修项目列表查询失败======>" + e.getMessage());
			e.printStackTrace();
		}

		return AppResultUtil.createErrorDto("100", "获取项目列表失败");
	}

	/**
	 * 获取航电客户声音项目列表信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/hdVoiceOrgList")
	@ResponseBody
	public AppResultDto getHdVoiceOrgList(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

		String hdUrl = PropertiesKit.readPropertiesValue("hdUrl", "wechat.properties");
		log.info("PropertyController getHdOrgList 获取客户声音项目列表接口=========>域名前缀为 hdUrl:" + hdUrl);

		String projectName = request.getParameter("projectName");

		if (StringUtils.isBlank(projectName)) {
			return AppResultUtil.createErrorDto("100", "项目名称不能为空");
		}
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

			String              url = hdUrl + "/user/lyzc/getProjectName.htm";
			Map<String, String> map = new HashMap<String, String>();
			map.put("projectName", projectName);
			map.put("date", dateFormat.format(new Date()));

			String sign = EncryptionUtils.getSign(map);
			log.info("WechatIndexController hdRegister====> 航电用户注册接口加密 sign:" + sign);
			map.put("sign", sign);

			ArrayList<Map<String, Object>> projectList      = new ArrayList<Map<String, Object>>();
			HttpClientResult               httpClientResult = HttpClientUtils.doPost(url, map);
			Map<String, Object>            result           = (Map<String, Object>) JSON.parse(httpClientResult.getContent());
			Map                            data             = (Map) result.get("data");
			JSONArray                      list             = (JSONArray) data.get("data");
			for (int i = 0; i < list.size(); i++) {
				JSONObject          object = list.getJSONObject(i);
				Map<String, Object> map1   = new HashMap<String, Object>();
				map1.put("projectId", object.get("projectId"));
				map1.put("projectName", object.get("projectName"));
				projectList.add(map1);
			}
			return AppResultUtil.createSuccesDto(projectList);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("getHdVoiceOrgList 客户声音项目列表查询失败======>" + e.getMessage());
		}

		return AppResultUtil.createErrorDto("100", "获取项目列表失败");
	}
}
