package com.palmnest.service.virtProject.impl;

import com.palmnest.application.AppConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.ListPage;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.input.MeetingOrgDto;
import com.palmnest.application.dto.input.MetingCompanyDto;
import com.palmnest.application.dto.input.VirtualInputDto;
import com.palmnest.application.dto.output.VirAccountDto;
import com.palmnest.application.dto.output.VirUserOutputDto;
import com.palmnest.model.Element;
import com.palmnest.model.FloorInfo;
import com.palmnest.model.OrgElement;
import com.palmnest.model.RoomInfo;
import com.palmnest.model.VirtUserInfo;
import com.palmnest.model.dinner.Department;
import com.palmnest.model.dinner.OrderDinnerSet;
import com.palmnest.model.enterprise.VirPermConfig;
import com.palmnest.model.estateserve.*;
import com.palmnest.model.property.TbBuild;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.model.property.VirtualArchitectureAgent;
import com.palmnest.model.release.GoodsRelease;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.dinner.manager.DeptManager;
import com.palmnest.service.dinner.manager.OrderDinnerSetManager;
import com.palmnest.service.dinner.service.PlaceAnOrderService;
import com.palmnest.service.estateserve.*;
import com.palmnest.service.estateserve.release.GoodsReleaseManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.virtProject.VirtualArchService;
import com.palmnest.service.virtProject.manager.UserAccountManager;
import com.palmnest.service.virtProject.manager.VirtualAccountManager;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service("virtualArchService")
public class VirtualArchServiceImpl implements VirtualArchService {


	@Autowired
	private PropertyManager             propertyManager;
	@Autowired
	private VirtualArchManager          virtualArchManager;
	@Autowired
	private VirtualAccountManager       virtualAccountManager;
	@Autowired
	private UserAccountManager          userAccountManager;
	@Autowired
	private ScWxuserManager             scWxuserManager;
	@Autowired
	private VirtUserManager             virtUserManager;
	@Autowired
	private ElementGroupManager         elementGroupManager;
	@Autowired
	private AppUserManager              appUserManager;
	@Autowired
	private OrganizationManager         organizationManager;
	@Autowired
	private RoomInfoManager             roomInfoManager;
	@Autowired
	private FloorInfoManager            floorInfoManager;
	@Autowired
	private PlaceAnOrderService         placeAnOrderService;
	@Autowired
	private DeptManager                 deptManager;
	@Autowired
	private UserManager                 userManager;
	@Autowired
	private VisitorInFoManager          visitorInFoManager;
	@Autowired
	private EnterprisePermissionManager enterprisePermissionManager;

	@Autowired
	private GoodsReleaseManager goodsReleaseManager;

	@Autowired
	private OrderDinnerSetManager orderDinnerSetManager;

	public static String image_server = PropertiesKit.readPropertiesValue("image_server", "wechat.properties");

