package com.palmnest.service.property.impl;

import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.bean.Pagenation;
import com.palmnest.application.core.util.FirstLetterUtil;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.application.dto.OrgComplexDTO;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.OutTreeDTO;
import com.palmnest.dao.UserDao;
import com.palmnest.dao.estateserve.ScWxuserDao;
import com.palmnest.dao.property.PropertyDao;
import com.palmnest.dao.wechat.ReplayContentDao;
import com.palmnest.model.*;
import com.palmnest.model.estateserve.ServiceProjectAllocation;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.*;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.outer.KafkaOuterService;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.wechat.WeChatApiManager;
import com.palmnest.service.ws.UserinformationSync;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 项目组织信息业务层接口实现类
 *
 * @author yubing
 * @since 2014
 */
@Slf4j
@Service("propertyManager")
public class PropertyManagerImpl extends GenericManagerImpl<Object, Integer> implements PropertyManager {


	private PropertyDao       propertyDao;
	@Autowired
	private UserDao           userDao;
	@Autowired
	private ReplayContentDao  replayContentDao;
	@Autowired
	private ScWxuserDao       scWxuserDao;
	@Autowired
	private WeChatApiManager  weChatApiManager;
	@Autowired
	private KafkaOuterService kafkaOuterService;

	@Autowired
	public void setPropertyDao(PropertyDao propertyDao) {
		this.propertyDao = propertyDao;
		dao = propertyDao;
	}

	@Override
	public boolean saveOrganization(User user, TbOrganization organizaiton, int companyId) {
		boolean dealFlag = true;
		try {
			//保存项目信息
			propertyDao.saveObj(organizaiton);

			TbBuild build = new TbBuild();
			build.setOrganizationId(organizaiton.getId());
			build.setName(organizaiton.getName());
			build.setAddress(organizaiton.getAddress());
			build.setVip("1");
			build.setLat(organizaiton.getLat());
			build.setLng(organizaiton.getLng());
			build.setCreateTime(new Date());
			build.setCreator(organizaiton.getCreator());
			build.setIsEnabled("1");
			propertyDao.saveObj(build);

			BuildOrgRelation relation = new BuildOrgRelation();
			relation.setType(ElementConstant.USER_ORG_COMPANY);
			relation.setOrgId(companyId);
			relation.setBuildId(build.getId());
			relation.setCreateTime(new Date());
			relation.setCreator(build.getCreator());
			propertyDao.saveObj(relation);

			//保存项目运营中心关系
			CompanyRelationOrg cr = new CompanyRelationOrg();
			cr.setCompanyId(companyId);
			cr.setOrganizationId(organizaiton.getId());
			propertyDao.saveObj(cr);

			//发送到消息通道，同步到子系统
			kafkaOuterService.syncBuild(build, companyId);

			//新增项目默认与当前创建者绑定
			AppUserOrgnizationRelation re = new AppUserOrgnizationRelation();
			re.setOrgId(organizaiton.getId());
			re.setUserId(user.getId());
			re.setCreateTime(new Date());
			re.setCreator(user.getLastUpdatedBy());
			userDao.saveAppUserOrgRelation(re);
		} catch (Exception e) {
			log.error("saveOrganization occur error.{}" + LogExceptionStackUtil.LogExceptionStack(e));
			dealFlag = false;
		}
		return dealFlag;
	}

	@Override
	public List<TbOrganization> queryTbOrganizationList() {
		return propertyDao.queryTbOrganizationList();
	}

	@Override
	public List<AppUserFloorRelation> queryUserOrgFloorList() {
		return propertyDao.queryUserOrgFloorList();
	}

	@Override
	public TbOrganization getTbOrganizationById(Integer id) {
		return propertyDao.getTbOrganizationById(id);
	}

	@Override
	public TbOrganization getTbOrganizationByNumber(String number) {
		return propertyDao.getTbOrganizationByNumber(number);
	}

	@Override
	public Pagenation<TbOrganization> queryTbOrganizaitonPage(int pageNo, int pageSize,
															  List<Criterion> filterList) {
		Map<String, String> aliasMap  = Collections.<String, String>emptyMap();
		List<Order>         orderList = new ArrayList<Order>();
		orderList.add(Order.desc("createTime"));
		return propertyDao.queryPage(pageNo, pageSize, aliasMap, filterList, orderList, TbOrganization.class);
	}

	@Override
	public void deleteTbOrganization(TbOrganization organization) {
		//1.更新项目状态
		propertyDao.updateObj(organization);
		//删除关系表中信息
		propertyDao.deleteCompanyOrg(organization.getId());
		//TODO
		//2.更新楼栋地址状态
		//3.更新虚拟组织结构状态
		//4.删除物业组织-项目组织之间的关系
		//5.同步项目到一键服务
		assignAnsyOrganization(organization);
	}

	@Override
	public Page queryBuildListPage(int pageNo, int pageSize, String whereSQL) {
		return propertyDao.queryBuildListPage(pageNo, pageSize, whereSQL);
	}

	@Override
	public TbBuild getTbBuildById(int buildId) {
		return propertyDao.getTbBuildById(buildId);
	}

	@Override
	public List<TbBuild> getTbBuildListByOrgaid(int organizationID) {
		return propertyDao.getTbBuildListByOrgaid(organizationID);
	}

	@Override
	public Integer getMaxvirtualArchId() {
		return propertyDao.getMaxvirtualArchId();
	}

	@Override
	public List<VirtualArchitecture> getVirtualArchitectureList(
			int organizationId) {
		return propertyDao.getVirtualArchitectureList(organizationId);
	}

	@Override
	public VirtualArchitecture getVirtualArchBycode(String code,
													String parentCode) {
		return propertyDao.getVirtualArchBycode(code, parentCode);
	}

	@Override
	public List<BuildOrgRelation> getBuildOrgRelationList(String type,
														  int orgId) {
		return propertyDao.getBuildOrgRelationList(type, orgId);
	}

	@Override
	public List<OutTreeDTO> getOrganizationBuildTree(String queryType,
													 Integer userId, Integer deptId, Integer companyId) {
		List<OutTreeDTO> trees = new ArrayList<OutTreeDTO>();
		//根节点
		OutTreeDTO obj = new OutTreeDTO();
		obj.setId("0");
		obj.setName("所有项目");
		obj.setpId("-1");
		trees.add(obj);

		List<Map<String, Object>> dataList  = null;
		List<BuildOrgRelation>    relations = new ArrayList<BuildOrgRelation>();
		List<Integer>             orgIds    = new ArrayList<Integer>();
		//物业组织
		if ("1".equals(queryType)) {
			//1、查询系统管理员的物业组织管辖权限
			//2、更加物业组织，关联查询项目楼栋
			//3、组装数据
			//TODO 1-2步骤目前省略，权限讨论清楚再加上去
			dataList = propertyDao.getBuildList();
			//物业组织编辑，ID存在
			if (companyId != null) {
				relations = propertyDao.getBuildOrgRelationList(queryType, companyId);
			}

		} else {//部门团队组织
			dataList = propertyDao.getBuildList(companyId);
			//部门组织编辑，ID存在
			if (deptId != null) {
				relations = propertyDao.getBuildOrgRelationList(queryType, deptId);
			}
		}
		for (Map<String, Object> data : dataList) {
			Integer organizationId = (Integer) data.get("organizationId");
			Integer buildId        = (Integer) data.get("buildId");
			String  buildName      = (String) data.get("buildName");
			if (!orgIds.contains(organizationId)) {
				String     organizationName = (String) data.get("organizationName");
				OutTreeDTO obj1             = new OutTreeDTO();
				obj1.setId("o_" + organizationId.intValue());
				obj1.setName(organizationName);
				obj1.setpId("0");
				obj1.setLevel("1");
				trees.add(obj1);

				orgIds.add(organizationId);
			}
			OutTreeDTO obj2 = new OutTreeDTO();
			obj2.setId(buildId.intValue() + "");
			obj2.setName(buildName);
			obj2.setLevel("2");
			obj2.setpId("o_" + organizationId.intValue());
			for (BuildOrgRelation relation : relations) {
				if (buildId.intValue() == relation.getBuildId().intValue()) {
					obj2.setChecked(true);
				}
			}
			trees.add(obj2);
		}
		return trees;
	}

	@Override
	public List<OutTreeDTO> getCompanyOrgTree(Integer companyId, Integer userId, User user) {
		List<OutTreeDTO> trees = new ArrayList<OutTreeDTO>();
		//根节点
		OutTreeDTO obj = new OutTreeDTO();
		obj.setId("0");
		obj.setName("所有项目");
		obj.setpId("-1");
		trees.add(obj);

		List<Map<String, Object>>        dataList  = null;
		List<AppUserOrgnizationRelation> relations = new ArrayList<AppUserOrgnizationRelation>();

		if (user.isAdmin()) {
			//如果当前登录用户是admin或者系统管理员 则查询指定运营中心所管辖的所有项目列表
			dataList = propertyDao.getOrgListByCompany(companyId);
		} else {
			//如果当前登录用户不是admin或者系统管理员 则只查询他自己所管辖的项目列表
			dataList = propertyDao.getOrgListByUser(user.getId());
		}
		//查询当前用户所管辖的项目列表
		if (userId != null) {
			relations = propertyDao.getAppUserOrgRelationList(userId);
		}

		for (Map<String, Object> data : dataList) {
			Integer organizationId   = (Integer) data.get("organizationId");
			String  organizationName = (String) data.get("organizationName");

			OutTreeDTO obj2 = new OutTreeDTO();
			obj2.setId(organizationId.intValue() + "");
			obj2.setName(organizationName);
			obj2.setpId("0");
			obj2.setLevel("1");

			for (AppUserOrgnizationRelation relation : relations) {
				if (organizationId.intValue() == relation.getOrgId()) {
					obj2.setChecked(true);
				}
			}
			trees.add(obj2);
		}
		return trees;
	}

	@Override
	public List<TbOrganization> getAppUserOrganizationRelation(
			String companyIdStr) {
		List<TbOrganization>      organizationList = new ArrayList<TbOrganization>();
		List<Map<String, Object>> organizationIds  = propertyDao.getAppUserOrganizationRelation(companyIdStr);
		if (!CollectionUtils.isEmpty(organizationIds)) {
			for (Map<String, Object> data : organizationIds) {
				Integer        organizationId = (Integer) data.get("organizationId");
				TbOrganization organization   = propertyDao.getTbOrganizationById(organizationId);
				//可用状态+审核通过状态
				if (ElementConstant.YESORNO_1.equals(organization.getIsEnabled())) {
					organizationList.add(propertyDao.getTbOrganizationById(organizationId));
				}
			}
		}
		return organizationList;
	}

	@Override
	public void delectOrgFloorRelationByUserId(String userId) {
		propertyDao.delectOrgFloorRelationByUserId(userId);
	}

	@Override
	public VirtualArchitecture getVirtualArchitectureById(int vaitualId) {
		return propertyDao.getVirtualArchitectureById(vaitualId);
	}