	public Map<String, Object> importVirtualInfo(InputStream ins, String buildId) throws Exception {
		Map<String, Object>   retMap   = new HashMap<String, Object>();
		List<VirtualInputDto> list     = new ArrayList<VirtualInputDto>();
		int                   bugCount = 0;
		StringBuffer          bugStr   = new StringBuffer("");
		Sheet                 sheet    = null;
		try {
			Workbook workbook = WorkbookFactory.create(ins);
			sheet = workbook.getSheet("VirtualArchitecture");
		} catch (Exception e) {
			bugStr.append("模板格式有问题，请下载最新的模板");
		}

		try {
			if (sheet == null) {
				bugStr.append("模板格式有问题，请下载最新的模板");
			} else {
				int rows = sheet.getLastRowNum();
				//如果大于2000行数据
				if (rows > 20000) {
					bugStr.append("数据量太大，不能大于2w行");
					bugCount++;
				} else if (rows < 1) {
					bugStr.append("数据为空，请录入企业信息");
					bugCount++;
				} else {
					for (int i = 1; i <= rows; i++) {
						if (sheet.getRow(i) == null) {
							continue;
						}

						//楼层号
						String floorNames = "";
						if (sheet.getRow(i).getCell(0) != null) {
							sheet.getRow(i).getCell(0).setCellType(Cell.CELL_TYPE_STRING);
							floorNames = sheet.getRow(i).getCell(0).getStringCellValue();
						}

						//房间号
						String roomNames = "";
						if (sheet.getRow(i).getCell(1) != null) {
							sheet.getRow(i).getCell(1).setCellType(Cell.CELL_TYPE_STRING);
							roomNames = sheet.getRow(i).getCell(1).getStringCellValue();
						}

						String floorIds = "";
						if (StringUtils.isNotBlank(floorNames)) {
							floorNames = floorNames.replace("，", ",").trim();
							String[] floorStr = floorNames.split(",");
							if (floorStr == null || floorStr.length <= 0) {
								bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：楼层信息有误(以逗号','隔开)，请导出系统模板匹配录入<br/>");
								bugCount++;
								continue;
							} else {
								String str = "";
								for (int j = 0; j < floorStr.length; j++) {
									if (StringUtils.isNotBlank(floorStr[j])) {
										str += "'" + floorStr[j] + "',";
									}
								}
								if (StringUtils.isNotEmpty(str)) {
									str = str.substring(0, str.length() - 1);
									List<FloorInfo> floorList = floorInfoManager.getFloorListByOrgId(Integer.parseInt(buildId), str);
									if (floorList == null || floorList.size() <= 0) {
										bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：楼层信息不存在，请导出系统模板匹配录入<br/>");
										bugCount++;
										continue;
									}
									for (int j = 0; j < floorList.size(); j++) {
										FloorInfo info = floorList.get(j);
										floorIds += info.getId() + ",";
									}
									if (StringUtils.isNotBlank(floorIds)) {
										floorIds = floorIds.substring(0, floorIds.length() - 1);
									} else {
										bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：楼层信息不存在，请导出系统模板匹配录入<br/>");
										bugCount++;
										continue;
									}
								} else {
									bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：楼层信息有误(以逗号','隔开)，请导出系统模板匹配录入<br/>");
									bugCount++;
									continue;
								}

							}
						}

						String roomIds = "";
						if (StringUtils.isNotBlank(roomNames) && StringUtils.isNotBlank(floorIds)) {
							roomNames = roomNames.replace("，", ",").trim();
							String[] roomStr = roomNames.split(",");
							if (roomStr == null || roomStr.length <= 0) {
								bugStr.append("第" + i + "行第2列数据有问题，请检查，问题：房间号信息有误(以逗号','隔开)，请导出系统模板匹配录入<br/>");
								bugCount++;
								continue;
							} else {
								String str = "";
								for (int j = 0; j < roomStr.length; j++) {
									if (StringUtils.isNotBlank(roomStr[j])) {
										str += "'" + roomStr[j] + "',";
									}
								}
								if (StringUtils.isNotEmpty(str)) {
									str = str.substring(0, str.length() - 1);
									List<RoomInfo> roomList = roomInfoManager.getRoomListByRooms(floorIds, str);
									if (roomList == null) {
										bugStr.append("第" + i + "行第2列数据有问题，请检查，问题：房间号信息不存在，请导出系统模板匹配录入<br/>");
										bugCount++;
										continue;
									}
									for (int j = 0; j < roomList.size(); j++) {
										RoomInfo info = roomList.get(j);
										roomIds += info.getId() + ",";
										List<Map<String, Object>> virList = virtualArchManager.getVirtualByRoomId(info.getId().toString());
										if (virList != null && virList.size() > 0) {
											bugStr.append("第" + i + "行第2列数据有问题，请检查，问题：所输入房间号已有企业存在，请详细检查导入数据的真实性，请导出系统模板匹配录入<br/>");
											bugCount++;
											continue;
										}
									}
									if (StringUtils.isNotBlank(roomIds)) {
										roomIds = roomIds.substring(0, roomIds.length() - 1);
									} else {
										bugStr.append("第" + i + "行第2列数据有问题，请检查，问题：房间号信息不存在，请导出系统模板匹配录入<br/>");
										bugCount++;
										continue;
									}
								} else {
									bugStr.append("第" + i + "行第2列数据有问题，请检查，问题：房间号信息有误(以逗号','隔开)，请导出系统模板匹配录入<br/>");
									bugCount++;
									continue;
								}
							}
						}

						//企业名称
						if (sheet.getRow(i).getCell(2) == null) {
							bugStr.append("第" + i + "行第3列数据有问题，请检查，问题：企业名称必填，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						sheet.getRow(i).getCell(2).setCellType(Cell.CELL_TYPE_STRING);

						if (StringUtils.isBlank(sheet.getRow(i).getCell(2).getStringCellValue())) {
							bugStr.append("第" + i + "行第3列数据有问题，请检查，问题：企业名称必填，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						String virName = sheet.getRow(i).getCell(2).getStringCellValue();

						//详细地址
						String address = "";
						if (sheet.getRow(i).getCell(3) != null) {
							sheet.getRow(i).getCell(3).setCellType(Cell.CELL_TYPE_STRING);
							address = sheet.getRow(i).getCell(3).getStringCellValue();
						}

						//签约日期
						if (sheet.getRow(i).getCell(4) == null) {
							bugStr.append("第" + i + "行第5列数据有问题，请检查，问题：签约日期必填，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						sheet.getRow(i).getCell(4).setCellType(Cell.CELL_TYPE_STRING);

						if (StringUtils.isBlank(sheet.getRow(i).getCell(4).getStringCellValue())) {
							bugStr.append("第" + i + "行第5列数据有问题，请检查，问题：签约日期必填，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}

						String signingTime = sheet.getRow(i).getCell(4).getStringCellValue();

						//合同到期日期
						if (sheet.getRow(i).getCell(5) == null) {
							bugStr.append("第" + i + "行第6列数据有问题，请检查，问题：合同到期日期必填，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						sheet.getRow(i).getCell(5).setCellType(Cell.CELL_TYPE_STRING);

						if (StringUtils.isBlank(sheet.getRow(i).getCell(5).getStringCellValue())) {
							bugStr.append("第" + i + "行第6列数据有问题，请检查，问题：合同到期日期必填，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}

						String contExpireTime = sheet.getRow(i).getCell(5).getStringCellValue();

						try {
							if (StringUtil.isNotEmpty(signingTime)) {
								Date day = DateHelper.parseToDate(signingTime, DateHelper.CURRENT_DATE);
								if (null == day) {
									bugStr.append("日期格式有误，请输入如2019-01-01格式的日期，请导出系统模板匹配录入<br/>");
									bugCount++;
									continue;
								}
							}
							if (StringUtil.isNotEmpty(contExpireTime)) {
								Date day = DateHelper.parseToDate(contExpireTime, DateHelper.CURRENT_DATE);
								if (null == day) {
									bugStr.append("日期格式有误，请输入如2019-01-01格式的日期，请导出系统模板匹配录入<br/>");
									bugCount++;
									continue;
								}
							}
						} catch (Exception e) {
							bugStr.append("日期格式有误，请输入如2019-01-01格式的日期，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						String userName = "";
						if (sheet.getRow(i).getCell(6) != null) {
							//企业联系人
							sheet.getRow(i).getCell(6).setCellType(Cell.CELL_TYPE_STRING);
							userName = sheet.getRow(i).getCell(6).getStringCellValue();
						}


						String mobile = "";
						if (sheet.getRow(i).getCell(7) != null) {
							//企业电话
							sheet.getRow(i).getCell(7).setCellType(Cell.CELL_TYPE_STRING);
							mobile = sheet.getRow(i).getCell(7).getStringCellValue();

							boolean bool = RegularPattern.isMobileNO(mobile);//验证手机格式是否正确
							if (StringUtils.isNotEmpty(mobile) && !bool) {
								bugStr.append("第" + i + "行第8列数据有问题，请检查，问题：" + mobile + "手机号码格式有问题，请导出系统模板匹配录入<br/>");
								bugCount++;
								continue;
							}
						}


						String email = "";
						if (sheet.getRow(i).getCell(8) != null) {
							//企业邮箱
							sheet.getRow(i).getCell(8).setCellType(Cell.CELL_TYPE_STRING);
							email = sheet.getRow(i).getCell(8).getStringCellValue();
							if (!RegularPattern.checkEmail(email)) {
								bugStr.append("第" + i + "行第9列数据有问题，请检查，问题：邮箱格式有误，请导出系统模板匹配录入<br/>");
								bugCount++;
								continue;
							}
						}

						VirtualInputDto dto = new VirtualInputDto();
						dto.setAddress(address);

						if (StringUtils.isNotEmpty(floorNames)) {
							dto.setFloorNames(floorNames + ",");
							dto.setFloorIds(floorIds + ",");
						} else {
							dto.setFloorNames("");
							dto.setFloorIds("");
						}

						if (StringUtils.isNotEmpty(roomNames)) {
							dto.setRoomIds(roomIds + ",");
							dto.setRoomNames(roomNames + ",");
						} else {
							dto.setRoomIds("");
							dto.setRoomNames("");
						}
						dto.setMobile(mobile);
						dto.setUserName(userName);
						dto.setVirName(virName);
						dto.setBuildId(buildId);
						dto.setEmail(email);
						dto.setContExpireTime(contExpireTime);
						dto.setSigningTime(signingTime);
						TbBuild buildInfo = floorInfoManager.getTbBuildById(Integer.parseInt(buildId));
						dto.setBuildName(buildInfo.getName());
						dto.setOrgId(buildInfo.getOrganizationId() == null ? "" : buildInfo.getOrganizationId().toString());
						list.add(dto);
					}
				}
			}
			retMap.put("bugCount", bugCount);
			retMap.put("bugStr", bugStr.toString());
			retMap.put("list", list);
			retMap.put("okCount", list.size());
			return retMap;

		} catch (Exception e) {
			log.error(e.getMessage());
			if (bugCount == 0) {
				bugCount++;
			}
			retMap.put("bugCount", bugCount);
			retMap.put("bugStr", e.getMessage());
			retMap.put("list", list);
			retMap.put("okCount", list.size());
			e.printStackTrace();
			return retMap;
		}
	}

	@Override
	public Map<String, Object> getAccount(int virId, int type) {
		Map<String, Object>    map         = new HashMap<String, Object>();
		List<VirUserOutputDto> appUserList = new ArrayList<VirUserOutputDto>();
		map.put("account", "");
		map.put("password", "");
		try {
			if (virtualArchManager.exists(virId)) {
				VirtualArchitecture virInfo = virtualArchManager.get(virId);
				if (virInfo != null) {
					List<VirtualAccount> list = virtualAccountManager.getVirAccountByVirId(virId);
					if (list != null && list.size() > 0) {//从表中获取
						if (list.size() > 1) {
							map.put("msg", "数据异常：该企业下出现多个企业账号");
						} else {
							VirtualAccount virAcc = list.get(0);
							map.put("account", virAcc.getVirAccount());
							map.put("password", virAcc.getPassword());
						}
					} else {
						// 企业编码+加三位随时数(字母+数字)
						String custNumber = virInfo.getCustomerNumber();
						if (StringUtils.isNotEmpty(custNumber)) {//当企业编码不为空的时候，才提供自动生成账号密码功能
							if (type == 1) {//获取账号密码
								map.put("account", CodeGenerateUtils.account(custNumber));
								map.put("password", CodeGenerateUtils.password());
							} else {//重新设置密码
								map.put("password", CodeGenerateUtils.password());
							}

						}
					}
					List<VirtUserInfo> vuserList = virtUserManager.getVirtUserByVirtId(virId);
					if (vuserList != null && vuserList.size() > 0) {
						for (int i = 0; i < vuserList.size(); i++) {
							VirtUserInfo     vuser   = vuserList.get(i);
							VirUserOutputDto dto     = new VirUserOutputDto();
							AppUser          appUser = appUserManager.get(vuser.getUserId());
							dto.setReOrder(vuser.getReorder());
							dto.setUserMobile(appUser.getUserMobile());
							dto.setEmail(appUser.getEmail());
							dto.setId(appUser.getId());
							dto.setUserName(appUser.getUserName());
							appUserList.add(dto);
						}
					}
				}
			} else {
				map.put("msg", "查不到该企业");
			}
			map.put("userList", appUserList);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			map.put("msg", "失败原因：" + e.getMessage());
		}

		return map;
	}

	@Override
	public String saveAccount(String orgId, int virId, String account, String password, String userId) {
		String msg = "";
		try {
			List<VirtualAccount> list = virtualAccountManager.getVirAccountByVirId(virId);
			if (list != null && list.size() > 0) {//修改账号密码
				if (list.size() > 1) {
					msg = "数据异常：该企业下出现多个企业账号";
				} else {
					VirtualAccount virAcc = list.get(0);
					//账号密码未改动时直接跳过修改操作
					if (virAcc.getVirAccount().equals(account) && virAcc.getPassword().equals(password)) {
						msg = "SUCCESS";
						return msg;
					}
					virAcc.setPassword(password);
					virAcc.setVirAccount(account);
					virAcc.setOrgId(orgId);
					virAcc.setModifier(userId);
					virAcc.setModifyTime(new Date());
					virtualAccountManager.updateModel(virAcc);
					userAccountManager.updateUserAccountByAccId(virAcc.getId());
					msg = "SUCCESS";
				}

			} else {//新增账号密码
				VirtualAccount virAcc = new VirtualAccount();
				virAcc.setCreateTime(new Date());
				virAcc.setCreator(userId);
				virAcc.setIsEnable("1");
				virAcc.setOrgId(orgId);
				virAcc.setPassword(password);
				virAcc.setVirAccount(account);
				virAcc.setVirId(virId);
				virtualAccountManager.save(virAcc);
				msg = "SUCCESS";
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			msg = e.getMessage();
		}
		return msg;
	}

//	@Override
//	public String saveAccount(VirUserAccountInputDto virUserDto,String userId) {
//		String msg="";
//		try{
//			List<VirtualAccount>  list=virtualAccountManager.getVirAccountByVirId(Integer.parseInt(virUserDto.getId()));
//			List<VirUserOutputDto> virUserList=virUserDto.getVirUserList();
//			String res=virtualArchManager.saveVirUserList(Integer.parseInt(virUserDto.getId()), virUserList);
//			if("SUCCESS".equals(res)){
//				if(list!=null&&list.size()>0){//修改账号密码
//					if(list.size()>1){
//						msg="数据异常：该企业下出现多个企业账号";
//					}else{
//						VirtualAccount virAcc=list.get(0);
//						virAcc.setPassword(virUserDto.getPassword());
//						virAcc.setVirAccount(virUserDto.getAccount());
//						virAcc.setModifier(userId);
//						virAcc.setModifyTime(new Date());
//						virtualAccountManager.updateModel(virAcc);
//						msg="SUCCESS";
//					}
//					
//				}else{//新增账号密码
//					VirtualAccount virAcc=new VirtualAccount();
//					virAcc.setCreateTime(new Date());
//					virAcc.setCreator(userId);
//					virAcc.setIsEnable("1");
//					virAcc.setPassword(virUserDto.getPassword());
//					virAcc.setVirAccount(virUserDto.getAccount());
//					virAcc.setVirId(Integer.parseInt(virUserDto.getId()));
//					virtualAccountManager.save(virAcc);
//					msg="SUCCESS";
//				}
//			}else{
//				msg="保存企业负责人失败，请联系管理员.";
//			}
//		}catch(Exception e){
//			log.error(e.getMessage());
//			e.printStackTrace();
//			msg=e.getMessage();
//		}
//		return msg;
//	}

	@Override
	public String updateVirFreeTime(int id, String settleType,
									String freeLenTime, String remainderTime, String userId, String virPermId) {
		String msg = "";
		try {
			if (virtualArchManager.exists(id)) {
				VirtualArchitecture virInfo = virtualArchManager.get(id);
				if (virInfo != null) {
					if (StringUtils.isNotEmpty(settleType)) {
						virInfo.setSettleType(Integer.parseInt(settleType));
					} else {
						virInfo.setSettleType(0);
					}

					if (StringUtils.isNotEmpty(freeLenTime)) {
						virInfo.setFreeLenTime(new BigDecimal(freeLenTime));
					} else {
						virInfo.setFreeLenTime(BigDecimal.ZERO);
					}

					if (StringUtils.isNotEmpty(remainderTime)) {
						virInfo.setRemainderTime(new BigDecimal(remainderTime));
					} else {
						virInfo.setRemainderTime(BigDecimal.ZERO);
					}
					virInfo.setModifier(userId);
					virInfo.setModifyTime(new Date());
					if (StringUtils.isNotBlank(virPermId)) {
						virInfo.setVirType(Long.parseLong(virPermId));
					} else {
						virInfo.setVirType(null);
					}

					virtualArchManager.updateModel(virInfo);
					msg = "SUCCESS";
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			msg = e.getMessage();
			e.printStackTrace();
		}

		return msg;
	}

	@Transactional
	public AppResultDto accLogin(String orgId, String openId, String account, String password) throws Exception {
		//首先查看该账号数据库有没有，然后再看该openId以及该账号有没有登录记录，有就改变这条记录的在线状态
		Map<String, Object> map = new HashMap<String, Object>();
		try {
//			//查找当前项目下的企业账号
//			WxUser wxUser=scWxuserManager.getScWxuserByOpenId(openId);
//			if(wxUser == null || wxUser.getOrganizationId() == null) {
//				return AppResultUtil.createErrorDto("100", "登录失败");
//			}
//			Integer orgId = wxUser.getOrganizationId();
			List<VirtualAccount> virAccList = virtualAccountManager.getVirAccountByAccount(orgId, account, password);
			if (virAccList != null && virAccList.size() > 0) {
				VirtualAccount virAcc = virAccList.get(0);
				if (virAcc != null) {
					//验证企业账号所属项目是否和当前项目一致
					VirtualArchitecture va = virtualArchManager.get(virAcc.getVirId());
					if (va == null || va.getOrganizationId().intValue() != Integer.parseInt(orgId)) {
						return AppResultUtil.createErrorDto(AppConstants.USER_NAME_OR_PASSWORD_NULL, "用户名或密码错误");
					}
					List<UserAccountRecode> userAccList = userAccountManager.getUserAccountByAccount(orgId, virAcc.getId().toString(), openId);
					if (userAccList != null && userAccList.size() > 0) {//如果有记录修改记录
						UserAccountRecode userAcc = userAccList.get(0);
						userAcc.setModifier(openId);
						userAcc.setModifyTime(new Date());
						userAcc.setIsOnline("2");
						userAcc.setOrgId(orgId);
						userAccountManager.updateModel(userAcc);
						if (userAcc.getAccountId() != 0) {
							VirtualAccount acc = virtualAccountManager.get(userAcc.getAccountId());
							map.put("accId", acc.getId());
							map.put("virId", acc.getVirId());
							map.put("account", acc.getVirAccount());
							map.put("password", acc.getPassword());
						}
					} else {//如果没记录需要新增记录
						UserAccountRecode userAcc = new UserAccountRecode();
						userAcc.setAccountId(virAcc.getId());
						userAcc.setIsOnline("2");
						userAcc.setOpenId(openId);
						userAcc.setUserId("");
						userAcc.setOrgId(orgId);
						userAcc.setCreateTime(new Date());
						userAcc.setCreator(openId);
						userAcc = userAccountManager.save(userAcc);
						if (userAcc.getAccountId() != 0) {
							VirtualAccount acc = virtualAccountManager.get(userAcc.getAccountId());
							map.put("accId", acc.getId());
							map.put("virId", acc.getVirId());
							map.put("account", acc.getVirAccount());
							map.put("password", acc.getPassword());
						}
					}
					return AppResultUtil.createSuccesDto("登录成功", map);
				} else {
					return AppResultUtil.createErrorDto(AppConstants.USER_NAME_OR_PASSWORD_NULL, "用户名或密码错误");
				}
			} else {
				return AppResultUtil.createErrorDto(AppConstants.USER_NAME_OR_PASSWORD_NULL, "用户名或密码错误");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "登录失败：" + e.getMessage());
		}
	}

	@Override
	public AppResultDto getUserInfo(String openId, String organizationId, String userId) throws Exception {
		VirAccountDto dto    = new VirAccountDto();
		WxUser        wxUser = scWxuserManager.getScWxuserByOpenId(openId);
		if (wxUser != null) {
			try {
				if (StringUtils.isNotEmpty(organizationId)) {
					TbOrganization org = organizationManager.getOrganizationById(Integer.parseInt(organizationId));
					dto.setAccountType(org.getAccountType());//账号类型
					dto.setIsLogin(1);//默认设置未登录 1-未登录 2-已登录

					if (org != null) {
						dto.setOrgId(org.getId().toString());//项目id
						dto.setOrgName(org.getName());//项目名称
					}
					//20190423 add dz 
					String meal_card = "";
					if (org.getAccountType() == 0) {//企业账号类

						List<UserAccountRecode> userList = userAccountManager.getUserAccountRecode(organizationId, openId);
						if (userList != null && userList.size() > 0) {
							dto.setIsLogin(2);//已登录
							UserAccountRecode userAcc = userList.get(0);
							if (userAcc != null) {
								VirtualAccount virAcc = virtualAccountManager.get(userAcc.getAccountId());
								dto.setAccount(virAcc.getVirAccount());//企业账号
								dto.setAccountId(virAcc.getId());//企业账号id
								dto.setCompId(virAcc.getVirId());//企业id
								if (virAcc.getVirId() != 0) {
									VirtualArchitecture virInfo = virtualArchManager.get(virAcc.getVirId());
									dto.setCompName(virInfo.getName());//企业名称
									meal_card = virInfo.getMeal_card();
								}
							}

						} else {
							dto.setIsLogin(1);//未登录
						}
					} else if (org.getAccountType() == 1) {//个人账号类
						//绑定与否

						//根据用户微信userid和orgid获取当前用户信息
						AppUser userInfo = appUserManager.getAppUserByWxUserAndOrg(wxUser.getId(), Integer.parseInt(organizationId));
						if (userInfo == null && StringUtils.isNotBlank(userId)) {
							//获取当前用户信息
							userInfo = appUserManager.get(Integer.parseInt(userId));
						}

						if (userInfo != null) {
							dto.setMobile(userInfo.getUserMobile());//手机号码
							dto.setUserName(userInfo.getUserName());//用户名
							dto.setIsLogin(userInfo.getIsLogin() == 1 ? 2 : 1);//登录状态 2-登录 1-未登录
							dto.setUserId(userInfo.getId() + "");//用户id
							dto.setIntegral(userInfo.getIntegral());//积分
							//设置该用户是否是白名单
							if (StringUtil.isEqual("0", userInfo.getUserType())) {
								// 白名单用户
								dto.setIsWhite(1);
							} else {
								// 非白名单用户
								dto.setIsWhite(0);
							}
							if(StringUtils.isEmpty(userInfo.getIsPushState())){
								dto.setPushState("1");
							}else{
								dto.setPushState(userInfo.getIsPushState());
							}
							dto.setPassType(org.getPassType());
//							if(org.getPassType()!=null&&org.getPassType()==1){
							// 查询该员工人脸照片信息
							List<UserImageInfo> userImageList = visitorInFoManager.getUserImageInfo(userInfo.getId(), "1");
							if (userImageList != null && userImageList.size() > 0) {
								//为图片拼接前缀
								for (UserImageInfo userImageInfo : userImageList) {
									userImageInfo.setImageUrl(image_server + userImageInfo.getImageUrl());
								}
							}
							dto.setFacePicList(userImageList);
							
							
							dto.setFacePlusImageId(userInfo.getFacePlusImageId());//koala img id
							dto.setImageUrl01(userInfo.getImageUrl01());// koala img url
							
//							}

							int roleType = 2;
							if (StringUtils.isNotEmpty(userInfo.getRoleType())) {
								roleType = Integer.parseInt(userInfo.getRoleType());
								if (roleType == 1) {
									List<AppUser> list = appUserManager.getUserByOrgIdAndRoleType(organizationId, "'1','3'");//获取所有该项目下代订账号
									if (list != null && list.size() > 0) {
										dto.setSubAccount(list.size());
									} else {
										dto.setSubAccount(0);
									}
									SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
									dto.setMeetFoodCount(placeAnOrderService.getMeetFoodCount(organizationId, sdf.format(new Date())));
									dto.setTempFoodCount(placeAnOrderService.getTempOrderCount(organizationId, sdf.format(new Date())));
								}
							}
							dto.setRoleType(roleType);
							if (userInfo.getVirtualArchId() != null && userInfo.getVirtualArchId() != 0) {
								VirtualArchitecture virInfo = virtualArchManager.get(userInfo.getVirtualArchId());
								dto.setAddress(virInfo.getAddress());//地址
								dto.setCompName(virInfo.getName());//企业名称
								dto.setCompId(virInfo.getId());//企业id
								// 企业饭卡号
								meal_card = virInfo.getMeal_card();
								if (StringUtils.isBlank(meal_card)) {
									// 如果用户在该企业下未绑定企业饭卡,则去查询该用户其它企业绑定的企业饭卡号
									meal_card = appUserManager.getUserMealcard(userInfo.getUserMobile());
								}
							}
							//获取用户部门信息 如果DepartmentName字段不为空,则使用该字段;否则拿deptId去数据库字典查询
							if (userInfo.getDepartmentId() != null) {
								if (deptManager.exists(Long.parseLong(userInfo.getDepartmentId().toString()))) {
									Department dept = deptManager.get(Long.parseLong(userInfo.getDepartmentId().toString()));
									if (dept != null) {
										dto.setDeptName(dept.getName());
										dto.setDeptId(userInfo.getDepartmentId());
										if (StringUtil.isNotEmpty(dept.getAddress())) {
											dto.setAddress(dept.getAddress());
										}
									}
								}
							}

							//获取用户地址


							if (StringUtils.isNotBlank(userInfo.getAddress())){
								OrgElement OrgEl=elementGroupManager.getOrgElementId(Long.valueOf(userInfo.getAddress()));
								if(OrgEl!=null){
									dto.setAddress(OrgEl.getItemname());
									dto.setAddressId(OrgEl.getId());
								}else{
									Element byItemCode = elementGroupManager.getElementId(Long.valueOf(userInfo.getAddress()));
									if(byItemCode!=null){
										dto.setAddress(byItemCode.getItemname());
										dto.setAddressId(byItemCode.getId());
									}
								}
								
							}

							// 权限
							if (!Objects.isNull(userInfo.getVirPermId())) {
								String relationStr = enterprisePermissionManager.getVirPermServiceRelationStr(userInfo.getVirPermId());
								dto.setFuncListStr(relationStr);
								VirPermConfig config = enterprisePermissionManager.get(userInfo.getVirPermId());
								dto.setPermName(config.getName());
								dto.setPermId(config.getId());
								dto.setCheckRole(config.getCheckRole());
							}

							if (!Objects.isNull(userInfo.getId())) {

								Map<String, Object> params = new HashMap<String, Object>();
								params.put("userId", userInfo.getId());
								params.put("virtualArchId", userInfo.getVirtualArchId());
								params.put("releaseStatus", "1,10");
								params.put("applyType", 1);
								List<GoodsRelease> listGoodsRelease = goodsReleaseManager.getGoodsReleaseByParams(params);
								if (listGoodsRelease.size() >= 1) {
									dto.setPassRecordStatus(listGoodsRelease.get(0).getReleaseStatus());
								}

							}

						}

						//个人时获得企业及企业账号信息 空调加时使用 by qzy
						List<UserAccountRecode> userList = userAccountManager.getUserAccountRecode(organizationId, openId);
						if (userList != null && userList.size() > 0) {
							UserAccountRecode userAcc = userList.get(0);
							if (userAcc != null) {
								VirtualAccount virAcc = virtualAccountManager.get(userAcc.getAccountId());
								dto.setAccount(virAcc.getVirAccount());//企业账号
								dto.setAccountId(virAcc.getId());//企业账号id
								dto.setCompId(virAcc.getVirId());//企业id
								if (virAcc.getVirId() != 0) {
									VirtualArchitecture virInfo = virtualArchManager.get(virAcc.getVirId());
									dto.setCompName(virInfo.getName());//企业名称
									dto.setCompId(virInfo.getId());//企业id
								}
							}
						}

					}
					//dz-20190311 add 20190423 change
					//String foodCardNo=PropertiesKit.readPropertiesValue("food_card_company_id","wechat.properties"); ////饭卡企业号

					dto.setFoodCardNo(meal_card);
					String foodCardH5 = PropertiesKit.readPropertiesValue("food_card_H5", "wechat.properties"); ////饭卡企业号
					dto.setFoodCardH5(foodCardH5);



					return AppResultUtil.createSuccesDto(dto);
				} else {
					return AppResultUtil.createErrorDto("100", "楼宇不允许为空");
				}
			} catch (Exception e) {
				log.error(e.getMessage());
				e.printStackTrace();
				return AppResultUtil.createErrorDto("100", "获取用户信息失败：" + e.getMessage());
			}
		} else {
			return AppResultUtil.createErrorDto("100", "微信用户不存在");
		}
	}

	@Override
	public VirAccountDto getUser(String openId, String organizationId, String userMobile) throws Exception {
		VirAccountDto dto    = new VirAccountDto();
		WxUser        wxUser = scWxuserManager.getScWxuserByOpenId(openId);
		if (wxUser == null || StringUtils.isEmpty(organizationId) || StringUtils.isEmpty(userMobile)) {
			return null;
		}
		String meal_card = "";
		//根据用户手机号和orgid获取当前用户信息
		AppUser userInfo = appUserManager.getAppUsersByPhoneAndOrg(userMobile, Integer.parseInt(organizationId));
		if (userInfo != null) {
			dto.setMobile(userInfo.getUserMobile());//手机号码
			dto.setUserName(userInfo.getUserName());//用户名
			if (userInfo.getVirtualArchId() != null && userInfo.getVirtualArchId() != 0) {
				VirtualArchitecture virInfo = virtualArchManager.get(userInfo.getVirtualArchId());
				meal_card = virInfo.getMeal_card();
			}
		}
		dto.setFoodCardNo(meal_card);
		String foodCardH5 = PropertiesKit.readPropertiesValue("food_card_H5", "wechat.properties"); ////饭卡企业号
		dto.setFoodCardH5(foodCardH5);
		return dto;
	}

	@Transactional
	public String deleteAccount(String virId, String isEnable, String userId) {
		String               res  = "";
		List<VirtualAccount> list = new ArrayList<VirtualAccount>();
		try {
			if ("1".equals(isEnable)) {//启用状态的单据，需要禁用
				list = virtualAccountManager.getVirAccountByVirId(Integer.parseInt(virId));
			} else if ("0".equals(isEnable)) {//禁用的数据需要启用
				list = virtualAccountManager.getVirAccountByVirIdIsEnable(Integer.parseInt(virId));
			}
			if (list != null && list.size() > 0) {
				if (list.size() == 1) {//修改企业账号并且将已登录该账号的人设置为退出状态
					VirtualAccount va = list.get(0);
					if ("1".equals(isEnable)) {//启用状态的单据，需要禁用
						va.setIsEnable("0");
					} else if ("0".equals(isEnable)) {//禁用的数据需要启用
						va.setIsEnable("1");
					}
					va.setModifier(userId);
					va.setModifyTime(new Date());
					virtualAccountManager.updateModel(va);
					if ("1".equals(isEnable)) {//禁用企业账号的时候需要将账号退出
						userAccountManager.updateUserAccountByAccId(va.getId());
					}
					res = "SUCCESS";
				} else {
					res = "账号异常";
				}
			} else {
				res = "没有企业帐号";
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return res;
	}

	@Override
	public VirAccountDto getVirAccountBy(Long virAccountId) {
		VirAccountDto  dto    = new VirAccountDto();
		VirtualAccount virAcc = virtualAccountManager.get(virAccountId);
		dto.setAccount(virAcc.getVirAccount());//企业账号
		dto.setAccountId(virAcc.getId());//企业账号id
		dto.setCompId(virAcc.getVirId());//企业id
		if (virAcc.getVirId() != 0) {
			VirtualArchitecture virInfo = virtualArchManager.get(virAcc.getVirId());
			dto.setCompName(virInfo.getName());//企业名称
		}
		return dto;
	}

	@Transactional
	public String saveImpVirtualInfo(List<VirtualInputDto> list, String userId, String pre_id)
			throws Exception {
		String                    res     = "FAIL";
		List<VirtualArchitecture> virList = new ArrayList<VirtualArchitecture>();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				VirtualInputDto     dto     = list.get(i);
				VirtualArchitecture virInfo = new VirtualArchitecture();
				virInfo.setCodeNumber(dto.getCodeNumber());
				virInfo.setCustomerNumber(dto.getCodeNumber());
				virInfo.setStatus("1");
				virInfo.setType("1");
				virInfo.setLeaseStatus(1);
				virInfo.setAddress(dto.getAddress());
				virInfo.setBuildId(Integer.parseInt(dto.getBuildId()));
				virInfo.setFloorIds(dto.getFloorIds().replace(",", ";"));
				virInfo.setFloorNames(dto.getFloorNames().replace(",", ";"));
				virInfo.setRoomIds(dto.getRoomIds().replace(",", ";"));
				virInfo.setRoomNames(dto.getRoomNames().replace(",", ";"));
				virInfo.setIsEnabled("1");
				virInfo.setName(dto.getVirName());
				if (StringUtils.isNotEmpty(dto.getOrgId())) {
					virInfo.setOrganizationId(Integer.parseInt(dto.getOrgId()));
				}
				if (StringUtils.isNotEmpty(dto.getRoomIds())) {
					virInfo.setFloorAndNames(getFloorAndRoom(dto.getRoomIds()));
				}
				virInfo.setPhone(dto.getMobile());
				virInfo.setContacts(dto.getUserName());
				virInfo.setCreateTime(new Date());
				virInfo.setCreator(userId);

				virInfo.setEmail(dto.getEmail());
				virInfo.setContExpireTime(dto.getContExpireTime());
				virInfo.setSigningTime(dto.getSigningTime());

				virInfo = virtualArchManager.save(virInfo);
				if (StringUtils.isNotBlank(pre_id) && !pre_id.equals("0")) {
					VirtualArchitectureAgent virtualArchitectureAgent = new VirtualArchitectureAgent();
					virtualArchitectureAgent.setId(virInfo.getId());
					virtualArchitectureAgent.setAgent_id(Integer.parseInt(pre_id));
					propertyManager.saveVirtualArchAgent(virtualArchitectureAgent);
				}
				virList.add(virInfo);
			}
			if (list.size() == virList.size()) {
				res = "SUCCESS";
			}
		}
		return res;
	}

	@Override
	public String getFloorAndRoom(String roomIds) {
		String floorAndRoom = "";
		roomIds = roomIds.replace(",", ";");
		String[] roomIdStr = roomIds.split(";");
		if (roomIdStr != null && roomIdStr.length > 0) {
			for (int j = 0; j < roomIdStr.length; j++) {
				RoomInfo  roomInfo  = roomInfoManager.get(Integer.parseInt(roomIdStr[j]));
				FloorInfo floorInfo = floorInfoManager.get(Integer.parseInt(String.valueOf(roomInfo.getFloorId())));
				floorAndRoom = floorAndRoom + floorInfo.getName() + "楼" + roomInfo.getName() + "、";
			}
		}
		if (StringUtils.isNotEmpty(floorAndRoom)) {
			floorAndRoom = floorAndRoom.substring(0, floorAndRoom.length() - 1);
		}
		return floorAndRoom;
	}

	@Override
	public AppResultDto synchroCompanyData(String startTime) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date                   date    = new Date();
			String                 endTime = sdf.format(date);
			Map<String, Object>    map     = new HashMap<>();
			List<MetingCompanyDto> dtoList = virtualArchManager.getVirByStartTime(startTime, endTime);
			map.put("currentTime", endTime);
			map.put("companyList", dtoList);
			return AppResultUtil.createSuccesDto(map);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "同步数据失败：" + e.getMessage());
		}
	}

	@Override
	public AppResultDto synchroFloorData(String startTime) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date                date    = new Date();
			String              endTime = sdf.format(date);
			Map<String, Object> map     = new HashMap<String, Object>();
			List<MeetingOrgDto> dtoList = floorInfoManager.getFloorByStartTime(startTime, endTime);
			map.put("currentTime", endTime);
			map.put("orgList", dtoList);
			return AppResultUtil.createSuccesDto(map);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "同步数据失败：" + e.getMessage());
		}
	}

	@Override
	public VirtualArchitecture findById(int id) {
		return virtualArchManager.get(id);
	}

	@Override
	public AppResultDto synchroMeetingRole(String clientNo) {
		try {
			List<Map<String, Object>> listMeetingRole = userManager.findMeetingAuditRoleByOrdId(clientNo);
			return AppResultUtil.createSuccesDto(listMeetingRole);

		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "同步数据失败：" + e.getMessage());
		}
	}

	@Override
	public WebPageResultDto getVirtualArchAgent(int pageSize, int pageNo) {
		List<Map<String, Object>> platList = virtualArchManager.getVirtualArchAgent();
		ListPage                  page     = PageUtils.getListPage(platList, pageNo, pageSize);
		WebPageResultDto          dto      = new WebPageResultDto("200", "成功", page.getDataList());
		if (platList != null && platList.size() > 0) {
			dto.setCount(Long.parseLong(String.valueOf(platList.size())));
		} else {
			dto.setCount(Long.parseLong("0"));
		}
		return dto;
	}


	@Override
	public WebPageResultDto getVirtualDataByInfo(String orgId, int dateType,
												 String date, String endDate, int pageSize, int pageNo) {
		List<Map<String, Object>> platList = getStatisticsVirtualInfo(orgId, dateType, date, endDate);
		ListPage                  page     = PageUtils.getListPage(platList, pageNo, pageSize);
		WebPageResultDto          dto      = new WebPageResultDto("200", "成功", page.getDataList());
		if (platList != null && platList.size() > 0) {
			dto.setCount(Long.parseLong(String.valueOf(platList.size())));
		} else {
			dto.setCount(Long.parseLong("0"));
		}
		return dto;
	}

	private List<Map<String, Object>> getStatisticsVirtualInfo(String orgIds, int dateType,
															   String date, String endDate) {
		List<Map<String, Object>> sumCountList = virtualArchManager.getVirtualDataByInfo(orgIds, dateType, date, endDate);
		if (sumCountList != null && sumCountList.size() > 0) {
			String dateString         = StringUtil.getDateString(dateType, date, endDate, 1);
			int    sumVirCount        = 0;
			int    virCount           = 0;
			int    emigCount          = 0;
			int    contExpireVirCount = 0;
			int    contDueVirCount    = 0;
			for (int i = 0; i < sumCountList.size(); i++) {
				Map<String, Object> map = sumCountList.get(i);
				map.put("dateInfo", dateString);
				map.put("orderno", (i + 1));
				if (map.containsKey("sumVirCount") && map.get("sumVirCount") != null) {
					sumVirCount = sumVirCount + Integer.parseInt(map.get("sumVirCount").toString());
				}
				if (map.containsKey("virCount") && map.get("virCount") != null) {
					virCount = virCount + Integer.parseInt(map.get("virCount").toString());
				}
				if (map.containsKey("emigCount") && map.get("emigCount") != null) {
					emigCount = emigCount + Integer.parseInt(map.get("emigCount").toString());
				}
				if (map.containsKey("contExpireVirCount") && map.get("contExpireVirCount") != null) {
					contExpireVirCount = contExpireVirCount + Integer.parseInt(map.get("contExpireVirCount").toString());
				}
				if (map.containsKey("contDueVirCount") && map.get("contDueVirCount") != null) {
					contDueVirCount = contDueVirCount + Integer.parseInt(map.get("contDueVirCount").toString());
				}
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("dateInfo", dateString);
			map.put("orgName", "合计");
			map.put("orderno", 0);
			map.put("sumVirCount", sumVirCount);
			map.put("virCount", virCount);
			map.put("emigCount", emigCount);
			map.put("contExpireVirCount", contExpireVirCount);
			map.put("contDueVirCount", contDueVirCount);
			sumCountList.add(map);

			//排序
			Collections.sort(sumCountList, new Comparator<Map<String, Object>>() {
				public int compare(Map<String, Object> o1, Map<String, Object> o2) {
					Integer name1 = Integer.parseInt(o1.get("orderno").toString());
					Integer name2 = Integer.parseInt(o2.get("orderno").toString());
					return name1.compareTo(name2);
				}
			});
		}
		return sumCountList;
	}

	@Override
	public AppResultDto exportVirtualStatistics(String orgId, Integer dateType,
												String date, String endDate) {
		log.info("begin exportVirtualStatistics/orgId:" + orgId + "/dateType:" + dateType + "/date:" + date + "/endDate:" + endDate);
		HSSFWorkbook              wb       = new HSSFWorkbook();
		List<Map<String, Object>> platList = getStatisticsVirtualInfo(orgId, dateType, date, endDate);
		String                    path     = placeAnOrderService.setPath("upload/VirtualDataExcel.xls");
		log.info("begin exportVirtualStatistics/path" + path);
		try {
			if (platList != null && platList.size() > 0) {
				String   sheetName  = "企业数据统计";
				File     file       = new File(new ExcelUtils().getPath(path));
				String[] titles     = {"序号", "项目", "统计时间", "企业总数", "新增企业数", "迁出企业数", "合同即将到期企业数", "合同到期企业数", "代理企业", "普通企业", "被代理企业"};
				String[] fieldNames = {"orderno", "orgName", "dateInfo", "sumVirCount", "virCount", "emigCount", "contExpireVirCount", "contDueVirCount", "sumVirCountLevel2", "sumVirCountLevel1", "sumVirCountRelation"};
				ExcelUtils.exportExcel(file, wb, sheetName, platList, titles, fieldNames);
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "导出异常");
		}
		return AppResultUtil.createSuccesDto(path);
	}
}