	@Override
	public List<Map<String, Object>> getOrganizationList(
			String organizationIdsStr) {
		return propertyDao.getOrganizationList(organizationIdsStr);
	}

	@Override
	public List<VirtualArchitecture> getVirtualArchitectureList(
			String parentCode) {
		return propertyDao.getVirtualArchitectureList(parentCode);
	}

	@Override
	public List<VirtualArchitecture> getVirtualArchitectureList(
			int organizationId, String type) {
		return propertyDao.getVirtualArchitectureList(organizationId, type);
	}

	@Override
	public List<Map<String, Object>> getAddVirtualArchitectureList(
			int organizationId, String type) {
		return propertyDao.getAddVirtualArchitectureList(organizationId, type);
	}

	@Override
	public VirtualArchitecture getVirtualArchitectureByCustomerNumber(
			String customerNumber) {
		return propertyDao.getVirtualArchitectureByCustomerNumber(customerNumber);
	}

	@Override
	public Map<String, Object> assiginBatchImportArchitecture(String organizationId,
															  InputStream ins, String controller) {
		Map<String, Object>       retMap      = new HashMap<String, Object>();
		List<VirtualArchitecture> virtualList = new ArrayList<VirtualArchitecture>();

		StringBuffer bugStr       = new StringBuffer("");
		int          bugCount     = 0;
		int          correctCount = 0;
		XSSFSheet    sheet        = null;
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(ins);
			sheet = workbook.getSheet("Sheet1");
		} catch (Exception e) {
			bugStr.append("模板格式有问题，请获取最新的模板");
		}
		if (sheet == null) {
			bugStr.append("模板格式有问题，请获取最新的模板");
		} else {
			int rows = sheet.getLastRowNum();
			//如果大于2000行数据
			if (rows > 20000) {
				bugStr.append("数据量太大，不能大于2w行");
			} else if (rows < 1) {
				bugStr.append("数据为空，请录入企业资料信息");
			} else {
				//遍历Excel每一行，取每列的数据
				for (int i = 1; i <= rows; i++) {
					System.out.println(i);
					XSSFRow row   = sheet.getRow(i);
					String  cell1 = "";        //企业名称
					row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
					if (StringUtils.isNotEmpty(row.getCell(1).getStringCellValue())) {
						cell1 = row.getCell(1).getStringCellValue().trim();

						String cell2 = "";    //客户编号
						row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
						if (StringUtils.isNotEmpty(row.getCell(2).getStringCellValue())) {
							cell2 = row.getCell(2).getStringCellValue().trim();
							VirtualArchitecture virtual = propertyDao.getVirtualArchitectureByCustomerNumber(cell2);
							if (virtual != null) {
								bugStr.append("第" + i + "行第3列数据有问题，请检查，问题：客户编号在系统中已存在<br/>");
								bugCount++;
								continue;
							}
						}

						String cell3 = "";        //联系人
						row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
						if (StringUtils.isNotEmpty(row.getCell(3).getStringCellValue())) {
							cell3 = row.getCell(3).getStringCellValue().trim();
						}

						String cell4 = "";        //联系电话
						row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
						if (StringUtils.isNotEmpty(row.getCell(4).getStringCellValue())) {
							cell4 = row.getCell(4).getStringCellValue().trim();
						}

						String cell5 = "1";        //企业人数
						row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
						if (StringUtils.isNotEmpty(row.getCell(5).getStringCellValue())) {
							cell5 = row.getCell(5).getStringCellValue().trim();
						}

						String cell6 = "1";        //地址
						row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
						if (StringUtils.isNotEmpty(row.getCell(6).getStringCellValue())) {
							cell6 = row.getCell(6).getStringCellValue().trim();
						}

						VirtualArchitecture newVirtual = new VirtualArchitecture();
						newVirtual.setName(cell1);
						newVirtual.setOrganizationId(Integer.parseInt(organizationId));
						newVirtual.setType("1");
						newVirtual.setParentCode("0");
						newVirtual.setIsEnabled("1");
						newVirtual.setCustomerNumber(cell2);
						newVirtual.setCodeNumber(cell2);
						newVirtual.setContacts(cell3);
						newVirtual.setPhone(cell4);
						newVirtual.setEmployees(Integer.parseInt(cell5));
						newVirtual.setAddress(cell6);
						newVirtual.setCreateTime(new Date());
						newVirtual.setCreator(controller);
						newVirtual.setCustomerType("0");    //普通企业
						newVirtual.setContractStatus("0");    //未签约
						newVirtual.setStatus("1");            //审核通过
						newVirtual.setReserveBalance(new BigDecimal(0.00));
						virtualList.add(newVirtual);
						correctCount++;
					} else {
						bugStr.append("第" + i + "行第2列数据有问题，请检查，问题：企业名称不能为空<br/>");
						bugCount++;
					}
				}
			}
		}
		retMap.put("bugStr", bugStr.toString());
		retMap.put("bugCount", bugCount);
		retMap.put("correctCount", correctCount);
		retMap.put("data", virtualList);
		return retMap;
	}

	@Override
	public void saveBatchArchitecture(List<VirtualArchitecture> datas) {
		int maxVirtualId = propertyDao.getMaxvirtualArchId();
		for (VirtualArchitecture virtualArchitecture : datas) {
			maxVirtualId++;
			virtualArchitecture.setCode(maxVirtualId + "");
			virtualArchitecture.setReserveBalance(new BigDecimal(0.00));
			if (StringUtils.isEmpty(virtualArchitecture.getCustomerNumber())) {
				String customerNo = getVirtualCustomerNo(virtualArchitecture.getOrganizationId());
				virtualArchitecture.setCustomerNumber(customerNo);
				virtualArchitecture.setCodeNumber(customerNo);
			}
			propertyDao.save(virtualArchitecture);
		}
	}

	@Override
	public List<Map<String, Object>> getOrgExistCityList() {
		return propertyDao.getOrgExistCityList();
	}

	@Override
	public List<TbOrganization> getOrgByCityCode(String cityCode) {
		return propertyDao.getOrgByCityCode(cityCode);
	}

	@Override
	public List<Map<String, Object>> getVirtualarchitectureList(
			String paramValue, String organizationIds) {
		try {
			return propertyDao.getVirtualarchitectureList(paramValue, organizationIds);
		} catch (Exception e) {
			LogExceptionStackUtil.LogExceptionStack(e);
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> getVirtualArchitectureList(
			int organizationId, String type, String paramValue) {
		return propertyDao.getVirtualArchitectureList(organizationId, type, paramValue);
	}

	@Override
	public Page getVirtualArchitecturePage(int pageSize,
										   int pageNo, String whereSQL) {
		return propertyDao.getVirtualArchitecturePage(pageSize, pageNo, whereSQL);
	}

	@Override
	public Map<String, Object> getVirtualArchitectureMap(String id) {
		return propertyDao.getVirtualArchitectureMap(id);
	}

	@Override
	public Map<String, String> saveOrUpdateVirtualArch(VirtualArchitecture virtualArch, String status, String agent_id, String[] relationId, String[] rangeId) {
		Map<String, String> retMap = new HashMap<String, String>();
		try {
			Integer currentId = virtualArch.getId();
			//修改
			if (currentId != null) {
				VirtualArchitecture ckVirtual = propertyDao.getVirtualArchitectureByCustomerNumber(virtualArch.getCustomerNumber(), virtualArch.getId());
				if (ckVirtual != null) {
					retMap.put("dealFlag", "fail");
					retMap.put("resultDesc", "抱歉，更新失败，客户编号重复！");
				} else {
					//如果审核状态发生改变
					if (StringUtils.isNotEmpty(status)) {
						if (!status.equals(virtualArch.getStatus())) {
							virtualArch.setStatus(status);
							if (virtualArch.getWxUserId() != null) {
								//微信审核结果模板消息提醒
								List<Map<String, Object>> templateList = replayContentDao.getWxTemplate(ElementConstant.TemplateType03, 0);
								if (!CollectionUtils.isEmpty(templateList)) {
									Map<String, String> paramMap = new HashMap<String, String>();
									WxUser              wxUser   = scWxuserDao.get(virtualArch.getWxUserId());
									//通过
									if ("1".equals(status)) {
										paramMap.put("templateId", templateList.get(0).get("templateId").toString());
										paramMap.put("title", "您申请的公司信息已审核通过，欢迎使用\\n"
												+ "公司信息：" + virtualArch.getName());
										paramMap.put("openId", wxUser.getOpenId());
										paramMap.put("developId", wxUser.getDevelopId());
										paramMap.put("type", "公司入驻申请");
										paramMap.put("result", "通过");
										paramMap.put("suggestion", virtualArch.getReviewRemark());
										paramMap.put("remark", "\\n如有问题请拨打尚美集团客服热线4008386065或在公众号留言，谢谢");
										String result = weChatApiManager.sendTemplateMsg02(paramMap);
										log.info("assginMassnotification result:" + result);

									}
									//不通过
									else if ("2".equals(virtualArch.getStatus())) {
										paramMap.put("templateId", templateList.get(0).get("templateId").toString());
										paramMap.put("title", "非常抱歉，您申请的公司信息审核未通过\\n"
												+ "公司信息：" + virtualArch.getName());
										paramMap.put("openId", wxUser.getOpenId());
										paramMap.put("developId", wxUser.getDevelopId());
										paramMap.put("type", "公司入驻申请");
										paramMap.put("result", "未通过");
										paramMap.put("suggestion", virtualArch.getReviewRemark());
										paramMap.put("remark", "\\n如有问题请拨打尚美集团客服热线4008386065或在公众号留言，谢谢");
										String result = weChatApiManager.sendTemplateMsg02(paramMap);
										log.info("assginMassnotification result:" + result);
									}
								}
							}
						}
					}
					retMap.put("dealFlag", "success");
					propertyDao.updateObj(virtualArch);
				}
			}
			//新增
			else {
				int maxVirtualId = getMaxvirtualArchId();
				virtualArch.setCode(maxVirtualId + "");
				virtualArch.setParentCode("0");
				virtualArch.setCustomerNumber(getVirtualCustomerNo(virtualArch.getOrganizationId()));
				virtualArch.setStatus(status);
				virtualArch.setReserveBalance(new BigDecimal(0));
				propertyDao.saveObj(virtualArch);
				if (StringUtils.isNotBlank(agent_id) && !agent_id.equals("0")) {
					VirtualArchitectureAgent virtualArchitectureAgent = new VirtualArchitectureAgent();
					virtualArchitectureAgent.setId(virtualArch.getId());
					virtualArchitectureAgent.setAgent_id(Integer.parseInt(agent_id));
					propertyDao.saveObj(virtualArchitectureAgent);
//					propertyDao.saveVirtualArchAgent(virtualArch.getId(), Integer.parseInt(agent_id));
				}
				if (relationId != null && relationId.length > 0) {
					for (String id : relationId) {
						VirtualArchitectureAgent virtualArchitectureAgent = new VirtualArchitectureAgent();
						virtualArchitectureAgent.setId(Integer.parseInt(id));
						virtualArchitectureAgent.setAgent_id(virtualArch.getId());
						propertyDao.saveObj(virtualArchitectureAgent);
					}
				}
				if (rangeId != null && rangeId.length > 0) {
					for (String id : rangeId) {
						VirtualArchitectureRange virtualArchitectureRange = new VirtualArchitectureRange();
						virtualArchitectureRange.setId(virtualArch.getId());
						virtualArchitectureRange.setRoom_id(Integer.parseInt(id));
						propertyDao.saveObj(virtualArchitectureRange);
					}
				}
				retMap.put("dealFlag", "success");
			}

			if ("success".equals(retMap.get("dealFlag")) && "1".equals(status)) {
				//企业信息同步到信息到一键服务
				TbOrganization organization = propertyDao.getTbOrganizationById(virtualArch.getOrganizationId());

				StringBuffer strParams = new StringBuffer();
				strParams.append("userName=" + virtualArch.getName());
				strParams.append("&userMobile=" + virtualArch.getPhone());
				strParams.append("&address=" + virtualArch.getAddress());
				strParams.append("&organizationCode=" + organization.getCode());
				strParams.append("&customerNo=" + virtualArch.getCustomerNumber());
				strParams.append("&customerType=" + 1);
				strParams.append("&signStatus=" + virtualArch.getContractStatus());
				if (currentId == null) {
					strParams.append("&operateType=" + ElementConstant.OPRATETYPE_ADD);
				} else {
					strParams.append("&operateType=" + ElementConstant.OPRATETYPE_UPD);
				}
				log.info("saveOrUpdateVirtualArch assignSyncUser----------");
				log.info("strParams:" + strParams);
				boolean result = UserinformationSync.assignuser(strParams.toString());
				log.info("result:" + result);
			}
		} catch (Exception e) {
			log.error("saveOrUpdateVirtualArch occur error.{}" + LogExceptionStackUtil.LogExceptionStack(e));
			e.printStackTrace();
			retMap.put("dealFlag", "fail");
			retMap.put("resultDesc", "抱歉，系统处理失败，请稍后再试或者联系管理员");
		}
		return retMap;
	}

	@Override
	public String getVirtualCustomerNo(int organizationId) {
		TbOrganization organization = propertyDao.getTbOrganizationById(organizationId);
		String         cityNameCh   = organization.getCityName().replace("市", "");
		String         cityNameEng  = FirstLetterUtil.getPinYinHeadChar(cityNameCh).toUpperCase();
		//当前的企业编号信息
		String currentCustomer = propertyDao.findCustomerNumberMaxId(cityNameEng);

		return FirstLetterUtil.getPinYinHeadCharCode(organization.getCityName().replace("市", ""), currentCustomer).toUpperCase();
	}

	@Override
	public void deleteVirtualArch(VirtualArchitecture virtual) {
		//更新可用状态
		propertyDao.updateObj(virtual);

		//企业信息同步到信息到一键服务
		TbOrganization organization = propertyDao.getTbOrganizationById(virtual.getOrganizationId());
		StringBuffer   strParams    = new StringBuffer();
		strParams.append("userName=" + virtual.getName());
		strParams.append("&userMobile=" + virtual.getPhone());
		strParams.append("&address=" + virtual.getAddress());
		strParams.append("&organizationCode=" + organization.getCode());
		strParams.append("&customerNo=" + virtual.getCustomerNumber());
		strParams.append("&customerType=" + 1);
		strParams.append("&signStatus=" + virtual.getContractStatus());
		strParams.append("&operateType=" + ElementConstant.OPRATETYPE_DEL);
		log.info("deleteVirtualArch assignSyncUser----------");
		log.info("strParams:" + strParams);
		boolean result = UserinformationSync.assignuser(strParams.toString());
		log.info("result:" + result);
	}

	@Override
	public Map<String, Object> assiginBatchImportOrganization(
			InputStream ins, String controller) {

		Map<String, Object> retMap     = new HashMap<String, Object>();
		List<OrgComplexDTO> orgComplex = new ArrayList<OrgComplexDTO>();

		StringBuffer bugStr       = new StringBuffer("");
		int          bugCount     = 0;
		int          correctCount = 0;
		XSSFSheet    sheet        = null;
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(ins);
			sheet = workbook.getSheet("Sheet1");
		} catch (Exception e) {
			bugStr.append("模板格式有问题，请获取最新的模板");
		}
		if (sheet == null) {
			bugStr.append("模板格式有问题，请获取最新的模板");
		} else {
			int rows = sheet.getLastRowNum();
			//如果大于2000行数据
			if (rows > 20000) {
				bugStr.append("数据量太大，不能大于2w行");
			} else if (rows < 1) {
				bugStr.append("数据为空，请录入项目资料信息");
			} else {
				//遍历Excel每一行，取每列的数据
				for (int i = 1; i <= rows; i++) {
					XSSFRow row   = sheet.getRow(i);
					String  cell1 = "";        //项目名称
					row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
					if (StringUtils.isNotEmpty(row.getCell(3).getStringCellValue())) {
						cell1 = row.getCell(3).getStringCellValue().trim();

						String cell2 = "";    //项目编号
						row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
						if (StringUtils.isNotEmpty(row.getCell(4).getStringCellValue())) {
							cell2 = row.getCell(4).getStringCellValue().trim();
							//验证项目编号在系统中是否存在，重复
							TbOrganization tbOrganization = propertyDao.getOrganization(cell2);
							if (tbOrganization != null) {
								bugStr.append("第" + i + "行第5列数据有问题，请检查，问题：项目编号在系统中已存在<br/>");
								bugCount++;
							} else {
								String cell3 = "";        //电话号码
								row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
								if (StringUtils.isNotEmpty(row.getCell(5).getStringCellValue())) {
									cell3 = row.getCell(5).getStringCellValue().trim();
								}

								String cell4 = "";        //省份编码
								row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
								if (StringUtils.isNotEmpty(row.getCell(6).getStringCellValue())) {
									cell4 = row.getCell(6).getStringCellValue().trim();
								}
								String cell5 = "";        //省份名称
								row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
								if (StringUtils.isNotEmpty(row.getCell(7).getStringCellValue())) {
									cell5 = row.getCell(7).getStringCellValue().trim();
								}
								String cell6 = "";        //城市编码
								row.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
								if (StringUtils.isNotEmpty(row.getCell(8).getStringCellValue())) {
									cell6 = row.getCell(8).getStringCellValue().trim();
								}
								String cell7 = "";        //城市名称
								row.getCell(9).setCellType(Cell.CELL_TYPE_STRING);
								if (StringUtils.isNotEmpty(row.getCell(9).getStringCellValue())) {
									cell7 = row.getCell(9).getStringCellValue().trim();
								}

								String cell8 = "";        //企业名称
								row.getCell(10).setCellType(Cell.CELL_TYPE_STRING);
								if (StringUtils.isNotEmpty(row.getCell(10).getStringCellValue())) {
									cell8 = row.getCell(10).getStringCellValue().trim();

									String cell9 = "";    //企业编号
									row.getCell(11).setCellType(Cell.CELL_TYPE_STRING);
									if (StringUtils.isNotEmpty(row.getCell(11).getStringCellValue())) {
										cell9 = row.getCell(11).getStringCellValue().trim();
										VirtualArchitecture virtual = propertyDao.getVirtualArchitecture(cell9);
										if (virtual != null) {
											bugStr.append("第" + i + "行第12列数据有问题，请检查，问题：企业编号在系统中已存在<br/>");
											bugCount++;
										} else {
											String cell10 = "";    //地址
											row.getCell(12).setCellType(Cell.CELL_TYPE_STRING);
											if (StringUtils.isNotEmpty(row.getCell(12).getStringCellValue())) {
												cell10 = row.getCell(12).getStringCellValue().trim();
											}
											OrgComplexDTO dto = new OrgComplexDTO();
											dto.setOrganizationName(cell1);
											dto.setCode(cell2);
											dto.setTelephone(cell3);
											dto.setProvinceCode(cell4);
											dto.setProvinceName(cell5);
											dto.setCityCode(cell6);
											dto.setCityName(cell7);
											dto.setVirtualName(cell8);
											dto.setCodeNumber(cell9);
											dto.setAddress(cell10);
											dto.setOperateUser(controller);
											orgComplex.add(dto);

											correctCount++;
										}
									} else {
										bugStr.append("第" + i + "行第12列数据有问题，请检查，问题：企业编号不能为空<br/>");
										bugCount++;
									}
								} else {
									bugStr.append("第" + i + "行第11列数据有问题，请检查，问题：企业名称不能为空<br/>");
									bugCount++;
								}
							}
						} else {
							bugStr.append("第" + i + "行第5列数据有问题，请检查，问题：项目编号不能为空<br/>");
							bugCount++;
						}
					} else {
						bugStr.append("第" + i + "行第4列数据有问题，请检查，问题：项目名称不能为空<br/>");
						bugCount++;
					}
				}
			}
		}
		retMap.put("bugStr", bugStr.toString());
		retMap.put("bugCount", bugCount);
		retMap.put("correctCount", correctCount);
		retMap.put("data", orgComplex);
		return retMap;
	}

	@Override
	public void saveBatchOrganization(List<OrgComplexDTO> datas) {
		int maxVirtualId = propertyDao.getMaxvirtualArchId();

		for (OrgComplexDTO dto : datas) {
			//保存项目
			TbOrganization organization = new TbOrganization();
			organization.setName(dto.getOrganizationName());
			organization.setCode(dto.getCode());
			organization.setTelephone(dto.getTelephone());
			organization.setProvinceCode(dto.getProvinceCode());
			organization.setProvinceName(dto.getProvinceName());
			organization.setCityCode(dto.getCityCode());
			organization.setCityName(dto.getCityName());
			organization.setAddress(dto.getAddress());
			organization.setStatus("1");
			organization.setCreateTime(new Date());
			organization.setCreator(dto.getOperateUser());
			organization.setIsEnabled("1");
			organization.setLat(0.0);
			organization.setLng(0.0);
			propertyDao.saveObj(organization);

			//保存企业
			maxVirtualId++;
			VirtualArchitecture virtual = new VirtualArchitecture();
			virtual.setOrganizationId(organization.getId());
			virtual.setName(dto.getVirtualName());
			virtual.setType("1");
			virtual.setCodeNumber(dto.getCodeNumber());
			virtual.setCustomerNumber(getVirtualCustomerNo(organization.getId()));
			virtual.setCode(maxVirtualId + "");
			virtual.setParentCode("0");
			virtual.setCustomerType("0");
			virtual.setContractStatus("1");
			virtual.setReserveBalance(new BigDecimal(0.00));
			virtual.setAddress(dto.getAddress());
			virtual.setCreateTime(new Date());
			virtual.setCreator(organization.getCreator());
			virtual.setIsEnabled("1");
			virtual.setStatus("1");
			propertyDao.saveObj(virtual);

			//保存楼栋
			TbBuild build = new TbBuild();
			build.setOrganizationId(organization.getId());
			build.setName(dto.getOrganizationName());
			build.setVip("0");
			build.setAddress(dto.getAddress());
			build.setCreateTime(new Date());
			build.setCreator(organization.getCreator());
			build.setIsEnabled("1");
			propertyDao.saveObj(build);

			//项目主页服务配置
			String[] str = new String[]{"3", "17", "19", "22", "14"};
			for (String typeId : str) {
				ServiceProjectAllocation localtion = new ServiceProjectAllocation();
				localtion.setServiceTypeId(Integer.parseInt(typeId));
				localtion.setProjectId(organization.getId());
				localtion.setRoleGroup("0,1,");
				localtion.setType("0");
				localtion.setStatus("1");
				localtion.setOrderNo("1");
				localtion.setCreator(organization.getCreator());
				localtion.setCreateTime(new Date());
				localtion.setIsEnabled("1");
				propertyDao.saveObj(localtion);
			}

			//保存企业签约
			ContractIinformation contractIinformation = new ContractIinformation();
			contractIinformation.setOrganizationId(organization.getId());
			contractIinformation.setVirtualArchitectureId(virtual.getId());
			contractIinformation.setStatus("1");
			contractIinformation.setType("9,");
			contractIinformation.setCreateTime(new Date());
			contractIinformation.setCreator(organization.getCreator());
			contractIinformation.setIsEnabled("1");
			propertyDao.saveObj(contractIinformation);

			assignAnsyOrganization(organization);
		}
	}

	@Override
	public boolean assignAnsyOrganization(TbOrganization organization) {
		//同步项目到一键服务
		StringBuffer strParams = new StringBuffer();
		strParams.append("name=" + organization.getName());
		strParams.append("&telephone=" + organization.getTelephone());
		strParams.append("&code=" + organization.getCode());
		strParams.append("&address=" + organization.getAddress());
		strParams.append("&cityCode=" + organization.getCityCode());
		if ("1".equals(organization.getIsEnabled())
				&& "1".equals(organization.getStatus())) {
			strParams.append("&operateType=" + ElementConstant.OPRATETYPE_ADD);
		} else {
			strParams.append("&operateType=" + ElementConstant.OPRATETYPE_DEL);
		}
		log.info("saveBatchOrganization assignOrganization----------");
		log.info("strParams:" + strParams);
		boolean result = UserinformationSync.assignOrganization(strParams.toString());
		log.info("result:" + result);
		return result;
	}


	@Override
	public List<Map<String, Object>> getCityList() throws Exception {
		try {
			return propertyDao.getCityList();
		} catch (Exception e) {
			LogExceptionStackUtil.LogExceptionStack(e);
		}
		return null;
	}

	@Override
	public Map<String, Object> saveUpdateOrganization(
			TbOrganization tbOrganization) throws Exception {
		try {
			if (tbOrganization.getId() != null) {

			} else {

			}
		} catch (Exception e) {
			LogExceptionStackUtil.LogExceptionStack(e);
		}
		return null;
	}

	@Override
	public String updateOrganizationStatus(TbOrganization organization) {
		if (organization.getWxUserId() != null) {
			//微信审核结果模板消息提醒
			List<Map<String, Object>> templateList = replayContentDao.getWxTemplate(ElementConstant.TemplateType03, 0);
			if (!CollectionUtils.isEmpty(templateList)) {
				Map<String, String> paramMap = new HashMap<String, String>();
				WxUser              wxUser   = scWxuserDao.get(organization.getWxUserId());
				//通过
				if ("1".equals(organization.getStatus())) {
					paramMap.put("templateId", templateList.get(0).get("templateId").toString());
					paramMap.put("title", "您申请的楼宇信息已审核通过，欢迎使用\\n"
							+ "楼宇信息：" + organization.getName());
					paramMap.put("openId", wxUser.getOpenId());
					paramMap.put("developId", wxUser.getDevelopId());
					paramMap.put("type", "楼宇申请");
					paramMap.put("result", "通过");
					paramMap.put("suggestion", organization.getReviewRemark());
					paramMap.put("remark", "\\n如有问题请拨打尚美集团客服热线4008386065或在公众号留言，谢谢");
					String result = weChatApiManager.sendTemplateMsg02(paramMap);
					log.info("assginMassnotification result:" + result);

				}
				//不通过
				else if ("2".equals(organization.getStatus())) {
					paramMap.put("templateId", templateList.get(0).get("templateId").toString());
					paramMap.put("title", "非常抱歉，您申请的楼宇信息审核未通过\\n"
							+ "楼宇信息：" + organization.getName());
					paramMap.put("openId", wxUser.getOpenId());
					paramMap.put("developId", wxUser.getDevelopId());
					paramMap.put("type", "楼宇申请");
					paramMap.put("result", "未通过");
					paramMap.put("suggestion", organization.getReviewRemark());
					paramMap.put("remark", "\\n如有问题请拨打尚美集团客服热线4008386065或在公众号留言，谢谢");
					String result = weChatApiManager.sendTemplateMsg02(paramMap);
					log.info("assginMassnotification result:" + result);
				}
			}
		}
		propertyDao.updateObj(organization);

		//同步项目到一键服务
		assignAnsyOrganization(organization);

		return "success";
	}

	@Override
	public String saveOrganizationFromApply(TbOrganization organization) {
		String resultStr = "success";
		try {
			//保存项目
			organization.setStatus("0");
			organization.setLat(0.0);
			organization.setLng(0.0);
			organization.setCreateTime(new Date());
			organization.setIsEnabled(ElementConstant.YESORNO_1);
			propertyDao.saveObj(organization);

			//保存楼栋
			TbBuild build = new TbBuild();
			build.setOrganizationId(organization.getId());
			build.setName(organization.getName());
			build.setVip("0");
			build.setAddress(organization.getAddress());
			build.setCreateTime(new Date());
			build.setCreator(organization.getCreator());
			build.setIsEnabled("1");
			propertyDao.saveObj(build);

			//关联到中航物业内购运营中心
			BuildOrgRelation relation = new BuildOrgRelation();
			relation.setType("1");
			relation.setBuildId(build.getId());
			relation.setOrgId(35);
			relation.setCreator(organization.getCreator());
			relation.setCreateTime(new Date());
			propertyDao.saveObj(relation);
		} catch (Exception e) {
			resultStr = "error";
			log.error("save organization occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return resultStr;
	}

	@Override
	public String saveVirtualFromApply(VirtualArchitecture virtual) {
		String resultStr = "success";
		try {
			//保存企业
			String customerNo   = getVirtualCustomerNo(virtual.getOrganizationId());
			int    maxVirtualId = propertyDao.getMaxvirtualArchId();
			maxVirtualId++;

			virtual.setType("1");
			virtual.setCodeNumber(customerNo);
			virtual.setCustomerNumber(customerNo);
			virtual.setCode(maxVirtualId + "");
			virtual.setParentCode("0");
			virtual.setCustomerType("0");
			virtual.setContractStatus("0");
			virtual.setReserveBalance(new BigDecimal(0.00));
			virtual.setCreateTime(new Date());
			virtual.setIsEnabled("1");
			virtual.setStatus("0");
			propertyDao.saveObj(virtual);
		} catch (Exception e) {
			resultStr = "error";
			log.error("save saveVirtualFromApply occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return resultStr;
	}

	@Override
	public List<Map<String, Object>> getVirtualarchitectureList(
			String organizationId, String type, String paramValue) {
		return propertyDao.getVirtualarchitectureList(organizationId, type, paramValue);
	}

	@Override
	public List<Map<String, Object>> getProvincecityByCityList(String paramValue, String orgIds) {
		return propertyDao.getProvincecityByCityList(paramValue, orgIds);
	}

	@Override
	public List<Map<String, Object>> getOrganizationListByName(
			String paramValue, String cityCode, String orgIds) {
		return propertyDao.getOrganizationListByName(paramValue, cityCode, orgIds);
	}

	@Override
	public List<Map<String, Object>> getProvincecityList(
			String province) {
		List<Map<String, Object>> listMap     = propertyDao.getProvincecityList(province);//所有省份
		Map<String, Object>       provinceMap = propertyDao.getProvincecityByName(province);//定位的省份
		if (provinceMap != null) {
			listMap.add(0, provinceMap);
		}
		return listMap;
	}

	@Override
	public Map<String, Object> getCityList(String city, String province) {
		Map<String, Object>       resultMap   = new HashMap<String, Object>();
		List<Map<String, Object>> listMap     = propertyDao.getProvincecityList(province);//所有省份
		Map<String, Object>       provinceMap = propertyDao.getProvincecityByName(province);//定位的省份
		for (int i = 0; i < listMap.size(); i++) {
			String                    provinceCode = listMap.get(i).get("value").toString();
			List<Map<String, Object>> mapList      = propertyDao.getCityList(provinceCode);
			resultMap.put(provinceCode, mapList);
		}
		if (provinceMap != null) {
			String                    provinceCode = provinceMap.get("value").toString();
			List<Map<String, Object>> mapList      = propertyDao.getCityList(provinceCode, city);
			Map<String, Object>       mapCity      = propertyDao.getCityObect(provinceCode, city);
			if (mapCity != null) {
				mapList.add(0, mapCity);
			}
			resultMap.put(provinceCode, mapList);
		}
		return resultMap;
	}

	@Override
	public ProvinceCity findProvinceCityByName(String paramName, String type) {
		return propertyDao.findProvinceCityByName(paramName, type);
	}

	@Override
	public List<ProvinceCity> getProvinceCityList(String type, String code) {
		return propertyDao.getProvinceCityList(type, code);
	}

	@Override
	public List<TbBuild> getBuildByOrgIdAndBuildName(int organizationId,
													 String buildName) {
		return propertyDao.getBuildByOrgIdAndBuildName(organizationId, buildName);
	}

	@Override
	public CompanyRelationOrg getCompanyByOrgId(Integer orgId) {
		return propertyDao.getCompanyByOrgId(orgId);
	}

	@Override
	public Integer getSuperDeskOrgId(Integer id) {
		return propertyDao.getSuperDeskOrgId(id);
	}

	@Override
	public void saveVirtualArchAgent(VirtualArchitectureAgent virtualArchitectureAgent) {
		propertyDao.saveObj(virtualArchitectureAgent);
	}

	@Override
	public void deleteVirtualArchAgentById(Integer id) {
		propertyDao.deleteVirtualArchAgentById(id);
	}

	@Override
	public void deleteVirtualArchAgentByAgentId(Integer agentId) {
		propertyDao.deleteVirtualArchAgentByAgentId(agentId);
	}

	@Override
	public void saveVirtualArchRange(VirtualArchitectureRange virtualArchitectureRange) {
		propertyDao.saveObj(virtualArchitectureRange);
	}

	@Override
	public void deleteVirtualArchRangeById(Integer id) {
		propertyDao.deleteVirtualArchRangeById(id);
	}

	@Override
	public List<OrgDto> getScopeOrgList(ScopeEntity scopeEntity, String developId) {

		List<TbOrganization> list   = propertyDao.getScopeOrgList(scopeEntity, developId);
		List<OrgDto>         result = new ArrayList<>();
		for (TbOrganization org : list) {
			result.add(new OrgDto(org.getId(), org.getName()));
		}
		return result;
	}
}
